everclaw 0.3.18 → 0.3.19
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 +70 -65
- package/agent/tools/chrome-session/daemon-worker.js +19 -14
- package/index.js +266 -261
- package/package.json +1 -1
package/agent/subagent-worker.js
CHANGED
|
@@ -1,62 +1,67 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
`);let $;while(($=dX.exec(y))!=null){let X=$[1],A=$[2]||"";A=A.trim();let L=A[0];if(A=A.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),L==='"')A=A.replace(/\\n/g,`
|
|
5
|
-
`),A=A.replace(/\\r/g,"\r");_[X]=A}return _}function pX(J){J=J||{};let _=jy(J);J.path=_;let y=h.configDotenv(J);if(!y.parsed){let L=new Error(`MISSING_DATA: Cannot parse ${_} for an unknown reason`);throw L.code="MISSING_DATA",L}let $=Fy(J).split(","),X=$.length,A;for(let L=0;L<X;L++)try{let q=$[L].trim(),N=nX(y,q);A=h.decrypt(N.ciphertext,N.key);break}catch(q){if(L+1>=X)throw q}return h.parse(A)}function iX(J){console.log(`[dotenv@${B0}][WARN] ${J}`)}function tJ(J){console.log(`[dotenv@${B0}][DEBUG] ${J}`)}function Ty(J){console.log(`[dotenv@${B0}] ${J}`)}function Fy(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 nX(J,_){let y;try{y=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 $=y.password;if(!$){let q=new Error("INVALID_DOTENV_KEY: Missing key part");throw q.code="INVALID_DOTENV_KEY",q}let X=y.searchParams.get("environment");if(!X){let q=new Error("INVALID_DOTENV_KEY: Missing environment part");throw q.code="INVALID_DOTENV_KEY",q}let A=`DOTENV_VAULT_${X.toUpperCase()}`,L=J.parsed[A];if(!L){let q=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${A} in your .env.vault file.`);throw q.code="NOT_FOUND_DOTENV_ENVIRONMENT",q}return{ciphertext:L,key:$}}function jy(J){let _=null;if(J&&J.path&&J.path.length>0)if(Array.isArray(J.path)){for(let y of J.path)if(G0.existsSync(y))_=y.endsWith(".vault")?y:`${y}.vault`}else _=J.path.endsWith(".vault")?J.path:`${J.path}.vault`;else _=Z_.resolve(process.cwd(),".env.vault");if(G0.existsSync(_))return _;return null}function Oy(J){return J[0]==="~"?Z_.join(cX.homedir(),J.slice(1)):J}function rX(J){let _=Boolean(J&&J.debug),y=J&&"quiet"in J?J.quiet:!0;if(_||!y)Ty("Loading env from encrypted .env.vault");let $=h._parseVault(J),X=process.env;if(J&&J.processEnv!=null)X=J.processEnv;return h.populate(X,$,J),{parsed:$}}function oX(J){let _=Z_.resolve(process.cwd(),".env"),y="utf8",$=Boolean(J&&J.debug),X=J&&"quiet"in J?J.quiet:!0;if(J&&J.encoding)y=J.encoding;else if($)tJ("No encoding is specified. UTF-8 is used by default");let A=[_];if(J&&J.path)if(!Array.isArray(J.path))A=[Oy(J.path)];else{A=[];for(let G of J.path)A.push(Oy(G))}let L,q={};for(let G of A)try{let B=h.parse(G0.readFileSync(G,{encoding:y}));h.populate(q,B,J)}catch(B){if($)tJ(`Failed to load ${G} ${B.message}`);L=B}let N=process.env;if(J&&J.processEnv!=null)N=J.processEnv;if(h.populate(N,q,J),$||!X){let G=Object.keys(q).length,B=[];for(let R of A)try{let Q=Z_.relative(process.cwd(),R);B.push(Q)}catch(Q){if($)tJ(`Failed to load ${R} ${Q.message}`);L=Q}Ty(`injecting env (${G}) from ${B.join(",")}`)}if(L)return{parsed:q,error:L};else return{parsed:q}}function sX(J){if(Fy(J).length===0)return h.configDotenv(J);let _=jy(J);if(!_)return iX(`You set DOTENV_KEY but you are missing a .env.vault file at ${_}. Did you forget to build it?`),h.configDotenv(J);return h._configVault(J)}function aX(J,_){let y=Buffer.from(_.slice(-64),"hex"),$=Buffer.from(J,"base64"),X=$.subarray(0,12),A=$.subarray(-16);$=$.subarray(12,-16);try{let L=uX.createDecipheriv("aes-256-gcm",y,X);return L.setAuthTag(A),`${L.update($)}${L.final()}`}catch(L){let q=L instanceof RangeError,N=L.message==="Invalid key length",G=L.message==="Unsupported state or unable to authenticate data";if(q||N){let B=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw B.code="INVALID_DOTENV_KEY",B}else if(G){let B=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw B.code="DECRYPTION_FAILED",B}else throw L}}function tX(J,_,y={}){let $=Boolean(y&&y.debug),X=Boolean(y&&y.override);if(typeof _!=="object"){let A=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw A.code="OBJECT_REQUIRED",A}for(let A of Object.keys(_))if(Object.prototype.hasOwnProperty.call(J,A)){if(X===!0)J[A]=_[A];if($)if(X===!0)tJ(`"${A}" is already defined and WAS overwritten`);else tJ(`"${A}" is already defined and was NOT overwritten`)}else J[A]=_[A]}var h={configDotenv:oX,_configVault:rX,_parseVault:pX,config:sX,decrypt:aX,parse:lX,populate:tX};D4.configDotenv=h.configDotenv;D4._configVault=h._configVault;D4._parseVault=h._parseVault;D4.config=h.config;D4.decrypt=h.decrypt;D4.parse=h.parse;D4.populate=h.populate;LJ.exports=h});var xy=a((h4,Py)=>{var VJ={};if(process.env.DOTENV_CONFIG_ENCODING!=null)VJ.encoding=process.env.DOTENV_CONFIG_ENCODING;if(process.env.DOTENV_CONFIG_PATH!=null)VJ.path=process.env.DOTENV_CONFIG_PATH;if(process.env.DOTENV_CONFIG_QUIET!=null)VJ.quiet=process.env.DOTENV_CONFIG_QUIET;if(process.env.DOTENV_CONFIG_DEBUG!=null)VJ.debug=process.env.DOTENV_CONFIG_DEBUG;if(process.env.DOTENV_CONFIG_OVERRIDE!=null)VJ.override=process.env.DOTENV_CONFIG_OVERRIDE;if(process.env.DOTENV_CONFIG_DOTENV_KEY!=null)VJ.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY;Py.exports=VJ});var Dy=a((v4,Iy)=>{var LA=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;Iy.exports=function J(_){let y=_.reduce(function($,X){let A=X.match(LA);if(A)$[A[1]]=A[2];return $},{});if(!("quiet"in y))y.quiet="true";return y}});var hy=a(()=>{(function(){Wy().config(Object.assign({},xy(),Dy()(process.argv)))})()});var u$=a((c$)=>{Object.defineProperty(c$,"__esModule",{value:!0});class UJ extends Error{}class h1 extends UJ{constructor(J){super(`Invalid DateTime: ${J.toMessage()}`)}}class v1 extends UJ{constructor(J){super(`Invalid Interval: ${J.toMessage()}`)}}class f1 extends UJ{constructor(J){super(`Invalid Duration: ${J.toMessage()}`)}}class wJ extends UJ{}class f0 extends UJ{constructor(J){super(`Invalid unit ${J}`)}}class g extends UJ{}class NJ extends UJ{constructor(){super("Zone is an abstract class")}}var H="numeric",JJ="short",p="long",h_={year:H,month:H,day:H},k1={year:H,month:JJ,day:H},ZA={year:H,month:JJ,day:H,weekday:JJ},g1={year:H,month:p,day:H},c1={year:H,month:p,day:H,weekday:p},u1={hour:H,minute:H},m1={hour:H,minute:H,second:H},d1={hour:H,minute:H,second:H,timeZoneName:JJ},l1={hour:H,minute:H,second:H,timeZoneName:p},p1={hour:H,minute:H,hourCycle:"h23"},i1={hour:H,minute:H,second:H,hourCycle:"h23"},n1={hour:H,minute:H,second:H,hourCycle:"h23",timeZoneName:JJ},r1={hour:H,minute:H,second:H,hourCycle:"h23",timeZoneName:p},o1={year:H,month:H,day:H,hour:H,minute:H},s1={year:H,month:H,day:H,hour:H,minute:H,second:H},a1={year:H,month:JJ,day:H,hour:H,minute:H},t1={year:H,month:JJ,day:H,hour:H,minute:H,second:H},SA={year:H,month:JJ,day:H,weekday:JJ,hour:H,minute:H},e1={year:H,month:p,day:H,hour:H,minute:H,timeZoneName:JJ},J$={year:H,month:p,day:H,hour:H,minute:H,second:H,timeZoneName:JJ},_$={year:H,month:p,day:H,weekday:p,hour:H,minute:H,timeZoneName:p},y$={year:H,month:p,day:H,weekday:p,hour:H,minute:H,second:H,timeZoneName:p};class OJ{get type(){throw new NJ}get name(){throw new NJ}get ianaName(){return this.name}get isUniversal(){throw new NJ}offsetName(J,_){throw new NJ}formatOffset(J,_){throw new NJ}offset(J){throw new NJ}equals(J){throw new NJ}get isValid(){throw new NJ}}var E0=null;class G_ extends OJ{static get instance(){if(E0===null)E0=new G_;return E0}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(J,{format:_,locale:y}){return Y$(J,_,y)}formatOffset(J,_){return q_(this.offset(J),_)}offset(J){return-new Date(J).getTimezoneOffset()}equals(J){return J.type==="system"}get isValid(){return!0}}var O0=new Map;function CA(J){let _=O0.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"}),O0.set(J,_);return _}var wA={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function zA(J,_){let y=J.format(_).replace(/\u200E/g,""),$=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(y),[,X,A,L,q,N,G,B]=$;return[L,X,A,q,N,G,B]}function OA(J,_){let y=J.formatToParts(_),$=[];for(let X=0;X<y.length;X++){let{type:A,value:L}=y[X],q=wA[A];if(A==="era")$[q]=L;else if(!V(q))$[q]=parseInt(L,10)}return $}var V0=new Map;class XJ extends OJ{static create(J){let _=V0.get(J);if(_===void 0)V0.set(J,_=new XJ(J));return _}static resetCache(){V0.clear(),O0.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=XJ.isValidZone(J)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(J,{format:_,locale:y}){return Y$(J,_,y,this.name)}formatOffset(J,_){return q_(this.offset(J),_)}offset(J){if(!this.valid)return NaN;let _=new Date(J);if(isNaN(_))return NaN;let y=CA(this.name),[$,X,A,L,q,N,G]=y.formatToParts?OA(y,_):zA(y,_);if(L==="BC")$=-Math.abs($)+1;let R=c_({year:$,month:X,day:A,hour:q===24?0:q,minute:N,second:G,millisecond:0}),Q=+_,K=Q%1000;return Q-=K>=0?K:1000+K,(R-Q)/60000}equals(J){return J.type==="iana"&&J.name===this.name}get isValid(){return this.valid}}var A1={};function TA(J,_={}){let y=JSON.stringify([J,_]),$=A1[y];if(!$)$=new Intl.ListFormat(J,_),A1[y]=$;return $}var T0=new Map;function F0(J,_={}){let y=JSON.stringify([J,_]),$=T0.get(y);if($===void 0)$=new Intl.DateTimeFormat(J,_),T0.set(y,$);return $}var j0=new Map;function FA(J,_={}){let y=JSON.stringify([J,_]),$=j0.get(y);if($===void 0)$=new Intl.NumberFormat(J,_),j0.set(y,$);return $}var W0=new Map;function jA(J,_={}){let{base:y,...$}=_,X=JSON.stringify([J,$]),A=W0.get(X);if(A===void 0)A=new Intl.RelativeTimeFormat(J,_),W0.set(X,A);return A}var X_=null;function WA(){if(X_)return X_;else return X_=new Intl.DateTimeFormat().resolvedOptions().locale,X_}var P0=new Map;function $$(J){let _=P0.get(J);if(_===void 0)_=new Intl.DateTimeFormat(J).resolvedOptions(),P0.set(J,_);return _}var x0=new Map;function PA(J){let _=x0.get(J);if(!_){let y=new Intl.Locale(J);if(_="getWeekInfo"in y?y.getWeekInfo():y.weekInfo,!("minimalDays"in _))_={...q$,..._};x0.set(J,_)}return _}function xA(J){let _=J.indexOf("-x-");if(_!==-1)J=J.substring(0,_);let y=J.indexOf("-u-");if(y===-1)return[J];else{let $,X;try{$=F0(J).resolvedOptions(),X=J}catch(q){let N=J.substring(0,y);$=F0(N).resolvedOptions(),X=N}let{numberingSystem:A,calendar:L}=$;return[X,A,L]}}function IA(J,_,y){if(y||_){if(!J.includes("-u-"))J+="-u";if(y)J+=`-ca-${y}`;if(_)J+=`-nu-${_}`;return J}else return J}function DA(J){let _=[];for(let y=1;y<=12;y++){let $=b.utc(2009,y,1);_.push(J($))}return _}function hA(J){let _=[];for(let y=1;y<=7;y++){let $=b.utc(2016,11,13+y);_.push(J($))}return _}function F_(J,_,y,$){let X=J.listingMode();if(X==="error")return null;else if(X==="en")return y(_);else return $(_)}function vA(J){if(J.numberingSystem&&J.numberingSystem!=="latn")return!1;else return J.numberingSystem==="latn"||!J.locale||J.locale.startsWith("en")||$$(J.locale).numberingSystem==="latn"}class X${constructor(J,_,y){this.padTo=y.padTo||0,this.floor=y.floor||!1;let{padTo:$,floor:X,...A}=y;if(!_||Object.keys(A).length>0){let L={useGrouping:!1,...y};if(y.padTo>0)L.minimumIntegerDigits=y.padTo;this.inf=FA(J,L)}}format(J){if(this.inf){let _=this.floor?Math.floor(J):J;return this.inf.format(_)}else{let _=this.floor?Math.floor(J):d0(J,3);return D(_,this.padTo)}}}class A${constructor(J,_,y){this.opts=y,this.originalZone=void 0;let $=void 0;if(this.opts.timeZone)this.dt=J;else if(J.zone.type==="fixed"){let A=-1*(J.offset/60),L=A>=0?`Etc/GMT+${A}`:`Etc/GMT${A}`;if(J.offset!==0&&XJ.create(L).valid)$=L,this.dt=J;else $="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,$=J.zone.name;else $="UTC",this.dt=J.setZone("UTC").plus({minutes:J.offset}),this.originalZone=J.zone;let X={...this.opts};X.timeZone=X.timeZone||$,this.dtf=F0(_,X)}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 y=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{..._,value:y}}else return _});return J}resolvedOptions(){return this.dtf.resolvedOptions()}}class L${constructor(J,_,y){if(this.opts={style:"long",...y},!_&&H$())this.rtf=jA(J,y)}format(J,_){if(this.rtf)return this.rtf.format(J,_);else return $L(_,J,this.opts.numeric,this.opts.style!=="long")}formatToParts(J,_){if(this.rtf)return this.rtf.formatToParts(J,_);else return[]}}var q$={firstDay:1,minimalDays:4,weekend:[6,7]};class T{static fromOpts(J){return T.create(J.locale,J.numberingSystem,J.outputCalendar,J.weekSettings,J.defaultToEN)}static create(J,_,y,$,X=!1){let A=J||W.defaultLocale,L=A||(X?"en-US":WA()),q=_||W.defaultNumberingSystem,N=y||W.defaultOutputCalendar,G=D0($)||W.defaultWeekSettings;return new T(L,q,N,G,A)}static resetCache(){X_=null,T0.clear(),j0.clear(),W0.clear(),P0.clear(),x0.clear()}static fromObject({locale:J,numberingSystem:_,outputCalendar:y,weekSettings:$}={}){return T.create(J,_,y,$)}constructor(J,_,y,$,X){let[A,L,q]=xA(J);this.locale=A,this.numberingSystem=_||L||null,this.outputCalendar=y||q||null,this.weekSettings=$,this.intl=IA(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=X,this.fastNumbersCached=null}get fastNumbers(){if(this.fastNumbersCached==null)this.fastNumbersCached=vA(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 T.create(J.locale||this.specifiedLocale,J.numberingSystem||this.numberingSystem,J.outputCalendar||this.outputCalendar,D0(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 F_(this,J,b$,()=>{let y=this.intl==="ja"||this.intl.startsWith("ja-");_&=!y;let $=_?{month:J,day:"numeric"}:{month:J},X=_?"format":"standalone";if(!this.monthsCache[X][J]){let A=!y?(L)=>this.extract(L,$,"month"):(L)=>this.dtFormatter(L,$).format();this.monthsCache[X][J]=DA(A)}return this.monthsCache[X][J]})}weekdays(J,_=!1){return F_(this,J,S$,()=>{let y=_?{weekday:J,year:"numeric",month:"long",day:"numeric"}:{weekday:J},$=_?"format":"standalone";if(!this.weekdaysCache[$][J])this.weekdaysCache[$][J]=hA((X)=>this.extract(X,y,"weekday"));return this.weekdaysCache[$][J]})}meridiems(){return F_(this,void 0,()=>C$,()=>{if(!this.meridiemCache){let J={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[b.utc(2016,11,13,9),b.utc(2016,11,13,19)].map((_)=>this.extract(_,J,"dayperiod"))}return this.meridiemCache})}eras(J){return F_(this,J,w$,()=>{let _={era:J};if(!this.eraCache[J])this.eraCache[J]=[b.utc(-40,1,1),b.utc(2017,1,1)].map((y)=>this.extract(y,_,"era"));return this.eraCache[J]})}extract(J,_,y){let $=this.dtFormatter(J,_),X=$.formatToParts(),A=X.find((L)=>L.type.toLowerCase()===y);return A?A.value:null}numberFormatter(J={}){return new X$(this.intl,J.forceSimple||this.fastNumbers,J)}dtFormatter(J,_={}){return new A$(J,this.intl,_)}relFormatter(J={}){return new L$(this.intl,this.isEnglish(),J)}listFormatter(J={}){return TA(this.intl,J)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||$$(this.intl).locale.startsWith("en-us")}getWeekSettings(){if(this.weekSettings)return this.weekSettings;else if(!U$())return q$;else return PA(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 b0=null;class u extends OJ{static get utcInstance(){if(b0===null)b0=new u(0);return b0}static instance(J){return J===0?u.utcInstance:new u(J)}static parseSpecifier(J){if(J){let _=J.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(_)return new u(u_(_[1],_[2]))}return null}constructor(J){super();this.fixed=J}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${q_(this.fixed,"narrow")}`}get ianaName(){if(this.fixed===0)return"Etc/UTC";else return`Etc/GMT${q_(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(J,_){return q_(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 k0 extends OJ{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 RJ(J,_){if(V(J)||J===null)return _;else if(J instanceof OJ)return J;else if(mA(J)){let y=J.toLowerCase();if(y==="default")return _;else if(y==="local"||y==="system")return G_.instance;else if(y==="utc"||y==="gmt")return u.utcInstance;else return u.parseSpecifier(y)||XJ.create(J)}else if(HJ(J))return u.instance(J);else if(typeof J==="object"&&"offset"in J&&typeof J.offset==="function")return J;else return new k0(J)}var g0={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},L1={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]},fA=g0.hanidec.replace(/[\[|\]]/g,"").split("");function kA(J){let _=parseInt(J,10);if(isNaN(_)){_="";for(let y=0;y<J.length;y++){let $=J.charCodeAt(y);if(J[y].search(g0.hanidec)!==-1)_+=fA.indexOf(J[y]);else for(let X in L1){let[A,L]=L1[X];if($>=A&&$<=L)_+=$-A}}return parseInt(_,10)}else return _}var I0=new Map;function gA(){I0.clear()}function t({numberingSystem:J},_=""){let y=J||"latn",$=I0.get(y);if($===void 0)$=new Map,I0.set(y,$);let X=$.get(_);if(X===void 0)X=new RegExp(`${g0[y]}${_}`),$.set(_,X);return X}var q1=()=>Date.now(),N1="system",G1=null,B1=null,Q1=null,K1=60,R1,H1=null;class W{static get now(){return q1}static set now(J){q1=J}static set defaultZone(J){N1=J}static get defaultZone(){return RJ(N1,G_.instance)}static get defaultLocale(){return G1}static set defaultLocale(J){G1=J}static get defaultNumberingSystem(){return B1}static set defaultNumberingSystem(J){B1=J}static get defaultOutputCalendar(){return Q1}static set defaultOutputCalendar(J){Q1=J}static get defaultWeekSettings(){return H1}static set defaultWeekSettings(J){H1=D0(J)}static get twoDigitCutoffYear(){return K1}static set twoDigitCutoffYear(J){K1=J%100}static get throwOnInvalid(){return R1}static set throwOnInvalid(J){R1=J}static resetCaches(){T.resetCache(),XJ.resetCache(),b.resetCache(),gA()}}class n{constructor(J,_){this.reason=J,this.explanation=_}toMessage(){if(this.explanation)return`${this.reason}: ${this.explanation}`;else return this.reason}}var N$=[0,31,59,90,120,151,181,212,243,273,304,334],G$=[0,31,60,91,121,152,182,213,244,274,305,335];function r(J,_){return new n("unit out of range",`you specified ${_} (of type ${typeof _}) as a ${J}, which is invalid`)}function c0(J,_,y){let $=new Date(Date.UTC(J,_-1,y));if(J<100&&J>=0)$.setUTCFullYear($.getUTCFullYear()-1900);let X=$.getUTCDay();return X===0?7:X}function B$(J,_,y){return y+(B_(J)?G$:N$)[_-1]}function Q$(J,_){let y=B_(J)?G$:N$,$=y.findIndex((A)=>A<_),X=_-y[$];return{month:$+1,day:X}}function u0(J,_){return(J-_+7)%7+1}function v_(J,_=4,y=1){let{year:$,month:X,day:A}=J,L=B$($,X,A),q=u0(c0($,X,A),y),N=Math.floor((L-q+14-_)/7),G;if(N<1)G=$-1,N=N_(G,_,y);else if(N>N_($,_,y))G=$+1,N=1;else G=$;return{weekYear:G,weekNumber:N,weekday:q,...m_(J)}}function U1(J,_=4,y=1){let{weekYear:$,weekNumber:X,weekday:A}=J,L=u0(c0($,1,_),y),q=uJ($),N=X*7+A-L-7+_,G;if(N<1)G=$-1,N+=uJ(G);else if(N>q)G=$+1,N-=uJ($);else G=$;let{month:B,day:R}=Q$(G,N);return{year:G,month:B,day:R,...m_(J)}}function M0(J){let{year:_,month:y,day:$}=J,X=B$(_,y,$);return{year:_,ordinal:X,...m_(J)}}function Y1(J){let{year:_,ordinal:y}=J,{month:$,day:X}=Q$(_,y);return{year:_,month:$,day:X,...m_(J)}}function E1(J,_){if(!V(J.localWeekday)||!V(J.localWeekNumber)||!V(J.localWeekYear)){if(!V(J.weekday)||!V(J.weekNumber)||!V(J.weekYear))throw new wJ("Cannot mix locale-based week fields with ISO-based week fields");if(!V(J.localWeekday))J.weekday=J.localWeekday;if(!V(J.localWeekNumber))J.weekNumber=J.localWeekNumber;if(!V(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 cA(J,_=4,y=1){let $=g_(J.weekYear),X=o(J.weekNumber,1,N_(J.weekYear,_,y)),A=o(J.weekday,1,7);if(!$)return r("weekYear",J.weekYear);else if(!X)return r("week",J.weekNumber);else if(!A)return r("weekday",J.weekday);else return!1}function uA(J){let _=g_(J.year),y=o(J.ordinal,1,uJ(J.year));if(!_)return r("year",J.year);else if(!y)return r("ordinal",J.ordinal);else return!1}function K$(J){let _=g_(J.year),y=o(J.month,1,12),$=o(J.day,1,f_(J.year,J.month));if(!_)return r("year",J.year);else if(!y)return r("month",J.month);else if(!$)return r("day",J.day);else return!1}function R$(J){let{hour:_,minute:y,second:$,millisecond:X}=J,A=o(_,0,23)||_===24&&y===0&&$===0&&X===0,L=o(y,0,59),q=o($,0,59),N=o(X,0,999);if(!A)return r("hour",_);else if(!L)return r("minute",y);else if(!q)return r("second",$);else if(!N)return r("millisecond",X);else return!1}function V(J){return typeof J==="undefined"}function HJ(J){return typeof J==="number"}function g_(J){return typeof J==="number"&&J%1===0}function mA(J){return typeof J==="string"}function dA(J){return Object.prototype.toString.call(J)==="[object Date]"}function H$(){try{return typeof Intl!=="undefined"&&!!Intl.RelativeTimeFormat}catch(J){return!1}}function U$(){try{return typeof Intl!=="undefined"&&!!Intl.Locale&&(("weekInfo"in Intl.Locale.prototype)||("getWeekInfo"in Intl.Locale.prototype))}catch(J){return!1}}function lA(J){return Array.isArray(J)?J:[J]}function V1(J,_,y){if(J.length===0)return;return J.reduce(($,X)=>{let A=[_(X),X];if(!$)return A;else if(y($[0],A[0])===$[0])return $;else return A},null)[1]}function pA(J,_){return _.reduce((y,$)=>{return y[$]=J[$],y},{})}function dJ(J,_){return Object.prototype.hasOwnProperty.call(J,_)}function D0(J){if(J==null)return null;else if(typeof J!=="object")throw new g("Week settings must be an object");else{if(!o(J.firstDay,1,7)||!o(J.minimalDays,1,7)||!Array.isArray(J.weekend)||J.weekend.some((_)=>!o(_,1,7)))throw new g("Invalid week settings");return{firstDay:J.firstDay,minimalDays:J.minimalDays,weekend:Array.from(J.weekend)}}}function o(J,_,y){return g_(J)&&J>=_&&J<=y}function iA(J,_){return J-_*Math.floor(J/_)}function D(J,_=2){let y=J<0,$;if(y)$="-"+(""+-J).padStart(_,"0");else $=(""+J).padStart(_,"0");return $}function KJ(J){if(V(J)||J===null||J==="")return;else return parseInt(J,10)}function SJ(J){if(V(J)||J===null||J==="")return;else return parseFloat(J)}function m0(J){if(V(J)||J===null||J==="")return;else{let _=parseFloat("0."+J)*1000;return Math.floor(_)}}function d0(J,_,y="round"){let $=10**_;switch(y){case"expand":return J>0?Math.ceil(J*$)/$:Math.floor(J*$)/$;case"trunc":return Math.trunc(J*$)/$;case"round":return Math.round(J*$)/$;case"floor":return Math.floor(J*$)/$;case"ceil":return Math.ceil(J*$)/$;default:throw new RangeError(`Value rounding ${y} is out of range`)}}function B_(J){return J%4===0&&(J%100!==0||J%400===0)}function uJ(J){return B_(J)?366:365}function f_(J,_){let y=iA(_-1,12)+1,$=J+(_-y)/12;if(y===2)return B_($)?29:28;else return[31,null,31,30,31,30,31,31,30,31,30,31][y-1]}function c_(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 b1(J,_,y){return-u0(c0(J,1,_),y)+_-1}function N_(J,_=4,y=1){let $=b1(J,_,y),X=b1(J+1,_,y);return(uJ(J)-$+X)/7}function h0(J){if(J>99)return J;else return J>W.twoDigitCutoffYear?1900+J:2000+J}function Y$(J,_,y,$=null){let X=new Date(J),A={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};if($)A.timeZone=$;let L={timeZoneName:_,...A},q=new Intl.DateTimeFormat(y,L).formatToParts(X).find((N)=>N.type.toLowerCase()==="timezonename");return q?q.value:null}function u_(J,_){let y=parseInt(J,10);if(Number.isNaN(y))y=0;let $=parseInt(_,10)||0,X=y<0||Object.is(y,-0)?-$:$;return y*60+X}function E$(J){let _=Number(J);if(typeof J==="boolean"||J===""||!Number.isFinite(_))throw new g(`Invalid unit value ${J}`);return _}function k_(J,_){let y={};for(let $ in J)if(dJ(J,$)){let X=J[$];if(X===void 0||X===null)continue;y[_($)]=E$(X)}return y}function q_(J,_){let y=Math.trunc(Math.abs(J/60)),$=Math.trunc(Math.abs(J%60)),X=J>=0?"+":"-";switch(_){case"short":return`${X}${D(y,2)}:${D($,2)}`;case"narrow":return`${X}${y}${$>0?`:${$}`:""}`;case"techie":return`${X}${D(y,2)}${D($,2)}`;default:throw new RangeError(`Value format ${_} is out of range for property format`)}}function m_(J){return pA(J,["hour","minute","second","millisecond"])}var nA=["January","February","March","April","May","June","July","August","September","October","November","December"],V$=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],rA=["J","F","M","A","M","J","J","A","S","O","N","D"];function b$(J){switch(J){case"narrow":return[...rA];case"short":return[...V$];case"long":return[...nA];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 M$=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Z$=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],oA=["M","T","W","T","F","S","S"];function S$(J){switch(J){case"narrow":return[...oA];case"short":return[...Z$];case"long":return[...M$];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var C$=["AM","PM"],sA=["Before Christ","Anno Domini"],aA=["BC","AD"],tA=["B","A"];function w$(J){switch(J){case"narrow":return[...tA];case"short":return[...aA];case"long":return[...sA];default:return null}}function eA(J){return C$[J.hour<12?0:1]}function JL(J,_){return S$(_)[J.weekday-1]}function _L(J,_){return b$(_)[J.month-1]}function yL(J,_){return w$(_)[J.year<0?0:1]}function $L(J,_,y="always",$=!1){let X={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."]},A=["hours","minutes","seconds"].indexOf(J)===-1;if(y==="auto"&&A){let R=J==="days";switch(_){case 1:return R?"tomorrow":`next ${X[J][0]}`;case-1:return R?"yesterday":`last ${X[J][0]}`;case 0:return R?"today":`this ${X[J][0]}`}}let L=Object.is(_,-0)||_<0,q=Math.abs(_),N=q===1,G=X[J],B=$?N?G[1]:G[2]||G[1]:N?X[J][0]:J;return L?`${q} ${B} ago`:`in ${q} ${B}`}function M1(J,_){let y="";for(let $ of J)if($.literal)y+=$.val;else y+=_($.val);return y}var XL={D:h_,DD:k1,DDD:g1,DDDD:c1,t:u1,tt:m1,ttt:d1,tttt:l1,T:p1,TT:i1,TTT:n1,TTTT:r1,f:o1,ff:a1,fff:e1,ffff:_$,F:s1,FF:t1,FFF:J$,FFFF:y$};class c{static create(J,_={}){return new c(J,_)}static parseFormat(J){let _=null,y="",$=!1,X=[];for(let A=0;A<J.length;A++){let L=J.charAt(A);if(L==="'"){if(y.length>0||$)X.push({literal:$||/^\s+$/.test(y),val:y===""?"'":y});_=null,y="",$=!$}else if($)y+=L;else if(L===_)y+=L;else{if(y.length>0)X.push({literal:/^\s+$/.test(y),val:y});y=L,_=L}}if(y.length>0)X.push({literal:$||/^\s+$/.test(y),val:y});return X}static macroTokenToFormatOpts(J){return XL[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,y=void 0){if(this.opts.forceSimple)return D(J,_);let $={...this.opts};if(_>0)$.padTo=_;if(y)$.signDisplay=y;return this.loc.numberFormatter($).format(J)}formatDateTimeFromString(J,_){let y=this.loc.listingMode()==="en",$=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",X=(Q,K)=>this.loc.extract(J,Q,K),A=(Q)=>{if(J.isOffsetFixed&&J.offset===0&&Q.allowZ)return"Z";return J.isValid?J.zone.formatOffset(J.ts,Q.format):""},L=()=>y?eA(J):X({hour:"numeric",hourCycle:"h12"},"dayperiod"),q=(Q,K)=>y?_L(J,Q):X(K?{month:Q}:{month:Q,day:"numeric"},"month"),N=(Q,K)=>y?JL(J,Q):X(K?{weekday:Q}:{weekday:Q,month:"long",day:"numeric"},"weekday"),G=(Q)=>{let K=c.macroTokenToFormatOpts(Q);if(K)return this.formatWithSystemDefault(J,K);else return Q},B=(Q)=>y?yL(J,Q):X({era:Q},"era"),R=(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 A({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return A({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return A({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 L();case"d":return $?X({day:"numeric"},"day"):this.num(J.day);case"dd":return $?X({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({month:"numeric",day:"numeric"},"month"):this.num(J.month);case"LL":return $?X({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({month:"numeric"},"month"):this.num(J.month);case"MM":return $?X({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({year:"numeric"},"year"):this.num(J.year);case"yy":return $?X({year:"2-digit"},"year"):this.num(J.year.toString().slice(-2),2);case"yyyy":return $?X({year:"numeric"},"year"):this.num(J.year,4);case"yyyyyy":return $?X({year:"numeric"},"year"):this.num(J.year,6);case"G":return B("short");case"GG":return B("long");case"GGGGG":return B("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 G(Q)}};return M1(c.parseFormat(_),R)}formatDurationFromString(J,_){let y=this.opts.signMode==="negativeLargestOnly"?-1:1,$=(G)=>{switch(G[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}},X=(G,B)=>(R)=>{let Q=$(R);if(Q){let K=B.isNegativeDuration&&Q!==B.largestUnit?y:1,Y;if(this.opts.signMode==="negativeLargestOnly"&&Q!==B.largestUnit)Y="never";else if(this.opts.signMode==="all")Y="always";else Y="auto";return this.num(G.get(Q)*K,R.length,Y)}else return R},A=c.parseFormat(_),L=A.reduce((G,{literal:B,val:R})=>B?G:G.concat(R),[]),q=J.shiftTo(...L.map($).filter((G)=>G)),N={isNegativeDuration:q<0,largestUnit:Object.keys(q.values)[0]};return M1(A,X(q,N))}}var z$=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function lJ(...J){let _=J.reduce((y,$)=>y+$.source,"");return RegExp(`^${_}$`)}function pJ(...J){return(_)=>J.reduce(([y,$,X],A)=>{let[L,q,N]=A(_,X);return[{...y,...L},q||$,N]},[{},null,1]).slice(0,2)}function iJ(J,..._){if(J==null)return[null,null];for(let[y,$]of _){let X=y.exec(J);if(X)return $(X)}return[null,null]}function O$(...J){return(_,y)=>{let $={},X;for(X=0;X<J.length;X++)$[J[X]]=KJ(_[y+X]);return[$,null,y+X]}}var T$=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,AL=`(?:${T$.source}?(?:\\[(${z$.source})\\])?)?`,l0=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,F$=RegExp(`${l0.source}${AL}`),p0=RegExp(`(?:[Tt]${F$.source})?`),LL=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,qL=/(\d{4})-?W(\d\d)(?:-?(\d))?/,NL=/(\d{4})-?(\d{3})/,GL=O$("weekYear","weekNumber","weekDay"),BL=O$("year","ordinal"),QL=/(\d{4})-(\d\d)-(\d\d)/,j$=RegExp(`${l0.source} ?(?:${T$.source}|(${z$.source}))?`),KL=RegExp(`(?: ${j$.source})?`);function mJ(J,_,y){let $=J[_];return V($)?y:KJ($)}function RL(J,_){return[{year:mJ(J,_),month:mJ(J,_+1,1),day:mJ(J,_+2,1)},null,_+3]}function nJ(J,_){return[{hours:mJ(J,_,0),minutes:mJ(J,_+1,0),seconds:mJ(J,_+2,0),milliseconds:m0(J[_+3])},null,_+4]}function Q_(J,_){let y=!J[_]&&!J[_+1],$=u_(J[_+1],J[_+2]),X=y?null:u.instance($);return[{},X,_+3]}function K_(J,_){let y=J[_]?XJ.create(J[_]):null;return[{},y,_+1]}var HL=RegExp(`^T?${l0.source}$`),UL=/^-?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 YL(J){let[_,y,$,X,A,L,q,N,G]=J,B=_[0]==="-",R=N&&N[0]==="-",Q=(K,Y=!1)=>K!==void 0&&(Y||K&&B)?-K:K;return[{years:Q(SJ(y)),months:Q(SJ($)),weeks:Q(SJ(X)),days:Q(SJ(A)),hours:Q(SJ(L)),minutes:Q(SJ(q)),seconds:Q(SJ(N),N==="-0"),milliseconds:Q(m0(G),R)}]}var EL={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function i0(J,_,y,$,X,A,L){let q={year:_.length===2?h0(KJ(_)):KJ(_),month:V$.indexOf(y)+1,day:KJ($),hour:KJ(X),minute:KJ(A)};if(L)q.second=KJ(L);if(J)q.weekday=J.length>3?M$.indexOf(J)+1:Z$.indexOf(J)+1;return q}var VL=/^(?:(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 bL(J){let[,_,y,$,X,A,L,q,N,G,B,R]=J,Q=i0(_,X,$,y,A,L,q),K;if(N)K=EL[N];else if(G)K=0;else K=u_(B,R);return[Q,new u(K)]}function ML(J){return J.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var ZL=/^(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$/,SL=/^(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$/,CL=/^(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 Z1(J){let[,_,y,$,X,A,L,q]=J;return[i0(_,X,$,y,A,L,q),u.utcInstance]}function wL(J){let[,_,y,$,X,A,L,q]=J;return[i0(_,q,y,$,X,A,L),u.utcInstance]}var zL=lJ(LL,p0),OL=lJ(qL,p0),TL=lJ(NL,p0),FL=lJ(F$),W$=pJ(RL,nJ,Q_,K_),jL=pJ(GL,nJ,Q_,K_),WL=pJ(BL,nJ,Q_,K_),PL=pJ(nJ,Q_,K_);function xL(J){return iJ(J,[zL,W$],[OL,jL],[TL,WL],[FL,PL])}function IL(J){return iJ(ML(J),[VL,bL])}function DL(J){return iJ(J,[ZL,Z1],[SL,Z1],[CL,wL])}function hL(J){return iJ(J,[UL,YL])}var vL=pJ(nJ);function fL(J){return iJ(J,[HL,vL])}var kL=lJ(QL,KL),gL=lJ(j$),cL=pJ(nJ,Q_,K_);function uL(J){return iJ(J,[kL,W$],[gL,cL])}var S1="Invalid Duration",P$={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}},mL={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},...P$},i=365.2425,fJ=30.436875,dL={years:{quarters:4,months:12,weeks:i/7,days:i,hours:i*24,minutes:i*24*60,seconds:i*24*60*60,milliseconds:i*24*60*60*1000},quarters:{months:3,weeks:i/28,days:i/4,hours:i*24/4,minutes:i*24*60/4,seconds:i*24*60*60/4,milliseconds:i*24*60*60*1000/4},months:{weeks:fJ/7,days:fJ,hours:fJ*24,minutes:fJ*24*60,seconds:fJ*24*60*60,milliseconds:fJ*24*60*60*1000},...P$},zJ=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],lL=zJ.slice(0).reverse();function qJ(J,_,y=!1){let $={values:y?_.values:{...J.values,..._.values||{}},loc:J.loc.clone(_.loc),conversionAccuracy:_.conversionAccuracy||J.conversionAccuracy,matrix:_.matrix||J.matrix};return new w($)}function x$(J,_){var y;let $=(y=_.milliseconds)!=null?y:0;for(let X of lL.slice(1))if(_[X])$+=_[X]*J[X].milliseconds;return $}function C1(J,_){let y=x$(J,_)<0?-1:1;zJ.reduceRight(($,X)=>{if(!V(_[X])){if($){let A=_[$]*y,L=J[X][$],q=Math.floor(A/L);_[X]+=q*y,_[$]-=q*L*y}return X}else return $},null),zJ.reduce(($,X)=>{if(!V(_[X])){if($){let A=_[$]%1;_[$]-=A,_[X]+=A*J[$][X]}return X}else return $},null)}function w1(J){let _={};for(let[y,$]of Object.entries(J))if($!==0)_[y]=$;return _}class w{constructor(J){let _=J.conversionAccuracy==="longterm"||!1,y=_?dL:mL;if(J.matrix)y=J.matrix;this.values=J.values,this.loc=J.loc||T.create(),this.conversionAccuracy=_?"longterm":"casual",this.invalid=J.invalid||null,this.matrix=y,this.isLuxonDuration=!0}static fromMillis(J,_){return w.fromObject({milliseconds:J},_)}static fromObject(J,_={}){if(J==null||typeof J!=="object")throw new g(`Duration.fromObject: argument expected to be an object, got ${J===null?"null":typeof J}`);return new w({values:k_(J,w.normalizeUnit),loc:T.fromObject(_),conversionAccuracy:_.conversionAccuracy,matrix:_.matrix})}static fromDurationLike(J){if(HJ(J))return w.fromMillis(J);else if(w.isDuration(J))return J;else if(typeof J==="object")return w.fromObject(J);else throw new g(`Unknown duration argument ${J} of type ${typeof J}`)}static fromISO(J,_){let[y]=hL(J);if(y)return w.fromObject(y,_);else return w.invalid("unparsable",`the input "${J}" can't be parsed as ISO 8601`)}static fromISOTime(J,_){let[y]=fL(J);if(y)return w.fromObject(y,_);else return w.invalid("unparsable",`the input "${J}" can't be parsed as ISO 8601`)}static invalid(J,_=null){if(!J)throw new g("need to specify a reason the Duration is invalid");let y=J instanceof n?J:new n(J,_);if(W.throwOnInvalid)throw new f1(y);else return new w({invalid:y})}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 f0(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 y={..._,floor:_.round!==!1&&_.floor!==!1};return this.isValid?c.create(this.loc,y).formatDurationFromString(this,J):S1}toHuman(J={}){if(!this.isValid)return S1;let _=J.showZeros!==!1,y=zJ.map(($)=>{let X=this.values[$];if(V(X)||X===0&&!_)return null;return this.loc.numberFormatter({style:"unit",unitDisplay:"long",...J,unit:$.slice(0,-1)}).format(X)}).filter(($)=>$);return this.loc.listFormatter({type:"conjunction",style:J.listStyle||"narrow",...J}).format(y)}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+=d0(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},b.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 x$(this.matrix,this.values)}valueOf(){return this.toMillis()}plus(J){if(!this.isValid)return this;let _=w.fromDurationLike(J),y={};for(let $ of zJ)if(dJ(_.values,$)||dJ(this.values,$))y[$]=_.get($)+this.get($);return qJ(this,{values:y},!0)}minus(J){if(!this.isValid)return this;let _=w.fromDurationLike(J);return this.plus(_.negate())}mapUnits(J){if(!this.isValid)return this;let _={};for(let y of Object.keys(this.values))_[y]=E$(J(this.values[y],y));return qJ(this,{values:_},!0)}get(J){return this[w.normalizeUnit(J)]}set(J){if(!this.isValid)return this;let _={...this.values,...k_(J,w.normalizeUnit)};return qJ(this,{values:_})}reconfigure({locale:J,numberingSystem:_,conversionAccuracy:y,matrix:$}={}){let A={loc:this.loc.clone({locale:J,numberingSystem:_}),matrix:$,conversionAccuracy:y};return qJ(this,A)}as(J){return this.isValid?this.shiftTo(J).get(J):NaN}normalize(){if(!this.isValid)return this;let J=this.toObject();return C1(this.matrix,J),qJ(this,{values:J},!0)}rescale(){if(!this.isValid)return this;let J=w1(this.normalize().shiftToAll().toObject());return qJ(this,{values:J},!0)}shiftTo(...J){if(!this.isValid)return this;if(J.length===0)return this;J=J.map((A)=>w.normalizeUnit(A));let _={},y={},$=this.toObject(),X;for(let A of zJ)if(J.indexOf(A)>=0){X=A;let L=0;for(let N in y)L+=this.matrix[N][A]*y[N],y[N]=0;if(HJ($[A]))L+=$[A];let q=Math.trunc(L);_[A]=q,y[A]=(L*1000-q*1000)/1000}else if(HJ($[A]))y[A]=$[A];for(let A in y)if(y[A]!==0)_[X]+=A===X?y[A]:y[A]/this.matrix[X][A];return C1(this.matrix,_),qJ(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 qJ(this,{values:J},!0)}removeZeros(){if(!this.isValid)return this;let J=w1(this.values);return qJ(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 _(y,$){if(y===void 0||y===0)return $===void 0||$===0;return y===$}for(let y of zJ)if(!_(this.values[y],J.values[y]))return!1;return!0}}var kJ="Invalid Interval";function pL(J,_){if(!J||!J.isValid)return x.invalid("missing or invalid start");else if(!_||!_.isValid)return x.invalid("missing or invalid end");else if(_<J)return x.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 x{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 g("need to specify a reason the Interval is invalid");let y=J instanceof n?J:new n(J,_);if(W.throwOnInvalid)throw new v1(y);else return new x({invalid:y})}static fromDateTimes(J,_){let y=$_(J),$=$_(_),X=pL(y,$);if(X==null)return new x({start:y,end:$});else return X}static after(J,_){let y=w.fromDurationLike(_),$=$_(J);return x.fromDateTimes($,$.plus(y))}static before(J,_){let y=w.fromDurationLike(_),$=$_(J);return x.fromDateTimes($.minus(y),$)}static fromISO(J,_){let[y,$]=(J||"").split("/",2);if(y&&$){let X,A;try{X=b.fromISO(y,_),A=X.isValid}catch(N){A=!1}let L,q;try{L=b.fromISO($,_),q=L.isValid}catch(N){q=!1}if(A&&q)return x.fromDateTimes(X,L);if(A){let N=w.fromISO($,_);if(N.isValid)return x.after(X,N)}else if(q){let N=w.fromISO(y,_);if(N.isValid)return x.before(L,N)}}return x.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 y=this.start.startOf(J,_),$;if(_!=null&&_.useLocaleWeeks)$=this.end.reconfigure({locale:y.locale});else $=this.end;return $=$.startOf(J,_),Math.floor($.diff(y,J).get(J))+($.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 x.fromDateTimes(J||this.s,_||this.e)}splitAt(...J){if(!this.isValid)return[];let _=J.map($_).filter((A)=>this.contains(A)).sort((A,L)=>A.toMillis()-L.toMillis()),y=[],{s:$}=this,X=0;while($<this.e){let A=_[X]||this.e,L=+A>+this.e?this.e:A;y.push(x.fromDateTimes($,L)),$=L,X+=1}return y}splitBy(J){let _=w.fromDurationLike(J);if(!this.isValid||!_.isValid||_.as("milliseconds")===0)return[];let{s:y}=this,$=1,X,A=[];while(y<this.e){let L=this.start.plus(_.mapUnits((q)=>q*$));X=+L>+this.e?this.e:L,A.push(x.fromDateTimes(y,X)),y=X,$+=1}return A}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,y=this.e<J.e?this.e:J.e;if(_>=y)return null;else return x.fromDateTimes(_,y)}union(J){if(!this.isValid)return this;let _=this.s<J.s?this.s:J.s,y=this.e>J.e?this.e:J.e;return x.fromDateTimes(_,y)}static merge(J){let[_,y]=J.sort(($,X)=>$.s-X.s).reduce(([$,X],A)=>{if(!X)return[$,A];else if(X.overlaps(A)||X.abutsStart(A))return[$,X.union(A)];else return[$.concat([X]),A]},[[],null]);if(y)_.push(y);return _}static xor(J){let _=null,y=0,$=[],X=J.map((q)=>[{time:q.s,type:"s"},{time:q.e,type:"e"}]),A=Array.prototype.concat(...X),L=A.sort((q,N)=>q.time-N.time);for(let q of L)if(y+=q.type==="s"?1:-1,y===1)_=q.time;else{if(_&&+_!==+q.time)$.push(x.fromDateTimes(_,q.time));_=null}return x.merge($)}difference(...J){return x.xor([this].concat(J)).map((_)=>this.intersection(_)).filter((_)=>_&&!_.isEmpty())}toString(){if(!this.isValid)return kJ;return`[${this.s.toISO()} \u2013 ${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=h_,_={}){return this.isValid?c.create(this.s.loc.clone(_),J).formatInterval(this):kJ}toISO(J){if(!this.isValid)return kJ;return`${this.s.toISO(J)}/${this.e.toISO(J)}`}toISODate(){if(!this.isValid)return kJ;return`${this.s.toISODate()}/${this.e.toISODate()}`}toISOTime(J){if(!this.isValid)return kJ;return`${this.s.toISOTime(J)}/${this.e.toISOTime(J)}`}toFormat(J,{separator:_=" \u2013 "}={}){if(!this.isValid)return kJ;return`${this.s.toFormat(J)}${_}${this.e.toFormat(J)}`}toDuration(J,_){if(!this.isValid)return w.invalid(this.invalidReason);return this.e.diff(this.s,J,_)}mapEndpoints(J){return x.fromDateTimes(J(this.s),J(this.e))}}class cJ{static hasDST(J=W.defaultZone){let _=b.now().setZone(J).set({month:12});return!J.isUniversal&&_.offset!==_.set({month:6}).offset}static isValidIANAZone(J){return XJ.isValidZone(J)}static normalizeZone(J){return RJ(J,W.defaultZone)}static getStartOfWeek({locale:J=null,locObj:_=null}={}){return(_||T.create(J)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:J=null,locObj:_=null}={}){return(_||T.create(J)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:J=null,locObj:_=null}={}){return(_||T.create(J)).getWeekendDays().slice()}static months(J="long",{locale:_=null,numberingSystem:y=null,locObj:$=null,outputCalendar:X="gregory"}={}){return($||T.create(_,y,X)).months(J)}static monthsFormat(J="long",{locale:_=null,numberingSystem:y=null,locObj:$=null,outputCalendar:X="gregory"}={}){return($||T.create(_,y,X)).months(J,!0)}static weekdays(J="long",{locale:_=null,numberingSystem:y=null,locObj:$=null}={}){return($||T.create(_,y,null)).weekdays(J)}static weekdaysFormat(J="long",{locale:_=null,numberingSystem:y=null,locObj:$=null}={}){return($||T.create(_,y,null)).weekdays(J,!0)}static meridiems({locale:J=null}={}){return T.create(J).meridiems()}static eras(J="short",{locale:_=null}={}){return T.create(_,null,"gregory").eras(J)}static features(){return{relative:H$(),localeWeek:U$()}}}function z1(J,_){let y=(X)=>X.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),$=y(_)-y(J);return Math.floor(w.fromMillis($).as("days"))}function iL(J,_,y){let $=[["years",(N,G)=>G.year-N.year],["quarters",(N,G)=>G.quarter-N.quarter+(G.year-N.year)*4],["months",(N,G)=>G.month-N.month+(G.year-N.year)*12],["weeks",(N,G)=>{let B=z1(N,G);return(B-B%7)/7}],["days",z1]],X={},A=J,L,q;for(let[N,G]of $)if(y.indexOf(N)>=0)if(L=N,X[N]=G(J,_),q=A.plus(X),q>_){if(X[N]--,J=A.plus(X),J>_)q=J,X[N]--,J=A.plus(X)}else J=q;return[J,X,q,L]}function nL(J,_,y,$){let[X,A,L,q]=iL(J,_,y),N=_-X,G=y.filter((R)=>["hours","minutes","seconds","milliseconds"].indexOf(R)>=0);if(G.length===0){if(L<_)L=X.plus({[q]:1});if(L!==X)A[q]=(A[q]||0)+N/(L-X)}let B=w.fromObject(A,$);if(G.length>0)return w.fromMillis(N,$).shiftTo(...G).plus(B);else return B}var rL="missing Intl.DateTimeFormat.formatToParts support";function z(J,_=(y)=>y){return{regex:J,deser:([y])=>_(kA(y))}}var oL=String.fromCharCode(160),I$=`[ ${oL}]`,D$=new RegExp(I$,"g");function sL(J){return J.replace(/\./g,"\\.?").replace(D$,I$)}function O1(J){return J.replace(/\./g,"").replace(D$," ").toLowerCase()}function e(J,_){if(J===null)return null;else return{regex:RegExp(J.map(sL).join("|")),deser:([y])=>J.findIndex(($)=>O1(y)===O1($))+_}}function T1(J,_){return{regex:J,deser:([,y,$])=>u_(y,$),groups:_}}function j_(J){return{regex:J,deser:([_])=>_}}function aL(J){return J.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function tL(J,_){let y=t(_),$=t(_,"{2}"),X=t(_,"{3}"),A=t(_,"{4}"),L=t(_,"{6}"),q=t(_,"{1,2}"),N=t(_,"{1,3}"),G=t(_,"{1,6}"),B=t(_,"{1,9}"),R=t(_,"{2,4}"),Q=t(_,"{4,6}"),K=(S)=>({regex:RegExp(aL(S.val)),deser:([E])=>E,literal:!0}),Z=((S)=>{if(J.literal)return K(S);switch(S.val){case"G":return e(_.eras("short"),0);case"GG":return e(_.eras("long"),0);case"y":return z(G);case"yy":return z(R,h0);case"yyyy":return z(A);case"yyyyy":return z(Q);case"yyyyyy":return z(L);case"M":return z(q);case"MM":return z($);case"MMM":return e(_.months("short",!0),1);case"MMMM":return e(_.months("long",!0),1);case"L":return z(q);case"LL":return z($);case"LLL":return e(_.months("short",!1),1);case"LLLL":return e(_.months("long",!1),1);case"d":return z(q);case"dd":return z($);case"o":return z(N);case"ooo":return z(X);case"HH":return z($);case"H":return z(q);case"hh":return z($);case"h":return z(q);case"mm":return z($);case"m":return z(q);case"q":return z(q);case"qq":return z($);case"s":return z(q);case"ss":return z($);case"S":return z(N);case"SSS":return z(X);case"u":return j_(B);case"uu":return j_(q);case"uuu":return z(y);case"a":return e(_.meridiems(),0);case"kkkk":return z(A);case"kk":return z(R,h0);case"W":return z(q);case"WW":return z($);case"E":case"c":return z(y);case"EEE":return e(_.weekdays("short",!1),1);case"EEEE":return e(_.weekdays("long",!1),1);case"ccc":return e(_.weekdays("short",!0),1);case"cccc":return e(_.weekdays("long",!0),1);case"Z":case"ZZ":return T1(new RegExp(`([+-]${q.source})(?::(${$.source}))?`),2);case"ZZZ":return T1(new RegExp(`([+-]${q.source})(${$.source})?`),2);case"z":return j_(/[a-z_+-/]{1,256}?/i);case" ":return j_(/[^\S\n\r]/);default:return K(S)}})(J)||{invalidReason:rL};return Z.token=J,Z}var eL={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 Jq(J,_,y){let{type:$,value:X}=J;if($==="literal"){let N=/^\s+$/.test(X);return{literal:!N,val:N?" ":X}}let A=_[$],L=$;if($==="hour")if(_.hour12!=null)L=_.hour12?"hour12":"hour24";else if(_.hourCycle!=null)if(_.hourCycle==="h11"||_.hourCycle==="h12")L="hour12";else L="hour24";else L=y.hour12?"hour12":"hour24";let q=eL[L];if(typeof q==="object")q=q[A];if(q)return{literal:!1,val:q};return}function _q(J){return[`^${J.map((y)=>y.regex).reduce((y,$)=>`${y}(${$.source})`,"")}$`,J]}function yq(J,_,y){let $=J.match(_);if($){let X={},A=1;for(let L in y)if(dJ(y,L)){let q=y[L],N=q.groups?q.groups+1:1;if(!q.literal&&q.token)X[q.token.val[0]]=q.deser($.slice(A,A+N));A+=N}return[$,X]}else return[$,{}]}function $q(J){let _=(A)=>{switch(A){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}},y=null,$;if(!V(J.z))y=XJ.create(J.z);if(!V(J.Z)){if(!y)y=new u(J.Z);$=J.Z}if(!V(J.q))J.M=(J.q-1)*3+1;if(!V(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(!V(J.u))J.S=m0(J.u);return[Object.keys(J).reduce((A,L)=>{let q=_(L);if(q)A[q]=J[L];return A},{}),y,$]}var Z0=null;function Xq(){if(!Z0)Z0=b.fromMillis(1555555555555);return Z0}function Aq(J,_){if(J.literal)return J;let y=c.macroTokenToFormatOpts(J.val),$=f$(y,_);if($==null||$.includes(void 0))return J;return $}function h$(J,_){return Array.prototype.concat(...J.map((y)=>Aq(y,_)))}class n0{constructor(J,_){if(this.locale=J,this.format=_,this.tokens=h$(c.parseFormat(_),J),this.units=this.tokens.map((y)=>tL(y,J)),this.disqualifyingUnit=this.units.find((y)=>y.invalidReason),!this.disqualifyingUnit){let[y,$]=_q(this.units);this.regex=RegExp(y,"i"),this.handlers=$}}explainFromTokens(J){if(!this.isValid)return{input:J,tokens:this.tokens,invalidReason:this.invalidReason};else{let[_,y]=yq(J,this.regex,this.handlers),[$,X,A]=y?$q(y):[null,null,void 0];if(dJ(y,"a")&&dJ(y,"H"))throw new wJ("Can't include meridiem when specifying 24-hour format");return{input:J,tokens:this.tokens,regex:this.regex,rawMatches:_,matches:y,result:$,zone:X,specificOffset:A}}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function v$(J,_,y){return new n0(J,y).explainFromTokens(_)}function Lq(J,_,y){let{result:$,zone:X,specificOffset:A,invalidReason:L}=v$(J,_,y);return[$,X,A,L]}function f$(J,_){if(!J)return null;let $=c.create(_,J).dtFormatter(Xq()),X=$.formatToParts(),A=$.resolvedOptions();return X.map((L)=>Jq(L,J,A))}var S0="Invalid DateTime",F1=8640000000000000;function A_(J){return new n("unsupported zone",`the zone "${J.name}" is not supported`)}function C0(J){if(J.weekData===null)J.weekData=v_(J.c);return J.weekData}function w0(J){if(J.localWeekData===null)J.localWeekData=v_(J.c,J.loc.getMinDaysInFirstWeek(),J.loc.getStartOfWeek());return J.localWeekData}function CJ(J,_){let y={ts:J.ts,zone:J.zone,c:J.c,o:J.o,loc:J.loc,invalid:J.invalid};return new b({...y,..._,old:y})}function k$(J,_,y){let $=J-_*60*1000,X=y.offset($);if(_===X)return[$,_];$-=(X-_)*60*1000;let A=y.offset($);if(X===A)return[$,X];return[J-Math.min(X,A)*60*1000,Math.max(X,A)]}function W_(J,_){J+=_*60*1000;let y=new Date(J);return{year:y.getUTCFullYear(),month:y.getUTCMonth()+1,day:y.getUTCDate(),hour:y.getUTCHours(),minute:y.getUTCMinutes(),second:y.getUTCSeconds(),millisecond:y.getUTCMilliseconds()}}function x_(J,_,y){return k$(c_(J),_,y)}function j1(J,_){let y=J.o,$=J.c.year+Math.trunc(_.years),X=J.c.month+Math.trunc(_.months)+Math.trunc(_.quarters)*3,A={...J.c,year:$,month:X,day:Math.min(J.c.day,f_($,X))+Math.trunc(_.days)+Math.trunc(_.weeks)*7},L=w.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=c_(A),[N,G]=k$(q,y,J.zone);if(L!==0)N+=L,G=J.zone.offset(N);return{ts:N,o:G}}function gJ(J,_,y,$,X,A){let{setZone:L,zone:q}=y;if(J&&Object.keys(J).length!==0||_){let N=_||q,G=b.fromObject(J,{...y,zone:N,specificOffset:A});return L?G:G.setZone(q)}else return b.invalid(new n("unparsable",`the input "${X}" can't be parsed as ${$}`))}function P_(J,_,y=!0){return J.isValid?c.create(T.create("en-US"),{allowZ:y,forceSimple:!0}).formatDateTimeFromString(J,_):null}function z0(J,_,y){let $=J.c.year>9999||J.c.year<0,X="";if($&&J.c.year>=0)X+="+";if(X+=D(J.c.year,$?6:4),y==="year")return X;if(_){if(X+="-",X+=D(J.c.month),y==="month")return X;X+="-"}else if(X+=D(J.c.month),y==="month")return X;return X+=D(J.c.day),X}function W1(J,_,y,$,X,A,L){let q=!y||J.c.millisecond!==0||J.c.second!==0,N="";switch(L){case"day":case"month":case"year":break;default:if(N+=D(J.c.hour),L==="hour")break;if(_){if(N+=":",N+=D(J.c.minute),L==="minute")break;if(q)N+=":",N+=D(J.c.second)}else{if(N+=D(J.c.minute),L==="minute")break;if(q)N+=D(J.c.second)}if(L==="second")break;if(q&&(!$||J.c.millisecond!==0))N+=".",N+=D(J.c.millisecond,3)}if(X)if(J.isOffsetFixed&&J.offset===0&&!A)N+="Z";else if(J.o<0)N+="-",N+=D(Math.trunc(-J.o/60)),N+=":",N+=D(Math.trunc(-J.o%60));else N+="+",N+=D(Math.trunc(J.o/60)),N+=":",N+=D(Math.trunc(J.o%60));if(A)N+="["+J.zone.ianaName+"]";return N}var g$={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},qq={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Nq={ordinal:1,hour:0,minute:0,second:0,millisecond:0},I_=["year","month","day","hour","minute","second","millisecond"],Gq=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Bq=["year","ordinal","hour","minute","second","millisecond"];function D_(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 f0(J);return _}function P1(J){switch(J.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return D_(J)}}function Qq(J){if(L_===void 0)L_=W.now();if(J.type!=="iana")return J.offset(L_);let _=J.name,y=v0.get(_);if(y===void 0)y=J.offset(L_),v0.set(_,y);return y}function x1(J,_){let y=RJ(_.zone,W.defaultZone);if(!y.isValid)return b.invalid(A_(y));let $=T.fromObject(_),X,A;if(!V(J.year)){for(let N of I_)if(V(J[N]))J[N]=g$[N];let L=K$(J)||R$(J);if(L)return b.invalid(L);let q=Qq(y);[X,A]=x_(J,q,y)}else X=W.now();return new b({ts:X,zone:y,loc:$,o:A})}function I1(J,_,y){let $=V(y.round)?!0:y.round,X=V(y.rounding)?"trunc":y.rounding,A=(q,N)=>{return q=d0(q,$||y.calendary?0:2,y.calendary?"round":X),_.loc.clone(y).relFormatter(y).format(q,N)},L=(q)=>{if(y.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(y.unit)return A(L(y.unit),y.unit);for(let q of y.units){let N=L(q);if(Math.abs(N)>=1)return A(N,q)}return A(J>_?-0:0,y.units[y.units.length-1])}function D1(J){let _={},y;if(J.length>0&&typeof J[J.length-1]==="object")_=J[J.length-1],y=Array.from(J).slice(0,J.length-1);else y=Array.from(J);return[_,y]}var L_,v0=new Map;class b{constructor(J){let _=J.zone||W.defaultZone,y=J.invalid||(Number.isNaN(J.ts)?new n("invalid input"):null)||(!_.isValid?A_(_):null);this.ts=V(J.ts)?W.now():J.ts;let $=null,X=null;if(!y)if(J.old&&J.old.ts===this.ts&&J.old.zone.equals(_))[$,X]=[J.old.c,J.old.o];else{let L=HJ(J.o)&&!J.old?J.o:_.offset(this.ts);$=W_(this.ts,L),y=Number.isNaN($.year)?new n("invalid input"):null,$=y?null:$,X=y?null:L}this._zone=_,this.loc=J.loc||T.create(),this.invalid=y,this.weekData=null,this.localWeekData=null,this.c=$,this.o=X,this.isLuxonDateTime=!0}static now(){return new b({})}static local(){let[J,_]=D1(arguments),[y,$,X,A,L,q,N]=_;return x1({year:y,month:$,day:X,hour:A,minute:L,second:q,millisecond:N},J)}static utc(){let[J,_]=D1(arguments),[y,$,X,A,L,q,N]=_;return J.zone=u.utcInstance,x1({year:y,month:$,day:X,hour:A,minute:L,second:q,millisecond:N},J)}static fromJSDate(J,_={}){let y=dA(J)?J.valueOf():NaN;if(Number.isNaN(y))return b.invalid("invalid input");let $=RJ(_.zone,W.defaultZone);if(!$.isValid)return b.invalid(A_($));return new b({ts:y,zone:$,loc:T.fromObject(_)})}static fromMillis(J,_={}){if(!HJ(J))throw new g(`fromMillis requires a numerical input, but received a ${typeof J} with value ${J}`);else if(J<-F1||J>F1)return b.invalid("Timestamp out of range");else return new b({ts:J,zone:RJ(_.zone,W.defaultZone),loc:T.fromObject(_)})}static fromSeconds(J,_={}){if(!HJ(J))throw new g("fromSeconds requires a numerical input");else return new b({ts:J*1000,zone:RJ(_.zone,W.defaultZone),loc:T.fromObject(_)})}static fromObject(J,_={}){J=J||{};let y=RJ(_.zone,W.defaultZone);if(!y.isValid)return b.invalid(A_(y));let $=T.fromObject(_),X=k_(J,P1),{minDaysInFirstWeek:A,startOfWeek:L}=E1(X,$),q=W.now(),N=!V(_.specificOffset)?_.specificOffset:y.offset(q),G=!V(X.ordinal),B=!V(X.year),R=!V(X.month)||!V(X.day),Q=B||R,K=X.weekYear||X.weekNumber;if((Q||G)&&K)throw new wJ("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(R&&G)throw new wJ("Can't mix ordinal dates with month/day");let Y=K||X.weekday&&!Q,Z,S,E=W_(q,N);if(Y)Z=Gq,S=qq,E=v_(E,A,L);else if(G)Z=Bq,S=Nq,E=M0(E);else Z=I_,S=g$;let C=!1;for(let m of Z){let AJ=X[m];if(!V(AJ))C=!0;else if(C)X[m]=S[m];else X[m]=E[m]}let j=Y?cA(X,A,L):G?uA(X):K$(X),P=j||R$(X);if(P)return b.invalid(P);let l=Y?U1(X,A,L):G?Y1(X):X,[q0,F]=x_(l,N,y),$J=new b({ts:q0,zone:y,o:F,loc:$});if(X.weekday&&Q&&J.weekday!==$J.weekday)return b.invalid("mismatched weekday",`you can't specify both a weekday of ${X.weekday} and a date of ${$J.toISO()}`);if(!$J.isValid)return b.invalid($J.invalid);return $J}static fromISO(J,_={}){let[y,$]=xL(J);return gJ(y,$,_,"ISO 8601",J)}static fromRFC2822(J,_={}){let[y,$]=IL(J);return gJ(y,$,_,"RFC 2822",J)}static fromHTTP(J,_={}){let[y,$]=DL(J);return gJ(y,$,_,"HTTP",_)}static fromFormat(J,_,y={}){if(V(J)||V(_))throw new g("fromFormat requires an input string and a format");let{locale:$=null,numberingSystem:X=null}=y,A=T.fromOpts({locale:$,numberingSystem:X,defaultToEN:!0}),[L,q,N,G]=Lq(A,J,_);if(G)return b.invalid(G);else return gJ(L,q,y,`format ${_}`,J,N)}static fromString(J,_,y={}){return b.fromFormat(J,_,y)}static fromSQL(J,_={}){let[y,$]=uL(J);return gJ(y,$,_,"SQL",J)}static invalid(J,_=null){if(!J)throw new g("need to specify a reason the DateTime is invalid");let y=J instanceof n?J:new n(J,_);if(W.throwOnInvalid)throw new h1(y);else return new b({invalid:y})}static isDateTime(J){return J&&J.isLuxonDateTime||!1}static parseFormatForOpts(J,_={}){let y=f$(J,T.fromObject(_));return!y?null:y.map(($)=>$?$.val:null).join("")}static expandFormat(J,_={}){return h$(c.parseFormat(J),T.fromObject(_)).map(($)=>$.val).join("")}static resetCache(){L_=void 0,v0.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?C0(this).weekYear:NaN}get weekNumber(){return this.isValid?C0(this).weekNumber:NaN}get weekday(){return this.isValid?C0(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?w0(this).weekday:NaN}get localWeekNumber(){return this.isValid?w0(this).weekNumber:NaN}get localWeekYear(){return this.isValid?w0(this).weekYear:NaN}get ordinal(){return this.isValid?M0(this.c).ordinal:NaN}get monthShort(){return this.isValid?cJ.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?cJ.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?cJ.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?cJ.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,y=c_(this.c),$=this.zone.offset(y-J),X=this.zone.offset(y+J),A=this.zone.offset(y-$*_),L=this.zone.offset(y-X*_);if(A===L)return[this];let q=y-A*_,N=y-L*_,G=W_(q,A),B=W_(N,L);if(G.hour===B.hour&&G.minute===B.minute&&G.second===B.second&&G.millisecond===B.millisecond)return[CJ(this,{ts:q}),CJ(this,{ts:N})];return[this]}get isInLeapYear(){return B_(this.year)}get daysInMonth(){return f_(this.year,this.month)}get daysInYear(){return this.isValid?uJ(this.year):NaN}get weeksInWeekYear(){return this.isValid?N_(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?N_(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(J={}){let{locale:_,numberingSystem:y,calendar:$}=c.create(this.loc.clone(J),J).resolvedOptions(this);return{locale:_,numberingSystem:y,outputCalendar:$}}toUTC(J=0,_={}){return this.setZone(u.instance(J),_)}toLocal(){return this.setZone(W.defaultZone)}setZone(J,{keepLocalTime:_=!1,keepCalendarTime:y=!1}={}){if(J=RJ(J,W.defaultZone),J.equals(this.zone))return this;else if(!J.isValid)return b.invalid(A_(J));else{let $=this.ts;if(_||y){let X=J.offset(this.ts),A=this.toObject();[$]=x_(A,X,J)}return CJ(this,{ts:$,zone:J})}}reconfigure({locale:J,numberingSystem:_,outputCalendar:y}={}){let $=this.loc.clone({locale:J,numberingSystem:_,outputCalendar:y});return CJ(this,{loc:$})}setLocale(J){return this.reconfigure({locale:J})}set(J){if(!this.isValid)return this;let _=k_(J,P1),{minDaysInFirstWeek:y,startOfWeek:$}=E1(_,this.loc),X=!V(_.weekYear)||!V(_.weekNumber)||!V(_.weekday),A=!V(_.ordinal),L=!V(_.year),q=!V(_.month)||!V(_.day),N=L||q,G=_.weekYear||_.weekNumber;if((N||A)&&G)throw new wJ("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(q&&A)throw new wJ("Can't mix ordinal dates with month/day");let B;if(X)B=U1({...v_(this.c,y,$),..._},y,$);else if(!V(_.ordinal))B=Y1({...M0(this.c),..._});else if(B={...this.toObject(),..._},V(_.day))B.day=Math.min(f_(B.year,B.month),B.day);let[R,Q]=x_(B,this.o,this.zone);return CJ(this,{ts:R,o:Q})}plus(J){if(!this.isValid)return this;let _=w.fromDurationLike(J);return CJ(this,j1(this,_))}minus(J){if(!this.isValid)return this;let _=w.fromDurationLike(J).negate();return CJ(this,j1(this,_))}startOf(J,{useLocaleWeeks:_=!1}={}){if(!this.isValid)return this;let y={},$=w.normalizeUnit(J);switch($){case"years":y.month=1;case"quarters":case"months":y.day=1;case"weeks":case"days":y.hour=0;case"hours":y.minute=0;case"minutes":y.second=0;case"seconds":y.millisecond=0;break}if($==="weeks")if(_){let X=this.loc.getStartOfWeek(),{weekday:A}=this;if(A<X)y.weekNumber=this.weekNumber-1;y.weekday=X}else y.weekday=1;if($==="quarters"){let X=Math.ceil(this.month/3);y.month=(X-1)*3+1}return this.set(y)}endOf(J,_){return this.isValid?this.plus({[J]:1}).startOf(J,_).minus(1):this}toFormat(J,_={}){return this.isValid?c.create(this.loc.redefaultToEN(_)).formatDateTimeFromString(this,J):S0}toLocaleString(J=h_,_={}){return this.isValid?c.create(this.loc.clone(_),J).formatDateTime(this):S0}toLocaleParts(J={}){return this.isValid?c.create(this.loc.clone(J),J).formatDateTimeParts(this):[]}toISO({format:J="extended",suppressSeconds:_=!1,suppressMilliseconds:y=!1,includeOffset:$=!0,extendedZone:X=!1,precision:A="milliseconds"}={}){if(!this.isValid)return null;A=D_(A);let L=J==="extended",q=z0(this,L,A);if(I_.indexOf(A)>=3)q+="T";return q+=W1(this,L,_,y,$,X,A),q}toISODate({format:J="extended",precision:_="day"}={}){if(!this.isValid)return null;return z0(this,J==="extended",D_(_))}toISOWeekDate(){return P_(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:J=!1,suppressSeconds:_=!1,includeOffset:y=!0,includePrefix:$=!1,extendedZone:X=!1,format:A="extended",precision:L="milliseconds"}={}){if(!this.isValid)return null;return L=D_(L),($&&I_.indexOf(L)>=3?"T":"")+W1(this,A==="extended",_,J,y,X,L)}toRFC2822(){return P_(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return P_(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){if(!this.isValid)return null;return z0(this,!0)}toSQLTime({includeOffset:J=!0,includeZone:_=!1,includeOffsetSpace:y=!0}={}){let $="HH:mm:ss.SSS";if(_||J){if(y)$+=" ";if(_)$+="z";else if(J)$+="ZZ"}return P_(this,$,!0)}toSQL(J={}){if(!this.isValid)return null;return`${this.toSQLDate()} ${this.toSQLTime(J)}`}toString(){return this.isValid?this.toISO():S0}[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",y={}){if(!this.isValid||!J.isValid)return w.invalid("created by diffing an invalid DateTime");let $={locale:this.locale,numberingSystem:this.numberingSystem,...y},X=lA(_).map(w.normalizeUnit),A=J.valueOf()>this.valueOf(),L=A?this:J,q=A?J:this,N=nL(L,q,X,$);return A?N.negate():N}diffNow(J="milliseconds",_={}){return this.diff(b.now(),J,_)}until(J){return this.isValid?x.fromDateTimes(this,J):this}hasSame(J,_,y){if(!this.isValid)return!1;let $=J.valueOf(),X=this.setZone(J.zone,{keepLocalTime:!0});return X.startOf(_,y)<=$&&$<=X.endOf(_,y)}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||b.fromObject({},{zone:this.zone}),y=J.padding?this<_?-J.padding:J.padding:0,$=["years","months","days","hours","minutes","seconds"],X=J.unit;if(Array.isArray(J.unit))$=J.unit,X=void 0;return I1(_,this.plus(y),{...J,numeric:"always",units:$,unit:X})}toRelativeCalendar(J={}){if(!this.isValid)return null;return I1(J.base||b.fromObject({},{zone:this.zone}),this,{...J,numeric:"auto",units:["years","months","days"],calendary:!0})}static min(...J){if(!J.every(b.isDateTime))throw new g("min requires all arguments be DateTimes");return V1(J,(_)=>_.valueOf(),Math.min)}static max(...J){if(!J.every(b.isDateTime))throw new g("max requires all arguments be DateTimes");return V1(J,(_)=>_.valueOf(),Math.max)}static fromFormatExplain(J,_,y={}){let{locale:$=null,numberingSystem:X=null}=y,A=T.fromOpts({locale:$,numberingSystem:X,defaultToEN:!0});return v$(A,J,_)}static fromStringExplain(J,_,y={}){return b.fromFormatExplain(J,_,y)}static buildFormatParser(J,_={}){let{locale:y=null,numberingSystem:$=null}=_,X=T.fromOpts({locale:y,numberingSystem:$,defaultToEN:!0});return new n0(X,J)}static fromFormatParser(J,_,y={}){if(V(J)||V(_))throw new g("fromFormatParser requires an input string and a format parser");let{locale:$=null,numberingSystem:X=null}=y,A=T.fromOpts({locale:$,numberingSystem:X,defaultToEN:!0});if(!A.equals(_.locale))throw new g(`fromFormatParser called with a locale of ${A}, but the format parser was created for ${_.locale}`);let{result:L,zone:q,specificOffset:N,invalidReason:G}=_.explainFromTokens(J);if(G)return b.invalid(G);else return gJ(L,q,y,`format ${_.format}`,J,N)}static get DATE_SHORT(){return h_}static get DATE_MED(){return k1}static get DATE_MED_WITH_WEEKDAY(){return ZA}static get DATE_FULL(){return g1}static get DATE_HUGE(){return c1}static get TIME_SIMPLE(){return u1}static get TIME_WITH_SECONDS(){return m1}static get TIME_WITH_SHORT_OFFSET(){return d1}static get TIME_WITH_LONG_OFFSET(){return l1}static get TIME_24_SIMPLE(){return p1}static get TIME_24_WITH_SECONDS(){return i1}static get TIME_24_WITH_SHORT_OFFSET(){return n1}static get TIME_24_WITH_LONG_OFFSET(){return r1}static get DATETIME_SHORT(){return o1}static get DATETIME_SHORT_WITH_SECONDS(){return s1}static get DATETIME_MED(){return a1}static get DATETIME_MED_WITH_SECONDS(){return t1}static get DATETIME_MED_WITH_WEEKDAY(){return SA}static get DATETIME_FULL(){return e1}static get DATETIME_FULL_WITH_SECONDS(){return J$}static get DATETIME_HUGE(){return _$}static get DATETIME_HUGE_WITH_SECONDS(){return y$}}function $_(J){if(b.isDateTime(J))return J;else if(J&&J.valueOf&&HJ(J.valueOf()))return b.fromJSDate(J);else if(J&&typeof J==="object")return b.fromObject(J);else throw new g(`Unknown datetime argument: ${J}, of type ${typeof J}`)}var Kq="3.7.2";c$.DateTime=b;c$.Duration=w;c$.FixedOffsetZone=u;c$.IANAZone=XJ;c$.Info=cJ;c$.Interval=x;c$.InvalidZone=k0;c$.Settings=W;c$.SystemZone=G_;c$.VERSION=Kq;c$.Zone=OJ});var d$=a((D5,m$)=>{var TJ=u$();M.prototype.addYear=function(){this._date=this._date.plus({years:1})};M.prototype.addMonth=function(){this._date=this._date.plus({months:1}).startOf("month")};M.prototype.addDay=function(){this._date=this._date.plus({days:1}).startOf("day")};M.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})};M.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})};M.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})};M.prototype.subtractYear=function(){this._date=this._date.minus({years:1})};M.prototype.subtractMonth=function(){this._date=this._date.minus({months:1}).endOf("month").startOf("second")};M.prototype.subtractDay=function(){this._date=this._date.minus({days:1}).endOf("day").startOf("second")};M.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})};M.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})};M.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})};M.prototype.getDate=function(){return this._date.day};M.prototype.getFullYear=function(){return this._date.year};M.prototype.getDay=function(){var J=this._date.weekday;return J==7?0:J};M.prototype.getMonth=function(){return this._date.month-1};M.prototype.getHours=function(){return this._date.hour};M.prototype.getMinutes=function(){return this._date.minute};M.prototype.getSeconds=function(){return this._date.second};M.prototype.getMilliseconds=function(){return this._date.millisecond};M.prototype.getTime=function(){return this._date.valueOf()};M.prototype.getUTCDate=function(){return this._getUTC().day};M.prototype.getUTCFullYear=function(){return this._getUTC().year};M.prototype.getUTCDay=function(){var J=this._getUTC().weekday;return J==7?0:J};M.prototype.getUTCMonth=function(){return this._getUTC().month-1};M.prototype.getUTCHours=function(){return this._getUTC().hour};M.prototype.getUTCMinutes=function(){return this._getUTC().minute};M.prototype.getUTCSeconds=function(){return this._getUTC().second};M.prototype.toISOString=function(){return this._date.toUTC().toISO()};M.prototype.toJSON=function(){return this._date.toJSON()};M.prototype.setDate=function(J){this._date=this._date.set({day:J})};M.prototype.setFullYear=function(J){this._date=this._date.set({year:J})};M.prototype.setDay=function(J){this._date=this._date.set({weekday:J})};M.prototype.setMonth=function(J){this._date=this._date.set({month:J+1})};M.prototype.setHours=function(J){this._date=this._date.set({hour:J})};M.prototype.setMinutes=function(J){this._date=this._date.set({minute:J})};M.prototype.setSeconds=function(J){this._date=this._date.set({second:J})};M.prototype.setMilliseconds=function(J){this._date=this._date.set({millisecond:J})};M.prototype._getUTC=function(){return this._date.toUTC()};M.prototype.toString=function(){return this.toDate().toString()};M.prototype.toDate=function(){return this._date.toJSDate()};M.prototype.isLastDayOfMonth=function(){var J=this._date.plus({days:1}).startOf("day");return this._date.month!==J.month};M.prototype.isLastWeekdayOfMonth=function(){var J=this._date.plus({days:7}).startOf("day");return this._date.month!==J.month};function M(J,_){var y={zone:_};if(!J)this._date=TJ.DateTime.local();else if(J instanceof M)this._date=J._date;else if(J instanceof Date)this._date=TJ.DateTime.fromJSDate(J,y);else if(typeof J==="number")this._date=TJ.DateTime.fromMillis(J,y);else if(typeof J==="string")this._date=TJ.DateTime.fromISO(J,y),this._date.isValid||(this._date=TJ.DateTime.fromRFC2822(J,y)),this._date.isValid||(this._date=TJ.DateTime.fromSQL(J,y)),this._date.isValid||(this._date=TJ.DateTime.fromFormat(J,"EEE, d MMM yyyy HH:mm:ss",y));if(!this._date||!this._date.isValid)throw new Error("CronDate: unhandled timestamp: "+JSON.stringify(J));if(_&&_!==this._date.zoneName)this._date=this._date.setZone(_)}m$.exports=M});var i$=a((h5,p$)=>{function FJ(J){return{start:J,count:1}}function l$(J,_){J.end=_,J.step=_-J.start,J.count=2}function r0(J,_,y){if(_)if(_.count===2)J.push(FJ(_.start)),J.push(FJ(_.end));else J.push(_);if(y)J.push(y)}function wq(J){var _=[],y=void 0;for(var $=0;$<J.length;$++){var X=J[$];if(typeof X!=="number")r0(_,y,FJ(X)),y=void 0;else if(!y)y=FJ(X);else if(y.count===1)l$(y,X);else if(y.step===X-y.end)y.count++,y.end=X;else if(y.count===2)_.push(FJ(y.start)),y=FJ(y.end),l$(y,X);else r0(_,y),y=FJ(X)}return r0(_,y),_}p$.exports=wq});var r$=a((v5,n$)=>{var zq=i$();function Oq(J,_,y){var $=zq(J);if($.length===1){var X=$[0],A=X.step;if(A===1&&X.start===_&&X.end===y)return"*";if(A!==1&&X.start===_&&X.end===y-A+1)return"*/"+A}var L=[];for(var q=0,N=$.length;q<N;++q){var G=$[q];if(G.count===1){L.push(G.start);continue}var A=G.step;if(G.step===1){L.push(G.start+"-"+G.end);continue}var B=G.start==0?G.count-1:G.count;if(G.step*B>G.end)L=L.concat(Array.from({length:G.end-G.start+1}).map(function(Q,K){var Y=G.start+K;if((Y-G.start)%G.step===0)return Y;return null}).filter(function(Q){return Q!=null}));else if(G.end===y-G.step+1)L.push(G.start+"/"+G.step);else L.push(G.start+"-"+G.end+"/"+G.step)}return L.join(",")}n$.exports=Oq});var a$=a((f5,s$)=>{var jJ=d$(),Tq=r$(),o$=1e4;function U(J,_){this._options=_,this._utc=_.utc||!1,this._tz=this._utc?"UTC":_.tz,this._currentDate=new jJ(_.currentDate,this._tz),this._startDate=_.startDate?new jJ(_.startDate,this._tz):null,this._endDate=_.endDate?new jJ(_.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(_,y){if(typeof y!=="string")return!1;return _.chars.some(function($){return y.indexOf($)>-1})};U._parseField=function J(_,y,$){switch(_){case"month":case"dayOfWeek":var X=U.aliases[_];y=y.replace(/[a-z]{3}/gi,function(N){if(N=N.toLowerCase(),typeof X[N]!=="undefined")return X[N];else throw new Error('Validation error, cannot resolve alias "'+N+'"')});break}if(!U.validCharacters[_].test(y))throw new Error("Invalid characters, got value: "+y);if(y.indexOf("*")!==-1)y=y.replace(/\*/g,$.min+"-"+$.max);else if(y.indexOf("?")!==-1)y=y.replace(/\?/g,$.min+"-"+$.max);function A(N){var G=[];function B(Y){if(Y instanceof Array)for(var Z=0,S=Y.length;Z<S;Z++){var E=Y[Z];if(U._isValidConstraintChar($,E)){G.push(E);continue}if(typeof E!=="number"||Number.isNaN(E)||E<$.min||E>$.max)throw new Error("Constraint error, got value "+E+" expected range "+$.min+"-"+$.max);G.push(E)}else{if(U._isValidConstraintChar($,Y)){G.push(Y);return}var C=+Y;if(Number.isNaN(C)||C<$.min||C>$.max)throw new Error("Constraint error, got value "+Y+" expected range "+$.min+"-"+$.max);if(_==="dayOfWeek")C=C%7;G.push(C)}}var R=N.split(",");if(!R.every(function(Y){return Y.length>0}))throw new Error("Invalid list value format");if(R.length>1)for(var Q=0,K=R.length;Q<K;Q++)B(L(R[Q]));else B(L(N));return G.sort(U._sortCompareFn),G}function L(N){var G=1,B=N.split("/");if(B.length>2)throw new Error("Invalid repeat: "+N);if(B.length>1){if(B[0]==+B[0])B=[B[0]+"-"+$.max,B[1]];return q(B[0],B[B.length-1])}return q(N,G)}function q(N,G){var B=[],R=N.split("-");if(R.length>1){if(R.length<2)return+N;if(!R[0].length){if(!R[1].length)throw new Error("Invalid range: "+N);return+N}var Q=+R[0],K=+R[1];if(Number.isNaN(Q)||Number.isNaN(K)||Q<$.min||K>$.max)throw new Error("Constraint error, got range "+Q+"-"+K+" expected range "+$.min+"-"+$.max);else if(Q>K)throw new Error("Invalid range: "+N);var Y=+G;if(Number.isNaN(Y)||Y<=0)throw new Error("Constraint error, cannot repeat at every "+Y+" time.");if(_==="dayOfWeek"&&K%7===0)B.push(0);for(var Z=Q,S=K;Z<=S;Z++){var E=B.indexOf(Z)!==-1;if(!E&&Y>0&&Y%G===0)Y=1,B.push(Z);else Y++}return B}return Number.isNaN(+N)?N:+N}return A(y)};U._sortCompareFn=function(J,_){var y=typeof J==="number",$=typeof _==="number";if(y&&$)return J-_;if(!y&&$)return 1;if(y&&!$)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(y){return y==="L"?!0:y<=_}).sort(U._sortCompareFn)}};U._freezeFields=function(J){for(var _=0,y=U.map.length;_<y;++_){var $=U.map[_],X=J[$];J[$]=Object.freeze(X)}return Object.freeze(J)};U.prototype._applyTimezoneShift=function(J,_,y){if(y==="Month"||y==="Day"){var $=J.getTime();J[_+y]();var X=J.getTime();if($===X){if(J.getMinutes()===0&&J.getSeconds()===0)J.addHour();else if(J.getMinutes()===59&&J.getSeconds()===59)J.subtractHour()}}else{var A=J.getHours();J[_+y]();var L=J.getHours(),q=L-A;if(q===2){if(this.fields.hour.length!==24)this._dstStart=L}else if(q===0&&J.getMinutes()===0&&J.getSeconds()===0){if(this.fields.hour.length!==24)this._dstEnd=L}}};U.prototype._findSchedule=function J(_){function y(E,C){for(var j=0,P=C.length;j<P;j++)if(C[j]>=E)return C[j]===E;return C[0]===E}function $(E,C){if(C<6){if(E.getDate()<8&&C===1)return!0;var j=E.getDate()%7?1:0,P=E.getDate()-E.getDate()%7,l=Math.floor(P/7)+j;return l===C}return!1}function X(E){return E.length>0&&E.some(function(C){return typeof C==="string"&&C.indexOf("L")>=0})}_=_||!1;var A=_?"subtract":"add",L=new jJ(this._currentDate,this._tz),q=this._startDate,N=this._endDate,G=L.getTime(),B=0;function R(E){return E.some(function(C){if(!X([C]))return!1;var j=Number.parseInt(C[0])%7;if(Number.isNaN(j))throw new Error("Invalid last weekday of the month expression: "+C);return L.getDay()===j&&L.isLastWeekdayOfMonth()})}while(B<o$){if(B++,_){if(q&&L.getTime()-q.getTime()<0)throw new Error("Out of the timespan range")}else if(N&&N.getTime()-L.getTime()<0)throw new Error("Out of the timespan range");var Q=y(L.getDate(),this.fields.dayOfMonth);if(X(this.fields.dayOfMonth))Q=Q||L.isLastDayOfMonth();var K=y(L.getDay(),this.fields.dayOfWeek);if(X(this.fields.dayOfWeek))K=K||R(this.fields.dayOfWeek);var Y=this.fields.dayOfMonth.length>=U.daysInMonth[L.getMonth()],Z=this.fields.dayOfWeek.length===U.constraints[5].max-U.constraints[5].min+1,S=L.getHours();if(!Q&&(!K||Z)){this._applyTimezoneShift(L,A,"Day");continue}if(!Y&&Z&&!Q){this._applyTimezoneShift(L,A,"Day");continue}if(Y&&!Z&&!K){this._applyTimezoneShift(L,A,"Day");continue}if(this._nthDayOfWeek>0&&!$(L,this._nthDayOfWeek)){this._applyTimezoneShift(L,A,"Day");continue}if(!y(L.getMonth()+1,this.fields.month)){this._applyTimezoneShift(L,A,"Month");continue}if(!y(S,this.fields.hour)){if(this._dstStart!==S){this._dstStart=null,this._applyTimezoneShift(L,A,"Hour");continue}else if(!y(S-1,this.fields.hour)){L[A+"Hour"]();continue}}else if(this._dstEnd===S){if(!_){this._dstEnd=null,this._applyTimezoneShift(L,"add","Hour");continue}}if(!y(L.getMinutes(),this.fields.minute)){this._applyTimezoneShift(L,A,"Minute");continue}if(!y(L.getSeconds(),this.fields.second)){this._applyTimezoneShift(L,A,"Second");continue}if(G===L.getTime()){if(A==="add"||L.getMilliseconds()===0)this._applyTimezoneShift(L,A,"Second");else L.setMilliseconds(0);continue}break}if(B>=o$)throw new Error("Invalid expression, loop limit exceeded");return this._currentDate=new jJ(L,this._tz),this._hasIterated=!0,L};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(y){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(y){return!1}finally{this._currentDate=J,this._hasIterated=_}};U.prototype.iterate=function J(_,y){var $=[];if(_>=0)for(var X=0,A=_;X<A;X++)try{var L=this.next();if($.push(L),y)y(L,X)}catch(q){break}else for(var X=0,A=_;X>A;X--)try{var L=this.prev();if($.push(L),y)y(L,X)}catch(G){break}return $};U.prototype.reset=function J(_){this._currentDate=new jJ(_||this._options.currentDate)};U.prototype.stringify=function J(_){var y=[];for(var $=_?0:1,X=U.map.length;$<X;++$){var A=U.map[$],L=this.fields[A],q=U.constraints[$];if(A==="dayOfMonth"&&this.fields.month.length===1)q={min:1,max:U.daysInMonth[this.fields.month[0]-1]};else if(A==="dayOfWeek")q={min:0,max:6},L=L[L.length-1]===7?L.slice(0,-1):L;y.push(Tq(L,q.min,q.max))}return y.join(" ")};U.parse=function J(_,y){var $=this;if(typeof y==="function")y={};function X(A,L){if(!L)L={};if(typeof L.currentDate==="undefined")L.currentDate=new jJ(void 0,$._tz);if(U.predefined[A])A=U.predefined[A];var q=[],N=(A+"").trim().split(/\s+/);if(N.length>6)throw new Error("Invalid cron expression");var G=U.map.length-N.length;for(var B=0,R=U.map.length;B<R;++B){var Q=U.map[B],K=N[N.length>R?B:B-G];if(B<G||!K)q.push(U._parseField(Q,U.parseDefaults[B],U.constraints[B]));else{var Y=Q==="dayOfWeek"?C(K):K;q.push(U._parseField(Q,Y,U.constraints[B]))}}var Z={};for(var B=0,R=U.map.length;B<R;B++){var S=U.map[B];Z[S]=q[B]}var E=U._handleMaxDaysInMonth(Z);return Z.dayOfMonth=E||Z.dayOfMonth,new U(Z,L);function C(j){var P=j.split("#");if(P.length>1){var l=+P[P.length-1];if(/,/.test(j))throw new Error("Constraint error, invalid dayOfWeek `#` and `,` special characters are incompatible");if(/\//.test(j))throw new Error("Constraint error, invalid dayOfWeek `#` and `/` special characters are incompatible");if(/-/.test(j))throw new Error("Constraint error, invalid dayOfWeek `#` and `-` special characters are incompatible");if(P.length>2||Number.isNaN(l)||(l<1||l>5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return L.nthDayOfWeek=l,P[0]}return j}}return X(_,y)};U.fieldsToExpression=function J(_,y){function $(Q,K,Y){if(!K)throw new Error("Validation error, Field "+Q+" is missing");if(K.length===0)throw new Error("Validation error, Field "+Q+" contains no values");for(var Z=0,S=K.length;Z<S;Z++){var E=K[Z];if(U._isValidConstraintChar(Y,E))continue;if(typeof E!=="number"||Number.isNaN(E)||E<Y.min||E>Y.max)throw new Error("Constraint error, got value "+E+" expected range "+Y.min+"-"+Y.max)}}var X={};for(var A=0,L=U.map.length;A<L;++A){var q=U.map[A],N=_[q];$(q,N,U.constraints[A]);var G=[],B=-1;while(++B<N.length)G[B]=N[B];if(N=G.sort(U._sortCompareFn).filter(function(Q,K,Y){return!K||Q!==Y[K-1]}),N.length!==G.length)throw new Error("Validation error, Field "+q+" contains duplicate values");X[q]=N}var R=U._handleMaxDaysInMonth(X);return X.dayOfMonth=R||X.dayOfMonth,new U(X,y||{})};s$.exports=U});var e$=a((k5,t$)=>{var d_=a$();function YJ(){}YJ._parseEntry=function J(_){var y=_.split(" ");if(y.length===6)return{interval:d_.parse(_)};else if(y.length>6)return{interval:d_.parse(y.slice(0,6).join(" ")),command:y.slice(6,y.length)};else throw new Error("Invalid entry: "+_)};YJ.parseExpression=function J(_,y){return d_.parse(_,y)};YJ.fieldsToExpression=function J(_,y){return d_.fieldsToExpression(_,y)};YJ.parseString=function J(_){var y=_.split(`
|
|
6
|
-
`),$={variables:{},expressions:[],errors:{}};for(var X=0,A=y.length;X<A;X++){var L=y[X],q=null,N=L.trim();if(N.length>0)if(N.match(/^#/))continue;else if(q=N.match(/^(.*)=(.*)$/))$.variables[q[1]]=q[2];else{var G=null;try{G=YJ._parseEntry("0 "+N),$.expressions.push(G.interval)}catch(B){$.errors[N]=B}}}return $};YJ.parseFile=function J(_,y){aJ("fs").readFile(_,function($,X){if($){y($);return}return y(null,YJ.parseString(X.toString()))})};t$.exports=YJ});var K6=wy(hy(),1);import ay from"fs";import ky from"fs";import gy from"os";import bJ from"path";import{fileURLToPath as BA}from"url";import qA from"fs";import vy from"path";import NA from"os";function fy(){if(typeof globalThis.Bun==="undefined")return!1;try{return String(import.meta.url).includes("/$bunfs/")}catch{return!1}}function GA(){return vy.join(NA.homedir(),".everclaw","cache","embedded","0.3.0")}function Q0(){if(!fy())return null;let J=GA();return qA.existsSync(vy.join(J,".extracted"))?J:null}var R0=".everclaw",eJ="~/.everclaw/config.json",cy=bJ.join("~",R0,"workspace");function uy(J=gy.homedir()){return bJ.join(J,R0,"workspace")}function my(J=gy.homedir()){return bJ.join(J,R0,"config.json")}function QA(){let J=Q0();if(J)return J;let _=BA(import.meta.url),y=bJ.dirname(_);if(_.endsWith("/index.js")||_.endsWith("\\index.js"))return y;return bJ.resolve(y,"..")}var K0=null;function dy(){if(K0===null)K0=QA();return K0}function ly(...J){let _=bJ.resolve(dy(),...J);if(!ky.existsSync(_))throw new Error(`Runtime asset not found: ${_}`);return _}function S_(...J){let _=bJ.resolve(dy(),...J);return ky.existsSync(_)?_:null}var KA=[{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 H0(){return KA.map((J)=>J.spec)}var J_=H0(),RA=Object.fromEntries(H0().map((J)=>[J.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),C_="custom:",__={agents:{defaults:{workspace:cy,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:RA,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 IJ(J){return J.toLowerCase().replace(/[\s-]+/g,"_")}function py(J){return`${C_}${IJ(J)}`}function iy(J,_){let y=IJ(_.startsWith(C_)?_.slice(C_.length):_);return J.customLlmProviders.find(($)=>IJ($.name)===y)??null}function HA(J,_){if(!_.includes("/"))return null;let $=_.split("/",1)[0];if(!$)return null;return iy(J,$)}function MJ(J){return!!J&&J.startsWith(C_)}function DJ(J,_,y){let $=(_??J.agents.defaults.provider).trim();if($&&$!=="auto"&&!J.providers[$])return iy(J,$);let X=HA(J,y??J.agents.defaults.model);if(X)return X;let A=J.customLlmProviders.filter((L)=>L.name.trim()&&L.baseUrl.trim());return A.length===1?A[0]??null:null}function w_(J,_){let y=J.agents.defaults.provider;if(y!=="auto"){if(J.providers[y])return y;let q=DJ(J,y,_);return q?py(q.name):null}let $=(_??J.agents.defaults.model).toLowerCase(),X=IJ($),A=$.includes("/")?$.split("/",1)[0]:"";for(let q of J_){let N=J.providers[q.name];if(A&&IJ(A)===q.name&&(q.isOauth||N?.apiKey))return q.name}for(let q of J_){let N=J.providers[q.name];if(q.keywords.some((G)=>$.includes(G)||X.includes(IJ(G)))&&(q.isOauth||N?.apiKey))return q.name}for(let q of J_){if(q.isOauth)continue;if(J.providers[q.name]?.apiKey)return q.name}let L=DJ(J,y,_);if(L)return py(L.name);return null}function ny(J,_){let y=w_(J,_);if(y&&MJ(y)){let $=DJ(J,y,_);return $?{apiKey:$.apiKey,apiBase:$.baseUrl,extraHeaders:$.extraHeaders}:null}return y?J.providers[y]??null:null}function z_(J,_){let y=w_(J,_);if(!y)return null;if(MJ(y))return DJ(J,y,_)?.baseUrl??null;let $=J.providers[y];if($?.apiBase)return $.apiBase;let X=J_.find((A)=>A.name===y);return X?.isGateway?X.defaultApiBase:null}import UA from"fs";import YA from"path";import ry from"os";function oy(J){return UA.mkdirSync(J,{recursive:!0}),J}function sy(J){let _=J?J.replace(/^~(?=$|[\\/])/,ry.homedir()):uy(ry.homedir());return oy(YA.resolve(_))}function VA(){return my()}function ty(J,_){if(!_||typeof _!=="object")return J;let y=Array.isArray(J)?[...J]:{...J};for(let[$,X]of Object.entries(_))if(X&&typeof X==="object"&&!Array.isArray(X)&&y[$]&&typeof y[$]==="object"&&!Array.isArray(y[$]))y[$]=ty(y[$],X);else y[$]=X;return y}function ey(J){let _=J??VA();if(!ay.existsSync(_))return structuredClone(__);try{let y=ay.readFileSync(_,"utf8"),$=JSON.parse(y),X=ty(structuredClone(__),$),A=["advisor"];for(let L of A)if(!X.subagents.find((q)=>q.id===L)){let q=__.subagents.find((N)=>N.id===L);if(q)X.subagents.push(structuredClone(q))}return X}catch(y){return console.warn(`Warning: Failed to load config from ${_}: ${String(y)}`),structuredClone(__)}}function y_(J){return J.map((_)=>{let y=_.content;if(typeof y==="string"&&y.length===0){if(_.role==="assistant"&&_.tool_calls)return{..._,content:null};return{..._,content:"(empty)"}}if(Array.isArray(y)){let $=y.filter((X)=>!(typeof X==="object"&&X&&["text","input_text","output_text"].includes(X.type)&&!X.text));if($.length!==y.length){if($.length>0)return{..._,content:$};if(_.role==="assistant"&&_.tool_calls)return{..._,content:null};return{..._,content:"(empty)"}}}return _})}function U0(){let J=new Error("Operation aborted");return J.name="AbortError",J}function k(J){return J instanceof Error&&J.name==="AbortError"}function v(J){if(J?.aborted)throw U0()}function J1(J){return J.trim().toLowerCase().replace(/[\s-]+/g,"_")}function _1(J){if(typeof J!=="string")return J&&typeof J==="object"?J:{};try{return JSON.parse(J)}catch{return{}}}class Y0{apiKey;apiBase;defaultModel;options;constructor(J,_,y,$={}){this.apiKey=J;this.apiBase=_;this.defaultModel=y;this.options=$}getDefaultModel(){return this.defaultModel}get requestFormat(){return this.options.apiFormat??"v1/chat/completions"}resolveModel(J){let _=J.trim();if(!_.includes("/"))return _;let y=_.split("/",2),$=y[0],X=y[1];if(!$||!X)return _;return new Set(["custom",J1(this.options.providerLabel??"")]).has(J1($))?X:_}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:y_(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}:{}}),y=await this.readJson(_);if(!_.ok)return{content:`Error calling LLM: ${y?.error?.message??JSON.stringify(y)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let $=y.choices?.[0];if(!$?.message)return{content:`Error calling LLM: ${JSON.stringify(y)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let X=($.message.tool_calls??[]).map((A)=>({id:A.id,name:A.function.name,arguments:_1(A.function.arguments)}));return{content:$.message.content??null,toolCalls:X,finishReason:$.finish_reason??"stop",usage:{prompt_tokens:y.usage?.prompt_tokens??0,completion_tokens:y.usage?.completion_tokens??0,total_tokens:y.usage?.total_tokens??0},reasoningContent:$.message.reasoning_content??null}}toResponsesInput(J){let _=[];for(let y of y_(J)){let $=String(y.role??"");if($==="tool"){_.push({type:"function_call_output",call_id:String(y.tool_call_id??""),output:typeof y.content==="string"?y.content:JSON.stringify(y.content??null)});continue}if($==="assistant"&&Array.isArray(y.tool_calls))for(let X of y.tool_calls)_.push({type:"function_call",call_id:String(X.id??""),name:String(X.name??""),arguments:typeof X.arguments==="string"?X.arguments:JSON.stringify(X.arguments??{})});if($==="system"||$==="user"||$==="assistant")_.push({role:$,content:y.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}:{}}),y=await this.readJson(_);if(!_.ok)return{content:`Error calling LLM: ${y?.error?.message??JSON.stringify(y)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let $=Array.isArray(y.output)?y.output:[],X=$.filter((L)=>L?.type==="function_call").map((L)=>({id:String(L.call_id??L.id??""),name:String(L.name??""),arguments:_1(L.arguments)}));return{content:$.filter((L)=>L?.type==="message").flatMap((L)=>Array.isArray(L?.content)?L.content:[]).filter((L)=>L?.type==="output_text").map((L)=>String(L.text??"")).join(`
|
|
7
|
-
`)
|
|
8
|
-
|
|
9
|
-
`)
|
|
10
|
-
|
|
11
|
-
${$==="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};return{content:`Error calling LLM: ${R}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}let N=q.choices?.[0]?.message?q.choices[0]:null;if(!N)return{content:`Error calling LLM: ${JSON.stringify(q)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let G=(N.message.tool_calls??[]).map((B)=>({id:O_(9),name:B.function.name,arguments:typeof B.function.arguments==="string"?JSON.parse(B.function.arguments||"{}"):B.function.arguments}));return{content:N.message.content??null,toolCalls:G,finishReason:N.finish_reason??"stop",usage:q.usage??{},reasoningContent:N.message.reasoning_content??null}}catch($){if(k($))throw $;return{content:`Error calling LLM: ${String($)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}}function X1(J){let _=J.agents.defaults.model,y=w_(J,_),$=ny(J,_),X=y&&MJ(y)?DJ(J,y,_):null,A=new Set(["openai_codex","github_copilot"]),L=new Set(["anthropic"]);if(!y)throw new Error("No provider could be resolved from config. Run `everclaw onboard` and set provider/model/API key.");if(MJ(y)&&!X)throw new Error(`Custom provider '${y}' could not be found. Check ${eJ}.`);if(L.has(y))throw new Error(`Provider '${y}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`);if(!A.has(y)&&y!=="vllm"&&y!=="custom"&&!MJ(y)&&!($?.apiKey||"").trim())throw new Error(`No API key configured for provider '${y}'. Run 'everclaw onboard' or edit ${eJ}.`);if(y==="custom"||MJ(y))return new Y0($?.apiKey||X?.apiKey||"no-key",z_(J,_)||X?.baseUrl||"http://localhost:8000/v1",_,{providerLabel:X?.name??y,apiFormat:X?.apiFormat,extraHeaders:X?.extraHeaders??$?.extraHeaders??null});if(y==="gemini")return new T_($?.apiKey||"",z_(J,_),_);return new vJ($?.apiKey??null,z_(J,_),_,y)}import{randomUUID as F4}from"crypto";import z4 from"path";var Pq=wy(e$(),1);function o0(J){return J??"builtin"}function Fq(){return{beforeAgentTurn:[],afterAgentTurn:[],beforeOutbound:[],afterOutbound:[],beforeScheduledJob:[],afterScheduledJob:[],shutdown:[]}}function l_(J,_,y,$){let X=o0(y.source),A=_.get($.name);if(A)throw new Error(`${J} '${$.name}' from extension '${y.name}' conflicts with extension '${A.extension}'`);_.set($.name,{extension:y.name,source:X,contribution:$})}function jq(J,_,y){let $=(X,A)=>{let L=X.find((q)=>q.contribution.name===A.name);if(L)throw new Error(`lifecycle '${A.slot}:${A.name}' from extension '${_.name}' conflicts with extension '${L.extension}'`);X.push({extension:_.name,source:o0(_.source),contribution:A})};switch(y.slot){case"beforeAgentTurn":$(J.beforeAgentTurn,y);return;case"afterAgentTurn":$(J.afterAgentTurn,y);return;case"beforeOutbound":$(J.beforeOutbound,y);return;case"afterOutbound":$(J.afterOutbound,y);return;case"beforeScheduledJob":$(J.beforeScheduledJob,y);return;case"afterScheduledJob":$(J.afterScheduledJob,y);return;case"shutdown":$(J.shutdown,y);return}}function _J(J){return{...J,source:"builtin"}}class JX{extensions=new Map;register(J){if(this.extensions.has(J.name))throw new Error(`Extension '${J.name}' is already registered`);return this.extensions.set(J.name,{...J,source:o0(J.source)}),this}list(){return[...this.extensions.values()]}compose(){let J=new Map,_=new Map,y=new Map,$=new Map,X=Fq();for(let A of this.extensions.values()){for(let L of A.tools??[])l_("tool",J,A,L);for(let L of A.channels??[])l_("channel",_,A,L);for(let L of A.jobs??[])l_("job",y,A,L);for(let L of A.commands??[])l_("command",$,A,L);for(let L of A.lifecycle??[])jq(X,A,L)}return{extensions:this.list(),tools:J,channels:_,jobs:y,commands:$,lifecycle:{beforeAgentTurn:X.beforeAgentTurn,afterAgentTurn:X.afterAgentTurn,beforeOutbound:X.beforeOutbound,afterOutbound:X.afterOutbound,beforeScheduledJob:X.beforeScheduledJob,afterScheduledJob:X.afterScheduledJob,shutdown:X.shutdown}}}}function _X(J){let _=new JX;for(let y of J)_.register(y);return _.compose()}var u5=typeof globalThis.Bun!=="undefined";class O{static typeMap={string:(J)=>typeof J==="string",integer:(J)=>Number.isInteger(J),number:(J)=>typeof J==="number"&&Number.isFinite(J),boolean:(J)=>typeof J==="boolean",array:(J)=>Array.isArray(J),object:(J)=>!!J&&typeof J==="object"&&!Array.isArray(J)};validateParams(J){let _=this.parameters??{};if(_.type!=="object")throw new Error(`Schema must be object type, got ${String(_.type)}`);return this.validateValue(J,{..._,type:"object"},"parameter")}validateValue(J,_,y){let $=_.type,X=[];if($&&O.typeMap[$]&&!O.typeMap[$](J))return[`${y} should be ${$}`];if(_.enum&&!_.enum.includes(J))X.push(`${y} must be one of ${JSON.stringify(_.enum)}`);if($==="integer"||$==="number"){if(typeof J==="number"){if(typeof _.minimum==="number"&&J<_.minimum)X.push(`${y} must be >= ${_.minimum}`);if(typeof _.maximum==="number"&&J>_.maximum)X.push(`${y} must be <= ${_.maximum}`)}}if($==="string"&&typeof J==="string"){if(typeof _.minLength==="number"&&J.length<_.minLength)X.push(`${y} must be at least ${_.minLength} chars`);if(typeof _.maxLength==="number"&&J.length>_.maxLength)X.push(`${y} must be at most ${_.maxLength} chars`)}if($==="object"&&J&&typeof J==="object"&&!Array.isArray(J)){let A=J,L=_.properties??{};for(let q of _.required??[])if(!(q in A))X.push(`missing required ${y==="parameter"?q:`${y}.${q}`}`);for(let[q,N]of Object.entries(A))if(L[q])X.push(...this.validateValue(N,L[q],y==="parameter"?q:`${y}.${q}`))}if($==="array"&&Array.isArray(J)&&_.items&&typeof _.items==="object")J.forEach((A,L)=>X.push(...this.validateValue(A,_.items,`${y}[${L}]`)));return X}toSchema(){return{type:"function",function:{name:this.name,description:this.description,parameters:this.parameters}}}}class s0 extends O{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="";constructor(J){super();this.cron=J}setContext(J,_){this.channel=J,this.chatId=_}async execute(J,_){let y=String(J.action??"");if(y==="add")return this.addJob(J);if(y==="list")return this.listJobs();if(y==="remove")return this.removeJob(String(J.job_id??""));return`Unknown action: ${y}`}addJob(J){let _=String(J.message??"");if(!_)return"Error: message is required for add";if(!this.channel||!this.chatId)return"Error: no session context (channel/chat_id)";let y=J.every_seconds!=null?Number(J.every_seconds):null,$=J.cron_expr!=null?String(J.cron_expr):null,X=J.tz!=null?String(J.tz):null,A=J.at!=null?String(J.at):null,L,q=!1;if(y)L={kind:"every",everyMs:y*1000};else if($){let N={kind:"cron",expr:$};if(X)N.tz=X;L=N}else if(A){let N=new Date(A);if(Number.isNaN(N.getTime()))return"Error: invalid ISO datetime in at";L={kind:"at",atMs:N.getTime()},q=!0}else return"Error: either every_seconds, cron_expr, or at is required";try{let N=this.cron.addJob({name:_.slice(0,30),schedule:L,message:_,deliver:!0,channel:this.channel,to:this.chatId,deleteAfterRun:q});return`Created job '${N.name}' (id: ${N.id})`}catch(N){return`Error: ${String(N).replace(/^Error:\s*/,"")}`}}listJobs(){let J=this.cron.listJobs();if(!J.length)return"No scheduled jobs.";return`Scheduled jobs:
|
|
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
|
+
`);let X;while((X=s6.exec($))!=null){let A=X[1],G=X[2]||"";G=G.trim();let K=G[0];if(G=G.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),K==='"')G=G.replace(/\\n/g,`
|
|
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
|
+
`).join(`\r
|
|
7
|
+
`)),A.removeListener("error",M6),R.setSocket(A,G,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(R),R.on("close",()=>{if(this.clients.delete(R),this._shouldEmitClose&&!this.clients.size)process.nextTick(r0,this)});K(R,X)}}E6.exports=z6;function qG(J,_){for(let $ of Object.keys(_))J.on($,_[$]);return function $(){for(let X of Object.keys(_))J.removeListener(X,_[X])}}function r0(J){J._state=2,J.emit("close")}function M6(){this.destroy()}function o0(J,_,$,X){$=$||d_.STATUS_CODES[_],X={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength($),...X},J.once("finish",J.destroy),J.end(`HTTP/1.1 ${_} ${d_.STATUS_CODES[_]}\r
|
|
8
|
+
`+Object.keys(X).map((A)=>`${A}: ${X[A]}`).join(`\r
|
|
9
|
+
`)+`\r
|
|
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
|
+
`).trim()||null,toolCalls:A,finishReason:A.length?"tool_calls":$.status??"stop",usage:{prompt_tokens:$.usage?.input_tokens??0,completion_tokens:$.usage?.output_tokens??0,total_tokens:$.usage?.total_tokens??0},reasoningContent:null}}async chat(J){try{return u(J.signal),this.requestFormat==="v1/responses"?await this.responses(J):await this.chatCompletions(J)}catch(_){if(l(_))throw _;return{content:`Error calling LLM: ${String(_)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}}import{webcrypto as RX}from"node:crypto";var NX="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var S8=128,bJ,_0;function P8(J){if(!bJ||bJ.length<J)bJ=Buffer.allocUnsafe(J*S8),RX.getRandomValues(bJ),_0=0;else if(_0+J>bJ.length)RX.getRandomValues(bJ),_0=0;_0+=J}function K_(J=21){P8(J|=0);let _="";for(let $=_0-J;$<_0;$++)_+=NX[bJ[$]&63];return _}class Q_{apiKey;apiBase;defaultModel;static DEFAULT_BASE="https://generativelanguage.googleapis.com/v1beta";constructor(J,_,$){this.apiKey=J;this.apiBase=_;this.defaultModel=$}getDefaultModel(){return this.defaultModel}resolveModel(J){let _=J.trim();if(_.includes("/")){let $=_.split("/",2),X=$[0],A=$[1];if(!X||!A)return _;let G=X.toLowerCase();if(G==="gemini"||G==="google")_=A}return _.startsWith("models/")?_.slice(7):_}asText(J){if(typeof J==="string")return J;if(J==null)return"";try{return JSON.stringify(J)}catch{return String(J)}}parseToolArgs(J){if(J&&typeof J==="object"&&!Array.isArray(J))return J;if(typeof J==="string")try{let _=JSON.parse(J);if(_&&typeof _==="object"&&!Array.isArray(_))return _}catch{}return{}}toGemini(J){let _=[],$=[];for(let G of J.messages){let K=String(G.role??"");if(K==="system"){let Q=this.asText(G.content).trim();if(Q)_.push(Q);continue}if(K==="user"){let Q=this.asText(G.content).trim();if(!Q)continue;$.push({role:"user",parts:[{text:Q}]});continue}if(K==="assistant"||K==="model"){let Q=[],N=this.asText(G.content).trim();if(N)Q.push({text:N});let R=Array.isArray(G.tool_calls)?G.tool_calls:[];for(let Y of R){let H=Y.function;if(!H?.name)continue;Q.push({functionCall:{name:H.name,args:this.parseToolArgs(H.arguments)}})}if(Q.length)$.push({role:"model",parts:Q});continue}if(K==="tool"){let Q=typeof G.name==="string"?G.name:"";if(!Q)continue;let N=this.asText(G.content);$.push({role:"user",parts:[{functionResponse:{name:Q,response:{result:N}}}]})}}if(!$.length)$.push({role:"user",parts:[{text:"Hello"}]});let X={contents:$,generationConfig:{temperature:J.temperature??0.1,maxOutputTokens:Math.max(1,J.maxTokens??4096),...J.reasoning?{thinkingConfig:{thinkingBudget:Math.max(1,J.maxTokens??4096)}}:{}}};if(_.length)X.systemInstruction={parts:[{text:_.join(`
|
|
13
|
+
|
|
14
|
+
`)}]};let A=(J.tools??[]).map((G)=>G).filter((G)=>G.type==="function"&&G.function?.name).map((G)=>({name:G.function.name,description:G.function?.description??"",parameters:G.function?.parameters??{type:"object",properties:{}}}));if(A.length)X.tools=[{functionDeclarations:A}],X.toolConfig=J.toolChoice==="required"?{functionCallingConfig:{mode:"ANY",allowedFunctionNames:A.map((G)=>G.name)}}:{functionCallingConfig:{mode:"AUTO"}};if(J.imageOutput)X.responseModalities=["TEXT","IMAGE"];return X}async chat(J){try{u(J.signal);let _=this.resolveModel(J.model??this.defaultModel),X=`${(this.apiBase??Q_.DEFAULT_BASE).replace(/\/$/,"")}/models/${encodeURIComponent(_)}:generateContent`,A=this.toGemini(J),G=await fetch(X,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":this.apiKey},body:JSON.stringify(A),...J.signal?{signal:J.signal}:{}}),K=await G.json();if(!G.ok)return{content:`Error calling LLM: ${K?.error?.message??JSON.stringify(K)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let Q=K?.candidates?.[0],N=Q?.content?.parts??[],R=N.filter((V)=>typeof V?.text==="string").map((V)=>String(V.text)),Y=N.filter((V)=>V?.functionCall?.name).map((V)=>({id:K_(9),name:String(V.functionCall.name),arguments:this.parseToolArgs(V.functionCall.args)})),H={};if(K?.usageMetadata)H.prompt_tokens=Number(K.usageMetadata.promptTokenCount??0),H.completion_tokens=Number(K.usageMetadata.candidatesTokenCount??0),H.total_tokens=Number(K.usageMetadata.totalTokenCount??0);let q=String(Q?.finishReason??"STOP").toLowerCase();return{content:R.length?R.join(`
|
|
15
|
+
`):null,toolCalls:Y,finishReason:q,usage:H,reasoningContent:null}}catch(_){if(l(_))throw _;return{content:`Error calling LLM: ${String(_)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}}class $0{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"]);constructor(J,_,$,X){this.apiKey=J;this.apiBase=_;this.defaultModel=$;this.providerName=X}getDefaultModel(){return this.defaultModel}resolveModel(J){let _=($)=>$.toLowerCase().replace(/-/g,"_");if(J.includes("/")){let $=J.split("/",2),X=$[0],A=$[1];if(!X||!A)return J;if(_(X)==="github_copilot")return`github_copilot/${A}`;if(_(X)==="openai_codex")return`openai_codex/${A}`;if(_(X)==="groq"){if(A==="compound"||A==="compound-mini")return`groq/${A}`;return A}if(_(X)==="ollama")return A}return J}async chat(J){let $={model:this.resolveModel(J.model??this.defaultModel),messages:W0(J.messages),max_tokens:Math.max(1,J.maxTokens??4096),temperature:J.temperature??0.7};if(J.tools?.length)$.tools=J.tools,$.tool_choice=J.toolChoice??"auto";if(J.reasoning)$.reasoning_effort="medium";if(J.imageOutput)$.include_image_output=!0;try{u(J.signal);let X=(this.providerName??"").trim();if(X&&$0.UNSUPPORTED_PROVIDERS.has(X))return{content:`Error calling LLM: provider '${X}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let A=this.apiBase??(X?$0.DEFAULT_BASE_BY_PROVIDER[X]:void 0)??(this.apiKey?.startsWith("sk-or-")?$0.DEFAULT_BASE_BY_PROVIDER.openrouter:void 0);if(!A)return{content:`Error calling LLM: api_base not configured. Set provider/api_base in ${T0} or run everclaw onboard.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let G={"Content-Type":"application/json"};if(this.apiKey)G.Authorization=`Bearer ${this.apiKey}`;let K=await fetch(`${A.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:G,body:JSON.stringify($),...J.signal?{signal:J.signal}:{}}),Q=await K.json();if(!K.ok){let Y=Q?.error?.code??"",H=Q?.error?.message??JSON.stringify(Q);if(Y==="model_not_found")return{content:`Error calling LLM: ${H}
|
|
16
|
+
${X==="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};return{content:`Error calling LLM: ${H}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}let N=Q.choices?.[0]?.message?Q.choices[0]:null;if(!N)return{content:`Error calling LLM: ${JSON.stringify(Q)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let R=(N.message.tool_calls??[]).map((Y)=>({id:K_(9),name:Y.function.name,arguments:typeof Y.function.arguments==="string"?JSON.parse(Y.function.arguments||"{}"):Y.function.arguments}));return{content:N.message.content??null,toolCalls:R,finishReason:N.finish_reason??"stop",usage:Q.usage??{},reasoningContent:N.message.reasoning_content??null}}catch(X){if(l(X))throw X;return{content:`Error calling LLM: ${String(X)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}}function YX(J){let _=J.agents.defaults.model,$=A_(J,_),X=e$(J,_),A=$&&hJ($)?J0(J,$,_):null,G=new Set(["openai_codex","github_copilot"]),K=new Set(["anthropic"]);if(!$)throw new Error("No provider could be resolved from config. Run `everclaw onboard` and set provider/model/API key.");if(hJ($)&&!A)throw new Error(`Custom provider '${$}' could not be found. Check ${T0}.`);if(K.has($))throw new Error(`Provider '${$}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`);if(!G.has($)&&$!=="vllm"&&$!=="custom"&&!hJ($)&&!(X?.apiKey||"").trim())throw new Error(`No API key configured for provider '${$}'. Run 'everclaw onboard' or edit ${T0}.`);if($==="custom"||hJ($))return new N1(X?.apiKey||A?.apiKey||"no-key",G_(J,_)||A?.baseUrl||"http://localhost:8000/v1",_,{providerLabel:A?.name??$,apiFormat:A?.apiFormat,extraHeaders:A?.extraHeaders??X?.extraHeaders??null});if($==="gemini")return new Q_(X?.apiKey||"",G_(J,_),_);return new $0(X?.apiKey??null,G_(J,_),_,$)}import{randomUUID as NK}from"node:crypto";import GK from"node:path";var kA=HJ(G5(),1);function u1(J){return J??"builtin"}function bA(){return{beforeAgentTurn:[],afterAgentTurn:[],beforeOutbound:[],afterOutbound:[],beforeScheduledJob:[],afterScheduledJob:[],shutdown:[]}}function O_(J,_,$,X){let A=u1($.source),G=_.get(X.name);if(G)throw new Error(`${J} '${X.name}' from extension '${$.name}' conflicts with extension '${G.extension}'`);_.set(X.name,{extension:$.name,source:A,contribution:X})}function fA(J,_,$){let X=(A,G)=>{let K=A.find((Q)=>Q.contribution.name===G.name);if(K)throw new Error(`lifecycle '${G.slot}:${G.name}' from extension '${_.name}' conflicts with extension '${K.extension}'`);A.push({extension:_.name,source:u1(_.source),contribution:G})};switch($.slot){case"beforeAgentTurn":X(J.beforeAgentTurn,$);return;case"afterAgentTurn":X(J.afterAgentTurn,$);return;case"beforeOutbound":X(J.beforeOutbound,$);return;case"afterOutbound":X(J.afterOutbound,$);return;case"beforeScheduledJob":X(J.beforeScheduledJob,$);return;case"afterScheduledJob":X(J.afterScheduledJob,$);return;case"shutdown":X(J.shutdown,$);return}}function NJ(J){return{...J,source:"builtin"}}class K5{extensions=new Map;register(J){if(this.extensions.has(J.name))throw new Error(`Extension '${J.name}' is already registered`);return this.extensions.set(J.name,{...J,source:u1(J.source)}),this}list(){return[...this.extensions.values()]}compose(){let J=new Map,_=new Map,$=new Map,X=new Map,A=bA();for(let G of this.extensions.values()){for(let K of G.tools??[])O_("tool",J,G,K);for(let K of G.channels??[])O_("channel",_,G,K);for(let K of G.jobs??[])O_("job",$,G,K);for(let K of G.commands??[])O_("command",X,G,K);for(let K of G.lifecycle??[])fA(A,G,K)}return{extensions:this.list(),tools:J,channels:_,jobs:$,commands:X,lifecycle:{beforeAgentTurn:A.beforeAgentTurn,afterAgentTurn:A.afterAgentTurn,beforeOutbound:A.beforeOutbound,afterOutbound:A.afterOutbound,beforeScheduledJob:A.beforeScheduledJob,afterScheduledJob:A.afterScheduledJob,shutdown:A.shutdown}}}}function Q5(J){let _=new K5;for(let $ of J)_.register($);return _.compose()}var jQ=typeof globalThis.Bun!=="undefined";class S{static typeMap={string:(J)=>typeof J==="string",integer:(J)=>Number.isInteger(J),number:(J)=>typeof J==="number"&&Number.isFinite(J),boolean:(J)=>typeof J==="boolean",array:(J)=>Array.isArray(J),object:(J)=>!!J&&typeof J==="object"&&!Array.isArray(J)};validateParams(J){let _=this.parameters??{};if(_.type!=="object")throw new Error(`Schema must be object type, got ${String(_.type)}`);return this.validateValue(J,{..._,type:"object"},"parameter")}validateValue(J,_,$){let X=_.type,A=[];if(X&&S.typeMap[X]&&!S.typeMap[X](J))return[`${$} should be ${X}`];if(_.enum&&!_.enum.includes(J))A.push(`${$} must be one of ${JSON.stringify(_.enum)}`);if(X==="integer"||X==="number"){if(typeof J==="number"){if(typeof _.minimum==="number"&&J<_.minimum)A.push(`${$} must be >= ${_.minimum}`);if(typeof _.maximum==="number"&&J>_.maximum)A.push(`${$} must be <= ${_.maximum}`)}}if(X==="string"&&typeof J==="string"){if(typeof _.minLength==="number"&&J.length<_.minLength)A.push(`${$} must be at least ${_.minLength} chars`);if(typeof _.maxLength==="number"&&J.length>_.maxLength)A.push(`${$} must be at most ${_.maxLength} chars`)}if(X==="object"&&J&&typeof J==="object"&&!Array.isArray(J)){let G=J,K=_.properties??{};for(let Q of _.required??[])if(!(Q in G))A.push(`missing required ${$==="parameter"?Q:`${$}.${Q}`}`);for(let[Q,N]of Object.entries(G))if(K[Q])A.push(...this.validateValue(N,K[Q],$==="parameter"?Q:`${$}.${Q}`))}if(X==="array"&&Array.isArray(J)&&_.items&&typeof _.items==="object")J.forEach((G,K)=>A.push(...this.validateValue(G,_.items,`${$}[${K}]`)));return A}toSchema(){return{type:"function",function:{name:this.name,description:this.description,parameters:this.parameters}}}}class c1 extends S{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="";constructor(J){super();this.cron=J}setContext(J,_){this.channel=J,this.chatId=_}async execute(J,_){let $=String(J.action??"");if($==="add")return this.addJob(J);if($==="list")return this.listJobs();if($==="remove")return this.removeJob(String(J.job_id??""));return`Unknown action: ${$}`}addJob(J){let _=String(J.message??"");if(!_)return"Error: message is required for add";if(!this.channel||!this.chatId)return"Error: no session context (channel/chat_id)";let $=J.every_seconds!=null?Number(J.every_seconds):null,X=J.cron_expr!=null?String(J.cron_expr):null,A=J.tz!=null?String(J.tz):null,G=J.at!=null?String(J.at):null,K,Q=!1;if($)K={kind:"every",everyMs:$*1000};else if(X){let N={kind:"cron",expr:X};if(A)N.tz=A;K=N}else if(G){let N=new Date(G);if(Number.isNaN(N.getTime()))return"Error: invalid ISO datetime in at";K={kind:"at",atMs:N.getTime()},Q=!0}else return"Error: either every_seconds, cron_expr, or at is required";try{let N=this.cron.addJob({name:_.slice(0,30),schedule:K,message:_,deliver:!0,channel:this.channel,to:this.chatId,deleteAfterRun:Q});return`Created job '${N.name}' (id: ${N.id})`}catch(N){return`Error: ${String(N).replace(/^Error:\s*/,"")}`}}listJobs(){let J=this.cron.listJobs();if(!J.length)return"No scheduled jobs.";return`Scheduled jobs:
|
|
12
17
|
${J.map((_)=>`- ${_.name} (id: ${_.id}, ${_.schedule.kind})`).join(`
|
|
13
|
-
`)}`}removeJob(J){if(!J)return"Error: job_id is required for remove";return this.cron.removeJob(J)?`Removed job ${J}`:`Job ${J} not found`}}import
|
|
14
|
-
`)}catch(
|
|
15
|
-
`:""}`:"";if(this.rtkService?.getRuntime().available&&
|
|
18
|
+
`)}`}removeJob(J){if(!J)return"Error: job_id is required for remove";return this.cron.removeJob(J)?`Removed job ${J}`:`Job ${J} not found`}}import $J from"node:fs";import y0 from"node:path";import RJ from"node:fs";import r from"node:path";function N5(J){let _=r.resolve(J);while(_!=="/"&&_!==".")try{return RJ.lstatSync(_),_}catch{let $=r.dirname(_);if($===_)break;_=$}return _||"/"}function R5(J,_){let $=r.resolve(J),X=r.resolve(_),A=X.endsWith(r.sep)?X.slice(0,-1):X,G=$===A||$.startsWith(A+r.sep);if(!RJ.existsSync(A))return G;try{let K=A;try{K=RJ.realpathSync.native(A)}catch{}if(RJ.existsSync($)){let R=RJ.realpathSync.native($);return R===K||R.startsWith(K+r.sep)}let Q=N5($);if(Q===K||Q===A)return!0;if(Q!=="/")try{let R=RJ.realpathSync.native(Q);if(R===K||R.startsWith(K+r.sep))return!0;if(!G)return!1}catch{return G}let N=$;while(N!=="/"&&N!=="."){let R=r.dirname(N);if(R===N)break;try{if(RJ.lstatSync(R).isSymbolicLink()){let H=RJ.realpathSync.native(R);if(H!==K&&!H.startsWith(K+r.sep))return!1}}catch{}N=R}return G}catch{return!1}}function Y5(J,_){let $=r.resolve(J),X=r.resolve(_);if(!R5(J,_))throw new Error(`Path '${J}' is outside allowed workspace '${_}'`);let A=r.dirname($),G=N5(A),K=X;try{if(RJ.existsSync(X))K=RJ.realpathSync.native(X)}catch{}if(G!=="/"&&G!==K)try{let Q=RJ.realpathSync.native(G);if(Q!==K&&!Q.startsWith(K+r.sep))throw new Error(`Path '${J}' would be created outside workspace via symlinked parent directory`)}catch(Q){if(Q instanceof Error&&Q.message.includes("symlinked parent"))throw Q;throw new Error(`Could not validate path '${J}' is within workspace`)}}function H5(J,_){if(!R5(J,_))throw new Error(`Path '${J}' is outside allowed workspace '${_}'`)}function F_(J,_,$,X=!1){let A=J.startsWith("~")?y0.join(process.env.USERPROFILE||process.env.HOME||"",J.slice(1)):J,G=y0.isAbsolute(A)?A:_?y0.join(_,A):A,K=y0.resolve(G);if($)try{if(X)Y5(K,$);else H5(K,$)}catch(Q){throw new Error(Q instanceof Error?Q.message:`Path ${J} validation failed`)}return K}class d1 extends S{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"]};constructor(J,_){super();this.workspace=J;this.allowedDir=_}async execute(J,_){try{let $=F_(String(J.path),this.workspace,this.allowedDir);if(!$J.existsSync($))return`Error: File not found: ${String(J.path)}`;if(!$J.statSync($).isFile())return`Error: Not a file: ${String(J.path)}`;return $J.readFileSync($,"utf8")}catch($){return`Error reading file: ${String($)}`}}}class l1 extends S{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"]};constructor(J,_){super();this.workspace=J;this.allowedDir=_}async execute(J,_){try{let $=F_(String(J.path),this.workspace,this.allowedDir,!0);$J.mkdirSync(y0.dirname($),{recursive:!0});let X=String(J.content??"");return $J.writeFileSync($,X,"utf8"),`Successfully wrote ${X.length} bytes to ${$}`}catch($){return`Error writing file: ${String($)}`}}}class p1 extends S{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"]};constructor(J,_){super();this.workspace=J;this.allowedDir=_}async execute(J,_){try{let $=F_(String(J.path),this.workspace,this.allowedDir,!0);if(!$J.existsSync($))return`Error: File not found: ${String(J.path)}`;let X=$J.readFileSync($,"utf8"),A=String(J.old_text??""),G=String(J.new_text??"");if(!X.includes(A))return`Error: old_text not found in ${String(J.path)}. Verify the file content.`;if(X.split(A).length-1>1)return`Warning: old_text appears ${X.split(A).length-1} times. Please provide more context to make it unique.`;return $J.writeFileSync($,X.replace(A,G),"utf8"),`Successfully edited ${$}`}catch($){return`Error editing file: ${String($)}`}}}class i1 extends S{workspace;allowedDir;name="list_dir";description="List the contents of a directory.";parameters={type:"object",properties:{path:{type:"string"}},required:["path"]};constructor(J,_){super();this.workspace=J;this.allowedDir=_}async execute(J,_){try{let $=F_(String(J.path),this.workspace,this.allowedDir);if(!$J.existsSync($))return`Error: Directory not found: ${String(J.path)}`;if(!$J.statSync($).isDirectory())return`Error: Not a directory: ${String(J.path)}`;let X=$J.readdirSync($).sort().map((A)=>{let G=y0.join($,A);return`${$J.statSync(G).isDirectory()?"[DIR]":"[FILE]"} ${A}`});if(!X.length)return`Directory ${String(J.path)} is empty`;return X.join(`
|
|
19
|
+
`)}catch($){return`Error listing directory: ${String($)}`}}}class n1 extends S{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;constructor(J){super();this.sendCallback=J}setContext(J,_,$){this.defaultChannel=J,this.defaultChatId=_,this.defaultMessageId=$??null}setSendCallback(J){this.sendCallback=J}async execute(J,_){let $=String(J.content??""),X=String(J.channel??this.defaultChannel),A=String(J.chat_id??this.defaultChatId),G=String(J.message_id??this.defaultMessageId??""),K=Array.isArray(J.media)?J.media:[];if(!X||!A)return"Error: No target channel/chat specified";if(!this.sendCallback)return"Error: Message sending not configured";try{await this.sendCallback({channel:X,chatId:A,content:$,media:K,metadata:{message_id:G}});let Q=X===this.defaultChannel&&A===this.defaultChatId,N=`Message sent to ${X}:${A}${K.length?` with ${K.length} attachments`:""}`;return Q?`__TERMINAL__${N}`:N}catch(Q){return`Error sending message: ${String(Q)}`}}}import o1 from"node:path";import{spawn as q5}from"node:child_process";var mA={"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 r1(J){return{...mA[J]}}class L0{async run(J){let _=Math.max(1,J.maxCaptureBytes??1048576),$=typeof J.timeoutMs==="number"&&Number.isFinite(J.timeoutMs)&&J.timeoutMs>0?J.timeoutMs:null,X=this.launch(J);if(X instanceof Error)return{status:"failed",pid:null,stdout:"",stderr:"",exitCode:null,signal:null,failureAttribution:"spawn_error",cleanupTriggered:!1,cleanupReason:null,errorMessage:X.message};let{child:A,spawnError:G}=X;if(J.stdinText!=null)A.stdin?.end(J.stdinText,"utf8");else A.stdin?.end();let K="",Q="",N=!1,R=null,Y=!1,H=(Z,O)=>{let I=typeof Z==="string"?Z:Z.toString("utf8"),P=_-Buffer.byteLength(O);if(P<=0)return O;return O+I.slice(0,P)};A.stdout?.on("data",(Z)=>{K=H(Z,K)}),A.stderr?.on("data",(Z)=>{Q=H(Z,Q)});let q=null,V=(Z)=>{if(N)return;N=!0,R=Z,Y=Z==="timeout",this.killChild(A,"SIGTERM"),q=setTimeout(()=>this.killChild(A,"SIGKILL"),250),q.unref?.()},y=()=>V("abort");if(J.signal?.aborted)y();else J.signal?.addEventListener("abort",y,{once:!0});let B=$!=null?setTimeout(()=>V("timeout"),$):null;B?.unref?.();let M=await new Promise((Z)=>{let O=!1,I=(P)=>{if(O)return;O=!0,Z(P)};A.once("error",(P)=>{G.current=P,I({code:null,signal:null})}),A.once("close",(P,g)=>I({code:P,signal:g}))});if(B)clearTimeout(B);if(q)clearTimeout(q);if(J.signal?.removeEventListener("abort",y),R==="abort")return{status:"aborted",pid:A.pid??null,stdout:K,stderr:Q,exitCode:M.code,signal:M.signal,failureAttribution:"aborted",cleanupTriggered:N,cleanupReason:R,errorMessage:null};if(Y)return{status:"failed",pid:A.pid??null,stdout:K,stderr:Q,exitCode:M.code,signal:M.signal,failureAttribution:"timeout",cleanupTriggered:N,cleanupReason:R,errorMessage:null};if(G.current)return{status:"failed",pid:A.pid??null,stdout:K,stderr:Q,exitCode:M.code,signal:M.signal,failureAttribution:"spawn_error",cleanupTriggered:N,cleanupReason:R,errorMessage:G.current.message};if(M.code===0)return{status:"ok",pid:A.pid??null,stdout:K,stderr:Q,exitCode:0,signal:M.signal,failureAttribution:"none",cleanupTriggered:N,cleanupReason:R,errorMessage:null};return{status:"failed",pid:A.pid??null,stdout:K,stderr:Q,exitCode:M.code,signal:M.signal,failureAttribution:M.signal?"signal":"exit_code",cleanupTriggered:N,cleanupReason:R,errorMessage:null}}launch(J){try{return{child:J.command.kind==="shell"?q5(J.command.command,{cwd:J.cwd,env:J.env,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}):q5(J.command.file,J.command.args??[],{cwd:J.cwd,env:J.env,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),spawnError:{current:null}}}catch(_){return _ instanceof Error?_:new Error(String(_))}}killChild(J,_){try{if(process.platform!=="win32"&&typeof J.pid==="number"){process.kill(-J.pid,_);return}}catch{}try{J.kill(_)}catch{}}}class a1 extends S{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"]};constructor(J=60,_,$=!1,X="",A=new L0,G,K=!1){super();this.timeout=J;this.workingDir=_;this.restrictToWorkspace=$;this.pathAppend=X;this.runner=A;this.rtkService=G;this.rtkUltraCompact=K}guard(J,_){let $=J.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((A)=>A.test($)))return"Error: Command blocked by safety guard (dangerous pattern detected)";if(this.restrictToWorkspace){if(J.includes("../")||J.includes("..\\"))return"Error: Command blocked by safety guard (path traversal detected)";let A=J.match(/[A-Za-z]:\\[^\s"']+/g)??[];for(let G of A){let K=o1.resolve(G),Q=o1.resolve(_);if(!K.startsWith(Q))return"Error: Command blocked by safety guard (path outside working dir)"}}return null}async execute(J,_){let $=String(J.command??""),X=String(J.working_dir??this.workingDir??process.cwd()),A=this.guard($,X);if(A)return A;u(_?.signal);let G=r1("tool.exec"),K={...process.env};if(this.pathAppend)K.PATH=`${K.PATH??""}${o1.delimiter}${this.pathAppend}`;if(G.mode!=="local-process")return"Error: exec tool requires local-process isolation";let Q={command:{kind:"shell",command:$},cwd:X,env:K,timeoutMs:this.timeout*1000,maxCaptureBytes:1048576};if(_?.signal)Q.signal=_.signal;let N=await this.runner.run(Q);if(N.status==="aborted")throw Q1();if(N.failureAttribution==="timeout")return`Error: Command timed out after ${this.timeout} seconds`;let R=N.stdout?`${N.stdout}${N.status==="failed"?`
|
|
20
|
+
`:""}`:"";if(this.rtkService?.getRuntime().available&&R)try{let y=await this.rtkService.compress({command:$,stdout:R,stderr:N.stderr,exitCode:N.exitCode,ultraCompact:this.rtkUltraCompact});if(y.compressed)R=y.stdout}catch{}let Y=N.stderr.trim()?`STDERR:
|
|
16
21
|
${N.stderr}
|
|
17
|
-
`:"",
|
|
18
|
-
Exit code: ${N.exitCode}`:"",
|
|
19
|
-
Signal: ${N.signal}`:"",
|
|
20
|
-
... (truncated, ${
|
|
21
|
-
... (truncated for archival)`;function
|
|
22
|
-
`),omittedLines:
|
|
22
|
+
`:"",H=N.status==="failed"&&typeof N.exitCode==="number"?`
|
|
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()}
|
|
23
28
|
|
|
24
29
|
`,"utf8")}getMemoryContext(){let J=this.readLongTerm();return J?`## Long-term Memory
|
|
25
|
-
${J}`:""}async consolidate(J,_
|
|
26
|
-
`),
|
|
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.
|
|
27
32
|
|
|
28
33
|
## Current Long-term Memory
|
|
29
34
|
|
|
30
35
|
|
|
31
36
|
## Conversation to Process
|
|
32
|
-
`),
|
|
37
|
+
`),Z=T_(H||"(empty)"),O=T_(q),I=M+Z+O,P=B5($),g=Math.floor(P*0.9);if(I>g){let w=Math.max(1,g-M),o=Math.min(Z,Math.max(cA,Math.floor(w*0.3))),k=Math.min(Z,Math.max(0,w-U5),o),AJ=Math.max(U5,w-k);if(k<Z)V=dA(V,k);if(AJ<O){let jJ=lA(Y,AJ);B=jJ.text,y=jJ.text!==q?`## Conversation to Process (truncated, most recent ${Y.length-jJ.omittedLines} entries)`:"## Conversation to Process"}}let tJ=`Process this conversation and call the save_memory tool with your consolidation. If tool calling is unavailable, respond with JSON only using the shape {"history_entry":"...","memory_update":"..."}.
|
|
33
38
|
|
|
34
39
|
## Current Long-term Memory
|
|
35
|
-
${
|
|
40
|
+
${V}
|
|
36
41
|
|
|
37
|
-
${
|
|
38
|
-
${
|
|
42
|
+
${y}
|
|
43
|
+
${B}`;try{let w=await _.chat({model:$,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 history_entry and memory_update."},{role:"user",content:tJ}],tools:pA,toolChoice:"required"}),k=w.toolCalls[0]?.arguments??nA(w.content);if(!k)return!1;let{history_entry:AJ,memory_update:jJ}=k;if(AJ!=null)this.appendHistory(typeof AJ==="string"?AJ:JSON.stringify(AJ));if(jJ!=null){let xJ=typeof jJ==="string"?jJ:JSON.stringify(jJ);if(xJ!==H)this.writeLongTerm(xJ)}let P$=A?0:J.messages.length-Q,W$=J.messages.slice(0,P$),J1=-1;for(let xJ=W$.length-1;xJ>=0;xJ--)if(W$[xJ]?._type==="anchor"){J1=xJ;break}if(J1!==-1)J.lastConsolidated=J1+1;else J.lastConsolidated=P$;return!0}catch{return!1}}}import u0 from"node:fs";import c0 from"node:path";var M5=/^[a-z0-9][a-z0-9-]*$/;class e1{workspaceSkills;userSkills;builtinSkills;scannerConfig;scanner;constructor(J,_,$,X,A){this.workspaceSkills=c0.join(J,"skills"),this.userSkills=_??null,this.builtinSkills=$??a$("skills"),this.scannerConfig=X??null,this.scanner=A??null}listSkills(J=!0){return(J?this.getResolvedSkills().filter(($)=>$.status==="available"):this.getResolvedSkills()).map(({name:$,path:X,source:A})=>({name:$,path:X,source:A}))}listResolvedSkills(){return this.getResolvedSkills().map(({content:J,metadata:_,runtimeMeta:$,...X})=>X)}loadSkill(J){let _=this.getSkillByName(J);return _?.status==="available"?_.content:null}loadSkillsForContext(J){let _=[];for(let $ of J){let X=this.getSkillByName($);if(!X){_.push(this.renderLoadFailure($,`Skill '${$}' is not installed. ${this.getAvailableSkillsHint()}`));continue}if(X.status!=="available"){let A=X.status==="malformed"?`Skill '${$}' is malformed: ${X.reason}.`:X.status==="blocked"?`Skill '${$}' is blocked by security scanner: ${X.reason}.`:`Skill '${$}' is unavailable: ${X.reason}.`;_.push(this.renderLoadFailure($,A));continue}_.push(`### Skill: ${$}
|
|
39
44
|
|
|
40
|
-
${this.stripFrontmatter(
|
|
45
|
+
${this.stripFrontmatter(X.content)}`)}return _.join(`
|
|
41
46
|
|
|
42
47
|
---
|
|
43
48
|
|
|
44
|
-
`)}buildSkillsSummary(){let J=this.getResolvedSkills();if(!J.length)return"";let _=(
|
|
45
|
-
`)}getAlwaysSkills(){return this.getResolvedSkills().filter((J)=>J.status==="available"&&J.always).map((J)=>J.name)}getSkillMetadata(J){return this.getSkillByName(J)?.metadata??null}stripFrontmatter(J){let _=J.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return _?J.slice(_[0].length).trim():J}getResolvedSkills(){let J=new Map;for(let{root:_,source
|
|
49
|
+
`)}buildSkillsSummary(){let J=this.getResolvedSkills();if(!J.length)return"";let _=(X)=>X.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"),$=["<skills>"];for(let X of J){if($.push(` <skill available="${X.status==="available"}" source="${_(X.source)}">`),$.push(` <name>${_(X.name)}</name>`),$.push(` <description>${_(X.description)}</description>`),$.push(` <location>${_(X.path)}</location>`),$.push(` <status>${_(X.status)}</status>`),X.reason)$.push(` <reason>${_(X.reason)}</reason>`);$.push(" </skill>")}return $.push("</skills>"),$.join(`
|
|
50
|
+
`)}getAlwaysSkills(){return this.getResolvedSkills().filter((J)=>J.status==="available"&&J.always).map((J)=>J.name)}getSkillMetadata(J){return this.getSkillByName(J)?.metadata??null}stripFrontmatter(J){let _=J.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return _?J.slice(_[0].length).trim():J}getResolvedSkills(){let J=new Map;for(let{root:_,source:$}of this.getSkillRoots()){if(!u0.existsSync(_))continue;let X=u0.readdirSync(_,{withFileTypes:!0}).filter((A)=>A.isDirectory()).sort((A,G)=>A.name.localeCompare(G.name));for(let A of X){if(J.has(A.name))continue;let G=c0.join(_,A.name,"SKILL.md");if(!u0.existsSync(G))continue;J.set(A.name,this.readSkill(A.name,G,$))}}return[...J.values()].sort((_,$)=>_.name.localeCompare($.name))}getSkillByName(J){return this.getResolvedSkills().find((_)=>_.name===J)??null}getSkillRoots(){let J=[{root:this.workspaceSkills,source:"workspace"}];if(this.userSkills)J.push({root:this.userSkills,source:"user"});return J.push({root:this.builtinSkills,source:"builtin"}),J}readSkill(J,_,$){let X=u0.readFileSync(_,"utf8"),A=this.parseSkill(J,X);if(A.errors.length)return{name:J,path:_,source:$,content:X,metadata:A.metadata,runtimeMeta:{},description:A.description,status:"malformed",reason:A.errors.join("; "),always:!1};let G=this.getRequirementErrors(A.runtimeMeta),K=this.runSecurityScan(_,J);if(K&&!K.isSafe&&this.scannerConfig?.blockUnsafe)return{name:J,path:_,source:$,content:X,metadata:A.metadata,runtimeMeta:A.runtimeMeta,description:A.description,status:"blocked",reason:this.formatBlockedReason(K),always:A.always};if(K&&K.findings.length>0){let Q=K.findings.map((N)=>`[${N.severity}] ${N.title} (${N.category})`);console.warn(`SkillScanner: skill '${J}' has ${K.findings.length} finding(s): ${Q.join("; ")}`)}return{name:J,path:_,source:$,content:X,metadata:A.metadata,runtimeMeta:A.runtimeMeta,description:A.description,status:G.length?"unavailable":"available",reason:G.length?G.join("; "):null,always:A.always}}runSecurityScan(J,_){if(!this.scannerConfig?.enabled||!this.scannerConfig.scanOnLoad||!this.scanner)return null;let $=c0.dirname(J);return this.scanner.scanSkill($,_,{maxFileCount:this.scannerConfig.maxFileCount,maxFileSizeBytes:this.scannerConfig.maxFileSizeBytes})}formatBlockedReason(J){let _=J.findings.filter((X)=>X.severity==="CRITICAL");if(_.length===0)return"Security scan failed";return`Blocked by security scanner: ${_.map((X)=>`[${X.severity}] ${X.title} (${X.category})`).join("; ")}`}parseSkill(J,_){let $=this.extractFrontmatter(_);if(!$.frontmatter)return{metadata:null,runtimeMeta:{},description:J,always:!1,errors:[$.error??"missing YAML frontmatter"]};let X=this.parseFrontmatter($.frontmatter),A=X.metadata,G=typeof A.description==="string"&&A.description.trim()?A.description.trim():J,K=[...X.errors],Q=typeof A.name==="string"?A.name.trim():"";if(!Q)K.push("missing required frontmatter field 'name'");else if(Q!==J)K.push(`frontmatter name '${Q}' does not match directory '${J}'`);else if(!M5.test(Q))K.push(`frontmatter name '${Q}' must match ${M5}`);if(!(typeof A.description==="string"&&A.description.trim()))K.push("missing required frontmatter field 'description'");let N=this.parseRuntimeMetadata(A.metadata);K.push(...N.errors);let R=A.always;if(R!==void 0&&typeof R!=="boolean")K.push("frontmatter field 'always' must be a boolean");return{metadata:A,runtimeMeta:N.runtimeMeta,description:G,always:R??N.runtimeMeta.always??!1,errors:K}}extractFrontmatter(J){if(!(J.startsWith(`---
|
|
46
51
|
`)||J.startsWith(`---\r
|
|
47
|
-
`)))return{frontmatter:null,error:"missing YAML frontmatter"};let _=J.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);if(!_)return{frontmatter:null,error:"unterminated YAML frontmatter"};return{frontmatter:_[1]??null,error:null}}parseFrontmatter(J){let _={}
|
|
52
|
+
`)))return{frontmatter:null,error:"missing YAML frontmatter"};let _=J.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);if(!_)return{frontmatter:null,error:"unterminated YAML frontmatter"};return{frontmatter:_[1]??null,error:null}}parseFrontmatter(J){let _={},$=[];for(let X of J.split(/\r?\n/)){let A=X.trim();if(!A)continue;let G=A.indexOf(":");if(G<=0){$.push(`invalid frontmatter line '${A}'`);continue}let K=A.slice(0,G).trim(),Q=A.slice(G+1).trim();_[K]=this.parseFrontmatterValue(Q)}return{metadata:_,errors:$}}parseFrontmatterValue(J){let _=J.replace(/^['"]|['"]$/g,"");if(_==="true")return!0;if(_==="false")return!1;return _}parseRuntimeMetadata(J){if(J===void 0||J==="")return{runtimeMeta:{},errors:[]};if(typeof J!=="string")return{runtimeMeta:{},errors:["frontmatter field 'metadata' must be a JSON object string"]};let _;try{_=JSON.parse(J)}catch{return{runtimeMeta:{},errors:["frontmatter field 'metadata' must contain valid JSON"]}}if(!this.isRecord(_))return{runtimeMeta:{},errors:["frontmatter field 'metadata' must decode to an object"]};let $=_.everclaw??_.openclaw??{};if(!this.isRecord($))return{runtimeMeta:{},errors:["skill metadata for 'everclaw'/'openclaw' must be an object"]};let X=[],A={};if($.always!==void 0)if(typeof $.always!=="boolean")X.push("skill metadata field 'always' must be a boolean");else A.always=$.always;if($.requires!==void 0)if(!this.isRecord($.requires))X.push("skill metadata field 'requires' must be an object");else{let G=$.requires.bins,K=$.requires.env;if(G!==void 0&&!this.isStringArray(G))X.push("skill metadata field 'requires.bins' must be an array of strings");if(K!==void 0&&!this.isStringArray(K))X.push("skill metadata field 'requires.env' must be an array of strings");let Q={};if(this.isStringArray(G))Q.bins=G;if(this.isStringArray(K))Q.env=K;if(Object.keys(Q).length>0)A.requires=Q}return{runtimeMeta:A,errors:X}}getRequirementErrors(J){let _=J.requires??{},$=(_.bins??[]).filter((G)=>!this.hasBinary(G)),X=(_.env??[]).filter((G)=>!process.env[G]),A=[];if($.length)A.push(`missing required binaries: ${$.join(", ")}`);if(X.length)A.push(`missing required env vars: ${X.join(", ")}`);return A}hasBinary(J){let _=(process.env.PATH??"").split(c0.delimiter).filter(Boolean),$=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return _.some((X)=>$.some((A)=>u0.existsSync(c0.join(X,`${J}${A}`))))}getAvailableSkillsHint(){let J=this.getResolvedSkills().filter((_)=>_.status==="available").map((_)=>_.name);return J.length?`Available skills: ${J.join(", ")}`:"No skills are currently available."}renderLoadFailure(J,_){return`### Skill unavailable: ${J}
|
|
48
53
|
|
|
49
|
-
Error: ${_}`}isRecord(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}isStringArray(J){return Array.isArray(J)&&J.every((_)=>typeof _==="string"&&_.trim().length>0)}}class
|
|
54
|
+
Error: ${_}`}isRecord(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}isStringArray(J){return Array.isArray(J)&&J.every((_)=>typeof _==="string"&&_.trim().length>0)}}class UJ{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(J){if(!J)return 0;let _=typeof J==="string"?J:JSON.stringify(J);return Math.ceil(_.length/4)}static estimateMessageTokens(J){let _=0;if(typeof J.content==="string")_+=UJ.estimateTokens(J.content);if(Array.isArray(J.tool_calls))for(let $ of J.tool_calls)_+=UJ.estimateTokens($);return _}static findLastAnchor(J){for(let _=J.length-1;_>=0;_--){let $=J[_];if(!$)continue;let X=$.content;if(typeof X==="string"&&X.includes(UJ.ANCHOR_TAG))return{name:X.match(/\[anchor\]\s*(\S+)/)?.[1]??null,index:_}}return{name:null,index:-1}}defaultMemory;skills;constructor(J,_,$){this.workspace=J;this.defaultMemory=new W_(J),this.skills=new e1(J,null,void 0,_,$)}getMemoryStore(J){return J?new W_(this.workspace,J):this.defaultMemory}buildSystemPrompt(J,_){let $=[this.getIdentity()],X=this.loadBootstrapFiles();if(X)$.push(X);let G=this.getMemoryStore(_).getMemoryContext();if(G)$.push(`# Memory
|
|
50
55
|
|
|
51
|
-
${
|
|
56
|
+
${G}`);let K=this.skills.getAlwaysSkills();if(K.length){let N=this.skills.loadSkillsForContext(K);if(N)$.push(`# Active Skills
|
|
52
57
|
|
|
53
|
-
${N}`)}if(J?.length){let N=this.skills.loadSkillsForContext(J);if(N)
|
|
58
|
+
${N}`)}if(J?.length){let N=this.skills.loadSkillsForContext(J);if(N)$.push(`# Requested Skills
|
|
54
59
|
|
|
55
|
-
${N}`)}let
|
|
60
|
+
${N}`)}let Q=this.skills.buildSkillsSummary();if(Q)$.push(`# Skills
|
|
56
61
|
|
|
57
62
|
The following skills extend your capabilities. To use one, read its SKILL.md with read_file.
|
|
58
63
|
|
|
59
|
-
${
|
|
64
|
+
${Q}`);return $.join(`
|
|
60
65
|
|
|
61
66
|
---
|
|
62
67
|
|
|
@@ -65,29 +70,29 @@ ${q}`);return y.join(`
|
|
|
65
70
|
You are everclaw, a helpful AI assistant.
|
|
66
71
|
|
|
67
72
|
## Runtime
|
|
68
|
-
${
|
|
73
|
+
${E5.platform()} ${E5.arch()}, Node ${process.version}
|
|
69
74
|
|
|
70
75
|
## Workspace
|
|
71
76
|
Your workspace is at: ${this.workspace}
|
|
72
|
-
- Long-term memory: ${
|
|
73
|
-
- History log: ${
|
|
74
|
-
- Custom skills: ${
|
|
77
|
+
- Long-term memory: ${w_.join(this.workspace,"memory","MEMORY.md")}
|
|
78
|
+
- History log: ${w_.join(this.workspace,"memory","HISTORY.md")}
|
|
79
|
+
- Custom skills: ${w_.join(this.workspace,"skills","{skill-name}","SKILL.md")}
|
|
75
80
|
|
|
76
81
|
## Guidelines
|
|
77
82
|
- State intent before tool calls, but never claim results before receiving them.
|
|
78
83
|
- Before modifying a file, read it first.
|
|
79
|
-
- Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let J=[];for(let _ of
|
|
84
|
+
- Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let J=[];for(let _ of UJ.BOOTSTRAP_FILES){let $=w_.join(this.workspace,_);if(!z5.existsSync($))continue;J.push(`## ${_}
|
|
80
85
|
|
|
81
|
-
${
|
|
86
|
+
${z5.readFileSync($,"utf8")}`)}return J.join(`
|
|
82
87
|
|
|
83
|
-
`)}static buildRuntimeContext(J,_
|
|
84
|
-
${
|
|
85
|
-
`)}`}buildMessages(J){return[{role:"system",content:this.buildSystemPrompt(J.skillNames,J.memoryNamespace)},...J.history,{role:"user",content:
|
|
88
|
+
`)}static buildRuntimeContext(J,_,$){let A=[`Current Time: ${new Date().toISOString()}`];if(J&&_)A.push(`Channel: ${J}`),A.push(`Chat ID: ${_}`);if($?.chat_type)A.push(`Chat Type: ${$.chat_type}`);if($?.bot_mentioned)A.push("Bot Mentioned: yes");return`${UJ.RUNTIME_CONTEXT_TAG}
|
|
89
|
+
${A.join(`
|
|
90
|
+
`)}`}buildMessages(J){return[{role:"system",content:this.buildSystemPrompt(J.skillNames,J.memoryNamespace)},...J.history,{role:"user",content:UJ.buildRuntimeContext(J.channel,J.chatId,J.metadata)},{role:"user",content:J.currentMessage}]}addToolResult(J,_,$,X){return J.push({role:"tool",tool_call_id:_,name:$,content:X}),J}addAssistantMessage(J,_,$,X){let A={role:"assistant",content:_};if($?.length)A.tool_calls=$;if(X!=null)A.reasoning_content=X;return J.push(A),J}buildNotificationContext(J){let _=J.status==="completed"?"✓":"✗";if(J.kind==="cron_completed"||J.kind==="subagent_completed"||J.kind==="subagent_failed"){let $=[`[${_}] ${J.kind==="cron_completed"?"Cron Job":"Subagent"}: ${J.label}`,`Task: ${J.originalTask}`,`Status: ${J.status}`];if(J.result)$.push(`Result: ${J.result}`);if(J.error)$.push(`Error: ${J.error}`);let X=J.kind==="cron_completed"?"cron job":"subagent";return $.push("",`The ${X} has finished. Acknowledge this result briefly and continue with any follow-up work if needed.`),$.join(`
|
|
86
91
|
`)}return`[${_}] Task: ${J.label}
|
|
87
|
-
Status: ${J.status}`}}class
|
|
88
|
-
`),A
|
|
89
|
-
`)
|
|
90
|
-
`;return new Promise((
|
|
92
|
+
Status: ${J.status}`}}class J$ extends S{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(J){this.sessionManager=J}setContext(J){this.sessionKey=J}async execute(J){if(!this.sessionManager)return"Error: Session manager not available";let _=this.sessionManager.getOrCreate(this.sessionKey),$=_.getHistory(1000),X=0;for(let Q of $)X+=UJ.estimateMessageTokens(Q);let A=_.getLastAnchor(),G=_.getMessagesSinceLastAnchor().length,K={messageCount:_.messages.length,tokenEstimate:X,lastAnchor:A?.name??null,messagesSinceAnchor:G};return JSON.stringify(K,null,2)}}class _$ extends S{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(J){this.sessionManager=J}setContext(J){this.sessionKey=J}async execute(J){if(!this.sessionManager)return"Error: Session manager not available";let _=String(J.name??"");if(!_)return"Error: Anchor name is required";let $=J.summary!=null?String(J.summary):void 0,A=this.sessionManager.getOrCreate(this.sessionKey).anchor(_,$);return JSON.stringify({success:!0,anchor:{name:A.name,summary:A.summary,timestamp:A.timestamp}},null,2)}}import{readFileSync as zG,existsSync as EG}from"node:fs";import{join as b}from"node:path";import jG from"node:http";import{homedir as CG}from"node:os";import OG from"node:net";var VG=HJ(B6(),1),yG=HJ(g_(),1),LG=HJ(Z0(),1),BG=HJ(Q$(),1),UG=HJ(R$(),1),ZG=HJ(L$(),1),C6=HJ(c_(),1),MG=HJ(j6(),1);var B$=C6.default;var FG={existsSync:EG,readFileSync:zG},O6=FG;var TG=jG,F6=TG;var SG=1;var PG="/tmp/chrome-debug-profile";function WG(J){let _=J??process.platform,$=CG(),X=b(PG,"DevToolsActivePort");switch(_){case"darwin":return[X,b($,"Library/Application Support/Google/Chrome/DevToolsActivePort"),b($,"Library/Application Support/Chromium/DevToolsActivePort"),b($,"Library/Application Support/BraveSoftware/Brave-Browser/DevToolsActivePort"),b($,"Library/Application Support/Microsoft Edge/DevToolsActivePort"),b($,"Library/Application Support/Vivaldi/DevToolsActivePort")];case"linux":{let A=process.env.XDG_CONFIG_HOME||b($,".config");return[X,b(A,"google-chrome","DevToolsActivePort"),b(A,"chromium","DevToolsActivePort"),b(A,"BraveSoftware","Brave-Browser","DevToolsActivePort"),b(A,"microsoft-edge","DevToolsActivePort"),b(A,"vivaldi","DevToolsActivePort"),b($,".config","google-chrome","DevToolsActivePort"),b($,".config","chromium","DevToolsActivePort"),b($,"snap","chromium","common","chromium","DevToolsActivePort"),b($,".var","app","com.google.Chrome","config","google-chrome","DevToolsActivePort"),b($,".var","app","org.chromium.Chromium","config","chromium","DevToolsActivePort")]}case"win32":{let A=process.env.LOCALAPPDATA||b($,"AppData","Local");return[X,b(A,"Google","Chrome","User Data","DevToolsActivePort"),b(A,"Chromium","User Data","DevToolsActivePort"),b(A,"BraveSoftware","Brave-Browser","User Data","DevToolsActivePort"),b(A,"Microsoft","Edge","User Data","DevToolsActivePort"),b(A,"Vivaldi","User Data","DevToolsActivePort")]}default:return[]}}function l_(J){return p_(J)?.port}function p_(J){let _=WG(J);for(let $ of _)try{if(!O6.existsSync($))continue;let A=O6.readFileSync($,"utf-8").split(`
|
|
93
|
+
`),G=A[0]?.trim(),K=A[1]?.trim()||void 0;if(G){let Q=parseInt(G,10);if(Q>0&&Q<=65535)return{port:Q,browserWsPath:K}}}catch{}return}function wG(J=9222){return new Promise((_)=>{let $=`http://127.0.0.1:${J}/json/version`,X=F6.get($,{timeout:5000},(A)=>{if(A.statusCode!==200){A.resume(),_(void 0);return}let G=[];A.on("data",(K)=>G.push(K)),A.on("end",()=>{try{let K=Buffer.concat(G).toString("utf-8"),Q=JSON.parse(K);_(Q)}catch{_(void 0)}}),A.on("error",()=>_(void 0))});X.on("timeout",()=>{X.destroy(),_(void 0)}),X.on("error",()=>_(void 0))})}function IG(J,_="127.0.0.1"){return new Promise(($)=>{let X=new OG.Socket,A=2000;X.setTimeout(2000),X.once("connect",()=>{X.destroy(),$(!0)}),X.once("timeout",()=>{X.destroy(),$(!1)}),X.once("error",()=>{$(!1)}),X.connect(J,_)})}function xG(J){return new Promise((_)=>{try{let $=new B$(J),X=setTimeout(()=>{$.close(),_(!1)},3000);$.on("open",()=>{clearTimeout(X),$.close(),_(!0)}),$.on("error",()=>{clearTimeout(X),_(!1)})}catch{_(!1)}})}async function T6(J=9222){let _=p_(),$=_?.port??J;if(!await IG($))return;for(let A=0;A<2;A++){try{let G=await wG($);if(G)return{port:$,versionInfo:G}}catch{}if(A<1)await new Promise((G)=>setTimeout(G,500))}if(_?.browserWsPath){let A=`ws://127.0.0.1:${$}${_.browserWsPath}`;if(await xG(A))return{port:$,versionInfo:{Browser:"Chrome","Protocol-Version":"1.3","User-Agent":"","V8-Version":"","WebKit-Version":"",webSocketDebuggerUrl:A}}}return new Promise((A)=>{let G=F6.get(`http://127.0.0.1:${$}/json/version`,{timeout:3000},(K)=>{if(K.resume(),K.statusCode===404||K.statusCode===403)A({port:$,versionInfo:{},pendingApproval:!0});else A(void 0)});G.on("error",()=>A(void 0)),G.on("timeout",()=>{G.destroy(),A(void 0)})})}async function a0(J){let $=p_()?.browserWsPath;if(!$)return[];let X=await oJ.connect(`ws://127.0.0.1:${J}${$}`);try{return((await X.send("Target.getTargets")).targetInfos??[]).map((K)=>({id:K.targetId,type:K.type,title:K.title,url:K.url,webSocketDebuggerUrl:K.webSocketDebuggerUrl??`ws://127.0.0.1:${J}/devtools/page/${K.targetId}`}))}finally{X.close()}}async function S6(J,_){let X=p_()?.browserWsPath;if(!X)throw new Error("No browser WebSocket path found in DevToolsActivePort");let A=await oJ.connect(`ws://127.0.0.1:${J}${X}`);try{let K=(await A.send("Target.createTarget",{url:_})).targetId;if(!K)throw new Error("Target.createTarget returned no targetId");return{id:K,type:"page",title:"",url:_,webSocketDebuggerUrl:`ws://127.0.0.1:${J}/devtools/page/${K}`}}finally{A.close()}}class oJ{ws;nextId=1;pending=new Map;eventListeners=new Map;closed=!1;constructor(J){this.ws=J}static connect(J){return new Promise((_,$)=>{let X=new B$(J);X.on("open",()=>{let A=new oJ(X);oJ.attachHandlers(A,X),_(A)}),X.on("error",(...A)=>{let G=A[0];$(new Error(`Failed to connect to CDP: ${G.message}`))})})}static fromWebSocket(J){let _=new oJ(J);return oJ.attachHandlers(_,J),_}static attachHandlers(J,_){_.on("message",($)=>{let X=typeof $==="string"?$:Buffer.from($).toString("utf-8");J.handleMessage(X)}),_.on("close",()=>{J.closed=!0;for(let[,$]of J.pending)$.reject(new Error("WebSocket closed"));J.pending.clear()}),_.on("error",(...$)=>{let X=$[0];for(let[,A]of J.pending)A.reject(X);J.pending.clear()})}async send(J,_){if(this.closed||this.ws.readyState!==SG)throw new Error("WebSocket is closed");let $=this.nextId++,X=JSON.stringify({id:$,method:J,params:_??{}});return new Promise((A,G)=>{this.pending.set($,{resolve:A,reject:G}),this.ws.send(X)})}onEvent(J,_){if(!this.eventListeners.has(J))this.eventListeners.set(J,new Set);return this.eventListeners.get(J).add(_),()=>{this.eventListeners.get(J)?.delete(_)}}waitForEvent(J,_=1e4){return new Promise(($,X)=>{let A=setTimeout(()=>{G(),X(new Error(`Timeout waiting for event '${J}' after ${_}ms`))},_),G=this.onEvent(J,(K)=>{clearTimeout(A),G(),$(K)})})}close(){if(!this.closed){this.closed=!0;try{this.ws.close()}catch{}}}handleMessage(J){let _;try{_=JSON.parse(J)}catch{return}if("id"in _&&typeof _.id==="number"){let $=_,X=this.pending.get($.id);if(X)if(this.pending.delete($.id),$.error)X.reject(new Error(`CDP error ${$.error.code}: ${$.error.message}`));else X.resolve($.result??{});return}if("method"in _&&typeof _.method==="string"){let $=_,X=this.eventListeners.get($.method);if(X)for(let A of X)try{A($.params??{})}catch{}}}}import{spawn as vG}from"node:child_process";import{createConnection as hG}from"node:net";import{tmpdir as bG}from"node:os";import{join as W6,dirname as fG}from"node:path";import{unlink as gG,unlinkSync as kG,mkdirSync as mG,existsSync as i_}from"node:fs";import aJ from"node:fs";var DG=typeof globalThis.Bun!=="undefined";function U$(J){let _="electron"in process.versions,$=J;try{$=aJ.realpathSync(J)}catch{}let X,A;if($.endsWith(".js")){if(!aJ.existsSync($))throw new Error(`No executable found: ${$} does not exist.`);X=$,A=!1}else if($.endsWith(".ts")){if(!aJ.existsSync($))throw new Error(`No executable found: ${$} does not exist.`);X=$,A=!0}else{let Q=$+".js",N=$+".ts";if(aJ.existsSync(Q)){try{X=aJ.realpathSync(Q)}catch{X=Q}A=!1}else if(aJ.existsSync(N)){try{X=aJ.realpathSync(N)}catch{X=N}A=!0}else throw new Error(`No executable found: neither ${Q} nor ${N} exists.`)}let G=process.execPath,K=!DG&&A?["--import","tsx",X]:[X];if(_)return{file:G,args:K,env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}};return{file:G,args:K,env:process.env}}var uG=null,cG=null,dG=null,lG=!1;function s0(){return cG??process.platform}function pG(){return uG??vG}function iG(){return dG??hG}function nG(J,_){let $=s0(),X=_??bG(),A=J.replace(/[^a-zA-Z0-9]/g,"_").slice(0,32);if($==="win32")return`\\\\.\\pipe\\airclaw-daemon-${A}`;return W6(X,`airclaw-daemon-${A}.sock`)}function P6(J,_){let $=J.split(`
|
|
94
|
+
`),X=$.pop()??"";for(let A of $){let G=A.trim();if(G)try{let K=JSON.parse(G);_(K)}catch{}}return X}class sJ{static instance=null;daemons=new Map;constructor(){}static getInstance(){if(!sJ.instance)sJ.instance=new sJ;return sJ.instance}async getOrCreateDaemon(J,_,$){if(this.daemons.has(J))return;let X=nG(J,$?.socketDir),A=$?.idleTimeoutMs??1200000;if(s0()==="win32"||i_(X)){let q={targetId:J,child:null,socketPath:X,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};this.daemons.set(J,q);try{await this.connectToDaemon(J);return}catch{if(this.daemons.delete(J),s0()!=="win32"&&i_(X))try{kG(X)}catch{}}}let G=fG(X);if(!i_(G)&&s0()!=="win32")try{mG(G,{recursive:!0})}catch{}let K={targetId:J,child:null,socketPath:X,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};if(this.daemons.set(J,K),lG)return;let Q=$_("agent","tools","chrome-session","daemon-worker")??W6(import.meta.dirname,"daemon-worker"),{file:N,args:R,env:Y}=U$(Q),H=pG()(N,[...R,"--target",J,"--ws-url",_,"--socket",X,"--idle-timeout",String(A)],{stdio:["ignore","pipe","pipe"],detached:!1,env:Y});K.child=H,H.on("exit",()=>{this.cleanupDaemon(J)}),H.on("error",()=>{this.cleanupDaemon(J)}),await new Promise((q,V)=>{let y=setTimeout(()=>{V(new Error("Daemon startup timeout"))},1e4),B=(M)=>{if(M.toString("utf8").includes("READY"))clearTimeout(y),H.stdout?.off("data",B),q()};H.stdout?.on("data",B)}),await this.connectToDaemon(J)}async connectToDaemon(J){let _=this.daemons.get(J);if(!_)throw new Error(`No daemon for target ${J}`);return new Promise(($,X)=>{let A=iG()(_.socketPath);A.on("connect",()=>{_.clientSocket=A,A.on("data",(G)=>{_.ndjsonBuffer=P6(_.ndjsonBuffer+G.toString("utf8"),(K)=>{let Q=_.pendingCommands.get(K.id);if(Q)_.pendingCommands.delete(K.id),Q.resolve(K)})}),A.on("close",()=>{_.clientSocket=null;for(let[,G]of _.pendingCommands)G.reject(new Error("Daemon socket closed"));_.pendingCommands.clear()}),A.on("error",()=>{}),$()}),A.on("error",(G)=>{X(new Error(`Failed to connect to daemon: ${G.message}`))}),setTimeout(()=>{if(!_.clientSocket)A.destroy(),X(new Error("Daemon connection timeout"))},5000)})}async sendCommand(J,_,$={}){let X=this.daemons.get(J);if(!X)throw new Error(`No daemon for target ${J}`);if(!X.clientSocket)throw new Error(`Daemon socket not connected for ${J}`);let A=X.commandId++,K=JSON.stringify({id:A,cmd:_,args:$})+`
|
|
95
|
+
`;return new Promise((Q,N)=>{X.pendingCommands.set(A,{resolve:Q,reject:N});try{X.clientSocket.write(K)}catch(R){X.pendingCommands.delete(A),N(R)}setTimeout(()=>{if(X.pendingCommands.has(A))X.pendingCommands.delete(A),N(new Error(`Command ${A} timed out`))},30000)})}hasDaemon(J){return this.daemons.has(J)}getSocketPath(J){return this.daemons.get(J)?.socketPath}stopDaemon(J){let _=this.daemons.get(J);if(_){if(_.clientSocket)_.clientSocket.destroy();if(_.child)_.child.kill("SIGTERM");this.cleanupDaemon(J)}}stopAll(){for(let J of this.daemons.keys())this.stopDaemon(J)}getActiveTargets(){return Array.from(this.daemons.keys())}__setClientSocket(J,_){let $=this.daemons.get(J);if($){if($.clientSocket=_,_)_.on("data",(X)=>{$.ndjsonBuffer=P6($.ndjsonBuffer+X.toString("utf8"),(A)=>{let G=$.pendingCommands.get(A.id);if(G)$.pendingCommands.delete(A.id),G.resolve(A)})}),_.on("close",()=>{$.clientSocket=null;for(let[,X]of $.pendingCommands)X.reject(new Error("Daemon socket closed"));$.pendingCommands.clear()})}}cleanupDaemon(J){let _=this.daemons.get(J);if(!_)return;if(_.clientSocket)_.clientSocket.destroy();if(_.child)_.child.kill("SIGTERM");for(let[,$]of _.pendingCommands)$.reject(new Error("Daemon stopped"));if(s0()!=="win32"&&i_(_.socketPath))gG(_.socketPath,()=>{});this.daemons.delete(J)}}import{writeFileSync as rG,mkdirSync as oG,existsSync as aG}from"node:fs";import{dirname as sG,join as n_}from"node:path";import{tmpdir as tG}from"node:os";var Z$={minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8};class r_ extends S{name="chrome_session";description=`Interact with Chrome browser via Chrome DevTools Protocol (CDP).
|
|
91
96
|
|
|
92
97
|
Core Commands:
|
|
93
98
|
- status: Check Chrome connectivity, version, and remote debugging status
|
|
@@ -122,13 +127,13 @@ Examples:
|
|
|
122
127
|
- chrome_session clickxy --target "ABC123" --x 100 --y 200
|
|
123
128
|
- chrome_session type --target "ABC123" --text "Hello World"
|
|
124
129
|
- chrome_session loadall --target "ABC123" --selector "button.load-more" --interval 500
|
|
125
|
-
- 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={},_,y=!1){super();this.config={minChromeVersion:J.minChromeVersion??Qy.minChromeVersion,daemonIdleTimeoutS:J.daemonIdleTimeoutS??Qy.daemonIdleTimeoutS,targetPrefixLength:J.targetPrefixLength??Qy.targetPrefixLength,...J.stealth?{stealth:J.stealth}:{}},this.workspace=_,this.restrictToWorkspace=y,this.daemonManager=xJ.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 y=J.command;if(!y)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 $=this.commands.get(y);if(!$)return this.formatError(`Unknown command '${y}'. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw`);try{return await $(J,_)}catch(X){let A=X instanceof Error?X.message:String(X);return this.formatError(`Command '${y}' failed: ${A}`)}}async handleStatus(){let J=this.config,_=await bX();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:y,versionInfo:$}=_,X=$.Browser.match(/(\w+)\/(\d+)/),A=X?.[1]??"Chrome",L=X?parseInt(X[2],10):0;if(L>0&&L<J.minChromeVersion)return this.formatResult({available:!1,reason:`Chrome version ${L} is below minimum required version ${J.minChromeVersion}`,hint:`Update Chrome to version ${J.minChromeVersion} or higher`,version:$.Browser,port:y,browser:A});return this.formatResult({available:!0,version:$.Browser,protocolVersion:$["Protocol-Version"],userAgent:$["User-Agent"],webSocketDebuggerUrl:$.webSocketDebuggerUrl,port:y,browser:A})}async handleList(){let J=a_();if(!J)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let _;try{let A=await fetch(`http://127.0.0.1:${J}/json/list`);if(A.ok)_=await A.json();else _=await Y_(J)}catch{_=await Y_(J)}let y=_.filter((A)=>A.type==="page"&&!A.url.startsWith("chrome://"));if(y.length===0)return this.formatResult({tabs:[],message:"No open tabs found"});let $=this.config.targetPrefixLength,X=y.map((A)=>({id:A.id.slice(0,$),fullId:A.id,title:A.title,url:A.url}));return this.formatResult({tabs:X,count:X.length})}async handleOpen(J){let _=a_();if(!_)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let y=J.url??"about:blank",$=this.config.targetPrefixLength;try{let X=await fetch(`http://127.0.0.1:${_}/json/new?${y}`,{method:"PUT"});if(X.ok){let A=await X.json();return this.formatResult({success:!0,id:A.id.slice(0,$),fullId:A.id,url:A.url,message:`Opened new tab: ${A.url}`})}}catch{}try{let X=await MX(_,y);return this.formatResult({success:!0,id:X.id.slice(0,$),fullId:X.id,url:X.url,message:`Opened new tab: ${X.url}`})}catch(X){return this.formatError(`Cannot open tab via HTTP or WebSocket on port ${_}: ${X instanceof Error?X.message:String(X)}. Run 'chrome_session status' for details.`)}}async handleStop(J){let _=J.target;if(_){let X=this.daemonManager.getActiveTargets().find((A)=>A.toUpperCase().startsWith(_.toUpperCase()));if(!X)return this.formatError(`No daemon found for target prefix '${_}'`);return this.daemonManager.stopDaemon(X),this.formatResult({success:!0,target:X.slice(0,this.config.targetPrefixLength),message:`Stopped daemon for target ${X.slice(0,this.config.targetPrefixLength)}`})}let y=this.daemonManager.getActiveTargets().length;if(y===0)return this.formatResult({success:!0,message:"No active daemons to stop"});return this.daemonManager.stopAll(),this.formatResult({success:!0,message:`Stopped ${y} daemon(s)`})}async handleSnap(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$={};if(J.depth!==void 0)$.depth=J.depth;let X=await this.sendDaemonCommand(_,y,"snap",$);if(!X.ok)return this.formatError(X.error??"Failed to get accessibility tree");return this.formatResult({tree:X.result?.tree,nodeCount:X.result?.nodeCount})}async handleShot(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.path,X=this.resolveScreenshotPath($),A={};if(X)A.path=X;if(J.selector)A.selector=J.selector;let L=await this.sendDaemonCommand(_,y,"shot",A);if(!L.ok)return this.formatError(L.error??"Failed to capture screenshot");if(X&&L.result?.data)this.saveScreenshot(X,L.result.data);return this.formatResult({path:X,dpr:L.result?.dpr,viewport:L.result?.viewport,message:X?`Screenshot saved to ${X}`:"Screenshot captured (base64 data in 'data' field)",data:X?void 0:L.result?.data})}async handleEval(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.expression;if(!$)return this.formatError("Missing required 'expression' parameter");let X=await this.sendDaemonCommand(_,y,"eval",{expression:$,awaitPromise:!0});if(!X.ok)return this.formatError(X.error??"JavaScript evaluation failed");return this.formatResult({ok:!0,result:X.result?.result,type:X.result?.type,subtype:X.result?.subtype})}async handleHtml(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$={};if(J.selector)$.selector=J.selector;if(J.outer!==void 0)$.outer=J.outer;let X=await this.sendDaemonCommand(_,y,"html",$);if(!X.ok)return this.formatError(X.error??"Failed to get HTML");return this.formatResult({html:X.result?.html,selector:X.result?.selector})}async handleNav(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.url;if(!$)return this.formatError("Missing required 'url' parameter");let X={url:$};if(J.timeout!==void 0)X.timeout=J.timeout;let A=await this.sendDaemonCommand(_,y,"nav",X);if(!A.ok)return this.formatError(A.error??"Navigation failed");return this.formatResult({ok:!0,url:A.result?.url,frameId:A.result?.frameId,loaderId:A.result?.loaderId,message:A.result?.message})}async handleNet(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=await this.sendDaemonCommand(_,y,"net",{});if(!$.ok)return this.formatError($.error??"Failed to get network timing");return this.formatResult({entries:$.result?.entries,count:$.result?.count})}async handleClick(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.selector;if(!$)return this.formatError("Missing required 'selector' parameter");let X=await this.sendDaemonCommand(_,y,"click",{selector:$});if(!X.ok)return this.formatError(X.error??"Click failed");return this.formatResult({ok:!0,selector:$,tag:X.result?.tag,text:X.result?.text,message:X.result?.message})}async handleClickxy(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.x,X=J.y;if(typeof $!=="number"||typeof X!=="number")return this.formatError("Missing required 'x' and 'y' parameters");let A=await this.sendDaemonCommand(_,y,"clickxy",{x:$,y:X});if(!A.ok)return this.formatError(A.error??"Click at coordinates failed");return this.formatResult({ok:!0,x:$,y:X,message:`Clicked at (${$}, ${X})`})}async handleType(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.text;if(!$)return this.formatError("Missing required 'text' parameter");let X=await this.sendDaemonCommand(_,y,"type",{text:$});if(!X.ok)return this.formatError(X.error??"Type failed");return this.formatResult({ok:!0,text:$,message:`Typed ${$.length} character(s)`})}async handleLoadall(J,_){let{targetId:y,wsUrl:$}=await this.resolveTarget(J.target),X=J.selector,A=J.interval??500;if(!X)return this.formatError("Missing required 'selector' parameter");let L=await this.sendDaemonCommand(y,$,"loadall",{selector:X,interval:A,timeout:300000});if(!L.ok)return this.formatError(L.error??"Loadall failed");return this.formatResult({ok:!0,selector:X,clickCount:L.result?.clickCount,timedOut:L.result?.timedOut,message:L.result?.message})}async handleEvalraw(J){let{targetId:_,wsUrl:y}=await this.resolveTarget(J.target),$=J.method,X=J.params??{};if(!$)return this.formatError("Missing required 'method' parameter");let A=await this.sendDaemonCommand(_,y,"evalraw",{method:$,params:X});if(!A.ok)return this.formatError(A.error??"Raw CDP command failed");return this.formatResult({ok:!0,method:$,result:A.result?.result})}async resolveTarget(J){if(!J)throw new Error("Missing required 'target' parameter. Use 'chrome_session list' to see available targets.");let _=a_();if(!_)throw new Error("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let y;try{let q=await fetch(`http://127.0.0.1:${_}/json/list`);if(q.ok)y=await q.json();else y=await Y_(_)}catch{y=await Y_(_)}let $=y.filter((q)=>q.type==="page"&&!q.url.startsWith("chrome://")),X=J.toUpperCase(),A=$.filter((q)=>q.id.toUpperCase().startsWith(X));if(A.length===0)throw new Error(`No target found matching prefix '${J}'`);if(A.length>1){let q=A.map((N)=>N.id.slice(0,this.config.targetPrefixLength)).join(", ");throw new Error(`Ambiguous prefix '${J}' matches ${A.length} targets: ${q}`)}let L=A[0];return{targetId:L.id,wsUrl:L.webSocketDebuggerUrl}}async sendDaemonCommand(J,_,y,$){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,y,$)}resolveScreenshotPath(J){if(!J)return;let _;if(J.startsWith("/"))_=J;else if(J.startsWith("./")||J.startsWith("../"))if(this.restrictToWorkspace&&this.workspace)_=J0(this.workspace,J);else _=J0(process.cwd(),J);else if(this.restrictToWorkspace&&this.workspace)_=J0(this.workspace,J);else _=J0(V4(),`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 y=E4(J);if(!Y4(y))U4(y,{recursive:!0});let $=Buffer.from(_,"base64");H4(J,$)}formatResult(J){return JSON.stringify(J,null,2)}formatError(J){return JSON.stringify({error:J},null,2)}}class y0 extends O{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 y=await this.relay.listTabs();return JSON.stringify(y,null,2)}case"navigate":{let y=Number(J.tabId),$=String(J.url??"");if(!y)return"Error: tabId is required";if(!$)return"Error: url is required";return await this.relay.navigate(y,$),`Navigated tab ${y} to ${$}`}case"click":{let y=Number(J.tabId),$=String(J.selector??"");if(!y)return"Error: tabId is required";if(!$)return"Error: selector is required";return await this.relay.click(y,$),`Clicked "${$}" in tab ${y}`}case"type":{let y=Number(J.tabId),$=String(J.text??""),X=J.selector?String(J.selector):void 0;if(!y)return"Error: tabId is required";if(!$)return"Error: text is required";return await this.relay.type(y,$,X),`Typed "${$}" in tab ${y}${X?` (selector: ${X})`:""}`}case"screenshot":{let y=Number(J.tabId),$=String(J.format??"png");if(!y)return"Error: tabId is required";return`Screenshot captured: ${(await this.relay.screenshot(y,$)).slice(0,100)}...`}case"read":{let y=Number(J.tabId);if(!y)return"Error: tabId is required";let $=await this.relay.evaluate(y,"document.body.innerText");return JSON.stringify($,null,2)}case"evaluate":{let y=Number(J.tabId),$=String(J.expression??"");if(!y)return"Error: tabId is required";if(!$)return"Error: expression is required";let X=await this.relay.evaluate(y,$);return JSON.stringify(X,null,2)}case"attach":{let y=Number(J.tabId);if(!y)return"Error: tabId is required";return await this.relay.attachTab(y),`Attached to tab ${y}`}case"detach":{let y=Number(J.tabId);if(!y)return"Error: tabId is required";return await this.relay.detachTab(y),`Detached from tab ${y}`}default:return`Unknown command: ${_}. Available commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach`}}catch(y){return`Error: ${y instanceof Error?y.message:String(y)}`}}}import f from"fs";import V_ from"path";import{randomUUID as b4}from"crypto";var M4="automations",Z4="index.json";function S4(J){return J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)}function Ky(J){return V_.join(J,M4)}function CX(J){return V_.join(Ky(J),Z4)}function $0(J,_){return V_.join(Ky(J),_)}function Ry(J,_){return V_.join($0(J,_),"rule.json")}function Hy(J,_){return V_.join($0(J,_),"script.js")}function Uy(J){let _=Ky(J);if(!f.existsSync(_))f.mkdirSync(_,{recursive:!0})}function X0(J){Uy(J);let _=CX(J);if(!f.existsSync(_))return{rules:[]};try{let y=f.readFileSync(_,"utf-8"),$=JSON.parse(y),X=!1;for(let A of $.rules){if(A.stepCount===void 0){let L=sJ(J,A.id);A.stepCount=L?.steps?.length||0,X=!0}if(A.toolType===void 0){let L=sJ(J,A.id);if(L?.toolType)A.toolType=L.toolType,X=!0}}if(X)A0(J,$);return $}catch{return{rules:[]}}}function A0(J,_){Uy(J);let y=CX(J),$=`${y}.tmp`;f.writeFileSync($,JSON.stringify(_,null,2)),f.renameSync($,y)}function wX(J){return X0(J).rules}function sJ(J,_){let y=Ry(J,_);if(!f.existsSync(y))return null;try{let $=f.readFileSync(y,"utf-8"),X=JSON.parse($),A=Hy(J,_);if(f.existsSync(A))X.scriptContent=f.readFileSync(A,"utf-8");return X}catch{return null}}function zX(J,_){Uy(J);let y=S4(_.name)||b4().slice(0,8),$=Date.now(),X={id:y,name:_.name,description:_.description,createdAt:$,updatedAt:$,enabled:!0,stepCount:_.steps.length,steps:_.steps,scriptPath:`automations/${y}/script.js`,tags:_.tags||[],source:_.source||"manual",..._.toolType?{toolType:_.toolType}:{},..._.variables?{variables:_.variables}:{}},A=$0(J,y);if(!f.existsSync(A))f.mkdirSync(A,{recursive:!0});let L=Ry(J,y);f.writeFileSync(L,JSON.stringify(X,null,2));let q=FX(X),N=Hy(J,y);f.writeFileSync(N,q);let G=X0(J),B={id:X.id,name:X.name,description:X.description,enabled:X.enabled,updatedAt:X.updatedAt,stepCount:X.steps.length};if(_.toolType)B.toolType=_.toolType;return G.rules.push(B),A0(J,G),X}function OX(J,_,y){let $=sJ(J,_);if(!$)return null;let X=Date.now(),A={...$,...y,id:$.id,createdAt:$.createdAt,updatedAt:X,stepCount:(y.steps||$.steps).length},L=Ry(J,_);if(f.writeFileSync(L,JSON.stringify(A,null,2)),y.steps){let G=FX(A),B=Hy(J,_);f.writeFileSync(B,G)}let q=X0(J),N=q.rules.findIndex((G)=>G.id===_);if(N>=0){let G={id:A.id,name:A.name,description:A.description,enabled:A.enabled,updatedAt:A.updatedAt,stepCount:A.steps.length};if(A.toolType)G.toolType=A.toolType;q.rules[N]=G,A0(J,q)}return A}function TX(J,_){let y=$0(J,_);if(!f.existsSync(y))return!1;f.rmSync(y,{recursive:!0,force:!0});let $=X0(J),X=$.rules.length;if($.rules=$.rules.filter((A)=>A.id!==_),$.rules.length!==X)return A0(J,$),!0;return!1}function FX(J){let _=new Date().toISOString();return`// Automation: ${J.name}
|
|
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}
|
|
126
131
|
// Tool: ${J.toolType??"auto-detect"}
|
|
127
132
|
// Generated: ${_}
|
|
128
133
|
// Description: ${J.description}
|
|
129
134
|
//
|
|
130
135
|
// Steps:
|
|
131
|
-
${J.steps.map((
|
|
136
|
+
${J.steps.map(($)=>`// ${$.order}. ${$.description}`).join(`
|
|
132
137
|
`)}
|
|
133
138
|
//
|
|
134
139
|
// Usage: node script.js [--port=6767]
|
|
@@ -143,38 +148,38 @@ fetch(URL, { method: 'POST' })
|
|
|
143
148
|
else console.error('Failed:', r.error);
|
|
144
149
|
})
|
|
145
150
|
.catch(e => console.error('Could not reach everclaw:', e.message));
|
|
146
|
-
`}var
|
|
147
|
-
`)}}return
|
|
148
|
-
`)}async resolveTabContext(){if(!this.browserTool)return{};let J=this.browserTool.name;if(J==="chrome_relay"){try{let _=await this.browserTool.execute({command:"list_tabs"})
|
|
151
|
+
`}var b6={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"}},e0=(J)=>new Promise((_)=>setTimeout(_,J));class C$ extends S{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;constructor(J,_,$){super();this.browserTool=_;this.stealthConfig=$;this.workspace=$X(J)}async execute(J,_){let $=String(J.command??"");try{switch($){case"list":{let X=I6(this.workspace);return JSON.stringify(X,null,2)}case"get":{let X=String(J.id??"");if(!X)return"Error: id is required for get command";let A=O0(this.workspace,X);if(!A)return`Error: Automation '${X}' not found`;return JSON.stringify(A,null,2)}case"save":{let X=J.id?String(J.id):void 0,A=String(J.name??"Untitled Automation"),G=String(J.description??""),K=J.steps||[],Q=J.tags||[];if(K.length===0)return"Error: At least one step is required";let N=this.browserTool?.name,R;if(X){let Y={name:A,description:G,steps:K,tags:Q};if(N)Y.toolType=N;if(R=D6(this.workspace,X,Y),!R)return`Error: Automation '${X}' not found for update`;return`Updated automation '${R.name}' (${R.id})`}else{let Y={name:A,description:G,steps:K,tags:Q,source:"conversation"};if(N)Y.toolType=N;return R=x6(this.workspace,Y),`Created automation '${R.name}' (${R.id})`}}case"delete":{let X=String(J.id??"");if(!X)return"Error: id is required for delete command";if(!v6(this.workspace,X))return`Error: Automation '${X}' not found or could not be deleted`;return`Deleted automation '${X}'`}case"run":{let X=String(J.id??"");if(!X)return"Error: id is required for run command";let A=O0(this.workspace,X);if(!A)return`Error: Automation '${X}' not found`;if(!A.enabled)return`Error: Automation '${A.name}' is disabled`;let G=J.variables;return this.executeAutomation(A,_?.signal,G)}default:return`Unknown command: ${$}. Available commands: list, get, save, delete, run`}}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}async executeAutomation(J,_,$){if(!this.browserTool)return"Error: No browser tool available. Enable chrome_session or chrome_relay to run automations.";if(J.toolType&&J.toolType!==this.browserTool.name)return`Error: Automation '${J.name}' requires ${J.toolType} but ${this.browserTool.name} is active. Change browser tool or update the automation.`;let X=[];X.push(`Running automation: ${J.name}`),X.push(`Tool: ${this.browserTool.name}`),X.push(`Steps: ${J.steps.length}`);let A=await this.resolveTabContext();if(!A.tabId&&!A.target)return"Error: Could not resolve tab context. Open a browser tab first.";let G=[...J.steps].sort((K,Q)=>K.order-Q.order);for(let K of G){if(_?.aborted){X.push(`Aborted at step ${K.order}`);break}if(K.stealth?.preDelay)await e0(K.stealth.preDelay);X.push(`[Step ${K.order}] ${K.description}`);try{let Q=this.resolveStep(K,J.variables,$),N=await this.executeStepWithRetries(Q,_,A),R=this.maskSensitiveValues(N,J.variables);if(X.push(` -> ${R.slice(0,200)}${R.length>200?"...":""}`),this.stealthConfig?.enabled){let[Y,H]=this.stealthConfig.interStepDelay;await e0(Y+Math.random()*(H-Y))}}catch(Q){let N=Q instanceof Error?Q.message:String(Q);if(K.optional)X.push(` -> Optional step failed (continuing): ${N}`);else return X.push(` -> FAILED: ${N}`),X.push(`Automation '${J.name}' stopped due to error.`),X.join(`
|
|
152
|
+
`)}}return X.push(`Automation '${J.name}' completed successfully.`),X.join(`
|
|
153
|
+
`)}async resolveTabContext(){if(!this.browserTool)return{};let J=this.browserTool.name;if(J==="chrome_relay"){try{let _=await this.browserTool.execute({command:"list_tabs"}),$=JSON.parse(_);if(Array.isArray($)&&$.length>0)return{tabId:($.find((A)=>A.active)||$[0]).id}}catch{}return{}}if(J==="chrome_session"){try{let _=await this.browserTool.execute({command:"list"}),$=JSON.parse(_);if($.tabs&&Array.isArray($.tabs)&&$.tabs.length>0)return{target:$.tabs[0].id}}catch{}return{}}return{}}resolveStep(J,_,$){let X=(K)=>{if(!K)return K;return K.replace(/\$\{(\w+)\}/g,(Q,N)=>{if($&&$[N]!==void 0)return $[N];if(_&&_[N]?.defaultValue!==void 0)return _[N].defaultValue;if(_&&_[N]?.required)throw new Error(`Required variable '${N}' not provided`);return`\${${N}}`})},A=X(J.target),G=X(J.value);return{...J,...A!==void 0?{target:A}:{},...G!==void 0?{value:G}:{}}}maskSensitiveValues(J,_){if(!_)return J;let $=J;for(let[X,A]of Object.entries(_))if(A.sensitive)$=$.replaceAll(`\${${X}}`,`[REDACTED:${X}]`);return $}async executeStepWithRetries(J,_,$){let X=1+(J.retries??0),A=J.retryDelayMs??1000,G;for(let K=1;K<=X;K++)try{let Q=await this.executeStepOnce(J,_,$);if(J.assert)await this.pollAssertion(J.assert,_,$);return Q}catch(Q){if(G=Q instanceof Error?Q:new Error(String(Q)),K<X)await e0(A)}throw G??new Error("Unknown error")}async executeStepOnce(J,_,$){if(!this.browserTool)throw new Error("No browser tool available");let X=this.browserTool.name,A=b6[X];if(!A)throw new Error(`Unsupported browser tool: ${X}`);let G=A[J.action];if(!G)throw new Error(`Action '${J.action}' not supported by ${X}`);let K={command:G};if(X==="chrome_relay"&&$.tabId)K.tabId=$.tabId;if(X==="chrome_session"&&$.target)K.target=$.target;switch(J.action){case"navigate":K.url=J.value??J.target??"";break;case"click":K.selector=J.target??"";break;case"type":if(K.text=J.value??"",J.stealth?.typingSpeed)K.typingSpeed=J.stealth.typingSpeed;break;case"read":break;case"screenshot":if(J.target)K.selector=J.target;break;case"eval":K.expression=J.value??"";break;case"wait":let Q=parseInt(J.value??"1000",10);return await e0(Q),`Waited ${Q}ms`;default:throw new Error(`Unknown action: ${J.action}`)}return this.browserTool.execute(K,_?{signal:_}:void 0)}toExpression(J){switch(J.check){case"selector_exists":return`!!document.querySelector(${JSON.stringify(J.value)})`;case"selector_text":return`(document.querySelector(${JSON.stringify(J.value)})?.textContent?.trim() ?? "") === ${JSON.stringify(J.expected??"")}`;case"url_contains":return`window.location.href.includes(${JSON.stringify(J.value)})`;case"eval_truthy":return`!!(${J.value})`}}isAssertionPassing(J,_){try{let $=JSON.parse(J);if(_==="chrome_session"){let X=$.result;if(X&&typeof X.value==="boolean")return X.value;if(X&&typeof X.value==="string")return X.value.length>0;if(X&&typeof X.value==="number")return X.value!==0;return $.result===!0}if(_==="chrome_relay")return $===!0;return!1}catch{return!1}}async pollAssertion(J,_,$){if(!this.browserTool)throw new Error("No browser tool available");let X=J.timeoutMs??5000,A=500,G=this.toExpression(J),K=Date.now();do{if(_?.aborted)throw new Error("Aborted during assertion");try{let Q=this.browserTool.name,R=b6[Q]?.eval;if(!R)throw new Error(`Evaluation not supported by ${Q}`);let Y={command:R,expression:G};if(Q==="chrome_relay"&&$.tabId)Y.tabId=$.tabId;if(Q==="chrome_session"&&$.target)Y.target=$.target;let H=await this.browserTool.execute(Y);if(this.isAssertionPassing(H,Q))return}catch{}if(Date.now()-K>=X)break;await e0(A)}while(Date.now()-K<X);throw new Error(`Assertion failed after ${X}ms: ${J.check} (${J.value})`)}}class J_{tools=new Map;guardEngine=null;register(J){this.tools.set(J.name,J)}unregister(J){return this.tools.delete(J)}clear(){this.tools.clear()}get(J){return this.tools.get(J)}getDefinitions(){return[...this.tools.values()].map((J)=>J.toSchema())}get toolNames(){return[...this.tools.keys()]}setGuardEngine(J){this.guardEngine=J}getGuardEngine(){return this.guardEngine}filterByNames(J){let _=new J_;_.guardEngine=this.guardEngine;for(let $ of J){let X=this.tools.get($);if(X)_.register(X)}return _}excludeByNames(J){let _=new Set(J),$=new J_;$.guardEngine=this.guardEngine;for(let[X,A]of this.tools)if(!_.has(X))$.register(A);return $}async execute(J,_,$){let X=this.tools.get(J);if(!X)return{kind:"error",content:`Error: Tool '${J}' not found. Available: ${this.toolNames.join(", ")}`,retryable:!1};try{if(u($?.signal),this.guardEngine){let K=this.guardEngine.guard(J,_);if(K&&!K.isSafe){let Q=K.findings.map((N)=>` - [${N.severity}] ${N.title}: ${N.description}`).join(`
|
|
149
154
|
`);return{kind:"error",content:`Security: Tool call blocked. The tool '${J}' was denied by the security guard.
|
|
150
155
|
|
|
151
156
|
Findings:
|
|
152
|
-
${
|
|
157
|
+
${Q}`,retryable:!1}}}let A=X.validateParams(_);if(A.length)return{kind:"error",content:`Error: Invalid parameters for tool '${J}': ${A.join("; ")}
|
|
153
158
|
|
|
154
|
-
[Analyze the error above and try a different approach.]`,retryable:!0};let
|
|
159
|
+
[Analyze the error above and try a different approach.]`,retryable:!0};let G=await X.execute(_,$);if(u($?.signal),G.startsWith("__TERMINAL__"))return{kind:"terminal",content:G.slice(12)};return{kind:"ok",content:G}}catch(A){if(l(A))throw A;return{kind:"error",content:`Error executing ${J}: ${String(A)}
|
|
155
160
|
|
|
156
|
-
[Analyze the error above and try a different approach.]`,retryable:!0}}}}function
|
|
161
|
+
[Analyze the error above and try a different approach.]`,retryable:!0}}}}function f6(J){return J.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g,"").trim()}function XK(J){return J.replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
157
162
|
|
|
158
|
-
`).trim()}function
|
|
159
|
-
`)}catch(
|
|
163
|
+
`).trim()}function AK(J){try{let _=new URL(J);if(!["http:","https:"].includes(_.protocol))return[!1,`Only http/https allowed, got '${_.protocol.replace(":","")}'`];if(!_.hostname)return[!1,"Missing domain"];return[!0,""]}catch(_){return[!1,String(_)]}}class O$ extends S{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"]};constructor(J,_=5){super();this.apiKey=J;this.maxResults=_}async execute(J,_){let $=String(J.query??""),X=Math.min(Math.max(Number(J.count??this.maxResults),1),10),A=this.apiKey||process.env.BRAVE_API_KEY||"";if(!A)return"Error: Brave Search API key not configured. Set tools.web.search.apiKey or BRAVE_API_KEY.";try{u(_?.signal);let G=new URL("https://api.search.brave.com/res/v1/web/search");G.searchParams.set("q",$),G.searchParams.set("count",String(X));let K=await fetch(G,{headers:{Accept:"application/json","X-Subscription-Token":A},..._?.signal?{signal:_.signal}:{}});if(!K.ok)return`Error: ${K.status} ${K.statusText}`;let N=(await K.json()).web?.results??[];if(!N.length)return`No results for: ${$}`;let R=[`Results for: ${$}`,""];return N.slice(0,X).forEach((Y,H)=>{if(R.push(`${H+1}. ${Y.title??""}`),R.push(` ${Y.url??""}`),Y.description)R.push(` ${Y.description}`)}),R.join(`
|
|
164
|
+
`)}catch(G){if(l(G))throw G;return`Error: ${String(G)}`}}}class F$ extends S{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"]};constructor(J=50000){super();this.maxChars=J}async execute(J,_){let $=String(J.url??""),X=String(J.extractMode??"markdown"),A=Number(J.maxChars??this.maxChars),[G,K]=AK($);if(!G)return JSON.stringify({error:`URL validation failed: ${K}`,url:$});try{u(_?.signal);let Q=await fetch($,{redirect:"follow",headers:{"User-Agent":"Mozilla/5.0"},..._?.signal?{signal:_.signal}:{}}),N=Q.headers.get("content-type")||"",R="",Y="raw";if(N.includes("application/json"))R=JSON.stringify(await Q.json(),null,2),Y="json";else{let V=await Q.text();if(N.includes("text/html")||/^\s*<!doctype|^\s*<html/i.test(V.slice(0,256)))R=X==="text"?f6(V):XK(f6(V)),Y="html";else R=V}let H=R.length>A,q=H?R.slice(0,A):R;return JSON.stringify({url:$,finalUrl:Q.url,status:Q.status,extractor:Y,truncated:H,length:q.length,text:q})}catch(Q){if(l(Q))throw Q;return JSON.stringify({error:String(Q),url:$})}}}function EJ(J){return GK.resolve(J.workspace)}function e_(J){let _=EJ(J);return J.restrictToWorkspace?_:void 0}function KK(J){let _=[NJ({name:"builtin-filesystem-tools",tools:[{name:"read_file",create:($)=>new d1(EJ($),e_($))},{name:"write_file",create:($)=>new l1(EJ($),e_($))},{name:"edit_file",create:($)=>new p1(EJ($),e_($))},{name:"list_dir",create:($)=>new i1(EJ($),e_($))}]}),NJ({name:"builtin-shell-tools",tools:[{name:"exec",create:($)=>new a1($.execConfig?.timeout??60,EJ($),!!$.restrictToWorkspace,$.execConfig?.pathAppend??"",new L0,$.rtkService,$.rtkConfig?.ultraCompact??!1)}]}),NJ({name:"builtin-web-tools",tools:[{name:"web_search",create:($)=>new O$($.braveApiKey??null)},{name:"web_fetch",create:()=>new F$}]})];if(J.bus)_.push(NJ({name:"builtin-messaging-tools",tools:[{name:"message",create:($)=>{if(!$.bus)throw new Error("Builtin message tool requires a message bus");let X=new n1(async(A)=>{if($.turn?.isCurrent&&!$.turn.isCurrent())return;await $.bus.publishOutbound(A)});if($.turn)X.setContext($.turn.channel,$.turn.chatId,$.turn.messageId);return X}}]}));if(J.subagents)_.push(NJ({name:"builtin-subagent-tools",tools:[{name:"spawn",create:($)=>{if(!$.subagents)throw new Error("Builtin spawn tool requires a subagent manager");let X=new s1($.subagents);if($.turn)X.setContext($.turn.channel,$.turn.chatId,$.turn.sessionKey,$.turn.systemPrompt);return X}}]}));if(J.cronService)_.push(NJ({name:"builtin-scheduler-tools",tools:[{name:"cron",create:($)=>{if(!$.cronService)throw new Error("Builtin cron tool requires a cron service");let X=new c1($.cronService);if($.turn)X.setContext($.turn.channel,$.turn.chatId);return X}}]}));if(J.sessionManager)_.push(NJ({name:"builtin-session-tools",tools:[{name:"session.info",create:($)=>{if(!$.sessionManager)throw new Error("Builtin session.info tool requires a session manager");let X=new J$;if(X.setSessionManager($.sessionManager),$.turn)X.setContext($.turn.sessionKey);return X}},{name:"session.anchor",create:($)=>{if(!$.sessionManager)throw new Error("Builtin session.anchor tool requires a session manager");let X=new _$;if(X.setSessionManager($.sessionManager),$.turn)X.setContext($.turn.sessionKey);return X}},{name:"session.search",create:($)=>{if(!$.sessionManager)throw new Error("Builtin session.search tool requires a session manager");let X=new t1;if(X.setSessionManager($.sessionManager),$.turn)X.setContext($.turn.sessionKey);return X}}]}));if(J.chromeSessionConfig?.enabled)_.push(NJ({name:"builtin-chrome-session-tools",tools:[{name:"chrome_session",create:($)=>new r_($.chromeSessionConfig,EJ($),!!$.restrictToWorkspace)}]}));if(J.browserRelay)_.push(NJ({name:"builtin-browser-relay-tools",tools:[{name:"chrome_relay",create:($)=>{if(!$.browserRelay)throw new Error("Builtin chrome_relay tool requires a browser relay server");return new o_($.browserRelay)}}]}));return _.push(NJ({name:"builtin-automation-tools",tools:[{name:"automation",create:($)=>{let X=$.browserRelay?new o_($.browserRelay):$.chromeSessionConfig?.enabled?new r_($.chromeSessionConfig,EJ($),!!$.restrictToWorkspace):void 0;return new C$(EJ($),X,$.chromeSessionConfig?.stealth)}}]})),_}function QK(J){return Q5(KK(J))}function g6(J){let _=new J_,$=QK(J);for(let X of $.tools.values())_.register(X.contribution.create(J));return _}class T${tasks=new Map;order=[];register(J,_,$,X){let A=new Date().toISOString(),G={id:J,type:_,label:$,sessionKey:X,createdAt:A,status:"pending",startedAt:null,completedAt:null,result:null,error:null};return this.tasks.set(J,G),this.order.push(J),this.enforceLimit(),G}transition(J,_,$,X){let A=this.tasks.get(J);if(!A)return;let G=new Date().toISOString(),K={status:_};if(_==="running"&&A.startedAt===null)K.startedAt=G;if(this.isTerminal(_)){if(K.completedAt=G,$!==void 0)K.result=$;if(X!==void 0)K.error=X}Object.assign(A,K)}get(J){return this.tasks.get(J)}getBySession(J){return[...this.tasks.values()].filter((_)=>_.sessionKey===J)}getRunning(){return[...this.tasks.values()].filter((J)=>J.status==="running")}getPending(){return[...this.tasks.values()].filter((J)=>J.status==="pending")}getAll(){return[...this.tasks.values()].map((J)=>({...J}))}isTerminal(J){return J==="completed"||J==="failed"||J==="killed"}prune(J=3600000){let _=Date.now(),$=[];for(let X of this.tasks.values())if(this.isTerminal(X.status)&&X.completedAt){let A=new Date(X.completedAt).getTime();if(_-A>J)$.push(X.id)}for(let X of $){this.tasks.delete(X);let A=this.order.indexOf(X);if(A!==-1)this.order.splice(A,1)}return $.length}enforceLimit(){while(this.order.length>100){let J=this.order.shift();if(!J)continue;let _=this.tasks.get(J);if(!_)continue;if(this.isTerminal(_.status))this.tasks.delete(J);else{this.order.unshift(J);break}}}count(){return this.tasks.size}countByStatus(){let J={pending:0,running:0,completed:0,failed:0,killed:0};for(let _ of this.tasks.values())J[_.status]++;return J}}var m6="EVERCLAW_SUBAGENT_RESULT ";function k6(J,_){let $=new Date().toLocaleString(),X=_??"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.";if(J)return`${J}
|
|
160
165
|
|
|
161
166
|
---
|
|
162
167
|
|
|
163
168
|
# Subagent Mode
|
|
164
169
|
|
|
165
|
-
Current Time: ${
|
|
170
|
+
Current Time: ${$}
|
|
166
171
|
|
|
167
|
-
${
|
|
172
|
+
${X}`;return`# Subagent
|
|
168
173
|
|
|
169
|
-
Current Time: ${
|
|
174
|
+
Current Time: ${$}
|
|
170
175
|
|
|
171
|
-
${
|
|
176
|
+
${X}`}async function u6(J){let _=g6({workspace:J.workspace,restrictToWorkspace:J.restrictToWorkspace,braveApiKey:J.braveApiKey,execConfig:J.execConfig}),$=J.definition;if($?.allowedTools&&$.allowedTools.length>0)_=_.filterByNames($.allowedTools);else if($?.deniedTools&&$.deniedTools.length>0)_=_.excludeByNames($.deniedTools);let X=$?.systemPromptSuffix,A;if(J.contextMode==="fork"&&J.existingMessages?.length){let K=X?`# Subagent Mode
|
|
172
177
|
|
|
173
|
-
${
|
|
178
|
+
${X}`:`# Subagent Mode
|
|
174
179
|
|
|
175
|
-
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.`;
|
|
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.`;A=J.existingMessages.map((Q,N)=>{if(N===0&&Q.role==="system"&&typeof Q.content==="string")return{...Q,content:`${Q.content}
|
|
176
181
|
|
|
177
182
|
---
|
|
178
183
|
|
|
179
|
-
${
|
|
180
|
-
`)}async function
|
|
184
|
+
${K}`};return Q}),A.push({role:"user",content:J.task})}else if(J.contextMode==="inherit-system"&&J.parentSystemPrompt)A=[{role:"system",content:k6(J.parentSystemPrompt,X)},{role:"user",content:J.task}];else A=J.existingMessages?[...J.existingMessages,{role:"user",content:J.task}]:[{role:"system",content:k6(void 0,X)},{role:"user",content:J.task}];let G="Task completed but no final response was generated.";for(let K=0;K<15;K++){u(J.signal);let Q=await J.provider.chat({messages:A,tools:_.getDefinitions(),model:J.model,temperature:J.temperature,maxTokens:J.maxTokens,...J.signal?{signal:J.signal}:{}});if(u(J.signal),Q.toolCalls.length){A.push({role:"assistant",content:Q.content??"",tool_calls:Q.toolCalls.map((N)=>({id:N.id,type:"function",function:{name:N.name,arguments:JSON.stringify(N.arguments)}}))});for(let N of Q.toolCalls){u(J.signal);let R=await _.execute(N.name,N.arguments,J.signal?{signal:J.signal}:{});u(J.signal);let Y=typeof R==="object"&&"kind"in R?R.content??String(R):String(R);A.push({role:"tool",tool_call_id:N.id,name:N.name,content:Y})}continue}G=Q.content??G;break}return G}class RK{bus;processExecutor;inlineExecutor;settings;running=new Map;controllers=new Map;sessionTasks=new Map;sessionGenerations=new Map;taskTracker=new T$;constructor(J,_,$,X){this.bus=J;this.processExecutor=_;this.inlineExecutor=$;this.settings=X}getTaskTracker(){return this.taskTracker}getTaskSnapshot(){return this.taskTracker.prune(),this.taskTracker.getAll()}async spawn(J){let _=NK().slice(0,8),$=J.label??(J.task.length>30?`${J.task.slice(0,30)}...`:J.task),X=this.getSessionGeneration(J.sessionKey),A=new AbortController;this.controllers.set(_,A),this.taskTracker.register(_,"subagent",$,J.sessionKey);let G=J.mode??"process",K=J.agentType?y5(J.agentType):void 0,Q=this.runSubagent(_,J.task,$,{channel:J.originChannel,chatId:J.originChatId,sessionKey:J.sessionKey,generation:X},G,J.provider,J.model,J.providerName,J.contextMode,J.parentSystemPrompt,K).finally(()=>{this.running.delete(_),this.controllers.delete(_);let N=this.sessionTasks.get(J.sessionKey);if(N){if(N.delete(_),!N.size)this.sessionTasks.delete(J.sessionKey)}});if(this.running.set(_,Q),!this.sessionTasks.has(J.sessionKey))this.sessionTasks.set(J.sessionKey,new Set);return this.sessionTasks.get(J.sessionKey).add(_),`Subagent [${$}] started (id: ${_}). I'll notify you when it completes.`}async runSubagent(J,_,$,X,A="process",G,K,Q,N,R,Y){let H=this.controllers.get(J)?.signal,q=A==="inline"?this.inlineExecutor:this.processExecutor;this.taskTracker.transition(J,"running");try{let V={...this.settings,task:_};if(H)V.signal=H;if(G)V.provider=G;if(K)V.model=K;if(Q)V.providerName=Q;if(N)V.contextMode=N;if(R)V.parentSystemPrompt=R;if(Y)V.agentType=Y.name;let y=await q.execute(V);if(y.status==="aborted"){this.taskTracker.transition(J,"killed");return}if(!this.isSessionCurrent(X.sessionKey,X.generation)){this.taskTracker.transition(J,"killed");return}if(y.status==="completed")this.taskTracker.transition(J,"completed",y.finalResult??void 0);else this.taskTracker.transition(J,"failed",void 0,y.errorMessage??void 0);await this.publishOutcome(X,_,$,y,J)}catch(V){if(l(V)){this.taskTracker.transition(J,"killed");return}if(!this.isSessionCurrent(X.sessionKey,X.generation)){this.taskTracker.transition(J,"killed");return}let y=V instanceof Error?V.message:String(V);this.taskTracker.transition(J,"failed",void 0,y);try{await this.publishOutcome(X,_,$,{status:"failed",errorMessage:y,failureAttribution:"exception"},J)}catch{}}}async publishOutcome(J,_,$,X,A){let G={kind:X.status==="completed"?"subagent_completed":"subagent_failed",taskId:A,label:$,status:X.status==="completed"?"completed":"failed",originalTask:_,...X.finalResult?{result:X.finalResult}:{},...X.errorMessage?{error:X.errorMessage}:{}},K=X.status==="completed"?X.finalResult??"Task completed.":X.errorMessage??"Subagent failed.",Q={channel:"system",senderId:"subagent",chatId:`${J.channel}:${J.chatId}`,content:K,metadata:{_notification:G}};await this.bus.publishInbound(Q)}async cancelBySession(J){this.sessionGenerations.set(J,this.getSessionGeneration(J)+1);let _=[...this.sessionTasks.get(J)??[]],$=0;for(let X of _){let A=this.controllers.get(X);if(!A||A.signal.aborted)continue;A.abort(),$+=1}return $}async cancelAll(){let J=[...this.sessionTasks.keys()],_=0;for(let $ of J)_+=await this.cancelBySession($);return _}getRunningCount(){return this.running.size}getSessionGeneration(J){return this.sessionGenerations.get(J)??0}isSessionCurrent(J,_){return this.getSessionGeneration(J)===_}}async function YK(){let J=[];for await(let _ of process.stdin)J.push(typeof _==="string"?_:_.toString("utf8"));return J.join("")}function S$(J){process.stdout.write(`${m6}${JSON.stringify(J)}
|
|
185
|
+
`)}async function HK(){let J=new AbortController,_=()=>J.abort();process.once("SIGTERM",_),process.once("SIGINT",_);try{let $=(await YK()).trim();if(!$)throw new Error("Missing subagent payload.");let X=JSON.parse($),A=GX();if(X.providerName)A.agents.defaults.provider=X.providerName;if(X.model)A.agents.defaults.model=X.model;let G=YX(A),K=await u6({...X,provider:G,signal:J.signal});S$({status:"completed",finalResult:K})}catch($){if(J.signal.aborted||l($)){S$({status:"aborted",errorMessage:null,failureAttribution:"aborted"});return}let X=$ instanceof Error?$.message:String($);console.error($ instanceof Error&&$.stack?$.stack:X),S$({status:"failed",errorMessage:X,failureAttribution:"exception"}),process.exitCode=1}finally{process.removeListener("SIGTERM",_),process.removeListener("SIGINT",_)}}HK();
|