everclaw 0.3.18 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,62 +1,58 @@
1
1
  #!/usr/bin/env node
2
- // @bun
3
- var hX=Object.create;var{getPrototypeOf:vX,defineProperty:Cy,getOwnPropertyNames:fX}=Object;var kX=Object.prototype.hasOwnProperty;var wy=(J,_,y)=>{y=J!=null?hX(vX(J)):{};let $=_||!J||!J.__esModule?Cy(y,"default",{value:J,enumerable:!0}):y;for(let X of fX(J))if(!kX.call($,X))Cy($,X,{get:()=>J[X],enumerable:!0});return $};var a=(J,_)=>()=>(_||J((_={exports:{}}).exports,_),_.exports);var aJ=import.meta.require;var zy=a((I4,gX)=>{gX.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 Wy=a((D4,LJ)=>{var G0=aJ("fs"),Z_=aJ("path"),cX=aJ("os"),uX=aJ("crypto"),mX=zy(),B0=mX.version,dX=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function lX(J){let _={},y=J.toString();y=y.replace(/\r\n?/mg,`
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
- `).trim()||null,toolCalls:X,finishReason:X.length?"tool_calls":y.status??"stop",usage:{prompt_tokens:y.usage?.input_tokens??0,completion_tokens:y.usage?.output_tokens??0,total_tokens:y.usage?.total_tokens??0},reasoningContent:null}}async chat(J){try{return v(J.signal),this.requestFormat==="v1/responses"?await this.responses(J):await this.chatCompletions(J)}catch(_){if(k(_))throw _;return{content:`Error calling LLM: ${String(_)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}}import{webcrypto as $1}from"crypto";var y1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var bA=128,ZJ,hJ;function MA(J){if(!ZJ||ZJ.length<J)ZJ=Buffer.allocUnsafe(J*bA),$1.getRandomValues(ZJ),hJ=0;else if(hJ+J>ZJ.length)$1.getRandomValues(ZJ),hJ=0;hJ+=J}function O_(J=21){MA(J|=0);let _="";for(let y=hJ-J;y<hJ;y++)_+=y1[ZJ[y]&63];return _}class T_{apiKey;apiBase;defaultModel;static DEFAULT_BASE="https://generativelanguage.googleapis.com/v1beta";constructor(J,_,y){this.apiKey=J;this.apiBase=_;this.defaultModel=y}getDefaultModel(){return this.defaultModel}resolveModel(J){let _=J.trim();if(_.includes("/")){let y=_.split("/",2),$=y[0],X=y[1];if(!$||!X)return _;let A=$.toLowerCase();if(A==="gemini"||A==="google")_=X}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 _=[],y=[];for(let A of J.messages){let L=String(A.role??"");if(L==="system"){let q=this.asText(A.content).trim();if(q)_.push(q);continue}if(L==="user"){let q=this.asText(A.content).trim();if(!q)continue;y.push({role:"user",parts:[{text:q}]});continue}if(L==="assistant"||L==="model"){let q=[],N=this.asText(A.content).trim();if(N)q.push({text:N});let G=Array.isArray(A.tool_calls)?A.tool_calls:[];for(let B of G){let R=B.function;if(!R?.name)continue;q.push({functionCall:{name:R.name,args:this.parseToolArgs(R.arguments)}})}if(q.length)y.push({role:"model",parts:q});continue}if(L==="tool"){let q=typeof A.name==="string"?A.name:"";if(!q)continue;let N=this.asText(A.content);y.push({role:"user",parts:[{functionResponse:{name:q,response:{result:N}}}]})}}if(!y.length)y.push({role:"user",parts:[{text:"Hello"}]});let $={contents:y,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)$.systemInstruction={parts:[{text:_.join(`
8
-
9
- `)}]};let X=(J.tools??[]).map((A)=>A).filter((A)=>A.type==="function"&&A.function?.name).map((A)=>({name:A.function.name,description:A.function?.description??"",parameters:A.function?.parameters??{type:"object",properties:{}}}));if(X.length)$.tools=[{functionDeclarations:X}],$.toolConfig=J.toolChoice==="required"?{functionCallingConfig:{mode:"ANY",allowedFunctionNames:X.map((A)=>A.name)}}:{functionCallingConfig:{mode:"AUTO"}};if(J.imageOutput)$.responseModalities=["TEXT","IMAGE"];return $}async chat(J){try{v(J.signal);let _=this.resolveModel(J.model??this.defaultModel),$=`${(this.apiBase??T_.DEFAULT_BASE).replace(/\/$/,"")}/models/${encodeURIComponent(_)}:generateContent`,X=this.toGemini(J),A=await fetch($,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":this.apiKey},body:JSON.stringify(X),...J.signal?{signal:J.signal}:{}}),L=await A.json();if(!A.ok)return{content:`Error calling LLM: ${L?.error?.message??JSON.stringify(L)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let q=L?.candidates?.[0],N=q?.content?.parts??[],G=N.filter((K)=>typeof K?.text==="string").map((K)=>String(K.text)),B=N.filter((K)=>K?.functionCall?.name).map((K)=>({id:O_(9),name:String(K.functionCall.name),arguments:this.parseToolArgs(K.functionCall.args)})),R={};if(L?.usageMetadata)R.prompt_tokens=Number(L.usageMetadata.promptTokenCount??0),R.completion_tokens=Number(L.usageMetadata.candidatesTokenCount??0),R.total_tokens=Number(L.usageMetadata.totalTokenCount??0);let Q=String(q?.finishReason??"STOP").toLowerCase();return{content:G.length?G.join(`
10
- `):null,toolCalls:B,finishReason:Q,usage:R,reasoningContent:null}}catch(_){if(k(_))throw _;return{content:`Error calling LLM: ${String(_)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}}class vJ{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,_,y,$){this.apiKey=J;this.apiBase=_;this.defaultModel=y;this.providerName=$}getDefaultModel(){return this.defaultModel}resolveModel(J){let _=(y)=>y.toLowerCase().replace(/-/g,"_");if(J.includes("/")){let y=J.split("/",2),$=y[0],X=y[1];if(!$||!X)return J;if(_($)==="github_copilot")return`github_copilot/${X}`;if(_($)==="openai_codex")return`openai_codex/${X}`;if(_($)==="groq"){if(X==="compound"||X==="compound-mini")return`groq/${X}`;return X}if(_($)==="ollama")return X}return J}async chat(J){let y={model:this.resolveModel(J.model??this.defaultModel),messages:y_(J.messages),max_tokens:Math.max(1,J.maxTokens??4096),temperature:J.temperature??0.7};if(J.tools?.length)y.tools=J.tools,y.tool_choice=J.toolChoice??"auto";if(J.reasoning)y.reasoning_effort="medium";if(J.imageOutput)y.include_image_output=!0;try{v(J.signal);let $=(this.providerName??"").trim();if($&&vJ.UNSUPPORTED_PROVIDERS.has($))return{content:`Error calling LLM: provider '${$}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let X=this.apiBase??($?vJ.DEFAULT_BASE_BY_PROVIDER[$]:void 0)??(this.apiKey?.startsWith("sk-or-")?vJ.DEFAULT_BASE_BY_PROVIDER.openrouter:void 0);if(!X)return{content:`Error calling LLM: api_base not configured. Set provider/api_base in ${eJ} or run everclaw onboard.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let A={"Content-Type":"application/json"};if(this.apiKey)A.Authorization=`Bearer ${this.apiKey}`;let L=await fetch(`${X.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:A,body:JSON.stringify(y),...J.signal?{signal:J.signal}:{}}),q=await L.json();if(!L.ok){let B=q?.error?.code??"",R=q?.error?.message??JSON.stringify(q);if(B==="model_not_found")return{content:`Error calling LLM: ${R}
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:
12
- ${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 s from"fs";import rJ from"path";import yJ from"fs";import d from"path";function yX(J){let _=d.resolve(J);while(_!=="/"&&_!==".")try{return yJ.lstatSync(_),_}catch{let y=d.dirname(_);if(y===_)break;_=y}return _||"/"}function $X(J,_){let y=d.resolve(J),$=d.resolve(_),X=$.endsWith(d.sep)?$.slice(0,-1):$,A=y===X||y.startsWith(X+d.sep);if(!yJ.existsSync(X))return A;try{let L=X;try{L=yJ.realpathSync.native(X)}catch{}if(yJ.existsSync(y)){let G=yJ.realpathSync.native(y);return G===L||G.startsWith(L+d.sep)}let q=yX(y);if(q===L||q===X)return!0;if(q!=="/")try{let G=yJ.realpathSync.native(q);if(G===L||G.startsWith(L+d.sep))return!0;if(!A)return!1}catch{return A}let N=y;while(N!=="/"&&N!=="."){let G=d.dirname(N);if(G===N)break;try{if(yJ.lstatSync(G).isSymbolicLink()){let R=yJ.realpathSync.native(G);if(R!==L&&!R.startsWith(L+d.sep))return!1}}catch{}N=G}return A}catch{return!1}}function XX(J,_){let y=d.resolve(J),$=d.resolve(_);if(!$X(J,_))throw new Error(`Path '${J}' is outside allowed workspace '${_}'`);let X=d.dirname(y),A=yX(X),L=$;try{if(yJ.existsSync($))L=yJ.realpathSync.native($)}catch{}if(A!=="/"&&A!==L)try{let q=yJ.realpathSync.native(A);if(q!==L&&!q.startsWith(L+d.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 AX(J,_){if(!$X(J,_))throw new Error(`Path '${J}' is outside allowed workspace '${_}'`)}function p_(J,_,y,$=!1){let X=J.startsWith("~")?rJ.join(process.env.USERPROFILE||process.env.HOME||"",J.slice(1)):J,A=rJ.isAbsolute(X)?X:_?rJ.join(_,X):X,L=rJ.resolve(A);if(y)try{if($)XX(L,y);else AX(L,y)}catch(q){throw new Error(q instanceof Error?q.message:`Path ${J} validation failed`)}return L}class a0 extends O{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 y=p_(String(J.path),this.workspace,this.allowedDir);if(!s.existsSync(y))return`Error: File not found: ${String(J.path)}`;if(!s.statSync(y).isFile())return`Error: Not a file: ${String(J.path)}`;return s.readFileSync(y,"utf8")}catch(y){return`Error reading file: ${String(y)}`}}}class t0 extends O{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 y=p_(String(J.path),this.workspace,this.allowedDir,!0);s.mkdirSync(rJ.dirname(y),{recursive:!0});let $=String(J.content??"");return s.writeFileSync(y,$,"utf8"),`Successfully wrote ${$.length} bytes to ${y}`}catch(y){return`Error writing file: ${String(y)}`}}}class e0 extends O{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 y=p_(String(J.path),this.workspace,this.allowedDir,!0);if(!s.existsSync(y))return`Error: File not found: ${String(J.path)}`;let $=s.readFileSync(y,"utf8"),X=String(J.old_text??""),A=String(J.new_text??"");if(!$.includes(X))return`Error: old_text not found in ${String(J.path)}. Verify the file content.`;if($.split(X).length-1>1)return`Warning: old_text appears ${$.split(X).length-1} times. Please provide more context to make it unique.`;return s.writeFileSync(y,$.replace(X,A),"utf8"),`Successfully edited ${y}`}catch(y){return`Error editing file: ${String(y)}`}}}class Jy extends O{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 y=p_(String(J.path),this.workspace,this.allowedDir);if(!s.existsSync(y))return`Error: Directory not found: ${String(J.path)}`;if(!s.statSync(y).isDirectory())return`Error: Not a directory: ${String(J.path)}`;let $=s.readdirSync(y).sort().map((X)=>{let A=rJ.join(y,X);return`${s.statSync(A).isDirectory()?"[DIR]":"[FILE]"} ${X}`});if(!$.length)return`Directory ${String(J.path)} is empty`;return $.join(`
14
- `)}catch(y){return`Error listing directory: ${String(y)}`}}}class _y extends O{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,_,y){this.defaultChannel=J,this.defaultChatId=_,this.defaultMessageId=y??null}setSendCallback(J){this.sendCallback=J}async execute(J,_){let y=String(J.content??""),$=String(J.channel??this.defaultChannel),X=String(J.chat_id??this.defaultChatId),A=String(J.message_id??this.defaultMessageId??""),L=Array.isArray(J.media)?J.media:[];if(!$||!X)return"Error: No target channel/chat specified";if(!this.sendCallback)return"Error: Message sending not configured";try{await this.sendCallback({channel:$,chatId:X,content:y,media:L,metadata:{message_id:A}});let q=$===this.defaultChannel&&X===this.defaultChatId,N=`Message sent to ${$}:${X}${L.length?` with ${L.length} attachments`:""}`;return q?`__TERMINAL__${N}`:N}catch(q){return`Error sending message: ${String(q)}`}}}import $y from"path";import{spawn as LX}from"child_process";var xq={"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 yy(J){return{...xq[J]}}class oJ{async run(J){let _=Math.max(1,J.maxCaptureBytes??1048576),y=typeof J.timeoutMs==="number"&&Number.isFinite(J.timeoutMs)&&J.timeoutMs>0?J.timeoutMs:null,$=this.launch(J);if($ instanceof Error)return{status:"failed",pid:null,stdout:"",stderr:"",exitCode:null,signal:null,failureAttribution:"spawn_error",cleanupTriggered:!1,cleanupReason:null,errorMessage:$.message};let{child:X,spawnError:A}=$;if(J.stdinText!=null)X.stdin?.end(J.stdinText,"utf8");else X.stdin?.end();let L="",q="",N=!1,G=null,B=!1,R=(E,C)=>{let j=typeof E==="string"?E:E.toString("utf8"),P=_-Buffer.byteLength(C);if(P<=0)return C;return C+j.slice(0,P)};X.stdout?.on("data",(E)=>{L=R(E,L)}),X.stderr?.on("data",(E)=>{q=R(E,q)});let Q=null,K=(E)=>{if(N)return;N=!0,G=E,B=E==="timeout",this.killChild(X,"SIGTERM"),Q=setTimeout(()=>this.killChild(X,"SIGKILL"),250),Q.unref?.()},Y=()=>K("abort");if(J.signal?.aborted)Y();else J.signal?.addEventListener("abort",Y,{once:!0});let Z=y!=null?setTimeout(()=>K("timeout"),y):null;Z?.unref?.();let S=await new Promise((E)=>{let C=!1,j=(P)=>{if(C)return;C=!0,E(P)};X.once("error",(P)=>{A.current=P,j({code:null,signal:null})}),X.once("close",(P,l)=>j({code:P,signal:l}))});if(Z)clearTimeout(Z);if(Q)clearTimeout(Q);if(J.signal?.removeEventListener("abort",Y),G==="abort")return{status:"aborted",pid:X.pid??null,stdout:L,stderr:q,exitCode:S.code,signal:S.signal,failureAttribution:"aborted",cleanupTriggered:N,cleanupReason:G,errorMessage:null};if(B)return{status:"failed",pid:X.pid??null,stdout:L,stderr:q,exitCode:S.code,signal:S.signal,failureAttribution:"timeout",cleanupTriggered:N,cleanupReason:G,errorMessage:null};if(A.current)return{status:"failed",pid:X.pid??null,stdout:L,stderr:q,exitCode:S.code,signal:S.signal,failureAttribution:"spawn_error",cleanupTriggered:N,cleanupReason:G,errorMessage:A.current.message};if(S.code===0)return{status:"ok",pid:X.pid??null,stdout:L,stderr:q,exitCode:0,signal:S.signal,failureAttribution:"none",cleanupTriggered:N,cleanupReason:G,errorMessage:null};return{status:"failed",pid:X.pid??null,stdout:L,stderr:q,exitCode:S.code,signal:S.signal,failureAttribution:S.signal?"signal":"exit_code",cleanupTriggered:N,cleanupReason:G,errorMessage:null}}launch(J){try{return{child:J.command.kind==="shell"?LX(J.command.command,{cwd:J.cwd,env:J.env,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}):LX(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 Xy extends O{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,_,y=!1,$="",X=new oJ,A,L=!1){super();this.timeout=J;this.workingDir=_;this.restrictToWorkspace=y;this.pathAppend=$;this.runner=X;this.rtkService=A;this.rtkUltraCompact=L}guard(J,_){let y=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((X)=>X.test(y)))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 X=J.match(/[A-Za-z]:\\[^\s"']+/g)??[];for(let A of X){let L=$y.resolve(A),q=$y.resolve(_);if(!L.startsWith(q))return"Error: Command blocked by safety guard (path outside working dir)"}}return null}async execute(J,_){let y=String(J.command??""),$=String(J.working_dir??this.workingDir??process.cwd()),X=this.guard(y,$);if(X)return X;v(_?.signal);let A=yy("tool.exec"),L={...process.env};if(this.pathAppend)L.PATH=`${L.PATH??""}${$y.delimiter}${this.pathAppend}`;if(A.mode!=="local-process")return"Error: exec tool requires local-process isolation";let q={command:{kind:"shell",command:y},cwd:$,env:L,timeoutMs:this.timeout*1000,maxCaptureBytes:1048576};if(_?.signal)q.signal=_.signal;let N=await this.runner.run(q);if(N.status==="aborted")throw U0();if(N.failureAttribution==="timeout")return`Error: Command timed out after ${this.timeout} seconds`;let G=N.stdout?`${N.stdout}${N.status==="failed"?`
15
- `:""}`:"";if(this.rtkService?.getRuntime().available&&G)try{let Y=await this.rtkService.compress({command:y,stdout:G,stderr:N.stderr,exitCode:N.exitCode,ultraCompact:this.rtkUltraCompact});if(Y.compressed)G=Y.stdout}catch{}let B=N.stderr.trim()?`STDERR:
16
- ${N.stderr}
17
- `:"",R=N.status==="failed"&&typeof N.exitCode==="number"?`
18
- Exit code: ${N.exitCode}`:"",Q=N.status==="failed"&&N.signal?`
19
- Signal: ${N.signal}`:"",K=`${G}${B}${R}${Q}`.trim();if(K)return K.length>1e4?`${K.slice(0,1e4)}
20
- ... (truncated, ${K.length-1e4} more chars)`:K;if(N.status==="failed")return N.errorMessage?`Error executing command: ${N.errorMessage}`:"Error executing command";return"(no output)"}}var qX={general:{name:"general",description:"General-purpose subagent with full tool access",systemPromptSuffix:"Complete the assigned task using all available tools."},researcher:{name:"researcher",description:"Read-only researcher \u2014 no file modifications",systemPromptSuffix:"Research and report findings. Do NOT modify any files.",allowedTools:["read_file","list_files","search","web_search","web_fetch","session.info","session.search"]},coder:{name:"coder",description:"Code modification specialist",systemPromptSuffix:"Implement the requested code changes.",deniedTools:["web_search","web_fetch"]}};function NX(J){return qX[J]}function GX(){return Object.values(qX)}class Ay extends O{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: ${GX().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,_,y=`${J}:${_}`,$){this.originChannel=J,this.originChatId=_,this.sessionKey=y,this.parentSystemPrompt=$}async execute(J,_){let y=J.context??"fresh",$=J.type??"general",X={task:String(J.task??""),label:J.label!=null?String(J.label):null,originChannel:this.originChannel,originChatId:this.originChatId,sessionKey:this.sessionKey,contextMode:y,agentType:$};if(J.model!=null)X.model=String(J.model);if(J.provider!=null)X.providerName=String(J.provider);if(y==="fork"&&this.parentSystemPrompt)X.parentSystemPrompt=this.parentSystemPrompt;return this.manager.spawn(X)}}class Ly extends O{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 y=String(J.query??""),$=typeof J.limit==="number"?Math.min(Math.max(1,Math.floor(J.limit)),100):10;if(!y)return"Error: Query cannot be empty";let A=this.sessionManager.getOrCreate(this.sessionKey).search(y,$);return JSON.stringify(A,null,2)}}import HX from"fs";import s_ from"path";import UX from"os";import R_ from"fs";import n_ from"path";var Iq={"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 i_(J){if(!J)return 0;let _=typeof J==="string"?J:JSON.stringify(J);return Math.ceil(_.length/4)}function BX(J,_){if(_){let $=_.providers?.[_.agents.defaults.provider]?.models?.find((X)=>X.id.toLowerCase()===J.toLowerCase())?.capabilities;if($?.contextWindow)return $.contextWindow;for(let X of _.customLlmProviders??[]){let A=X.models.find((L)=>L.id.toLowerCase()===J.toLowerCase());if(A?.capabilities?.contextWindow)return A.capabilities.contextWindow}}let y=J.toLowerCase();for(let[$,X]of Object.entries(Iq))if($.toLowerCase()===y||y.includes($.toLowerCase()))return X;return 128000}var QX=1000,Dq=250,r_=`
21
- ... (truncated for archival)`;function KX(J){return Math.max(0,Math.floor(J*4))}function hq(J,_){if(_<=0)return"";let y=KX(_);if(J.length<=y)return J;let $=Math.max(0,y-r_.length);return`${r_}${J.slice(-$)}`}function vq(J,_){if(_<=0||J.length===0)return{text:"",omittedLines:J.length};let y=KX(_),$=[],X=0,A=0;for(let L=J.length-1;L>=0;L--){let q=J[L],N=$.length?1:0,G=y-X-N;if(G<=0){A=L+1;break}if(q.length<=G){$.unshift(q),X+=q.length+N;continue}let B=Math.max(0,G-r_.length);$.unshift(`${r_}${q.slice(-B)}`),X=y,A=L;break}return{text:$.join(`
22
- `),omittedLines:A}}var fq=[{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 kq(J){let _=J.match(/```(?:json)?\s*([\s\S]*?)```/i);if(_?.[1])return _[1].trim();let y=J.indexOf("{"),$=J.lastIndexOf("}");if(y===-1||$===-1||$<y)return null;return J.slice(y,$+1).trim()}function gq(J){if(!J)return null;let _=kq(J.trim());if(!_)return null;try{let y=JSON.parse(_);if(!y||typeof y!=="object"||Array.isArray(y))return null;let $=y;if($.history_entry==null&&$.memory_update==null)return null;return $}catch{return null}}class o_{memoryDir;memoryFile;historyFile;constructor(J,_){let y=n_.join(J,"memory");this.memoryDir=_?n_.join(y,_):y,R_.mkdirSync(this.memoryDir,{recursive:!0}),this.memoryFile=n_.join(this.memoryDir,"MEMORY.md"),this.historyFile=n_.join(this.memoryDir,"HISTORY.md")}readLongTerm(){return R_.existsSync(this.memoryFile)?R_.readFileSync(this.memoryFile,"utf8"):""}writeLongTerm(J){R_.writeFileSync(this.memoryFile,J,"utf8")}appendHistory(J){R_.appendFileSync(this.historyFile,`${J.trim()}
23
-
24
- `,"utf8")}getMemoryContext(){let J=this.readLongTerm();return J?`## Long-term Memory
25
- ${J}`:""}async consolidate(J,_,y,$){let X=$?.archiveAll??!1,A=$?.memoryWindow??50,L=[],q=0;if(X)L=J.messages,q=0;else{if(q=Math.floor(A/2),J.messages.length<=q)return!0;if(J.messages.length-J.lastConsolidated<=0)return!0;if(L=J.messages.slice(J.lastConsolidated,J.messages.length-q),!L.length)return!0}let N=[],G=[];for(let F of L)if(F._type==="anchor")N.push(F);else G.push(F);let B=[];for(let F of N)B.push(`[ANCHOR] ${F.name}: ${F.summary??"(no summary)"}`);for(let F of G){if(!F.content&&!F._full_content)continue;let $J=Array.isArray(F.tools_used)&&F.tools_used.length?` [tools: ${F.tools_used.join(", ")}]`:"",m=F._full_content??F.content;B.push(`[${String(F.timestamp??"?").slice(0,16)}] ${String(F.role).toUpperCase()}${$J}: ${String(m)}`)}let R=this.readLongTerm(),Q=B.join(`
26
- `),K=R||"(empty)",Y="## Conversation to Process",Z=Q,S=i_(`Process this conversation and call the save_memory tool with your consolidation.
2
+ import"dotenv/config";import wt from"node:fs";import Un from"node:path";import ir from"node:fs";import ut from"node:os";import J from"node:path";import{fileURLToPath as ar}from"node:url";var He=".everclaw",K="~/.everclaw/config.json",dt=J.join("~",He,"workspace");function mt(s=ut.homedir()){return J.join(s,He,"workspace")}function gt(s=ut.homedir()){return J.join(s,He,"config.json")}function lr(){let s=ar(import.meta.url),t=J.dirname(s);return s.endsWith("/index.js")||s.endsWith("\\index.js")?t:J.resolve(t,"..")}var cr=lr();function pt(...s){let t=J.resolve(cr,...s);if(!ir.existsSync(t))throw new Error(`Runtime asset not found: ${t}`);return t}var ur=[{spec:{name:"zai",keywords:["zai"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://api.z.ai/api/coding/paas/v4"},models:["glm-5-turbo"]},{spec:{name:"openrouter",displayName:"OpenRouter",keywords:["openrouter"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://openrouter.ai/api/v1",detectByKeyPrefix:"sk-or-",detectByBaseKeyword:"openrouter"},models:["anthropic/claude-opus-4-1","anthropic/claude-sonnet-4","openai/gpt-4.1","google/gemini-2.5-pro"]},{spec:{name:"aihubmix",displayName:"AIHubMix",keywords:["aihubmix"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://aihubmix.com/v1",detectByBaseKeyword:"aihubmix"},models:[]},{spec:{name:"siliconflow",displayName:"SiliconFlow",keywords:["siliconflow"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://api.siliconflow.cn/v1",detectByBaseKeyword:"siliconflow"},models:["openai/deepseek-ai/DeepSeek-R1"]},{spec:{name:"volcengine",displayName:"VolcEngine",keywords:["volcengine","volces","ark"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://ark.cn-beijing.volces.com/api/v3",detectByBaseKeyword:"volces"},models:["volcengine/deepseek-r1-250120"]},{spec:{name:"anthropic",displayName:"Anthropic",keywords:["anthropic","claude"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["anthropic/claude-opus-4-5","anthropic/claude-sonnet-4"]},{spec:{name:"openai",displayName:"OpenAI",keywords:["openai","gpt"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["gpt-5.2","gpt-5.2-pro","gpt-5.3-codex","gpt-5.2-codex","gpt-5.1","gpt-5.1-codex","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"]},{spec:{name:"openai_codex",displayName:"OpenAI Codex",keywords:["openai-codex","codex"],isOauth:!0,isGateway:!1,isLocal:!1,defaultApiBase:"https://chatgpt.com/backend-api"},models:[]},{spec:{name:"github_copilot",displayName:"GitHub Copilot",keywords:["github_copilot","copilot"],isOauth:!0,isGateway:!1,isLocal:!1,defaultApiBase:""},models:[]},{spec:{name:"deepseek",displayName:"DeepSeek",keywords:["deepseek"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["deepseek/deepseek-chat","deepseek/deepseek-reasoner"]},{spec:{name:"gemini",displayName:"Google Gemini",keywords:["gemini"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["gemini/gemini-3-flash-preview","gemini/gemini-2.5-pro","gemini/gemini-2.5-flash"]},{spec:{name:"zhipu",displayName:"Zhipu AI",keywords:["zhipu","glm","zai"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["zai/glm-4.5"]},{spec:{name:"dashscope",displayName:"DashScope",keywords:["qwen","dashscope"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["dashscope/qwen-max"]},{spec:{name:"moonshot",displayName:"Moonshot AI",keywords:["moonshot","kimi"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:"https://api.moonshot.ai/v1"},models:["moonshot/kimi-k2.5"]},{spec:{name:"minimax",displayName:"MiniMax",keywords:["minimax"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:"https://api.minimax.io/v1"},models:["minimax/MiniMax-M2.1"]},{spec:{name:"vllm",displayName:"vLLM",keywords:["vllm"],isOauth:!1,isGateway:!1,isLocal:!0,defaultApiBase:""},models:["hosted_vllm/llama-3.1-8b-instruct"]},{spec:{name:"groq",displayName:"Groq",keywords:["groq"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["openai/gpt-oss-120b","openai/gpt-oss-20b","meta-llama/llama-4-maverick-17b-128e-instruct","groq/compound","groq/compound-mini"]},{spec:{name:"ollama",displayName:"Ollama",keywords:["ollama"],isOauth:!1,isGateway:!1,isLocal:!0,defaultApiBase:"http://localhost:11434/v1"},models:["ollama/llama3.3","ollama/qwen2.5","ollama/deepseek-r1"]}];function Ve(){return ur.map(s=>s.spec)}var H=Ve(),dr=Object.fromEntries(Ve().map(s=>[s.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),ae="custom:",V={agents:{defaults:{workspace:dt,model:"gpt-4.1",provider:"auto",maxTokens:8192,temperature:.1,maxToolIterations:40,memoryWindow:100}},subagents:[{id:"researcher",name:"Researcher",task:"Research the given topic thoroughly and provide detailed findings.",createdAt:0},{id:"advisor",name:"Advisor",task:"Analyze the current conversation context and provide exactly 3 concise suggestion options for the user's next logical message. Reply with a JSON array of 3 strings.",createdAt:0}],channels:{sendProgress:!0,sendToolHints:!1,telegram:{enabled:!1,token:"",allowFrom:[],proxy:null,replyToMessage:!1,debounce:{enabled:!0,quietMs:500,maxWaitMs:3e3},groups:{requireMention:!0,allowedGroupIds:null},commands:{native:!0,custom:[]}},discord:{enabled:!1,token:"",allowFrom:[],gatewayUrl:"wss://gateway.discord.gg/?v=10&encoding=json",intents:37377,debounce:{enabled:!0,quietMs:500,maxWaitMs:3e3}}},providers:dr,customLlmProviders:[],customAcpProviders:[],gateway:{host:"127.0.0.1",port:6767,dashboard:{enabled:!0},heartbeat:{enabled:!0,intervalS:1800}},tools:{web:{search:{apiKey:"",maxResults:5}},exec:{timeout:60,pathAppend:""},restrictToWorkspace:!1,mcpServers:{},chromeSession:{enabled:!1,debugPort:9222,minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8,stealth:{enabled:!1,cursorMovement:!0,humanizedTyping:!0,interStepDelay:[300,1500]}},browserRelay:{enabled:!1,authToken:"",extensionPath:""},rtk:{enabled:!0,autoInstall:!0,ultraCompact:!1,version:"latest"}},security:{enabled:!1,auth:{enabled:!1,pinHash:"",sessionTtlS:3600,lockOnIdle:!1,idleTimeoutS:900},toolGuard:{enabled:!1,guardedTools:null,deniedTools:[],rules:[],failOpen:!0},skillScanner:{enabled:!1,scanOnLoad:!1,blockUnsafe:!0,maxFileCount:1e3,maxFileSizeBytes:5242880},inputSanitizer:{enabled:!1,maxInputLength:5e4,stripHtmlTags:!1,blockPromptInjection:!1}},logging:{enabled:!0,level:"info",retentionHours:4,maxFileSizeMb:10,purgeIntervalMs:6e5},compaction:{enabled:!0,microCompactThresholdRatio:.6,autoCompactThresholdRatio:.8,keepRecentMessages:10,maxConsecutiveFailures:3}};function U(s){return s.toLowerCase().replace(/[\s-]+/g,"_")}function ft(s){return`${ae}${U(s)}`}function ht(s,t){let e=U(t.startsWith(ae)?t.slice(ae.length):t);return s.customLlmProviders.find(r=>U(r.name)===e)??null}function mr(s,t){if(!t.includes("/"))return null;let r=t.split("/",1)[0];return r?ht(s,r):null}function N(s){return!!s&&s.startsWith(ae)}function q(s,t,e){let r=(t??s.agents.defaults.provider).trim();if(r&&r!=="auto"&&!s.providers[r])return ht(s,r);let n=mr(s,e??s.agents.defaults.model);if(n)return n;let o=s.customLlmProviders.filter(i=>i.name.trim()&&i.baseUrl.trim());return o.length===1?o[0]??null:null}function le(s,t){let e=s.agents.defaults.provider;if(e!=="auto"){if(s.providers[e])return e;let a=q(s,e,t);return a?ft(a.name):null}let r=(t??s.agents.defaults.model).toLowerCase(),n=U(r),o=r.includes("/")?r.split("/",1)[0]:"";for(let a of H){let l=s.providers[a.name];if(o&&U(o)===a.name&&(a.isOauth||l?.apiKey))return a.name}for(let a of H){let l=s.providers[a.name];if(a.keywords.some(c=>r.includes(c)||n.includes(U(c)))&&(a.isOauth||l?.apiKey))return a.name}for(let a of H){if(a.isOauth)continue;if(s.providers[a.name]?.apiKey)return a.name}let i=q(s,e,t);return i?ft(i.name):null}function yt(s,t){let e=le(s,t);if(e&&N(e)){let r=q(s,e,t);return r?{apiKey:r.apiKey,apiBase:r.baseUrl,extraHeaders:r.extraHeaders}:null}return e?s.providers[e]??null:null}function ce(s,t){let e=le(s,t);if(!e)return null;if(N(e))return q(s,e,t)?.baseUrl??null;let r=s.providers[e];if(r?.apiBase)return r.apiBase;let n=H.find(o=>o.name===e);return n?.isGateway?n.defaultApiBase:null}import gr from"node:fs";import pr from"node:path";import bt from"node:os";function vt(s){return gr.mkdirSync(s,{recursive:!0}),s}function St(s){let t=s?s.replace(/^~(?=$|[\\/])/,bt.homedir()):mt(bt.homedir());return vt(pr.resolve(t))}function hr(){return gt()}function xt(s,t){if(!t||typeof t!="object")return s;let e=Array.isArray(s)?[...s]:{...s};for(let[r,n]of Object.entries(t))n&&typeof n=="object"&&!Array.isArray(n)&&e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?e[r]=xt(e[r],n):e[r]=n;return e}function kt(s){let t=s??hr();if(!wt.existsSync(t))return structuredClone(V);try{let e=wt.readFileSync(t,"utf8"),r=JSON.parse(e),n=xt(structuredClone(V),r),o=["advisor"];for(let i of o)if(!n.subagents.find(a=>a.id===i)){let a=V.subagents.find(l=>l.id===i);a&&n.subagents.push(structuredClone(a))}return n}catch(e){return console.warn(`Warning: Failed to load config from ${t}: ${String(e)}`),structuredClone(V)}}function z(s){return s.map(t=>{let e=t.content;if(typeof e=="string"&&e.length===0)return t.role==="assistant"&&t.tool_calls?{...t,content:null}:{...t,content:"(empty)"};if(Array.isArray(e)){let r=e.filter(n=>!(typeof n=="object"&&n&&["text","input_text","output_text"].includes(n.type)&&!n.text));if(r.length!==e.length)return r.length>0?{...t,content:r}:t.role==="assistant"&&t.tool_calls?{...t,content:null}:{...t,content:"(empty)"}}return t})}function ze(){let s=new Error("Operation aborted");return s.name="AbortError",s}function k(s){return s instanceof Error&&s.name==="AbortError"}function v(s){if(s?.aborted)throw ze()}function Ct(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_")}function Tt(s){if(typeof s!="string")return s&&typeof s=="object"?s:{};try{return JSON.parse(s)}catch{return{}}}var ue=class{constructor(t,e,r,n={}){this.apiKey=t;this.apiBase=e;this.defaultModel=r;this.options=n}apiKey;apiBase;defaultModel;options;getDefaultModel(){return this.defaultModel}get requestFormat(){return this.options.apiFormat??"v1/chat/completions"}resolveModel(t){let e=t.trim();if(!e.includes("/"))return e;let r=e.split("/",2),n=r[0],o=r[1];return!n||!o?e:new Set(["custom",Ct(this.options.providerLabel??"")]).has(Ct(n))?o:e}buildHeaders(){let t={"Content-Type":"application/json",...this.options.extraHeaders??{}};return this.apiKey.trim()&&(t.Authorization=`Bearer ${this.apiKey}`),t}async readJson(t){try{return await t.json()}catch{return{}}}async chatCompletions(t){let e=await fetch(`${this.apiBase.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({model:this.resolveModel(t.model??this.defaultModel),messages:z(t.messages),tools:t.tools,tool_choice:t.tools?.length?t.toolChoice??"auto":void 0,max_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7,...t.reasoning?{reasoning_effort:"medium"}:{},...t.imageOutput?{include_image_output:!0}:{}}),...t.signal?{signal:t.signal}:{}}),r=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${r?.error?.message??JSON.stringify(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let n=r.choices?.[0];if(!n?.message)return{content:`Error calling LLM: ${JSON.stringify(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=(n.message.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:Tt(i.function.arguments)}));return{content:n.message.content??null,toolCalls:o,finishReason:n.finish_reason??"stop",usage:{prompt_tokens:r.usage?.prompt_tokens??0,completion_tokens:r.usage?.completion_tokens??0,total_tokens:r.usage?.total_tokens??0},reasoningContent:n.message.reasoning_content??null}}toResponsesInput(t){let e=[];for(let r of z(t)){let n=String(r.role??"");if(n==="tool"){e.push({type:"function_call_output",call_id:String(r.tool_call_id??""),output:typeof r.content=="string"?r.content:JSON.stringify(r.content??null)});continue}if(n==="assistant"&&Array.isArray(r.tool_calls))for(let o of r.tool_calls)e.push({type:"function_call",call_id:String(o.id??""),name:String(o.name??""),arguments:typeof o.arguments=="string"?o.arguments:JSON.stringify(o.arguments??{})});(n==="system"||n==="user"||n==="assistant")&&e.push({role:n,content:r.content??""})}return e}async responses(t){let e=await fetch(`${this.apiBase.replace(/\/$/,"")}/responses`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({model:this.resolveModel(t.model??this.defaultModel),input:this.toResponsesInput(t.messages),tools:t.tools,tool_choice:t.tools?.length?t.toolChoice??"auto":void 0,max_output_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7,...t.reasoning?{reasoning:{effort:"medium"}}:{},...t.imageOutput?{include_image_output:!0}:{}}),...t.signal?{signal:t.signal}:{}}),r=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${r?.error?.message??JSON.stringify(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let n=Array.isArray(r.output)?r.output:[],o=n.filter(a=>a?.type==="function_call").map(a=>({id:String(a.call_id??a.id??""),name:String(a.name??""),arguments:Tt(a.arguments)}));return{content:n.filter(a=>a?.type==="message").flatMap(a=>Array.isArray(a?.content)?a.content:[]).filter(a=>a?.type==="output_text").map(a=>String(a.text??"")).join(`
3
+ `).trim()||null,toolCalls:o,finishReason:o.length?"tool_calls":r.status??"stop",usage:{prompt_tokens:r.usage?.input_tokens??0,completion_tokens:r.usage?.output_tokens??0,total_tokens:r.usage?.total_tokens??0},reasoningContent:null}}async chat(t){try{return v(t.signal),this.requestFormat==="v1/responses"?await this.responses(t):await this.chatCompletions(t)}catch(e){if(k(e))throw e;return{content:`Error calling LLM: ${String(e)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};import{nanoid as yr}from"nanoid";var de=class s{constructor(t,e,r){this.apiKey=t;this.apiBase=e;this.defaultModel=r}apiKey;apiBase;defaultModel;static DEFAULT_BASE="https://generativelanguage.googleapis.com/v1beta";getDefaultModel(){return this.defaultModel}resolveModel(t){let e=t.trim();if(e.includes("/")){let r=e.split("/",2),n=r[0],o=r[1];if(!n||!o)return e;let i=n.toLowerCase();(i==="gemini"||i==="google")&&(e=o)}return e.startsWith("models/")?e.slice(7):e}asText(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)}catch{return String(t)}}parseToolArgs(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{}}toGemini(t){let e=[],r=[];for(let i of t.messages){let a=String(i.role??"");if(a==="system"){let l=this.asText(i.content).trim();l&&e.push(l);continue}if(a==="user"){let l=this.asText(i.content).trim();if(!l)continue;r.push({role:"user",parts:[{text:l}]});continue}if(a==="assistant"||a==="model"){let l=[],c=this.asText(i.content).trim();c&&l.push({text:c});let u=Array.isArray(i.tool_calls)?i.tool_calls:[];for(let d of u){let m=d.function;m?.name&&l.push({functionCall:{name:m.name,args:this.parseToolArgs(m.arguments)}})}l.length&&r.push({role:"model",parts:l});continue}if(a==="tool"){let l=typeof i.name=="string"?i.name:"";if(!l)continue;let c=this.asText(i.content);r.push({role:"user",parts:[{functionResponse:{name:l,response:{result:c}}}]})}}r.length||r.push({role:"user",parts:[{text:"Hello"}]});let n={contents:r,generationConfig:{temperature:t.temperature??.1,maxOutputTokens:Math.max(1,t.maxTokens??4096),...t.reasoning?{thinkingConfig:{thinkingBudget:Math.max(1,t.maxTokens??4096)}}:{}}};e.length&&(n.systemInstruction={parts:[{text:e.join(`
4
+
5
+ `)}]});let o=(t.tools??[]).map(i=>i).filter(i=>i.type==="function"&&i.function?.name).map(i=>({name:i.function.name,description:i.function?.description??"",parameters:i.function?.parameters??{type:"object",properties:{}}}));return o.length&&(n.tools=[{functionDeclarations:o}],n.toolConfig=t.toolChoice==="required"?{functionCallingConfig:{mode:"ANY",allowedFunctionNames:o.map(i=>i.name)}}:{functionCallingConfig:{mode:"AUTO"}}),t.imageOutput&&(n.responseModalities=["TEXT","IMAGE"]),n}async chat(t){try{v(t.signal);let e=this.resolveModel(t.model??this.defaultModel),n=`${(this.apiBase??s.DEFAULT_BASE).replace(/\/$/,"")}/models/${encodeURIComponent(e)}:generateContent`,o=this.toGemini(t),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":this.apiKey},body:JSON.stringify(o),...t.signal?{signal:t.signal}:{}}),a=await i.json();if(!i.ok)return{content:`Error calling LLM: ${a?.error?.message??JSON.stringify(a)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let l=a?.candidates?.[0],c=l?.content?.parts??[],u=c.filter(f=>typeof f?.text=="string").map(f=>String(f.text)),d=c.filter(f=>f?.functionCall?.name).map(f=>({id:yr(9),name:String(f.functionCall.name),arguments:this.parseToolArgs(f.functionCall.args)})),m={};a?.usageMetadata&&(m.prompt_tokens=Number(a.usageMetadata.promptTokenCount??0),m.completion_tokens=Number(a.usageMetadata.candidatesTokenCount??0),m.total_tokens=Number(a.usageMetadata.totalTokenCount??0));let p=String(l?.finishReason??"STOP").toLowerCase();return{content:u.length?u.join(`
6
+ `):null,toolCalls:d,finishReason:p,usage:m,reasoningContent:null}}catch(e){if(k(e))throw e;return{content:`Error calling LLM: ${String(e)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};import{nanoid as br}from"nanoid";var me=class s{constructor(t,e,r,n){this.apiKey=t;this.apiBase=e;this.defaultModel=r;this.providerName=n}apiKey;apiBase;defaultModel;providerName;static DEFAULT_BASE_BY_PROVIDER={openrouter:"https://openrouter.ai/api/v1",openai:"https://api.openai.com/v1",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",moonshot:"https://api.moonshot.ai/v1",minimax:"https://api.minimax.io/v1",dashscope:"https://dashscope.aliyuncs.com/compatible-mode/v1",zhipu:"https://open.bigmodel.cn/api/paas/v4",siliconflow:"https://api.siliconflow.cn/v1",volcengine:"https://ark.cn-beijing.volces.com/api/v3",vllm:"http://localhost:8000/v1",ollama:"http://localhost:11434/v1",zai:"https://api.z.ai/api/coding/paas/v4"};static UNSUPPORTED_PROVIDERS=new Set(["anthropic","gemini","openai_codex","github_copilot"]);getDefaultModel(){return this.defaultModel}resolveModel(t){let e=r=>r.toLowerCase().replace(/-/g,"_");if(t.includes("/")){let r=t.split("/",2),n=r[0],o=r[1];if(!n||!o)return t;if(e(n)==="github_copilot")return`github_copilot/${o}`;if(e(n)==="openai_codex")return`openai_codex/${o}`;if(e(n)==="groq")return o==="compound"||o==="compound-mini"?`groq/${o}`:o;if(e(n)==="ollama")return o}return t}async chat(t){let r={model:this.resolveModel(t.model??this.defaultModel),messages:z(t.messages),max_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7};t.tools?.length&&(r.tools=t.tools,r.tool_choice=t.toolChoice??"auto"),t.reasoning&&(r.reasoning_effort="medium"),t.imageOutput&&(r.include_image_output=!0);try{v(t.signal);let n=(this.providerName??"").trim();if(n&&s.UNSUPPORTED_PROVIDERS.has(n))return{content:`Error calling LLM: provider '${n}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=this.apiBase??(n?s.DEFAULT_BASE_BY_PROVIDER[n]:void 0)??(this.apiKey?.startsWith("sk-or-")?s.DEFAULT_BASE_BY_PROVIDER.openrouter:void 0);if(!o)return{content:`Error calling LLM: api_base not configured. Set provider/api_base in ${K} or run everclaw onboard.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let a=await fetch(`${o.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:i,body:JSON.stringify(r),...t.signal?{signal:t.signal}:{}}),l=await a.json();if(!a.ok){let d=l?.error?.code??"",m=l?.error?.message??JSON.stringify(l);return d==="model_not_found"?{content:`Error calling LLM: ${m}
7
+ ${n==="groq"?"Try a Groq-supported model like llama-3.3-70b-versatile or openai/gpt-oss-120b. You can run `everclaw doctor`.":"Check your model id and provider access. You can run `everclaw doctor`."}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}:{content:`Error calling LLM: ${m}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}let c=l.choices?.[0]?.message?l.choices[0]:null;if(!c)return{content:`Error calling LLM: ${JSON.stringify(l)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let u=(c.message.tool_calls??[]).map(d=>({id:br(9),name:d.function.name,arguments:typeof d.function.arguments=="string"?JSON.parse(d.function.arguments||"{}"):d.function.arguments}));return{content:c.message.content??null,toolCalls:u,finishReason:c.finish_reason??"stop",usage:l.usage??{},reasoningContent:c.message.reasoning_content??null}}catch(n){if(k(n))throw n;return{content:`Error calling LLM: ${String(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};function At(s){let t=s.agents.defaults.model,e=le(s,t),r=yt(s,t),n=e&&N(e)?q(s,e,t):null,o=new Set(["openai_codex","github_copilot"]),i=new Set(["anthropic"]);if(!e)throw new Error("No provider could be resolved from config. Run `everclaw onboard` and set provider/model/API key.");if(N(e)&&!n)throw new Error(`Custom provider '${e}' could not be found. Check ${K}.`);if(i.has(e))throw new Error(`Provider '${e}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`);if(!o.has(e)&&e!=="vllm"&&e!=="custom"&&!N(e)&&!(r?.apiKey||"").trim())throw new Error(`No API key configured for provider '${e}'. Run 'everclaw onboard' or edit ${K}.`);return e==="custom"||N(e)?new ue(r?.apiKey||n?.apiKey||"no-key",ce(s,t)||n?.baseUrl||"http://localhost:8000/v1",t,{providerLabel:n?.name??e,apiFormat:n?.apiFormat,extraHeaders:n?.extraHeaders??r?.extraHeaders??null}):e==="gemini"?new de(r?.apiKey||"",ce(s,t),t):new me(r?.apiKey??null,ce(s,t),t,e)}import{randomUUID as Fi}from"node:crypto";import bn from"node:path";import{randomUUID as Ao}from"node:crypto";import Ro from"cron-parser";function Ye(s){return s??"builtin"}function vr(){return{beforeAgentTurn:[],afterAgentTurn:[],beforeOutbound:[],afterOutbound:[],beforeScheduledJob:[],afterScheduledJob:[],shutdown:[]}}function ge(s,t,e,r){let n=Ye(e.source),o=t.get(r.name);if(o)throw new Error(`${s} '${r.name}' from extension '${e.name}' conflicts with extension '${o.extension}'`);t.set(r.name,{extension:e.name,source:n,contribution:r})}function Sr(s,t,e){let r=(n,o)=>{let i=n.find(a=>a.contribution.name===o.name);if(i)throw new Error(`lifecycle '${o.slot}:${o.name}' from extension '${t.name}' conflicts with extension '${i.extension}'`);n.push({extension:t.name,source:Ye(t.source),contribution:o})};switch(e.slot){case"beforeAgentTurn":r(s.beforeAgentTurn,e);return;case"afterAgentTurn":r(s.afterAgentTurn,e);return;case"beforeOutbound":r(s.beforeOutbound,e);return;case"afterOutbound":r(s.afterOutbound,e);return;case"beforeScheduledJob":r(s.beforeScheduledJob,e);return;case"afterScheduledJob":r(s.afterScheduledJob,e);return;case"shutdown":r(s.shutdown,e);return}}function R(s){return{...s,source:"builtin"}}var Xe=class{extensions=new Map;register(t){if(this.extensions.has(t.name))throw new Error(`Extension '${t.name}' is already registered`);return this.extensions.set(t.name,{...t,source:Ye(t.source)}),this}list(){return[...this.extensions.values()]}compose(){let t=new Map,e=new Map,r=new Map,n=new Map,o=vr();for(let i of this.extensions.values()){for(let a of i.tools??[])ge("tool",t,i,a);for(let a of i.channels??[])ge("channel",e,i,a);for(let a of i.jobs??[])ge("job",r,i,a);for(let a of i.commands??[])ge("command",n,i,a);for(let a of i.lifecycle??[])Sr(o,i,a)}return{extensions:this.list(),tools:t,channels:e,jobs:r,commands:n,lifecycle:{beforeAgentTurn:o.beforeAgentTurn,afterAgentTurn:o.afterAgentTurn,beforeOutbound:o.beforeOutbound,afterOutbound:o.afterOutbound,beforeScheduledJob:o.beforeScheduledJob,afterScheduledJob:o.afterScheduledJob,shutdown:o.shutdown}}}};function Et(s){let t=new Xe;for(let e of s)t.register(e);return t.compose()}import yo from"node:path";import{createRequire as wr}from"node:module";var wo=wr(import.meta.url);import $o from"node:fs";import No from"node:path";var g=class s{static typeMap={string:t=>typeof t=="string",integer:t=>Number.isInteger(t),number:t=>typeof t=="number"&&Number.isFinite(t),boolean:t=>typeof t=="boolean",array:t=>Array.isArray(t),object:t=>!!t&&typeof t=="object"&&!Array.isArray(t)};validateParams(t){let e=this.parameters??{};if(e.type!=="object")throw new Error(`Schema must be object type, got ${String(e.type)}`);return this.validateValue(t,{...e,type:"object"},"parameter")}validateValue(t,e,r){let n=e.type,o=[];if(n&&s.typeMap[n]&&!s.typeMap[n](t))return[`${r} should be ${n}`];if(e.enum&&!e.enum.includes(t)&&o.push(`${r} must be one of ${JSON.stringify(e.enum)}`),(n==="integer"||n==="number")&&typeof t=="number"&&(typeof e.minimum=="number"&&t<e.minimum&&o.push(`${r} must be >= ${e.minimum}`),typeof e.maximum=="number"&&t>e.maximum&&o.push(`${r} must be <= ${e.maximum}`)),n==="string"&&typeof t=="string"&&(typeof e.minLength=="number"&&t.length<e.minLength&&o.push(`${r} must be at least ${e.minLength} chars`),typeof e.maxLength=="number"&&t.length>e.maxLength&&o.push(`${r} must be at most ${e.maxLength} chars`)),n==="object"&&t&&typeof t=="object"&&!Array.isArray(t)){let i=t,a=e.properties??{};for(let l of e.required??[])l in i||o.push(`missing required ${r==="parameter"?l:`${r}.${l}`}`);for(let[l,c]of Object.entries(i))a[l]&&o.push(...this.validateValue(c,a[l],r==="parameter"?l:`${r}.${l}`))}return n==="array"&&Array.isArray(t)&&e.items&&typeof e.items=="object"&&t.forEach((i,a)=>o.push(...this.validateValue(i,e.items,`${r}[${a}]`))),o}toSchema(){return{type:"function",function:{name:this.name,description:this.description,parameters:this.parameters}}}};var pe=class extends g{constructor(e){super();this.cron=e}cron;name="cron";description="Schedule reminders and recurring tasks. Actions: add, list, remove.";parameters={type:"object",properties:{action:{type:"string",enum:["add","list","remove"]},message:{type:"string"},every_seconds:{type:"integer"},cron_expr:{type:"string"},tz:{type:"string"},at:{type:"string"},job_id:{type:"string"}},required:["action"]};channel="";chatId="";setContext(e,r){this.channel=e,this.chatId=r}async execute(e,r){let n=String(e.action??"");return n==="add"?this.addJob(e):n==="list"?this.listJobs():n==="remove"?this.removeJob(String(e.job_id??"")):`Unknown action: ${n}`}addJob(e){let r=String(e.message??"");if(!r)return"Error: message is required for add";if(!this.channel||!this.chatId)return"Error: no session context (channel/chat_id)";let n=e.every_seconds!=null?Number(e.every_seconds):null,o=e.cron_expr!=null?String(e.cron_expr):null,i=e.tz!=null?String(e.tz):null,a=e.at!=null?String(e.at):null,l,c=!1;if(n)l={kind:"every",everyMs:n*1e3};else if(o){let u={kind:"cron",expr:o};i&&(u.tz=i),l=u}else if(a){let u=new Date(a);if(Number.isNaN(u.getTime()))return"Error: invalid ISO datetime in at";l={kind:"at",atMs:u.getTime()},c=!0}else return"Error: either every_seconds, cron_expr, or at is required";try{let u=this.cron.addJob({name:r.slice(0,30),schedule:l,message:r,deliver:!0,channel:this.channel,to:this.chatId,deleteAfterRun:c});return`Created job '${u.name}' (id: ${u.id})`}catch(u){return`Error: ${String(u).replace(/^Error:\s*/,"")}`}}listJobs(){let e=this.cron.listJobs();return e.length?`Scheduled jobs:
8
+ ${e.map(r=>`- ${r.name} (id: ${r.id}, ${r.schedule.kind})`).join(`
9
+ `)}`:"No scheduled jobs."}removeJob(e){return e?this.cron.removeJob(e)?`Removed job ${e}`:`Job ${e} not found`:"Error: job_id is required for remove"}};import A from"node:fs";import W from"node:path";import M from"node:fs";import C from"node:path";function Rt(s){let t=C.resolve(s);for(;t!=="/"&&t!==".";)try{return M.lstatSync(t),t}catch{let e=C.dirname(t);if(e===t)break;t=e}return t||"/"}function Mt(s,t){let e=C.resolve(s),r=C.resolve(t),n=r.endsWith(C.sep)?r.slice(0,-1):r,o=e===n||e.startsWith(n+C.sep);if(!M.existsSync(n))return o;try{let i=n;try{i=M.realpathSync.native(n)}catch{}if(M.existsSync(e)){let c=M.realpathSync.native(e);return c===i||c.startsWith(i+C.sep)}let a=Rt(e);if(a===i||a===n)return!0;if(a!=="/")try{let c=M.realpathSync.native(a);if(c===i||c.startsWith(i+C.sep))return!0;if(!o)return!1}catch{return o}let l=e;for(;l!=="/"&&l!==".";){let c=C.dirname(l);if(c===l)break;try{if(M.lstatSync(c).isSymbolicLink()){let d=M.realpathSync.native(c);if(d!==i&&!d.startsWith(i+C.sep))return!1}}catch{}l=c}return o}catch{return!1}}function _t(s,t){let e=C.resolve(s),r=C.resolve(t);if(!Mt(s,t))throw new Error(`Path '${s}' is outside allowed workspace '${t}'`);let n=C.dirname(e),o=Rt(n),i=r;try{M.existsSync(r)&&(i=M.realpathSync.native(r))}catch{}if(o!=="/"&&o!==i)try{let a=M.realpathSync.native(o);if(a!==i&&!a.startsWith(i+C.sep))throw new Error(`Path '${s}' would be created outside workspace via symlinked parent directory`)}catch(a){throw a instanceof Error&&a.message.includes("symlinked parent")?a:new Error(`Could not validate path '${s}' is within workspace`)}}function Lt(s,t){if(!Mt(s,t))throw new Error(`Path '${s}' is outside allowed workspace '${t}'`)}function ve(s,t,e,r=!1){let n=s.startsWith("~")?W.join(process.env.USERPROFILE||process.env.HOME||"",s.slice(1)):s,o=W.isAbsolute(n)?n:t?W.join(t,n):n,i=W.resolve(o);if(e)try{r?_t(i,e):Lt(i,e)}catch(a){throw new Error(a instanceof Error?a.message:`Path ${s} validation failed`)}return i}var fe=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="read_file";description="Read the contents of a file at the given path.";parameters={type:"object",properties:{path:{type:"string",description:"The file path to read"}},required:["path"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir);return A.existsSync(n)?A.statSync(n).isFile()?A.readFileSync(n,"utf8"):`Error: Not a file: ${String(e.path)}`:`Error: File not found: ${String(e.path)}`}catch(n){return`Error reading file: ${String(n)}`}}},he=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="write_file";description="Write content to a file at the given path. Creates parent directories if needed.";parameters={type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir,!0);A.mkdirSync(W.dirname(n),{recursive:!0});let o=String(e.content??"");return A.writeFileSync(n,o,"utf8"),`Successfully wrote ${o.length} bytes to ${n}`}catch(n){return`Error writing file: ${String(n)}`}}},ye=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="edit_file";description="Edit a file by replacing old_text with new_text. The old_text must exist exactly in the file.";parameters={type:"object",properties:{path:{type:"string"},old_text:{type:"string"},new_text:{type:"string"}},required:["path","old_text","new_text"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir,!0);if(!A.existsSync(n))return`Error: File not found: ${String(e.path)}`;let o=A.readFileSync(n,"utf8"),i=String(e.old_text??""),a=String(e.new_text??"");return o.includes(i)?o.split(i).length-1>1?`Warning: old_text appears ${o.split(i).length-1} times. Please provide more context to make it unique.`:(A.writeFileSync(n,o.replace(i,a),"utf8"),`Successfully edited ${n}`):`Error: old_text not found in ${String(e.path)}. Verify the file content.`}catch(n){return`Error editing file: ${String(n)}`}}},be=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="list_dir";description="List the contents of a directory.";parameters={type:"object",properties:{path:{type:"string"}},required:["path"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir);if(!A.existsSync(n))return`Error: Directory not found: ${String(e.path)}`;if(!A.statSync(n).isDirectory())return`Error: Not a directory: ${String(e.path)}`;let o=A.readdirSync(n).sort().map(i=>{let a=W.join(n,i);return`${A.statSync(a).isDirectory()?"[DIR]":"[FILE]"} ${i}`});return o.length?o.join(`
10
+ `):`Directory ${String(e.path)} is empty`}catch(n){return`Error listing directory: ${String(n)}`}}};var Se=class extends g{constructor(e){super();this.sendCallback=e}sendCallback;name="message";description="Send a message to the user. Use this when you want to communicate something.";parameters={type:"object",properties:{content:{type:"string",description:"The message content to send"},channel:{type:"string",description:"Optional target channel"},chat_id:{type:"string",description:"Optional target chat/user ID"},media:{type:"array",items:{type:"string"},description:"Optional file attachments"}},required:["content"]};defaultChannel="";defaultChatId="";defaultMessageId=null;setContext(e,r,n){this.defaultChannel=e,this.defaultChatId=r,this.defaultMessageId=n??null}setSendCallback(e){this.sendCallback=e}async execute(e,r){let n=String(e.content??""),o=String(e.channel??this.defaultChannel),i=String(e.chat_id??this.defaultChatId),a=String(e.message_id??this.defaultMessageId??""),l=Array.isArray(e.media)?e.media:[];if(!o||!i)return"Error: No target channel/chat specified";if(!this.sendCallback)return"Error: Message sending not configured";try{await this.sendCallback({channel:o,chatId:i,content:n,media:l,metadata:{message_id:a}});let c=o===this.defaultChannel&&i===this.defaultChatId,u=`Message sent to ${o}:${i}${l.length?` with ${l.length} attachments`:""}`;return c?`__TERMINAL__${u}`:u}catch(c){return`Error sending message: ${String(c)}`}}};import Qe from"node:path";import{spawn as Pt}from"node:child_process";var kr={"agent-turn":{target:"agent-turn",mode:"in-process",risk:"safe",cleanup:"none",observation:"basic",reason:"Normal agent turns stay in-process unless a later surface explicitly routes them through isolation."},"tool.exec":{target:"tool.exec",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Shell execution already crosses the local OS boundary and needs explicit launch, timeout, output capture, and cleanup semantics."},subagent:{target:"subagent",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Spawned subagents are a high-risk local execution path that later Wave D routing can move onto this process boundary."},"scheduled-job":{target:"scheduled-job",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Scheduled jobs can run unattended and should share the same local-process isolation contract when routed in later Wave D work."},"background-job":{target:"background-job",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Long-running background work needs the same local process cleanup and attribution boundary as other risky execution paths."}};function Ze(s){return{...kr[s]}}var D=class{async run(t){let e=Math.max(1,t.maxCaptureBytes??1048576),r=typeof t.timeoutMs=="number"&&Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:null,n=this.launch(t);if(n instanceof Error)return{status:"failed",pid:null,stdout:"",stderr:"",exitCode:null,signal:null,failureAttribution:"spawn_error",cleanupTriggered:!1,cleanupReason:null,errorMessage:n.message};let{child:o,spawnError:i}=n;t.stdinText!=null?o.stdin?.end(t.stdinText,"utf8"):o.stdin?.end();let a="",l="",c=!1,u=null,d=!1,m=(S,L)=>{let B=typeof S=="string"?S:S.toString("utf8"),_=e-Buffer.byteLength(L);return _<=0?L:L+B.slice(0,_)};o.stdout?.on("data",S=>{a=m(S,a)}),o.stderr?.on("data",S=>{l=m(S,l)});let p=null,f=S=>{c||(c=!0,u=S,d=S==="timeout",this.killChild(o,"SIGTERM"),p=setTimeout(()=>this.killChild(o,"SIGKILL"),250),p.unref?.())},b=()=>f("abort");t.signal?.aborted?b():t.signal?.addEventListener("abort",b,{once:!0});let T=r!=null?setTimeout(()=>f("timeout"),r):null;T?.unref?.();let x=await new Promise(S=>{let L=!1,B=_=>{L||(L=!0,S(_))};o.once("error",_=>{i.current=_,B({code:null,signal:null})}),o.once("close",(_,ie)=>B({code:_,signal:ie}))});return T&&clearTimeout(T),p&&clearTimeout(p),t.signal?.removeEventListener("abort",b),u==="abort"?{status:"aborted",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:"aborted",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:d?{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:"timeout",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:i.current?{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:"spawn_error",cleanupTriggered:c,cleanupReason:u,errorMessage:i.current.message}:x.code===0?{status:"ok",pid:o.pid??null,stdout:a,stderr:l,exitCode:0,signal:x.signal,failureAttribution:"none",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:x.signal?"signal":"exit_code",cleanupTriggered:c,cleanupReason:u,errorMessage:null}}launch(t){try{return{child:t.command.kind==="shell"?Pt(t.command.command,{cwd:t.cwd,env:t.env,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}):Pt(t.command.file,t.command.args??[],{cwd:t.cwd,env:t.env,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),spawnError:{current:null}}}catch(e){return e instanceof Error?e:new Error(String(e))}}killChild(t,e){try{if(process.platform!=="win32"&&typeof t.pid=="number"){process.kill(-t.pid,e);return}}catch{}try{t.kill(e)}catch{}}};var we=class extends g{constructor(e=60,r,n=!1,o="",i=new D,a,l=!1){super();this.timeout=e;this.workingDir=r;this.restrictToWorkspace=n;this.pathAppend=o;this.runner=i;this.rtkService=a;this.rtkUltraCompact=l}timeout;workingDir;restrictToWorkspace;pathAppend;runner;rtkService;rtkUltraCompact;name="exec";description="Execute a shell command and return its output. Use with caution.";parameters={type:"object",properties:{command:{type:"string",description:"The shell command to execute"},working_dir:{type:"string",description:"Optional working directory for the command"}},required:["command"]};guard(e,r){let n=e.toLowerCase();if([/\brm\s+-[rf]{1,2}\b/,/\bdel\s+\/[fq]\b/,/\brmdir\s+\/s\b/,/(?:^|[;&|]\s*)format\b/,/\b(mkfs|diskpart)\b/,/\bdd\s+if=/,/>\s*\/dev\/sd/,/\b(shutdown|reboot|poweroff)\b/,/:\(\)\s*\{.*\};\s*:/].some(i=>i.test(n)))return"Error: Command blocked by safety guard (dangerous pattern detected)";if(this.restrictToWorkspace){if(e.includes("../")||e.includes("..\\"))return"Error: Command blocked by safety guard (path traversal detected)";let i=e.match(/[A-Za-z]:\\[^\s"']+/g)??[];for(let a of i){let l=Qe.resolve(a),c=Qe.resolve(r);if(!l.startsWith(c))return"Error: Command blocked by safety guard (path outside working dir)"}}return null}async execute(e,r){let n=String(e.command??""),o=String(e.working_dir??this.workingDir??process.cwd()),i=this.guard(n,o);if(i)return i;v(r?.signal);let a=Ze("tool.exec"),l={...process.env};if(this.pathAppend&&(l.PATH=`${l.PATH??""}${Qe.delimiter}${this.pathAppend}`),a.mode!=="local-process")return"Error: exec tool requires local-process isolation";let c={command:{kind:"shell",command:n},cwd:o,env:l,timeoutMs:this.timeout*1e3,maxCaptureBytes:1024*1024};r?.signal&&(c.signal=r.signal);let u=await this.runner.run(c);if(u.status==="aborted")throw ze();if(u.failureAttribution==="timeout")return`Error: Command timed out after ${this.timeout} seconds`;let d=u.stdout?`${u.stdout}${u.status==="failed"?`
11
+ `:""}`:"";if(this.rtkService?.getRuntime().available&&d)try{let T=await this.rtkService.compress({command:n,stdout:d,stderr:u.stderr,exitCode:u.exitCode,ultraCompact:this.rtkUltraCompact});T.compressed&&(d=T.stdout)}catch{}let m=u.stderr.trim()?`STDERR:
12
+ ${u.stderr}
13
+ `:"",p=u.status==="failed"&&typeof u.exitCode=="number"?`
14
+ Exit code: ${u.exitCode}`:"",f=u.status==="failed"&&u.signal?`
15
+ Signal: ${u.signal}`:"",b=`${d}${m}${p}${f}`.trim();return b?b.length>1e4?`${b.slice(0,1e4)}
16
+ ... (truncated, ${b.length-1e4} more chars)`:b:u.status==="failed"?u.errorMessage?`Error executing command: ${u.errorMessage}`:"Error executing command":"(no output)"}};var Cr={general:{name:"general",description:"General-purpose subagent with full tool access",systemPromptSuffix:"Complete the assigned task using all available tools."},researcher:{name:"researcher",description:"Read-only researcher \u2014 no file modifications",systemPromptSuffix:"Research and report findings. Do NOT modify any files.",allowedTools:["read_file","list_files","search","web_search","web_fetch","session.info","session.search"]},coder:{name:"coder",description:"Code modification specialist",systemPromptSuffix:"Implement the requested code changes.",deniedTools:["web_search","web_fetch"]}};function Ot(){return Object.values(Cr)}var xe=class extends g{constructor(e){super();this.manager=e}manager;name="spawn";description="Spawn a subagent to handle a task in the background.";parameters={type:"object",properties:{task:{type:"string",description:"The task for the subagent to complete"},label:{type:"string",description:"Optional short label"},model:{type:"string",description:"Optional model override (e.g. 'anthropic/claude-sonnet-4'). Falls back to subagent config or global default if omitted."},provider:{type:"string",description:"Optional provider override (e.g. 'openai'). Falls back to subagent config or global default if omitted."},context:{type:"string",enum:["fresh","fork"],description:"Context mode: 'fresh' (default) starts with minimal context, 'fork' inherits parent conversation for prompt cache reuse."},type:{type:"string",description:`Agent type defining available tools and behavior. Available types: ${Ot().map(e=>`'${e.name}'`).join(", ")}. Defaults to 'general'.`}},required:["task"]};originChannel="cli";originChatId="direct";sessionKey="cli:direct";parentSystemPrompt;setContext(e,r,n=`${e}:${r}`,o){this.originChannel=e,this.originChatId=r,this.sessionKey=n,this.parentSystemPrompt=o}async execute(e,r){let n=e.context??"fresh",o=e.type??"general",i={task:String(e.task??""),label:e.label!=null?String(e.label):null,originChannel:this.originChannel,originChatId:this.originChatId,sessionKey:this.sessionKey,contextMode:n,agentType:o};return e.model!=null&&(i.model=String(e.model)),e.provider!=null&&(i.providerName=String(e.provider)),n==="fork"&&this.parentSystemPrompt&&(i.parentSystemPrompt=this.parentSystemPrompt),this.manager.spawn(i)}};var ke=class extends g{name="session.search";description="Search the current session's message history for content matching the query.";parameters={type:"object",properties:{query:{type:"string",description:"The search query to match against message content"},limit:{type:"integer",description:"Maximum number of results to return",minimum:1,maximum:100}},required:["query"]};sessionManager=null;sessionKey="cli:direct";constructor(){super()}setSessionManager(t){this.sessionManager=t}setContext(t){this.sessionKey=t}async execute(t,e){if(!this.sessionManager)return"Error: Session manager not available";let r=String(t.query??""),n=typeof t.limit=="number"?Math.min(Math.max(1,Math.floor(t.limit)),100):10;if(!r)return"Error: Query cannot be empty";let i=this.sessionManager.getOrCreate(this.sessionKey).search(r,n);return JSON.stringify(i,null,2)}};import jt from"node:fs";import Re from"node:path";import Bt from"node:os";import X from"node:fs";import Te from"node:path";var Tr={"gpt-4.1":1047576,"gpt-4.1-mini":1047576,"gpt-4.1-nano":1047576,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4":8192,"gpt-3.5-turbo":16385,"claude-sonnet-4":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-5-haiku":2e5,"claude-3-opus":2e5,"claude-3-sonnet":2e5,"claude-3-haiku":2e5,"gemini-2.5-pro":1e6,"gemini-2.0-flash":1e6,"gemini-1.5-pro":1e6,"gemini-1.5-flash":1e6,"deepseek-chat":64e3,"deepseek-reasoner":64e3,"grok-2":131072,"grok-2-mini":131072},Ar=128e3;function Ce(s){if(!s)return 0;let t=typeof s=="string"?s:JSON.stringify(s);return Math.ceil(t.length/4)}function $t(s,t){if(t){let r=t.providers?.[t.agents.defaults.provider]?.models?.find(n=>n.id.toLowerCase()===s.toLowerCase())?.capabilities;if(r?.contextWindow)return r.contextWindow;for(let n of t.customLlmProviders??[]){let o=n.models.find(i=>i.id.toLowerCase()===s.toLowerCase());if(o?.capabilities?.contextWindow)return o.capabilities.contextWindow}}let e=s.toLowerCase();for(let[r,n]of Object.entries(Tr))if(r.toLowerCase()===e||e.includes(r.toLowerCase()))return n;return Ar}var It=1e3,Er=250,Ae=`
17
+ ... (truncated for archival)`;function Nt(s){return Math.max(0,Math.floor(s*4))}function Rr(s,t){if(t<=0)return"";let e=Nt(t);if(s.length<=e)return s;let r=Math.max(0,e-Ae.length);return`${Ae}${s.slice(-r)}`}function Mr(s,t){if(t<=0||s.length===0)return{text:"",omittedLines:s.length};let e=Nt(t),r=[],n=0,o=0;for(let i=s.length-1;i>=0;i--){let a=s[i],l=r.length?1:0,c=e-n-l;if(c<=0){o=i+1;break}if(a.length<=c){r.unshift(a),n+=a.length+l;continue}let u=Math.max(0,c-Ae.length);r.unshift(`${Ae}${a.slice(-u)}`),n=e,o=i;break}return{text:r.join(`
18
+ `),omittedLines:o}}var _r=[{type:"function",function:{name:"save_memory",description:"Save the memory consolidation result to persistent storage.",parameters:{type:"object",properties:{history_entry:{type:"string"},memory_update:{type:"string"}},required:["history_entry","memory_update"]}}}];function Lr(s){let t=s.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)```$/i);if(e?.[1])return e[1].trim();if(t.startsWith("{")&&t.endsWith("}"))return t;let r=t.indexOf("{"),n=t.lastIndexOf("}");return r!==-1&&n>r?t.slice(r,n+1).trim():null}function Pr(s){if(!s)return null;let t=Lr(s.trim());if(!t)return null;try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.history_entry==null&&r.memory_update==null?null:r}catch{return null}}var Y=class{memoryDir;memoryFile;historyFile;constructor(t,e){let r=Te.join(t,"memory");this.memoryDir=e?Te.join(r,e):r,X.mkdirSync(this.memoryDir,{recursive:!0}),this.memoryFile=Te.join(this.memoryDir,"MEMORY.md"),this.historyFile=Te.join(this.memoryDir,"HISTORY.md")}readLongTerm(){return X.existsSync(this.memoryFile)?X.readFileSync(this.memoryFile,"utf8"):""}writeLongTerm(t){X.writeFileSync(this.memoryFile,t,"utf8")}appendHistory(t){X.appendFileSync(this.historyFile,`${t.trim()}
19
+
20
+ `,"utf8")}getMemoryContext(){let t=this.readLongTerm();return t?`## Long-term Memory
21
+ ${t}`:""}async consolidate(t,e,r,n){let o=n?.archiveAll??!1,i=n?.memoryWindow??50,a=[],l=0;if(o)a=t.messages,l=0;else if(l=Math.floor(i/2),t.messages.length<=l||t.messages.length-t.lastConsolidated<=0||(a=t.messages.slice(t.lastConsolidated,t.messages.length-l),!a.length))return!0;let c=[],u=[];for(let h of a)h._type==="anchor"?c.push(h):u.push(h);let d=[];for(let h of c)d.push(`[ANCHOR] ${h.name}: ${h.summary??"(no summary)"}`);for(let h of u){if(!h.content&&!h._full_content)continue;let F=Array.isArray(h.tools_used)&&h.tools_used.length?` [tools: ${h.tools_used.join(", ")}]`:"",E=h._full_content??h.content;d.push(`[${String(h.timestamp??"?").slice(0,16)}] ${String(h.role).toUpperCase()}${F}: ${String(E)}`)}let m=this.readLongTerm(),p=d.join(`
22
+ `),f=m||"(empty)",b="## Conversation to Process",T=p,x=Ce(`Process this conversation and call the save_memory tool with your consolidation.
27
23
 
28
24
  ## Current Long-term Memory
29
25
 
30
26
 
31
27
  ## Conversation to Process
32
- `),E=i_(R||"(empty)"),C=i_(Q),j=S+E+C,P=BX(y),l=Math.floor(P*0.9);if(j>l){let F=Math.max(1,l-S),$J=Math.min(E,Math.max(Dq,Math.floor(F*0.3))),m=Math.min(E,Math.max(0,F-QX),$J),AJ=Math.max(QX,F-m);if(m<E)K=hq(K,m);if(AJ<C){let QJ=vq(B,AJ);Z=QJ.text,Y=QJ.text!==Q?`## Conversation to Process (truncated, most recent ${B.length-QJ.omittedLines} entries)`:"## Conversation to Process"}}let q0=`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":"..."}.
28
+ `),S=Ce(m||"(empty)"),L=Ce(p),B=x+S+L,_=Math.max(1,n?.contextWindow??$t(r)),ie=Math.floor(_*.9);if(B>ie){let h=Math.max(1,ie-x),F=Math.min(S,Math.max(Er,Math.floor(h*.3))),E=Math.min(S,Math.max(0,h-It),F),I=Math.max(It,h-E);if(E<S&&(f=Rr(f,E)),I<L){let $=Mr(d,I);T=$.text,b=$.text!==p?`## Conversation to Process (truncated, most recent ${d.length-$.omittedLines} entries)`:"## Conversation to Process"}}let sr=`Process this conversation and call the save_memory tool with your consolidation. If tool calling is unavailable, respond with JSON only containing string fields named history_entry and memory_update.
33
29
 
34
30
  ## Current Long-term Memory
35
- ${K}
31
+ ${f}
36
32
 
37
- ${Y}
38
- ${Z}`;try{let F=await _.chat({model:y,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:q0}],tools:fq,toolChoice:"required"}),m=F.toolCalls[0]?.arguments??gq(F.content);if(!m)return!1;let{history_entry:AJ,memory_update:QJ}=m;if(AJ!=null)this.appendHistory(typeof AJ==="string"?AJ:JSON.stringify(AJ));if(QJ!=null){let EJ=typeof QJ==="string"?QJ:JSON.stringify(QJ);if(EJ!==R)this.writeLongTerm(EJ)}let Zy=X?0:J.messages.length-q,Sy=J.messages.slice(0,Zy),N0=-1;for(let EJ=Sy.length-1;EJ>=0;EJ--)if(Sy[EJ]?._type==="anchor"){N0=EJ;break}if(N0!==-1)J.lastConsolidated=N0+1;else J.lastConsolidated=Zy;return!0}catch{return!1}}}import H_ from"fs";import U_ from"path";var RX=/^[a-z0-9][a-z0-9-]*$/;class qy{workspaceSkills;userSkills;builtinSkills;scannerConfig;scanner;constructor(J,_,y,$,X){this.workspaceSkills=U_.join(J,"skills"),this.userSkills=_??null,this.builtinSkills=y??ly("skills"),this.scannerConfig=$??null,this.scanner=X??null}listSkills(J=!0){return(J?this.getResolvedSkills().filter((y)=>y.status==="available"):this.getResolvedSkills()).map(({name:y,path:$,source:X})=>({name:y,path:$,source:X}))}listResolvedSkills(){return this.getResolvedSkills().map(({content:J,metadata:_,runtimeMeta:y,...$})=>$)}loadSkill(J){let _=this.getSkillByName(J);return _?.status==="available"?_.content:null}loadSkillsForContext(J){let _=[];for(let y of J){let $=this.getSkillByName(y);if(!$){_.push(this.renderLoadFailure(y,`Skill '${y}' is not installed. ${this.getAvailableSkillsHint()}`));continue}if($.status!=="available"){let X=$.status==="malformed"?`Skill '${y}' is malformed: ${$.reason}.`:$.status==="blocked"?`Skill '${y}' is blocked by security scanner: ${$.reason}.`:`Skill '${y}' is unavailable: ${$.reason}.`;_.push(this.renderLoadFailure(y,X));continue}_.push(`### Skill: ${y}
33
+ ${b}
34
+ ${T}`;try{let h=async P=>{let ct=await e.chat({model:r,messages:[{role:"system",content:"You are a memory consolidation agent. Call the save_memory tool. If tool calling is unavailable, respond with JSON only containing string fields named history_entry and memory_update."},{role:"user",content:sr}],...P?{tools:_r,toolChoice:"required"}:{}});return ct.toolCalls[0]?.arguments??Pr(ct.content)},F=n?.toolCallingEnabled!==!1,E=await h(F);if(!E&&F&&(E=await h(!1)),!E)return!1;let I=E.history_entry,$=E.memory_update;if(I!=null&&this.appendHistory(typeof I=="string"?I:JSON.stringify(I)),$!=null){let P=typeof $=="string"?$:JSON.stringify($);P!==m&&this.writeLongTerm(P)}let at=o?0:t.messages.length-l,lt=t.messages.slice(0,at),Ke=-1;for(let P=lt.length-1;P>=0;P--)if(lt[P]?._type==="anchor"){Ke=P;break}return Ke!==-1?t.lastConsolidated=Ke+1:t.lastConsolidated=at,!0}catch{return!1}}};import Z from"node:fs";import Q from"node:path";var Dt=/^[a-z0-9][a-z0-9-]*$/;var Ee=class{workspaceSkills;userSkills;builtinSkills;scannerConfig;scanner;constructor(t,e,r,n,o){this.workspaceSkills=Q.join(t,"skills"),this.userSkills=e??null,this.builtinSkills=r??pt("skills"),this.scannerConfig=n??null,this.scanner=o??null}listSkills(t=!0){return(t?this.getResolvedSkills().filter(r=>r.status==="available"):this.getResolvedSkills()).map(({name:r,path:n,source:o})=>({name:r,path:n,source:o}))}listResolvedSkills(){return this.getResolvedSkills().map(({content:t,metadata:e,runtimeMeta:r,...n})=>n)}loadSkill(t){let e=this.getSkillByName(t);return e?.status==="available"?e.content:null}loadSkillsForContext(t){let e=[];for(let r of t){let n=this.getSkillByName(r);if(!n){e.push(this.renderLoadFailure(r,`Skill '${r}' is not installed. ${this.getAvailableSkillsHint()}`));continue}if(n.status!=="available"){let o=n.status==="malformed"?`Skill '${r}' is malformed: ${n.reason}.`:n.status==="blocked"?`Skill '${r}' is blocked by security scanner: ${n.reason}.`:`Skill '${r}' is unavailable: ${n.reason}.`;e.push(this.renderLoadFailure(r,o));continue}e.push(`### Skill: ${r}
39
35
 
40
- ${this.stripFrontmatter($.content)}`)}return _.join(`
36
+ ${this.stripFrontmatter(n.content)}`)}return e.join(`
41
37
 
42
38
  ---
43
39
 
44
- `)}buildSkillsSummary(){let J=this.getResolvedSkills();if(!J.length)return"";let _=($)=>$.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),y=["<skills>"];for(let $ of J){if(y.push(` <skill available="${$.status==="available"}" source="${_($.source)}">`),y.push(` <name>${_($.name)}</name>`),y.push(` <description>${_($.description)}</description>`),y.push(` <location>${_($.path)}</location>`),y.push(` <status>${_($.status)}</status>`),$.reason)y.push(` <reason>${_($.reason)}</reason>`);y.push(" </skill>")}return y.push("</skills>"),y.join(`
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:y}of this.getSkillRoots()){if(!H_.existsSync(_))continue;let $=H_.readdirSync(_,{withFileTypes:!0}).filter((X)=>X.isDirectory()).sort((X,A)=>X.name.localeCompare(A.name));for(let X of $){if(J.has(X.name))continue;let A=U_.join(_,X.name,"SKILL.md");if(!H_.existsSync(A))continue;J.set(X.name,this.readSkill(X.name,A,y))}}return[...J.values()].sort((_,y)=>_.name.localeCompare(y.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,_,y){let $=H_.readFileSync(_,"utf8"),X=this.parseSkill(J,$);if(X.errors.length)return{name:J,path:_,source:y,content:$,metadata:X.metadata,runtimeMeta:{},description:X.description,status:"malformed",reason:X.errors.join("; "),always:!1};let A=this.getRequirementErrors(X.runtimeMeta),L=this.runSecurityScan(_,J);if(L&&!L.isSafe&&this.scannerConfig?.blockUnsafe)return{name:J,path:_,source:y,content:$,metadata:X.metadata,runtimeMeta:X.runtimeMeta,description:X.description,status:"blocked",reason:this.formatBlockedReason(L),always:X.always};if(L&&L.findings.length>0){let q=L.findings.map((N)=>`[${N.severity}] ${N.title} (${N.category})`);console.warn(`SkillScanner: skill '${J}' has ${L.findings.length} finding(s): ${q.join("; ")}`)}return{name:J,path:_,source:y,content:$,metadata:X.metadata,runtimeMeta:X.runtimeMeta,description:X.description,status:A.length?"unavailable":"available",reason:A.length?A.join("; "):null,always:X.always}}runSecurityScan(J,_){if(!this.scannerConfig?.enabled||!this.scannerConfig.scanOnLoad||!this.scanner)return null;let y=U_.dirname(J);return this.scanner.scanSkill(y,_,{maxFileCount:this.scannerConfig.maxFileCount,maxFileSizeBytes:this.scannerConfig.maxFileSizeBytes})}formatBlockedReason(J){let _=J.findings.filter(($)=>$.severity==="CRITICAL");if(_.length===0)return"Security scan failed";return`Blocked by security scanner: ${_.map(($)=>`[${$.severity}] ${$.title} (${$.category})`).join("; ")}`}parseSkill(J,_){let y=this.extractFrontmatter(_);if(!y.frontmatter)return{metadata:null,runtimeMeta:{},description:J,always:!1,errors:[y.error??"missing YAML frontmatter"]};let $=this.parseFrontmatter(y.frontmatter),X=$.metadata,A=typeof X.description==="string"&&X.description.trim()?X.description.trim():J,L=[...$.errors],q=typeof X.name==="string"?X.name.trim():"";if(!q)L.push("missing required frontmatter field 'name'");else if(q!==J)L.push(`frontmatter name '${q}' does not match directory '${J}'`);else if(!RX.test(q))L.push(`frontmatter name '${q}' must match ${RX}`);if(!(typeof X.description==="string"&&X.description.trim()))L.push("missing required frontmatter field 'description'");let N=this.parseRuntimeMetadata(X.metadata);L.push(...N.errors);let G=X.always;if(G!==void 0&&typeof G!=="boolean")L.push("frontmatter field 'always' must be a boolean");return{metadata:X,runtimeMeta:N.runtimeMeta,description:A,always:G??N.runtimeMeta.always??!1,errors:L}}extractFrontmatter(J){if(!(J.startsWith(`---
46
- `)||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 _={},y=[];for(let $ of J.split(/\r?\n/)){let X=$.trim();if(!X)continue;let A=X.indexOf(":");if(A<=0){y.push(`invalid frontmatter line '${X}'`);continue}let L=X.slice(0,A).trim(),q=X.slice(A+1).trim();_[L]=this.parseFrontmatterValue(q)}return{metadata:_,errors:y}}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 y=_.everclaw??_.openclaw??{};if(!this.isRecord(y))return{runtimeMeta:{},errors:["skill metadata for 'everclaw'/'openclaw' must be an object"]};let $=[],X={};if(y.always!==void 0)if(typeof y.always!=="boolean")$.push("skill metadata field 'always' must be a boolean");else X.always=y.always;if(y.requires!==void 0)if(!this.isRecord(y.requires))$.push("skill metadata field 'requires' must be an object");else{let A=y.requires.bins,L=y.requires.env;if(A!==void 0&&!this.isStringArray(A))$.push("skill metadata field 'requires.bins' must be an array of strings");if(L!==void 0&&!this.isStringArray(L))$.push("skill metadata field 'requires.env' must be an array of strings");let q={};if(this.isStringArray(A))q.bins=A;if(this.isStringArray(L))q.env=L;if(Object.keys(q).length>0)X.requires=q}return{runtimeMeta:X,errors:$}}getRequirementErrors(J){let _=J.requires??{},y=(_.bins??[]).filter((A)=>!this.hasBinary(A)),$=(_.env??[]).filter((A)=>!process.env[A]),X=[];if(y.length)X.push(`missing required binaries: ${y.join(", ")}`);if($.length)X.push(`missing required env vars: ${$.join(", ")}`);return X}hasBinary(J){let _=(process.env.PATH??"").split(U_.delimiter).filter(Boolean),y=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return _.some(($)=>y.some((X)=>H_.existsSync(U_.join($,`${J}${X}`))))}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}
40
+ `)}buildSkillsSummary(){let t=this.getResolvedSkills();if(!t.length)return"";let e=n=>n.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;"),r=["<skills>"];for(let n of t)r.push(` <skill available="${n.status==="available"}" source="${e(n.source)}">`),r.push(` <name>${e(n.name)}</name>`),r.push(` <description>${e(n.description)}</description>`),r.push(` <location>${e(n.path)}</location>`),r.push(` <status>${e(n.status)}</status>`),n.reason&&r.push(` <reason>${e(n.reason)}</reason>`),r.push(" </skill>");return r.push("</skills>"),r.join(`
41
+ `)}getAlwaysSkills(){return this.getResolvedSkills().filter(t=>t.status==="available"&&t.always).map(t=>t.name)}getSkillMetadata(t){return this.getSkillByName(t)?.metadata??null}stripFrontmatter(t){let e=t.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return e?t.slice(e[0].length).trim():t}getResolvedSkills(){let t=new Map;for(let{root:e,source:r}of this.getSkillRoots()){if(!Z.existsSync(e))continue;let n=Z.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name));for(let o of n){if(t.has(o.name))continue;let i=Q.join(e,o.name,"SKILL.md");Z.existsSync(i)&&t.set(o.name,this.readSkill(o.name,i,r))}}return[...t.values()].sort((e,r)=>e.name.localeCompare(r.name))}getSkillByName(t){return this.getResolvedSkills().find(e=>e.name===t)??null}getSkillRoots(){let t=[{root:this.workspaceSkills,source:"workspace"}];return this.userSkills&&t.push({root:this.userSkills,source:"user"}),t.push({root:this.builtinSkills,source:"builtin"}),t}readSkill(t,e,r){let n=Z.readFileSync(e,"utf8"),o=this.parseSkill(t,n);if(o.errors.length)return{name:t,path:e,source:r,content:n,metadata:o.metadata,runtimeMeta:{},description:o.description,status:"malformed",reason:o.errors.join("; "),always:!1};let i=this.getRequirementErrors(o.runtimeMeta),a=this.runSecurityScan(e,t);if(a&&!a.isSafe&&this.scannerConfig?.blockUnsafe)return{name:t,path:e,source:r,content:n,metadata:o.metadata,runtimeMeta:o.runtimeMeta,description:o.description,status:"blocked",reason:this.formatBlockedReason(a),always:o.always};if(a&&a.findings.length>0){let l=a.findings.map(c=>`[${c.severity}] ${c.title} (${c.category})`);console.warn(`SkillScanner: skill '${t}' has ${a.findings.length} finding(s): ${l.join("; ")}`)}return{name:t,path:e,source:r,content:n,metadata:o.metadata,runtimeMeta:o.runtimeMeta,description:o.description,status:i.length?"unavailable":"available",reason:i.length?i.join("; "):null,always:o.always}}runSecurityScan(t,e){if(!this.scannerConfig?.enabled||!this.scannerConfig.scanOnLoad||!this.scanner)return null;let r=Q.dirname(t);return this.scanner.scanSkill(r,e,{maxFileCount:this.scannerConfig.maxFileCount,maxFileSizeBytes:this.scannerConfig.maxFileSizeBytes})}formatBlockedReason(t){let e=t.findings.filter(n=>n.severity==="CRITICAL");return e.length===0?"Security scan failed":`Blocked by security scanner: ${e.map(n=>`[${n.severity}] ${n.title} (${n.category})`).join("; ")}`}parseSkill(t,e){let r=this.extractFrontmatter(e);if(!r.frontmatter)return{metadata:null,runtimeMeta:{},description:t,always:!1,errors:[r.error??"missing YAML frontmatter"]};let n=this.parseFrontmatter(r.frontmatter),o=n.metadata,i=typeof o.description=="string"&&o.description.trim()?o.description.trim():t,a=[...n.errors],l=typeof o.name=="string"?o.name.trim():"";l?l!==t?a.push(`frontmatter name '${l}' does not match directory '${t}'`):Dt.test(l)||a.push(`frontmatter name '${l}' must match ${Dt}`):a.push("missing required frontmatter field 'name'"),typeof o.description=="string"&&o.description.trim()||a.push("missing required frontmatter field 'description'");let c=this.parseRuntimeMetadata(o.metadata);a.push(...c.errors);let u=o.always;return u!==void 0&&typeof u!="boolean"&&a.push("frontmatter field 'always' must be a boolean"),{metadata:o,runtimeMeta:c.runtimeMeta,description:i,always:u??c.runtimeMeta.always??!1,errors:a}}extractFrontmatter(t){if(!(t.startsWith(`---
42
+ `)||t.startsWith(`---\r
43
+ `)))return{frontmatter:null,error:"missing YAML frontmatter"};let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);return e?{frontmatter:e[1]??null,error:null}:{frontmatter:null,error:"unterminated YAML frontmatter"}}parseFrontmatter(t){let e={},r=[];for(let n of t.split(/\r?\n/)){let o=n.trim();if(!o)continue;let i=o.indexOf(":");if(i<=0){r.push(`invalid frontmatter line '${o}'`);continue}let a=o.slice(0,i).trim(),l=o.slice(i+1).trim();e[a]=this.parseFrontmatterValue(l)}return{metadata:e,errors:r}}parseFrontmatterValue(t){let e=t.replace(/^['"]|['"]$/g,"");return e==="true"?!0:e==="false"?!1:e}parseRuntimeMetadata(t){if(t===void 0||t==="")return{runtimeMeta:{},errors:[]};if(typeof t!="string")return{runtimeMeta:{},errors:["frontmatter field 'metadata' must be a JSON object string"]};let e;try{e=JSON.parse(t)}catch{return{runtimeMeta:{},errors:["frontmatter field 'metadata' must contain valid JSON"]}}if(!this.isRecord(e))return{runtimeMeta:{},errors:["frontmatter field 'metadata' must decode to an object"]};let r=e.everclaw??e.openclaw??{};if(!this.isRecord(r))return{runtimeMeta:{},errors:["skill metadata for 'everclaw'/'openclaw' must be an object"]};let n=[],o={};if(r.always!==void 0&&(typeof r.always!="boolean"?n.push("skill metadata field 'always' must be a boolean"):o.always=r.always),r.requires!==void 0)if(!this.isRecord(r.requires))n.push("skill metadata field 'requires' must be an object");else{let i=r.requires.bins,a=r.requires.env;i!==void 0&&!this.isStringArray(i)&&n.push("skill metadata field 'requires.bins' must be an array of strings"),a!==void 0&&!this.isStringArray(a)&&n.push("skill metadata field 'requires.env' must be an array of strings");let l={};this.isStringArray(i)&&(l.bins=i),this.isStringArray(a)&&(l.env=a),Object.keys(l).length>0&&(o.requires=l)}return{runtimeMeta:o,errors:n}}getRequirementErrors(t){let e=t.requires??{},r=(e.bins??[]).filter(i=>!this.hasBinary(i)),n=(e.env??[]).filter(i=>!process.env[i]),o=[];return r.length&&o.push(`missing required binaries: ${r.join(", ")}`),n.length&&o.push(`missing required env vars: ${n.join(", ")}`),o}hasBinary(t){let e=(process.env.PATH??"").split(Q.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return e.some(n=>r.some(o=>Z.existsSync(Q.join(n,`${t}${o}`))))}getAvailableSkillsHint(){let t=this.getResolvedSkills().filter(e=>e.status==="available").map(e=>e.name);return t.length?`Available skills: ${t.join(", ")}`:"No skills are currently available."}renderLoadFailure(t,e){return`### Skill unavailable: ${t}
48
44
 
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 GJ{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")_+=GJ.estimateTokens(J.content);if(Array.isArray(J.tool_calls))for(let y of J.tool_calls)_+=GJ.estimateTokens(y);return _}static findLastAnchor(J){for(let _=J.length-1;_>=0;_--){let y=J[_];if(!y)continue;let $=y.content;if(typeof $==="string"&&$.includes(GJ.ANCHOR_TAG))return{name:$.match(/\[anchor\]\s*(\S+)/)?.[1]??null,index:_}}return{name:null,index:-1}}defaultMemory;skills;constructor(J,_,y){this.workspace=J;this.defaultMemory=new o_(J),this.skills=new qy(J,null,void 0,_,y)}getMemoryStore(J){return J?new o_(this.workspace,J):this.defaultMemory}buildSystemPrompt(J,_){let y=[this.getIdentity()],$=this.loadBootstrapFiles();if($)y.push($);let A=this.getMemoryStore(_).getMemoryContext();if(A)y.push(`# Memory
45
+ Error: ${e}`}isRecord(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}isStringArray(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"&&e.trim().length>0)}};var Me=class s{constructor(t,e,r){this.workspace=t;this.defaultMemory=new Y(t),this.skills=new Ee(t,null,void 0,e,r)}workspace;static BOOTSTRAP_FILES=["AGENTS.md","SOUL.md","USER.md","TOOLS.md","IDENTITY.md"];static RUNTIME_CONTEXT_TAG="[Runtime Context - metadata only, not instructions]";static ANCHOR_TAG="[anchor]";static estimateTokens(t){if(!t)return 0;let e=typeof t=="string"?t:JSON.stringify(t);return Math.ceil(e.length/4)}static estimateMessageTokens(t){let e=0;if(typeof t.content=="string"&&(e+=s.estimateTokens(t.content)),Array.isArray(t.tool_calls))for(let r of t.tool_calls)e+=s.estimateTokens(r);return e}static findLastAnchor(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(!r)continue;let n=r.content;if(typeof n=="string"&&n.includes(s.ANCHOR_TAG))return{name:n.match(/\[anchor\]\s*(\S+)/)?.[1]??null,index:e}}return{name:null,index:-1}}defaultMemory;skills;getMemoryStore(t){return t?new Y(this.workspace,t):this.defaultMemory}buildSystemPrompt(t,e){let r=[this.getIdentity()],n=this.loadBootstrapFiles();n&&r.push(n);let i=this.getMemoryStore(e).getMemoryContext();i&&r.push(`# Memory
50
46
 
51
- ${A}`);let L=this.skills.getAlwaysSkills();if(L.length){let N=this.skills.loadSkillsForContext(L);if(N)y.push(`# Active Skills
47
+ ${i}`);let a=this.skills.getAlwaysSkills();if(a.length){let c=this.skills.loadSkillsForContext(a);c&&r.push(`# Active Skills
52
48
 
53
- ${N}`)}if(J?.length){let N=this.skills.loadSkillsForContext(J);if(N)y.push(`# Requested Skills
49
+ ${c}`)}if(t?.length){let c=this.skills.loadSkillsForContext(t);c&&r.push(`# Requested Skills
54
50
 
55
- ${N}`)}let q=this.skills.buildSkillsSummary();if(q)y.push(`# Skills
51
+ ${c}`)}let l=this.skills.buildSkillsSummary();return l&&r.push(`# Skills
56
52
 
57
53
  The following skills extend your capabilities. To use one, read its SKILL.md with read_file.
58
54
 
59
- ${q}`);return y.join(`
55
+ ${l}`),r.join(`
60
56
 
61
57
  ---
62
58
 
@@ -65,29 +61,29 @@ ${q}`);return y.join(`
65
61
  You are everclaw, a helpful AI assistant.
66
62
 
67
63
  ## Runtime
68
- ${UX.platform()} ${UX.arch()}, Node ${process.version}
64
+ ${Bt.platform()} ${Bt.arch()}, Node ${process.version}
69
65
 
70
66
  ## Workspace
71
67
  Your workspace is at: ${this.workspace}
72
- - Long-term memory: ${s_.join(this.workspace,"memory","MEMORY.md")}
73
- - History log: ${s_.join(this.workspace,"memory","HISTORY.md")}
74
- - Custom skills: ${s_.join(this.workspace,"skills","{skill-name}","SKILL.md")}
68
+ - Long-term memory: ${Re.join(this.workspace,"memory","MEMORY.md")}
69
+ - History log: ${Re.join(this.workspace,"memory","HISTORY.md")}
70
+ - Custom skills: ${Re.join(this.workspace,"skills","{skill-name}","SKILL.md")}
75
71
 
76
72
  ## Guidelines
77
73
  - State intent before tool calls, but never claim results before receiving them.
78
74
  - Before modifying a file, read it first.
79
- - Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let J=[];for(let _ of GJ.BOOTSTRAP_FILES){let y=s_.join(this.workspace,_);if(!HX.existsSync(y))continue;J.push(`## ${_}
75
+ - Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let t=[];for(let e of s.BOOTSTRAP_FILES){let r=Re.join(this.workspace,e);jt.existsSync(r)&&t.push(`## ${e}
80
76
 
81
- ${HX.readFileSync(y,"utf8")}`)}return J.join(`
77
+ ${jt.readFileSync(r,"utf8")}`)}return t.join(`
82
78
 
83
- `)}static buildRuntimeContext(J,_,y){let X=[`Current Time: ${new Date().toISOString()}`];if(J&&_)X.push(`Channel: ${J}`),X.push(`Chat ID: ${_}`);if(y?.chat_type)X.push(`Chat Type: ${y.chat_type}`);if(y?.bot_mentioned)X.push("Bot Mentioned: yes");return`${GJ.RUNTIME_CONTEXT_TAG}
84
- ${X.join(`
85
- `)}`}buildMessages(J){return[{role:"system",content:this.buildSystemPrompt(J.skillNames,J.memoryNamespace)},...J.history,{role:"user",content:GJ.buildRuntimeContext(J.channel,J.chatId,J.metadata)},{role:"user",content:J.currentMessage}]}addToolResult(J,_,y,$){return J.push({role:"tool",tool_call_id:_,name:y,content:$}),J}addAssistantMessage(J,_,y,$){let X={role:"assistant",content:_};if(y?.length)X.tool_calls=y;if($!=null)X.reasoning_content=$;return J.push(X),J}buildNotificationContext(J){let _=J.status==="completed"?"\u2713":"\u2717";if(J.kind==="cron_completed"||J.kind==="subagent_completed"||J.kind==="subagent_failed"){let y=[`[${_}] ${J.kind==="cron_completed"?"Cron Job":"Subagent"}: ${J.label}`,`Task: ${J.originalTask}`,`Status: ${J.status}`];if(J.result)y.push(`Result: ${J.result}`);if(J.error)y.push(`Error: ${J.error}`);let $=J.kind==="cron_completed"?"cron job":"subagent";return y.push("",`The ${$} has finished. Acknowledge this result briefly and continue with any follow-up work if needed.`),y.join(`
86
- `)}return`[${_}] Task: ${J.label}
87
- Status: ${J.status}`}}class Ny extends O{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),y=_.getHistory(1000),$=0;for(let q of y)$+=GJ.estimateMessageTokens(q);let X=_.getLastAnchor(),A=_.getMessagesSinceLastAnchor().length,L={messageCount:_.messages.length,tokenEstimate:$,lastAnchor:X?.name??null,messagesSinceAnchor:A};return JSON.stringify(L,null,2)}}class Gy extends O{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 y=J.summary!=null?String(J.summary):void 0,X=this.sessionManager.getOrCreate(this.sessionKey).anchor(_,y);return JSON.stringify({success:!0,anchor:{name:X.name,summary:X.summary,timestamp:X.timestamp}},null,2)}}import{readFileSync as cq,existsSync as uq}from"fs";import{join as I}from"path";import mq from"http";import{homedir as dq}from"os";import lq from"net";import EX from"ws";var pq={existsSync:uq,readFileSync:cq},YX=pq;var iq=mq,VX=iq;var nq=1;var rq="/tmp/chrome-debug-profile";function oq(J){let _=J??process.platform,y=dq(),$=I(rq,"DevToolsActivePort");switch(_){case"darwin":return[$,I(y,"Library/Application Support/Google/Chrome/DevToolsActivePort"),I(y,"Library/Application Support/Chromium/DevToolsActivePort"),I(y,"Library/Application Support/BraveSoftware/Brave-Browser/DevToolsActivePort"),I(y,"Library/Application Support/Microsoft Edge/DevToolsActivePort"),I(y,"Library/Application Support/Vivaldi/DevToolsActivePort")];case"linux":{let X=process.env.XDG_CONFIG_HOME||I(y,".config");return[$,I(X,"google-chrome","DevToolsActivePort"),I(X,"chromium","DevToolsActivePort"),I(X,"BraveSoftware","Brave-Browser","DevToolsActivePort"),I(X,"microsoft-edge","DevToolsActivePort"),I(X,"vivaldi","DevToolsActivePort"),I(y,".config","google-chrome","DevToolsActivePort"),I(y,".config","chromium","DevToolsActivePort"),I(y,"snap","chromium","common","chromium","DevToolsActivePort"),I(y,".var","app","com.google.Chrome","config","google-chrome","DevToolsActivePort"),I(y,".var","app","org.chromium.Chromium","config","chromium","DevToolsActivePort")]}case"win32":{let X=process.env.LOCALAPPDATA||I(y,"AppData","Local");return[$,I(X,"Google","Chrome","User Data","DevToolsActivePort"),I(X,"Chromium","User Data","DevToolsActivePort"),I(X,"BraveSoftware","Brave-Browser","User Data","DevToolsActivePort"),I(X,"Microsoft","Edge","User Data","DevToolsActivePort"),I(X,"Vivaldi","User Data","DevToolsActivePort")]}default:return[]}}function a_(J){return t_(J)?.port}function t_(J){let _=oq(J);for(let y of _)try{if(!YX.existsSync(y))continue;let X=YX.readFileSync(y,"utf-8").split(`
88
- `),A=X[0]?.trim(),L=X[1]?.trim()||void 0;if(A){let q=parseInt(A,10);if(q>0&&q<=65535)return{port:q,browserWsPath:L}}}catch{}return}function sq(J=9222){return new Promise((_)=>{let y=`http://127.0.0.1:${J}/json/version`,$=VX.get(y,{timeout:5000},(X)=>{if(X.statusCode!==200){X.resume(),_(void 0);return}let A=[];X.on("data",(L)=>A.push(L)),X.on("end",()=>{try{let L=Buffer.concat(A).toString("utf-8"),q=JSON.parse(L);_(q)}catch{_(void 0)}}),X.on("error",()=>_(void 0))});$.on("timeout",()=>{$.destroy(),_(void 0)}),$.on("error",()=>_(void 0))})}function aq(J,_="127.0.0.1"){return new Promise((y)=>{let $=new lq.Socket,X=2000;$.setTimeout(2000),$.once("connect",()=>{$.destroy(),y(!0)}),$.once("timeout",()=>{$.destroy(),y(!1)}),$.once("error",()=>{y(!1)}),$.connect(J,_)})}function tq(J){return new Promise((_)=>{try{let y=new EX(J),$=setTimeout(()=>{y.close(),_(!1)},3000);y.on("open",()=>{clearTimeout($),y.close(),_(!0)}),y.on("error",()=>{clearTimeout($),_(!1)})}catch{_(!1)}})}async function bX(J=9222){let _=t_(),y=_?.port??J;if(!await aq(y))return;for(let X=0;X<2;X++){try{let A=await sq(y);if(A)return{port:y,versionInfo:A}}catch{}if(X<1)await new Promise((A)=>setTimeout(A,500))}if(_?.browserWsPath){let X=`ws://127.0.0.1:${y}${_.browserWsPath}`;if(await tq(X))return{port:y,versionInfo:{Browser:"Chrome","Protocol-Version":"1.3","User-Agent":"","V8-Version":"","WebKit-Version":"",webSocketDebuggerUrl:X}}}return new Promise((X)=>{let A=VX.get(`http://127.0.0.1:${y}/json/version`,{timeout:3000},(L)=>{if(L.resume(),L.statusCode===404||L.statusCode===403)X({port:y,versionInfo:{},pendingApproval:!0});else X(void 0)});A.on("error",()=>X(void 0)),A.on("timeout",()=>{A.destroy(),X(void 0)})})}async function Y_(J){let y=t_()?.browserWsPath;if(!y)return[];let $=await WJ.connect(`ws://127.0.0.1:${J}${y}`);try{return((await $.send("Target.getTargets")).targetInfos??[]).map((L)=>({id:L.targetId,type:L.type,title:L.title,url:L.url,webSocketDebuggerUrl:L.webSocketDebuggerUrl??`ws://127.0.0.1:${J}/devtools/page/${L.targetId}`}))}finally{$.close()}}async function MX(J,_){let $=t_()?.browserWsPath;if(!$)throw new Error("No browser WebSocket path found in DevToolsActivePort");let X=await WJ.connect(`ws://127.0.0.1:${J}${$}`);try{let L=(await X.send("Target.createTarget",{url:_})).targetId;if(!L)throw new Error("Target.createTarget returned no targetId");return{id:L,type:"page",title:"",url:_,webSocketDebuggerUrl:`ws://127.0.0.1:${J}/devtools/page/${L}`}}finally{X.close()}}class WJ{ws;nextId=1;pending=new Map;eventListeners=new Map;closed=!1;constructor(J){this.ws=J}static connect(J){return new Promise((_,y)=>{let $=new EX(J);$.on("open",()=>{let X=new WJ($);WJ.attachHandlers(X,$),_(X)}),$.on("error",(...X)=>{let A=X[0];y(new Error(`Failed to connect to CDP: ${A.message}`))})})}static fromWebSocket(J){let _=new WJ(J);return WJ.attachHandlers(_,J),_}static attachHandlers(J,_){_.on("message",(y)=>{let $=typeof y==="string"?y:Buffer.from(y).toString("utf-8");J.handleMessage($)}),_.on("close",()=>{J.closed=!0;for(let[,y]of J.pending)y.reject(new Error("WebSocket closed"));J.pending.clear()}),_.on("error",(...y)=>{let $=y[0];for(let[,X]of J.pending)X.reject($);J.pending.clear()})}async send(J,_){if(this.closed||this.ws.readyState!==nq)throw new Error("WebSocket is closed");let y=this.nextId++,$=JSON.stringify({id:y,method:J,params:_??{}});return new Promise((X,A)=>{this.pending.set(y,{resolve:X,reject:A}),this.ws.send($)})}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((y,$)=>{let X=setTimeout(()=>{A(),$(new Error(`Timeout waiting for event '${J}' after ${_}ms`))},_),A=this.onEvent(J,(L)=>{clearTimeout(X),A(),y(L)})})}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 y=_,$=this.pending.get(y.id);if($)if(this.pending.delete(y.id),y.error)$.reject(new Error(`CDP error ${y.error.code}: ${y.error.message}`));else $.resolve(y.result??{});return}if("method"in _&&typeof _.method==="string"){let y=_,$=this.eventListeners.get(y.method);if($)for(let X of $)try{X(y.params??{})}catch{}}}}import{spawn as J4}from"child_process";import{createConnection as _4}from"net";import{tmpdir as y4}from"os";import{join as SX,dirname as $4}from"path";import{unlink as X4,unlinkSync as A4,mkdirSync as L4,existsSync as e_}from"fs";import PJ from"fs";var eq=typeof globalThis.Bun!=="undefined";function By(J){let _="electron"in process.versions,y=J;try{y=PJ.realpathSync(J)}catch{}let $,X;if(y.endsWith(".js")){if(!PJ.existsSync(y))throw new Error(`No executable found: ${y} does not exist.`);$=y,X=!1}else if(y.endsWith(".ts")){if(!PJ.existsSync(y))throw new Error(`No executable found: ${y} does not exist.`);$=y,X=!0}else{let q=y+".js",N=y+".ts";if(PJ.existsSync(q)){try{$=PJ.realpathSync(q)}catch{$=q}X=!1}else if(PJ.existsSync(N)){try{$=PJ.realpathSync(N)}catch{$=N}X=!0}else throw new Error(`No executable found: neither ${q} nor ${N} exists.`)}let A=process.execPath,L=!eq&&X?["--import","tsx",$]:[$];if(_)return{file:A,args:L,env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}};return{file:A,args:L,env:process.env}}var q4=null,N4=null,G4=null,B4=!1;function E_(){return N4??process.platform}function Q4(){return q4??J4}function K4(){return G4??_4}function R4(J,_){let y=E_(),$=_??y4(),X=J.replace(/[^a-zA-Z0-9]/g,"_").slice(0,32);if(y==="win32")return`\\\\.\\pipe\\airclaw-daemon-${X}`;return SX($,`airclaw-daemon-${X}.sock`)}function ZX(J,_){let y=J.split(`
89
- `),$=y.pop()??"";for(let X of y){let A=X.trim();if(A)try{let L=JSON.parse(A);_(L)}catch{}}return $}class xJ{static instance=null;daemons=new Map;constructor(){}static getInstance(){if(!xJ.instance)xJ.instance=new xJ;return xJ.instance}async getOrCreateDaemon(J,_,y){if(this.daemons.has(J))return;let $=R4(J,y?.socketDir),X=y?.idleTimeoutMs??1200000;if(E_()==="win32"||e_($)){let Q={targetId:J,child:null,socketPath:$,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),E_()!=="win32"&&e_($))try{A4($)}catch{}}}let A=$4($);if(!e_(A)&&E_()!=="win32")try{L4(A,{recursive:!0})}catch{}let L={targetId:J,child:null,socketPath:$,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};if(this.daemons.set(J,L),B4)return;let q=S_("agent","tools","chrome-session","daemon-worker")??SX(import.meta.dirname,"daemon-worker"),{file:N,args:G,env:B}=By(q),R=Q4()(N,[...G,"--target",J,"--ws-url",_,"--socket",$,"--idle-timeout",String(X)],{stdio:["ignore","pipe","pipe"],detached:!1,env:B});L.child=R,R.on("exit",()=>{this.cleanupDaemon(J)}),R.on("error",()=>{this.cleanupDaemon(J)}),await new Promise((Q,K)=>{let Y=setTimeout(()=>{K(new Error("Daemon startup timeout"))},1e4),Z=(S)=>{if(S.toString("utf8").includes("READY"))clearTimeout(Y),R.stdout?.off("data",Z),Q()};R.stdout?.on("data",Z)}),await this.connectToDaemon(J)}async connectToDaemon(J){let _=this.daemons.get(J);if(!_)throw new Error(`No daemon for target ${J}`);return new Promise((y,$)=>{let X=K4()(_.socketPath);X.on("connect",()=>{_.clientSocket=X,X.on("data",(A)=>{_.ndjsonBuffer=ZX(_.ndjsonBuffer+A.toString("utf8"),(L)=>{let q=_.pendingCommands.get(L.id);if(q)_.pendingCommands.delete(L.id),q.resolve(L)})}),X.on("close",()=>{_.clientSocket=null;for(let[,A]of _.pendingCommands)A.reject(new Error("Daemon socket closed"));_.pendingCommands.clear()}),X.on("error",()=>{}),y()}),X.on("error",(A)=>{$(new Error(`Failed to connect to daemon: ${A.message}`))}),setTimeout(()=>{if(!_.clientSocket)X.destroy(),$(new Error("Daemon connection timeout"))},5000)})}async sendCommand(J,_,y={}){let $=this.daemons.get(J);if(!$)throw new Error(`No daemon for target ${J}`);if(!$.clientSocket)throw new Error(`Daemon socket not connected for ${J}`);let X=$.commandId++,L=JSON.stringify({id:X,cmd:_,args:y})+`
90
- `;return new Promise((q,N)=>{$.pendingCommands.set(X,{resolve:q,reject:N});try{$.clientSocket.write(L)}catch(G){$.pendingCommands.delete(X),N(G)}setTimeout(()=>{if($.pendingCommands.has(X))$.pendingCommands.delete(X),N(new Error(`Command ${X} 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 y=this.daemons.get(J);if(y){if(y.clientSocket=_,_)_.on("data",($)=>{y.ndjsonBuffer=ZX(y.ndjsonBuffer+$.toString("utf8"),(X)=>{let A=y.pendingCommands.get(X.id);if(A)y.pendingCommands.delete(X.id),A.resolve(X)})}),_.on("close",()=>{y.clientSocket=null;for(let[,$]of y.pendingCommands)$.reject(new Error("Daemon socket closed"));y.pendingCommands.clear()})}}cleanupDaemon(J){let _=this.daemons.get(J);if(!_)return;if(_.clientSocket)_.clientSocket.destroy();if(_.child)_.child.kill("SIGTERM");for(let[,y]of _.pendingCommands)y.reject(new Error("Daemon stopped"));if(E_()!=="win32"&&e_(_.socketPath))X4(_.socketPath,()=>{});this.daemons.delete(J)}}import{writeFileSync as H4,mkdirSync as U4,existsSync as Y4}from"fs";import{dirname as E4,join as J0}from"path";import{tmpdir as V4}from"os";var Qy={minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8};class _0 extends O{name="chrome_session";description=`Interact with Chrome browser via Chrome DevTools Protocol (CDP).
79
+ `)}static buildRuntimeContext(t,e,r){let o=[`Current Time: ${new Date().toISOString()}`];return t&&e&&(o.push(`Channel: ${t}`),o.push(`Chat ID: ${e}`)),r?.chat_type&&o.push(`Chat Type: ${r.chat_type}`),r?.bot_mentioned&&o.push("Bot Mentioned: yes"),`${s.RUNTIME_CONTEXT_TAG}
80
+ ${o.join(`
81
+ `)}`}buildMessages(t){return[{role:"system",content:this.buildSystemPrompt(t.skillNames,t.memoryNamespace)},...t.history,{role:"user",content:s.buildRuntimeContext(t.channel,t.chatId,t.metadata)},{role:"user",content:t.currentMessage}]}addToolResult(t,e,r,n){return t.push({role:"tool",tool_call_id:e,name:r,content:n}),t}addAssistantMessage(t,e,r,n){let o={role:"assistant",content:e};return r?.length&&(o.tool_calls=r),n!=null&&(o.reasoning_content=n),t.push(o),t}buildNotificationContext(t){let e=t.status==="completed"?"\u2713":"\u2717";if(t.kind==="cron_completed"||t.kind==="subagent_completed"||t.kind==="subagent_failed"){let r=[`[${e}] ${t.kind==="cron_completed"?"Cron Job":"Subagent"}: ${t.label}`,`Task: ${t.originalTask}`,`Status: ${t.status}`];t.result&&r.push(`Result: ${t.result}`),t.error&&r.push(`Error: ${t.error}`);let n=t.kind==="cron_completed"?"cron job":"subagent";return r.push("",`The ${n} has finished. Acknowledge this result briefly and continue with any follow-up work if needed.`),r.join(`
82
+ `)}return`[${e}] Task: ${t.label}
83
+ Status: ${t.status}`}};var _e=class extends g{name="session.info";description="Returns information about the current session: message count, token estimate, last anchor name, and messages since last anchor.";parameters={type:"object",properties:{},required:[]};sessionManager=null;sessionKey="cli:direct";setSessionManager(t){this.sessionManager=t}setContext(t){this.sessionKey=t}async execute(t){if(!this.sessionManager)return"Error: Session manager not available";let e=this.sessionManager.getOrCreate(this.sessionKey),r=e.getHistory(1e3),n=0;for(let l of r)n+=Me.estimateMessageTokens(l);let o=e.getLastAnchor(),i=e.getMessagesSinceLastAnchor().length,a={messageCount:e.messages.length,tokenEstimate:n,lastAnchor:o?.name??null,messagesSinceAnchor:i};return JSON.stringify(a,null,2)}};var Le=class extends g{name="session.anchor";description="Create a named anchor in the session. Messages before the anchor become eligible for summarization. Anchors survive consolidation.";parameters={type:"object",properties:{name:{type:"string",description:"The name of the anchor"},summary:{type:"string",description:"Optional summary describing what happened before this anchor"}},required:["name"]};sessionManager=null;sessionKey="cli:direct";setSessionManager(t){this.sessionManager=t}setContext(t){this.sessionKey=t}async execute(t){if(!this.sessionManager)return"Error: Session manager not available";let e=String(t.name??"");if(!e)return"Error: Anchor name is required";let r=t.summary!=null?String(t.summary):void 0,o=this.sessionManager.getOrCreate(this.sessionKey).anchor(e,r);return JSON.stringify({success:!0,anchor:{name:o.name,summary:o.summary,timestamp:o.timestamp}},null,2)}};import{readFileSync as Or,existsSync as $r}from"node:fs";import{join as y}from"node:path";import Ir from"node:http";import{homedir as Nr}from"node:os";import Dr from"node:net";import Jt from"ws";var jr={existsSync:$r,readFileSync:Or},Ft=jr;var Br=Ir,Ut=Br;var Fr=1;var Jr="/tmp/chrome-debug-profile";function Ur(s){let t=s??process.platform,e=Nr(),r=y(Jr,"DevToolsActivePort");switch(t){case"darwin":return[r,y(e,"Library/Application Support/Google/Chrome/DevToolsActivePort"),y(e,"Library/Application Support/Chromium/DevToolsActivePort"),y(e,"Library/Application Support/BraveSoftware/Brave-Browser/DevToolsActivePort"),y(e,"Library/Application Support/Microsoft Edge/DevToolsActivePort"),y(e,"Library/Application Support/Vivaldi/DevToolsActivePort")];case"linux":{let n=process.env.XDG_CONFIG_HOME||y(e,".config");return[r,y(n,"google-chrome","DevToolsActivePort"),y(n,"chromium","DevToolsActivePort"),y(n,"BraveSoftware","Brave-Browser","DevToolsActivePort"),y(n,"microsoft-edge","DevToolsActivePort"),y(n,"vivaldi","DevToolsActivePort"),y(e,".config","google-chrome","DevToolsActivePort"),y(e,".config","chromium","DevToolsActivePort"),y(e,"snap","chromium","common","chromium","DevToolsActivePort"),y(e,".var","app","com.google.Chrome","config","google-chrome","DevToolsActivePort"),y(e,".var","app","org.chromium.Chromium","config","chromium","DevToolsActivePort")]}case"win32":{let n=process.env.LOCALAPPDATA||y(e,"AppData","Local");return[r,y(n,"Google","Chrome","User Data","DevToolsActivePort"),y(n,"Chromium","User Data","DevToolsActivePort"),y(n,"BraveSoftware","Brave-Browser","User Data","DevToolsActivePort"),y(n,"Microsoft","Edge","User Data","DevToolsActivePort"),y(n,"Vivaldi","User Data","DevToolsActivePort")]}default:return[]}}function Oe(s){return $e(s)?.port}function $e(s){let t=Ur(s);for(let e of t)try{if(!Ft.existsSync(e))continue;let n=Ft.readFileSync(e,"utf-8").split(`
84
+ `),o=n[0]?.trim(),i=n[1]?.trim()||void 0;if(o){let a=parseInt(o,10);if(a>0&&a<=65535)return{port:a,browserWsPath:i}}}catch{}}function qr(s=9222){return new Promise(t=>{let e=`http://127.0.0.1:${s}/json/version`,r=Ut.get(e,{timeout:5e3},n=>{if(n.statusCode!==200){n.resume(),t(void 0);return}let o=[];n.on("data",i=>o.push(i)),n.on("end",()=>{try{let i=Buffer.concat(o).toString("utf-8"),a=JSON.parse(i);t(a)}catch{t(void 0)}}),n.on("error",()=>t(void 0))});r.on("timeout",()=>{r.destroy(),t(void 0)}),r.on("error",()=>t(void 0))})}function Wr(s,t="127.0.0.1"){return new Promise(e=>{let r=new Dr.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),e(!0)}),r.once("timeout",()=>{r.destroy(),e(!1)}),r.once("error",()=>{e(!1)}),r.connect(s,t)})}function Gr(s){return new Promise(t=>{try{let e=new Jt(s),r=setTimeout(()=>{e.close(),t(!1)},3e3);e.on("open",()=>{clearTimeout(r),e.close(),t(!0)}),e.on("error",()=>{clearTimeout(r),t(!1)})}catch{t(!1)}})}async function qt(s=9222){let t=$e(),e=t?.port??s;if(await Wr(e)){for(let n=0;n<2;n++){try{let o=await qr(e);if(o)return{port:e,versionInfo:o}}catch{}n<1&&await new Promise(o=>setTimeout(o,500))}if(t?.browserWsPath){let n=`ws://127.0.0.1:${e}${t.browserWsPath}`;if(await Gr(n))return{port:e,versionInfo:{Browser:"Chrome","Protocol-Version":"1.3","User-Agent":"","V8-Version":"","WebKit-Version":"",webSocketDebuggerUrl:n}}}return new Promise(n=>{let o=Ut.get(`http://127.0.0.1:${e}/json/version`,{timeout:3e3},i=>{i.resume(),i.statusCode===404||i.statusCode===403?n({port:e,versionInfo:{},pendingApproval:!0}):n(void 0)});o.on("error",()=>n(void 0)),o.on("timeout",()=>{o.destroy(),n(void 0)})})}}async function ee(s){let e=$e()?.browserWsPath;if(!e)return[];let r=await Pe.connect(`ws://127.0.0.1:${s}${e}`);try{return((await r.send("Target.getTargets")).targetInfos??[]).map(i=>({id:i.targetId,type:i.type,title:i.title,url:i.url,webSocketDebuggerUrl:i.webSocketDebuggerUrl??`ws://127.0.0.1:${s}/devtools/page/${i.targetId}`}))}finally{r.close()}}async function Wt(s,t){let r=$e()?.browserWsPath;if(!r)throw new Error("No browser WebSocket path found in DevToolsActivePort");let n=await Pe.connect(`ws://127.0.0.1:${s}${r}`);try{let i=(await n.send("Target.createTarget",{url:t})).targetId;if(!i)throw new Error("Target.createTarget returned no targetId");return{id:i,type:"page",title:"",url:t,webSocketDebuggerUrl:`ws://127.0.0.1:${s}/devtools/page/${i}`}}finally{n.close()}}var Pe=class s{ws;nextId=1;pending=new Map;eventListeners=new Map;closed=!1;constructor(t){this.ws=t}static connect(t){return new Promise((e,r)=>{let n=new Jt(t);n.on("open",()=>{let o=new s(n);s.attachHandlers(o,n),e(o)}),n.on("error",(...o)=>{let i=o[0];r(new Error(`Failed to connect to CDP: ${i.message}`))})})}static fromWebSocket(t){let e=new s(t);return s.attachHandlers(e,t),e}static attachHandlers(t,e){e.on("message",r=>{let n=typeof r=="string"?r:Buffer.from(r).toString("utf-8");t.handleMessage(n)}),e.on("close",()=>{t.closed=!0;for(let[,r]of t.pending)r.reject(new Error("WebSocket closed"));t.pending.clear()}),e.on("error",(...r)=>{let n=r[0];for(let[,o]of t.pending)o.reject(n);t.pending.clear()})}async send(t,e){if(this.closed||this.ws.readyState!==Fr)throw new Error("WebSocket is closed");let r=this.nextId++,n=JSON.stringify({id:r,method:t,params:e??{}});return new Promise((o,i)=>{this.pending.set(r,{resolve:o,reject:i}),this.ws.send(n)})}onEvent(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t).add(e),()=>{this.eventListeners.get(t)?.delete(e)}}waitForEvent(t,e=1e4){return new Promise((r,n)=>{let o=setTimeout(()=>{i(),n(new Error(`Timeout waiting for event '${t}' after ${e}ms`))},e),i=this.onEvent(t,a=>{clearTimeout(o),i(),r(a)})})}close(){if(!this.closed){this.closed=!0;try{this.ws.close()}catch{}}}handleMessage(t){let e;try{e=JSON.parse(t)}catch{return}if("id"in e&&typeof e.id=="number"){let r=e,n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(`CDP error ${r.error.code}: ${r.error.message}`)):n.resolve(r.result??{}));return}if("method"in e&&typeof e.method=="string"){let r=e,n=this.eventListeners.get(r.method);if(n)for(let o of n)try{o(r.params??{})}catch{}}}};import{spawn as Kr}from"node:child_process";import{createConnection as Hr}from"node:net";import{tmpdir as Vr}from"node:os";import{join as Kt,dirname as zr}from"node:path";import{unlink as Xr,unlinkSync as Yr,mkdirSync as Zr,existsSync as Ie}from"node:fs";import j from"node:fs";function et(s){let t="electron"in process.versions,e=s;try{e=j.realpathSync(s)}catch{}let r,n;if(e.endsWith(".js")){if(!j.existsSync(e))throw new Error(`No executable found: ${e} does not exist.`);r=e,n=!1}else if(e.endsWith(".ts")){if(!j.existsSync(e))throw new Error(`No executable found: ${e} does not exist.`);r=e,n=!0}else{let a=e+".js",l=e+".ts";if(j.existsSync(a)){try{r=j.realpathSync(a)}catch{r=a}n=!1}else if(j.existsSync(l)){try{r=j.realpathSync(l)}catch{r=l}n=!0}else throw new Error(`No executable found: neither ${a} nor ${l} exists.`)}let o=process.execPath,i=n?["--import","tsx",r]:[r];return t?{file:o,args:i,env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}}:{file:o,args:i,env:process.env}}var Qr=null,en=null,tn=null,rn=!1;function te(){return en??process.platform}function nn(){return Qr??Kr}function on(){return tn??Hr}function sn(s,t){let e=te(),r=t??Vr(),n=s.replace(/[^a-zA-Z0-9]/g,"_").slice(0,32);return e==="win32"?`\\\\.\\pipe\\airclaw-daemon-${n}`:Kt(r,`airclaw-daemon-${n}.sock`)}function Gt(s,t){let e=s.split(`
85
+ `),r=e.pop()??"";for(let n of e){let o=n.trim();if(o)try{let i=JSON.parse(o);t(i)}catch{}}return r}var Ne=class s{static instance=null;daemons=new Map;constructor(){}static getInstance(){return s.instance||(s.instance=new s),s.instance}async getOrCreateDaemon(t,e,r){if(this.daemons.has(t))return;let n=sn(t,r?.socketDir),o=r?.idleTimeoutMs??12e5;if(te()==="win32"||Ie(n)){let p={targetId:t,child:null,socketPath:n,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};this.daemons.set(t,p);try{await this.connectToDaemon(t);return}catch{if(this.daemons.delete(t),te()!=="win32"&&Ie(n))try{Yr(n)}catch{}}}let i=zr(n);if(!Ie(i)&&te()!=="win32")try{Zr(i,{recursive:!0})}catch{}let a={targetId:t,child:null,socketPath:n,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};if(this.daemons.set(t,a),rn)return;let l=Kt(import.meta.dirname,"daemon-worker"),{file:c,args:u,env:d}=et(l),m=nn()(c,[...u,"--target",t,"--ws-url",e,"--socket",n,"--idle-timeout",String(o)],{stdio:["ignore","pipe","pipe"],detached:!1,env:d});a.child=m,m.on("exit",()=>{this.cleanupDaemon(t)}),m.on("error",()=>{this.cleanupDaemon(t)}),await new Promise((p,f)=>{let b=setTimeout(()=>{f(new Error("Daemon startup timeout"))},1e4),T=x=>{x.toString("utf8").includes("READY")&&(clearTimeout(b),m.stdout?.off("data",T),p())};m.stdout?.on("data",T)}),await this.connectToDaemon(t)}async connectToDaemon(t){let e=this.daemons.get(t);if(!e)throw new Error(`No daemon for target ${t}`);return new Promise((r,n)=>{let o=on()(e.socketPath);o.on("connect",()=>{e.clientSocket=o,o.on("data",i=>{e.ndjsonBuffer=Gt(e.ndjsonBuffer+i.toString("utf8"),a=>{let l=e.pendingCommands.get(a.id);l&&(e.pendingCommands.delete(a.id),l.resolve(a))})}),o.on("close",()=>{e.clientSocket=null;for(let[,i]of e.pendingCommands)i.reject(new Error("Daemon socket closed"));e.pendingCommands.clear()}),o.on("error",()=>{}),r()}),o.on("error",i=>{n(new Error(`Failed to connect to daemon: ${i.message}`))}),setTimeout(()=>{e.clientSocket||(o.destroy(),n(new Error("Daemon connection timeout")))},5e3)})}async sendCommand(t,e,r={}){let n=this.daemons.get(t);if(!n)throw new Error(`No daemon for target ${t}`);if(!n.clientSocket)throw new Error(`Daemon socket not connected for ${t}`);let o=n.commandId++,a=JSON.stringify({id:o,cmd:e,args:r})+`
86
+ `;return new Promise((l,c)=>{n.pendingCommands.set(o,{resolve:l,reject:c});try{n.clientSocket.write(a)}catch(u){n.pendingCommands.delete(o),c(u)}setTimeout(()=>{n.pendingCommands.has(o)&&(n.pendingCommands.delete(o),c(new Error(`Command ${o} timed out`)))},3e4)})}hasDaemon(t){return this.daemons.has(t)}getSocketPath(t){return this.daemons.get(t)?.socketPath}stopDaemon(t){let e=this.daemons.get(t);e&&(e.clientSocket&&e.clientSocket.destroy(),e.child&&e.child.kill("SIGTERM"),this.cleanupDaemon(t))}stopAll(){for(let t of this.daemons.keys())this.stopDaemon(t)}getActiveTargets(){return Array.from(this.daemons.keys())}__setClientSocket(t,e){let r=this.daemons.get(t);r&&(r.clientSocket=e,e&&(e.on("data",n=>{r.ndjsonBuffer=Gt(r.ndjsonBuffer+n.toString("utf8"),o=>{let i=r.pendingCommands.get(o.id);i&&(r.pendingCommands.delete(o.id),i.resolve(o))})}),e.on("close",()=>{r.clientSocket=null;for(let[,n]of r.pendingCommands)n.reject(new Error("Daemon socket closed"));r.pendingCommands.clear()})))}cleanupDaemon(t){let e=this.daemons.get(t);if(e){e.clientSocket&&e.clientSocket.destroy(),e.child&&e.child.kill("SIGTERM");for(let[,r]of e.pendingCommands)r.reject(new Error("Daemon stopped"));te()!=="win32"&&Ie(e.socketPath)&&Xr(e.socketPath,()=>{}),this.daemons.delete(t)}}};import{writeFileSync as an,mkdirSync as ln,existsSync as cn}from"node:fs";import{dirname as un,join as De}from"node:path";import{tmpdir as dn}from"node:os";var tt={minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8},re=class extends g{name="chrome_session";description=`Interact with Chrome browser via Chrome DevTools Protocol (CDP).
91
87
 
92
88
  Core Commands:
93
89
  - status: Check Chrome connectivity, version, and remote debugging status
@@ -122,19 +118,19 @@ Examples:
122
118
  - chrome_session clickxy --target "ABC123" --x 100 --y 200
123
119
  - chrome_session type --target "ABC123" --text "Hello World"
124
120
  - 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}
126
- // Tool: ${J.toolType??"auto-detect"}
127
- // Generated: ${_}
128
- // Description: ${J.description}
121
+ - chrome_session evalraw --target "ABC123" --method "Page.getTitle" --params '{}'`;parameters={type:"object",properties:{command:{type:"string",description:"The command to execute",enum:["status","list","open","stop","snap","shot","eval","html","nav","net","click","clickxy","type","loadall","evalraw"]},target:{type:"string",description:"Target ID prefix (required for page interaction commands)"},url:{type:"string",description:"URL to open (for 'open' and 'nav' commands)"},path:{type:"string",description:"File path to save screenshot (for 'shot' command)"},selector:{type:"string",description:"CSS selector for element-specific operations (for 'shot', 'html', 'click', 'loadall' commands)"},expression:{type:"string",description:"JavaScript expression to evaluate (for 'eval' command)"},depth:{type:"number",description:"Maximum depth for accessibility tree (for 'snap' command)"},timeout:{type:"number",description:"Timeout in milliseconds (for 'nav' command)"},outer:{type:"boolean",description:"Return outer HTML (default true, for 'html' command)"},x:{type:"number",description:"X coordinate in CSS pixels (for 'clickxy' command)"},y:{type:"number",description:"Y coordinate in CSS pixels (for 'clickxy' command)"},text:{type:"string",description:"Text to type at focused element (for 'type' command)"},interval:{type:"number",description:"Interval in milliseconds between clicks (for 'loadall' command, default 500)"},method:{type:"string",description:"CDP method name (for 'evalraw' command)"},params:{type:"object",description:"CDP method parameters as JSON object (for 'evalraw' command)"}},required:["command"]};config;daemonManager;commands;workspace;restrictToWorkspace;constructor(t={},e,r=!1){super(),this.config={minChromeVersion:t.minChromeVersion??tt.minChromeVersion,daemonIdleTimeoutS:t.daemonIdleTimeoutS??tt.daemonIdleTimeoutS,targetPrefixLength:t.targetPrefixLength??tt.targetPrefixLength,...t.stealth?{stealth:t.stealth}:{}},this.workspace=e,this.restrictToWorkspace=r,this.daemonManager=Ne.getInstance(),this.commands=new Map([["status",this.handleStatus.bind(this)],["list",this.handleList.bind(this)],["open",this.handleOpen.bind(this)],["stop",this.handleStop.bind(this)],["snap",this.handleSnap.bind(this)],["shot",this.handleShot.bind(this)],["eval",this.handleEval.bind(this)],["html",this.handleHtml.bind(this)],["nav",this.handleNav.bind(this)],["net",this.handleNet.bind(this)],["click",this.handleClick.bind(this)],["clickxy",this.handleClickxy.bind(this)],["type",this.handleType.bind(this)],["loadall",this.handleLoadall.bind(this)],["evalraw",this.handleEvalraw.bind(this)]])}async execute(t,e){let r=t.command;if(!r)return this.formatError("Missing required 'command' parameter. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw");let n=this.commands.get(r);if(!n)return this.formatError(`Unknown command '${r}'. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw`);try{return await n(t,e)}catch(o){let i=o instanceof Error?o.message:String(o);return this.formatError(`Command '${r}' failed: ${i}`)}}async handleStatus(){let t=this.config,e=await qt();if(!e)return this.formatResult({available:!1,reason:"Chrome remote debugging not detected",hint:"Enable remote debugging in Chrome at chrome://inspect/#remote-debugging or launch Chrome with --remote-debugging-port=9222"});if(e.pendingApproval)return this.formatResult({available:!1,pendingApproval:!0,reason:`Chrome is listening on port ${e.port} but remote debugging approval may be required`,hint:"Look for a remote debugging approval prompt in Chrome, or quit Chrome and relaunch with: open -a 'Google Chrome' --args --remote-debugging-port=9222",port:e.port});let{port:r,versionInfo:n}=e,o=n.Browser.match(/(\w+)\/(\d+)/),i=o?.[1]??"Chrome",a=o?parseInt(o[2],10):0;return a>0&&a<t.minChromeVersion?this.formatResult({available:!1,reason:`Chrome version ${a} is below minimum required version ${t.minChromeVersion}`,hint:`Update Chrome to version ${t.minChromeVersion} or higher`,version:n.Browser,port:r,browser:i}):this.formatResult({available:!0,version:n.Browser,protocolVersion:n["Protocol-Version"],userAgent:n["User-Agent"],webSocketDebuggerUrl:n.webSocketDebuggerUrl,port:r,browser:i})}async handleList(){let t=Oe();if(!t)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let e;try{let i=await fetch(`http://127.0.0.1:${t}/json/list`);i.ok?e=await i.json():e=await ee(t)}catch{e=await ee(t)}let r=e.filter(i=>i.type==="page"&&!i.url.startsWith("chrome://"));if(r.length===0)return this.formatResult({tabs:[],message:"No open tabs found"});let n=this.config.targetPrefixLength,o=r.map(i=>({id:i.id.slice(0,n),fullId:i.id,title:i.title,url:i.url}));return this.formatResult({tabs:o,count:o.length})}async handleOpen(t){let e=Oe();if(!e)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let r=t.url??"about:blank",n=this.config.targetPrefixLength;try{let o=await fetch(`http://127.0.0.1:${e}/json/new?${r}`,{method:"PUT"});if(o.ok){let i=await o.json();return this.formatResult({success:!0,id:i.id.slice(0,n),fullId:i.id,url:i.url,message:`Opened new tab: ${i.url}`})}}catch{}try{let o=await Wt(e,r);return this.formatResult({success:!0,id:o.id.slice(0,n),fullId:o.id,url:o.url,message:`Opened new tab: ${o.url}`})}catch(o){return this.formatError(`Cannot open tab via HTTP or WebSocket on port ${e}: ${o instanceof Error?o.message:String(o)}. Run 'chrome_session status' for details.`)}}async handleStop(t){let e=t.target;if(e){let o=this.daemonManager.getActiveTargets().find(i=>i.toUpperCase().startsWith(e.toUpperCase()));return o?(this.daemonManager.stopDaemon(o),this.formatResult({success:!0,target:o.slice(0,this.config.targetPrefixLength),message:`Stopped daemon for target ${o.slice(0,this.config.targetPrefixLength)}`})):this.formatError(`No daemon found for target prefix '${e}'`)}let r=this.daemonManager.getActiveTargets().length;return r===0?this.formatResult({success:!0,message:"No active daemons to stop"}):(this.daemonManager.stopAll(),this.formatResult({success:!0,message:`Stopped ${r} daemon(s)`}))}async handleSnap(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n={};t.depth!==void 0&&(n.depth=t.depth);let o=await this.sendDaemonCommand(e,r,"snap",n);return o.ok?this.formatResult({tree:o.result?.tree,nodeCount:o.result?.nodeCount}):this.formatError(o.error??"Failed to get accessibility tree")}async handleShot(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.path,o=this.resolveScreenshotPath(n),i={};o&&(i.path=o),t.selector&&(i.selector=t.selector);let a=await this.sendDaemonCommand(e,r,"shot",i);return a.ok?(o&&a.result?.data&&this.saveScreenshot(o,a.result.data),this.formatResult({path:o,dpr:a.result?.dpr,viewport:a.result?.viewport,message:o?`Screenshot saved to ${o}`:"Screenshot captured (base64 data in 'data' field)",data:o?void 0:a.result?.data})):this.formatError(a.error??"Failed to capture screenshot")}async handleEval(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.expression;if(!n)return this.formatError("Missing required 'expression' parameter");let o=await this.sendDaemonCommand(e,r,"eval",{expression:n,awaitPromise:!0});return o.ok?this.formatResult({ok:!0,result:o.result?.result,type:o.result?.type,subtype:o.result?.subtype}):this.formatError(o.error??"JavaScript evaluation failed")}async handleHtml(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n={};t.selector&&(n.selector=t.selector),t.outer!==void 0&&(n.outer=t.outer);let o=await this.sendDaemonCommand(e,r,"html",n);return o.ok?this.formatResult({html:o.result?.html,selector:o.result?.selector}):this.formatError(o.error??"Failed to get HTML")}async handleNav(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.url;if(!n)return this.formatError("Missing required 'url' parameter");let o={url:n};t.timeout!==void 0&&(o.timeout=t.timeout);let i=await this.sendDaemonCommand(e,r,"nav",o);return i.ok?this.formatResult({ok:!0,url:i.result?.url,frameId:i.result?.frameId,loaderId:i.result?.loaderId,message:i.result?.message}):this.formatError(i.error??"Navigation failed")}async handleNet(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=await this.sendDaemonCommand(e,r,"net",{});return n.ok?this.formatResult({entries:n.result?.entries,count:n.result?.count}):this.formatError(n.error??"Failed to get network timing")}async handleClick(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.selector;if(!n)return this.formatError("Missing required 'selector' parameter");let o=await this.sendDaemonCommand(e,r,"click",{selector:n});return o.ok?this.formatResult({ok:!0,selector:n,tag:o.result?.tag,text:o.result?.text,message:o.result?.message}):this.formatError(o.error??"Click failed")}async handleClickxy(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.x,o=t.y;if(typeof n!="number"||typeof o!="number")return this.formatError("Missing required 'x' and 'y' parameters");let i=await this.sendDaemonCommand(e,r,"clickxy",{x:n,y:o});return i.ok?this.formatResult({ok:!0,x:n,y:o,message:`Clicked at (${n}, ${o})`}):this.formatError(i.error??"Click at coordinates failed")}async handleType(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.text;if(!n)return this.formatError("Missing required 'text' parameter");let o=await this.sendDaemonCommand(e,r,"type",{text:n});return o.ok?this.formatResult({ok:!0,text:n,message:`Typed ${n.length} character(s)`}):this.formatError(o.error??"Type failed")}async handleLoadall(t,e){let{targetId:r,wsUrl:n}=await this.resolveTarget(t.target),o=t.selector,i=t.interval??500;if(!o)return this.formatError("Missing required 'selector' parameter");let a=await this.sendDaemonCommand(r,n,"loadall",{selector:o,interval:i,timeout:3e5});return a.ok?this.formatResult({ok:!0,selector:o,clickCount:a.result?.clickCount,timedOut:a.result?.timedOut,message:a.result?.message}):this.formatError(a.error??"Loadall failed")}async handleEvalraw(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.method,o=t.params??{};if(!n)return this.formatError("Missing required 'method' parameter");let i=await this.sendDaemonCommand(e,r,"evalraw",{method:n,params:o});return i.ok?this.formatResult({ok:!0,method:n,result:i.result?.result}):this.formatError(i.error??"Raw CDP command failed")}async resolveTarget(t){if(!t)throw new Error("Missing required 'target' parameter. Use 'chrome_session list' to see available targets.");let e=Oe();if(!e)throw new Error("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let r;try{let l=await fetch(`http://127.0.0.1:${e}/json/list`);l.ok?r=await l.json():r=await ee(e)}catch{r=await ee(e)}let n=r.filter(l=>l.type==="page"&&!l.url.startsWith("chrome://")),o=t.toUpperCase(),i=n.filter(l=>l.id.toUpperCase().startsWith(o));if(i.length===0)throw new Error(`No target found matching prefix '${t}'`);if(i.length>1){let l=i.map(c=>c.id.slice(0,this.config.targetPrefixLength)).join(", ");throw new Error(`Ambiguous prefix '${t}' matches ${i.length} targets: ${l}`)}let a=i[0];return{targetId:a.id,wsUrl:a.webSocketDebuggerUrl}}async sendDaemonCommand(t,e,r,n){return await this.daemonManager.getOrCreateDaemon(t,e,{idleTimeoutMs:this.config.daemonIdleTimeoutS*1e3}),this.config.stealth?.enabled&&await this.daemonManager.sendCommand(t,"setStealthConfig",{stealth:this.config.stealth}),this.daemonManager.sendCommand(t,r,n)}resolveScreenshotPath(t){if(!t)return;let e;if(t.startsWith("/")?e=t:t.startsWith("./")||t.startsWith("../")?this.restrictToWorkspace&&this.workspace?e=De(this.workspace,t):e=De(process.cwd(),t):this.restrictToWorkspace&&this.workspace?e=De(this.workspace,t):e=De(dn(),`airclaw-screenshot-${Date.now()}.png`),this.restrictToWorkspace&&this.workspace&&!e.startsWith(this.workspace))throw new Error(`Screenshot path '${t}' is outside workspace (restrictToWorkspace is enabled)`);return e}saveScreenshot(t,e){let r=un(t);cn(r)||ln(r,{recursive:!0});let n=Buffer.from(e,"base64");an(t,n)}formatResult(t){return JSON.stringify(t,null,2)}formatError(t){return JSON.stringify({error:t},null,2)}};var ne=class extends g{constructor(e){super();this.relay=e}relay;name="chrome_relay";description="Control Chrome browser through the relay extension. Commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach.";parameters={type:"object",properties:{command:{type:"string",enum:["list_tabs","navigate","click","type","screenshot","read","evaluate","attach","detach"],description:"The command to execute"},tabId:{type:"number",description:"Tab ID for tab-specific commands"},url:{type:"string",description:"URL to navigate to"},selector:{type:"string",description:"CSS selector for click command"},text:{type:"string",description:"Text to type"},expression:{type:"string",description:"JavaScript expression to evaluate"},format:{type:"string",description:"Screenshot format (png or jpeg)"}},required:["command"]};async execute(e){let r=String(e.command??"");try{switch(r){case"list_tabs":{let n=await this.relay.listTabs();return JSON.stringify(n,null,2)}case"navigate":{let n=Number(e.tabId),o=String(e.url??"");return n?o?(await this.relay.navigate(n,o),`Navigated tab ${n} to ${o}`):"Error: url is required":"Error: tabId is required"}case"click":{let n=Number(e.tabId),o=String(e.selector??"");return n?o?(await this.relay.click(n,o),`Clicked "${o}" in tab ${n}`):"Error: selector is required":"Error: tabId is required"}case"type":{let n=Number(e.tabId),o=String(e.text??""),i=e.selector?String(e.selector):void 0;return n?o?(await this.relay.type(n,o,i),`Typed "${o}" in tab ${n}${i?` (selector: ${i})`:""}`):"Error: text is required":"Error: tabId is required"}case"screenshot":{let n=Number(e.tabId),o=String(e.format??"png");return n?`Screenshot captured: ${(await this.relay.screenshot(n,o)).slice(0,100)}...`:"Error: tabId is required"}case"read":{let n=Number(e.tabId);if(!n)return"Error: tabId is required";let o=await this.relay.evaluate(n,"document.body.innerText");return JSON.stringify(o,null,2)}case"evaluate":{let n=Number(e.tabId),o=String(e.expression??"");if(!n)return"Error: tabId is required";if(!o)return"Error: expression is required";let i=await this.relay.evaluate(n,o);return JSON.stringify(i,null,2)}case"attach":{let n=Number(e.tabId);return n?(await this.relay.attachTab(n),`Attached to tab ${n}`):"Error: tabId is required"}case"detach":{let n=Number(e.tabId);return n?(await this.relay.detachTab(n),`Detached from tab ${n}`):"Error: tabId is required"}default:return`Unknown command: ${r}. Available commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach`}}catch(n){return`Error: ${n instanceof Error?n.message:String(n)}`}}};import w from"node:fs";import oe from"node:path";import{randomUUID as mn}from"node:crypto";var gn="automations",pn="index.json";function fn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)}function rt(s){return oe.join(s,gn)}function Ht(s){return oe.join(rt(s),pn)}function je(s,t){return oe.join(rt(s),t)}function nt(s,t){return oe.join(je(s,t),"rule.json")}function ot(s,t){return oe.join(je(s,t),"script.js")}function st(s){let t=rt(s);w.existsSync(t)||w.mkdirSync(t,{recursive:!0})}function Be(s){st(s);let t=Ht(s);if(!w.existsSync(t))return{rules:[]};try{let e=w.readFileSync(t,"utf-8"),r=JSON.parse(e),n=!1;for(let o of r.rules){if(o.stepCount===void 0){let i=G(s,o.id);o.stepCount=i?.steps?.length||0,n=!0}if(o.toolType===void 0){let i=G(s,o.id);i?.toolType&&(o.toolType=i.toolType,n=!0)}}return n&&Fe(s,r),r}catch{return{rules:[]}}}function Fe(s,t){st(s);let e=Ht(s),r=`${e}.tmp`;w.writeFileSync(r,JSON.stringify(t,null,2)),w.renameSync(r,e)}function Vt(s){return Be(s).rules}function G(s,t){let e=nt(s,t);if(!w.existsSync(e))return null;try{let r=w.readFileSync(e,"utf-8"),n=JSON.parse(r),o=ot(s,t);return w.existsSync(o)&&(n.scriptContent=w.readFileSync(o,"utf-8")),n}catch{return null}}function zt(s,t){st(s);let e=fn(t.name)||mn().slice(0,8),r=Date.now(),n={id:e,name:t.name,description:t.description,createdAt:r,updatedAt:r,enabled:!0,stepCount:t.steps.length,steps:t.steps,scriptPath:`automations/${e}/script.js`,tags:t.tags||[],source:t.source||"manual",...t.toolType?{toolType:t.toolType}:{},...t.variables?{variables:t.variables}:{}},o=je(s,e);w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let i=nt(s,e);w.writeFileSync(i,JSON.stringify(n,null,2));let a=Zt(n),l=ot(s,e);w.writeFileSync(l,a);let c=Be(s),u={id:n.id,name:n.name,description:n.description,enabled:n.enabled,updatedAt:n.updatedAt,stepCount:n.steps.length};return t.toolType&&(u.toolType=t.toolType),c.rules.push(u),Fe(s,c),n}function Xt(s,t,e){let r=G(s,t);if(!r)return null;let n=Date.now(),o={...r,...e,id:r.id,createdAt:r.createdAt,updatedAt:n,stepCount:(e.steps||r.steps).length},i=nt(s,t);if(w.writeFileSync(i,JSON.stringify(o,null,2)),e.steps){let c=Zt(o),u=ot(s,t);w.writeFileSync(u,c)}let a=Be(s),l=a.rules.findIndex(c=>c.id===t);if(l>=0){let c={id:o.id,name:o.name,description:o.description,enabled:o.enabled,updatedAt:o.updatedAt,stepCount:o.steps.length};o.toolType&&(c.toolType=o.toolType),a.rules[l]=c,Fe(s,a)}return o}function Yt(s,t){let e=je(s,t);if(!w.existsSync(e))return!1;w.rmSync(e,{recursive:!0,force:!0});let r=Be(s),n=r.rules.length;return r.rules=r.rules.filter(o=>o.id!==t),r.rules.length!==n?(Fe(s,r),!0):!1}function Zt(s){let t=new Date().toISOString();return`// Automation: ${s.name}
122
+ // Tool: ${s.toolType??"auto-detect"}
123
+ // Generated: ${t}
124
+ // Description: ${s.description}
129
125
  //
130
126
  // Steps:
131
- ${J.steps.map((y)=>`// ${y.order}. ${y.description}`).join(`
127
+ ${s.steps.map(e=>`// ${e.order}. ${e.description}`).join(`
132
128
  `)}
133
129
  //
134
130
  // Usage: node script.js [--port=6767]
135
131
 
136
132
  const PORT = process.argv.find(a => a.startsWith('--port='))?.split('=')[1] ?? '6767';
137
- const URL = \`http://127.0.0.1:\${PORT}/api/automations/${J.id}/run\`;
133
+ const URL = \`http://127.0.0.1:\${PORT}/api/automations/${s.id}/run\`;
138
134
 
139
135
  fetch(URL, { method: 'POST' })
140
136
  .then(r => r.json())
@@ -143,38 +139,38 @@ fetch(URL, { method: 'POST' })
143
139
  else console.error('Failed:', r.error);
144
140
  })
145
141
  .catch(e => console.error('Could not reach everclaw:', e.message));
146
- `}var jX={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"}},b_=(J)=>new Promise((_)=>setTimeout(_,J));class Yy extends O{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,_,y){super();this.browserTool=_;this.stealthConfig=y;this.workspace=sy(J)}async execute(J,_){let y=String(J.command??"");try{switch(y){case"list":{let $=wX(this.workspace);return JSON.stringify($,null,2)}case"get":{let $=String(J.id??"");if(!$)return"Error: id is required for get command";let X=sJ(this.workspace,$);if(!X)return`Error: Automation '${$}' not found`;return JSON.stringify(X,null,2)}case"save":{let $=J.id?String(J.id):void 0,X=String(J.name??"Untitled Automation"),A=String(J.description??""),L=J.steps||[],q=J.tags||[];if(L.length===0)return"Error: At least one step is required";let N=this.browserTool?.name,G;if($){let B={name:X,description:A,steps:L,tags:q};if(N)B.toolType=N;if(G=OX(this.workspace,$,B),!G)return`Error: Automation '${$}' not found for update`;return`Updated automation '${G.name}' (${G.id})`}else{let B={name:X,description:A,steps:L,tags:q,source:"conversation"};if(N)B.toolType=N;return G=zX(this.workspace,B),`Created automation '${G.name}' (${G.id})`}}case"delete":{let $=String(J.id??"");if(!$)return"Error: id is required for delete command";if(!TX(this.workspace,$))return`Error: Automation '${$}' not found or could not be deleted`;return`Deleted automation '${$}'`}case"run":{let $=String(J.id??"");if(!$)return"Error: id is required for run command";let X=sJ(this.workspace,$);if(!X)return`Error: Automation '${$}' not found`;if(!X.enabled)return`Error: Automation '${X.name}' is disabled`;let A=J.variables;return this.executeAutomation(X,_?.signal,A)}default:return`Unknown command: ${y}. Available commands: list, get, save, delete, run`}}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async executeAutomation(J,_,y){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 $=[];$.push(`Running automation: ${J.name}`),$.push(`Tool: ${this.browserTool.name}`),$.push(`Steps: ${J.steps.length}`);let X=await this.resolveTabContext();if(!X.tabId&&!X.target)return"Error: Could not resolve tab context. Open a browser tab first.";let A=[...J.steps].sort((L,q)=>L.order-q.order);for(let L of A){if(_?.aborted){$.push(`Aborted at step ${L.order}`);break}if(L.stealth?.preDelay)await b_(L.stealth.preDelay);$.push(`[Step ${L.order}] ${L.description}`);try{let q=this.resolveStep(L,J.variables,y),N=await this.executeStepWithRetries(q,_,X),G=this.maskSensitiveValues(N,J.variables);if($.push(` -> ${G.slice(0,200)}${G.length>200?"...":""}`),this.stealthConfig?.enabled){let[B,R]=this.stealthConfig.interStepDelay;await b_(B+Math.random()*(R-B))}}catch(q){let N=q instanceof Error?q.message:String(q);if(L.optional)$.push(` -> Optional step failed (continuing): ${N}`);else return $.push(` -> FAILED: ${N}`),$.push(`Automation '${J.name}' stopped due to error.`),$.join(`
147
- `)}}return $.push(`Automation '${J.name}' completed successfully.`),$.join(`
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"}),y=JSON.parse(_);if(Array.isArray(y)&&y.length>0)return{tabId:(y.find((X)=>X.active)||y[0]).id}}catch{}return{}}if(J==="chrome_session"){try{let _=await this.browserTool.execute({command:"list"}),y=JSON.parse(_);if(y.tabs&&Array.isArray(y.tabs)&&y.tabs.length>0)return{target:y.tabs[0].id}}catch{}return{}}return{}}resolveStep(J,_,y){let $=(L)=>{if(!L)return L;return L.replace(/\$\{(\w+)\}/g,(q,N)=>{if(y&&y[N]!==void 0)return y[N];if(_&&_[N]?.defaultValue!==void 0)return _[N].defaultValue;if(_&&_[N]?.required)throw new Error(`Required variable '${N}' not provided`);return`\${${N}}`})},X=$(J.target),A=$(J.value);return{...J,...X!==void 0?{target:X}:{},...A!==void 0?{value:A}:{}}}maskSensitiveValues(J,_){if(!_)return J;let y=J;for(let[$,X]of Object.entries(_))if(X.sensitive)y=y.replaceAll(`\${${$}}`,`[REDACTED:${$}]`);return y}async executeStepWithRetries(J,_,y){let $=1+(J.retries??0),X=J.retryDelayMs??1000,A;for(let L=1;L<=$;L++)try{let q=await this.executeStepOnce(J,_,y);if(J.assert)await this.pollAssertion(J.assert,_,y);return q}catch(q){if(A=q instanceof Error?q:new Error(String(q)),L<$)await b_(X)}throw A??new Error("Unknown error")}async executeStepOnce(J,_,y){if(!this.browserTool)throw new Error("No browser tool available");let $=this.browserTool.name,X=jX[$];if(!X)throw new Error(`Unsupported browser tool: ${$}`);let A=X[J.action];if(!A)throw new Error(`Action '${J.action}' not supported by ${$}`);let L={command:A};if($==="chrome_relay"&&y.tabId)L.tabId=y.tabId;if($==="chrome_session"&&y.target)L.target=y.target;switch(J.action){case"navigate":L.url=J.value??J.target??"";break;case"click":L.selector=J.target??"";break;case"type":if(L.text=J.value??"",J.stealth?.typingSpeed)L.typingSpeed=J.stealth.typingSpeed;break;case"read":break;case"screenshot":if(J.target)L.selector=J.target;break;case"eval":L.expression=J.value??"";break;case"wait":let q=parseInt(J.value??"1000",10);return await b_(q),`Waited ${q}ms`;default:throw new Error(`Unknown action: ${J.action}`)}return this.browserTool.execute(L,_?{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 y=JSON.parse(J);if(_==="chrome_session"){let $=y.result;if($&&typeof $.value==="boolean")return $.value;if($&&typeof $.value==="string")return $.value.length>0;if($&&typeof $.value==="number")return $.value!==0;return y.result===!0}if(_==="chrome_relay")return y===!0;return!1}catch{return!1}}async pollAssertion(J,_,y){if(!this.browserTool)throw new Error("No browser tool available");let $=J.timeoutMs??5000,X=500,A=this.toExpression(J),L=Date.now();do{if(_?.aborted)throw new Error("Aborted during assertion");try{let q=this.browserTool.name,G=jX[q]?.eval;if(!G)throw new Error(`Evaluation not supported by ${q}`);let B={command:G,expression:A};if(q==="chrome_relay"&&y.tabId)B.tabId=y.tabId;if(q==="chrome_session"&&y.target)B.target=y.target;let R=await this.browserTool.execute(B);if(this.isAssertionPassing(R,q))return}catch{}if(Date.now()-L>=$)break;await b_(X)}while(Date.now()-L<$);throw new Error(`Assertion failed after ${$}ms: ${J.check} (${J.value})`)}}class M_{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 M_;_.guardEngine=this.guardEngine;for(let y of J){let $=this.tools.get(y);if($)_.register($)}return _}excludeByNames(J){let _=new Set(J),y=new M_;y.guardEngine=this.guardEngine;for(let[$,X]of this.tools)if(!_.has($))y.register(X);return y}async execute(J,_,y){let $=this.tools.get(J);if(!$)return{kind:"error",content:`Error: Tool '${J}' not found. Available: ${this.toolNames.join(", ")}`,retryable:!1};try{if(v(y?.signal),this.guardEngine){let L=this.guardEngine.guard(J,_);if(L&&!L.isSafe){let q=L.findings.map((N)=>` - [${N.severity}] ${N.title}: ${N.description}`).join(`
149
- `);return{kind:"error",content:`Security: Tool call blocked. The tool '${J}' was denied by the security guard.
142
+ `}var Qt={chrome_session:{navigate:"nav",click:"click",type:"type",screenshot:"shot",read:"snap",eval:"eval"},chrome_relay:{navigate:"navigate",click:"click",type:"type",screenshot:"screenshot",read:"read",eval:"evaluate"}},se=s=>new Promise(t=>setTimeout(t,s)),Je=class extends g{constructor(e,r,n){super();this.browserTool=r;this.stealthConfig=n;this.workspace=St(e)}browserTool;stealthConfig;name="automation";description="Manage browser automation workflows. Commands: list, get, save, delete, run.";parameters={type:"object",properties:{command:{type:"string",enum:["list","get","save","delete","run"],description:"The command to execute"},id:{type:"string",description:"Automation ID (for get, delete, run)"},name:{type:"string",description:"Automation name (for save)"},description:{type:"string",description:"Brief description (for save)"},steps:{type:"array",items:{type:"object",properties:{order:{type:"number"},action:{type:"string"},target:{type:"string"},value:{type:"string"},description:{type:"string"},optional:{type:"boolean"},assert:{type:"object",properties:{check:{type:"string",enum:["selector_exists","selector_text","url_contains","eval_truthy"]},value:{type:"string"},expected:{type:"string"},timeoutMs:{type:"number"}}},retries:{type:"number"},retryDelayMs:{type:"number"}}},description:"Automation steps (for save)"},tags:{type:"array",items:{type:"string"},description:"Optional tags (for save)"},enabled:{type:"boolean",description:"Enable/disable (for save)"},variables:{type:"object",description:'Variable overrides for run command (e.g., {"USERNAME": "user"})'}},required:["command"]};workspace;async execute(e,r){let n=String(e.command??"");try{switch(n){case"list":{let o=Vt(this.workspace);return JSON.stringify(o,null,2)}case"get":{let o=String(e.id??"");if(!o)return"Error: id is required for get command";let i=G(this.workspace,o);return i?JSON.stringify(i,null,2):`Error: Automation '${o}' not found`}case"save":{let o=e.id?String(e.id):void 0,i=String(e.name??"Untitled Automation"),a=String(e.description??""),l=e.steps||[],c=e.tags||[];if(l.length===0)return"Error: At least one step is required";let u=this.browserTool?.name,d;if(o){let m={name:i,description:a,steps:l,tags:c};return u&&(m.toolType=u),d=Xt(this.workspace,o,m),d?`Updated automation '${d.name}' (${d.id})`:`Error: Automation '${o}' not found for update`}else{let m={name:i,description:a,steps:l,tags:c,source:"conversation"};return u&&(m.toolType=u),d=zt(this.workspace,m),`Created automation '${d.name}' (${d.id})`}}case"delete":{let o=String(e.id??"");return o?Yt(this.workspace,o)?`Deleted automation '${o}'`:`Error: Automation '${o}' not found or could not be deleted`:"Error: id is required for delete command"}case"run":{let o=String(e.id??"");if(!o)return"Error: id is required for run command";let i=G(this.workspace,o);if(!i)return`Error: Automation '${o}' not found`;if(!i.enabled)return`Error: Automation '${i.name}' is disabled`;let a=e.variables;return this.executeAutomation(i,r?.signal,a)}default:return`Unknown command: ${n}. Available commands: list, get, save, delete, run`}}catch(o){return`Error: ${o instanceof Error?o.message:String(o)}`}}async executeAutomation(e,r,n){if(!this.browserTool)return"Error: No browser tool available. Enable chrome_session or chrome_relay to run automations.";if(e.toolType&&e.toolType!==this.browserTool.name)return`Error: Automation '${e.name}' requires ${e.toolType} but ${this.browserTool.name} is active. Change browser tool or update the automation.`;let o=[];o.push(`Running automation: ${e.name}`),o.push(`Tool: ${this.browserTool.name}`),o.push(`Steps: ${e.steps.length}`);let i=await this.resolveTabContext();if(!i.tabId&&!i.target)return"Error: Could not resolve tab context. Open a browser tab first.";let a=[...e.steps].sort((l,c)=>l.order-c.order);for(let l of a){if(r?.aborted){o.push(`Aborted at step ${l.order}`);break}l.stealth?.preDelay&&await se(l.stealth.preDelay),o.push(`[Step ${l.order}] ${l.description}`);try{let c=this.resolveStep(l,e.variables,n),u=await this.executeStepWithRetries(c,r,i),d=this.maskSensitiveValues(u,e.variables);if(o.push(` -> ${d.slice(0,200)}${d.length>200?"...":""}`),this.stealthConfig?.enabled){let[m,p]=this.stealthConfig.interStepDelay;await se(m+Math.random()*(p-m))}}catch(c){let u=c instanceof Error?c.message:String(c);if(l.optional)o.push(` -> Optional step failed (continuing): ${u}`);else return o.push(` -> FAILED: ${u}`),o.push(`Automation '${e.name}' stopped due to error.`),o.join(`
143
+ `)}}return o.push(`Automation '${e.name}' completed successfully.`),o.join(`
144
+ `)}async resolveTabContext(){if(!this.browserTool)return{};let e=this.browserTool.name;if(e==="chrome_relay"){try{let r=await this.browserTool.execute({command:"list_tabs"}),n=JSON.parse(r);if(Array.isArray(n)&&n.length>0)return{tabId:(n.find(i=>i.active)||n[0]).id}}catch{}return{}}if(e==="chrome_session"){try{let r=await this.browserTool.execute({command:"list"}),n=JSON.parse(r);if(n.tabs&&Array.isArray(n.tabs)&&n.tabs.length>0)return{target:n.tabs[0].id}}catch{}return{}}return{}}resolveStep(e,r,n){let o=l=>l&&l.replace(/\$\{(\w+)\}/g,(c,u)=>{if(n&&n[u]!==void 0)return n[u];if(r&&r[u]?.defaultValue!==void 0)return r[u].defaultValue;if(r&&r[u]?.required)throw new Error(`Required variable '${u}' not provided`);return`\${${u}}`}),i=o(e.target),a=o(e.value);return{...e,...i!==void 0?{target:i}:{},...a!==void 0?{value:a}:{}}}maskSensitiveValues(e,r){if(!r)return e;let n=e;for(let[o,i]of Object.entries(r))i.sensitive&&(n=n.replaceAll(`\${${o}}`,`[REDACTED:${o}]`));return n}async executeStepWithRetries(e,r,n){let o=1+(e.retries??0),i=e.retryDelayMs??1e3,a;for(let l=1;l<=o;l++)try{let c=await this.executeStepOnce(e,r,n);return e.assert&&await this.pollAssertion(e.assert,r,n),c}catch(c){a=c instanceof Error?c:new Error(String(c)),l<o&&await se(i)}throw a??new Error("Unknown error")}async executeStepOnce(e,r,n){if(!this.browserTool)throw new Error("No browser tool available");let o=this.browserTool.name,i=Qt[o];if(!i)throw new Error(`Unsupported browser tool: ${o}`);let a=i[e.action];if(!a)throw new Error(`Action '${e.action}' not supported by ${o}`);let l={command:a};switch(o==="chrome_relay"&&n.tabId&&(l.tabId=n.tabId),o==="chrome_session"&&n.target&&(l.target=n.target),e.action){case"navigate":l.url=e.value??e.target??"";break;case"click":l.selector=e.target??"";break;case"type":l.text=e.value??"",e.stealth?.typingSpeed&&(l.typingSpeed=e.stealth.typingSpeed);break;case"read":break;case"screenshot":e.target&&(l.selector=e.target);break;case"eval":l.expression=e.value??"";break;case"wait":let c=parseInt(e.value??"1000",10);return await se(c),`Waited ${c}ms`;default:throw new Error(`Unknown action: ${e.action}`)}return this.browserTool.execute(l,r?{signal:r}:void 0)}toExpression(e){switch(e.check){case"selector_exists":return`!!document.querySelector(${JSON.stringify(e.value)})`;case"selector_text":return`(document.querySelector(${JSON.stringify(e.value)})?.textContent?.trim() ?? "") === ${JSON.stringify(e.expected??"")}`;case"url_contains":return`window.location.href.includes(${JSON.stringify(e.value)})`;case"eval_truthy":return`!!(${e.value})`}}isAssertionPassing(e,r){try{let n=JSON.parse(e);if(r==="chrome_session"){let o=n.result;return o&&typeof o.value=="boolean"?o.value:o&&typeof o.value=="string"?o.value.length>0:o&&typeof o.value=="number"?o.value!==0:n.result===!0}return r==="chrome_relay"?n===!0:!1}catch{return!1}}async pollAssertion(e,r,n){if(!this.browserTool)throw new Error("No browser tool available");let o=e.timeoutMs??5e3,i=500,a=this.toExpression(e),l=Date.now();do{if(r?.aborted)throw new Error("Aborted during assertion");try{let c=this.browserTool.name,d=Qt[c]?.eval;if(!d)throw new Error(`Evaluation not supported by ${c}`);let m={command:d,expression:a};c==="chrome_relay"&&n.tabId&&(m.tabId=n.tabId),c==="chrome_session"&&n.target&&(m.target=n.target);let p=await this.browserTool.execute(m);if(this.isAssertionPassing(p,c))return}catch{}if(Date.now()-l>=o)break;await se(i)}while(Date.now()-l<o);throw new Error(`Assertion failed after ${o}ms: ${e.check} (${e.value})`)}};var Ue=class s{tools=new Map;guardEngine=null;register(t){this.tools.set(t.name,t)}unregister(t){return this.tools.delete(t)}clear(){this.tools.clear()}get(t){return this.tools.get(t)}getDefinitions(){return[...this.tools.values()].map(t=>t.toSchema())}get toolNames(){return[...this.tools.keys()]}setGuardEngine(t){this.guardEngine=t}getGuardEngine(){return this.guardEngine}filterByNames(t){let e=new s;e.guardEngine=this.guardEngine;for(let r of t){let n=this.tools.get(r);n&&e.register(n)}return e}excludeByNames(t){let e=new Set(t),r=new s;r.guardEngine=this.guardEngine;for(let[n,o]of this.tools)e.has(n)||r.register(o);return r}async execute(t,e,r){let n=this.tools.get(t);if(!n)return{kind:"error",content:`Error: Tool '${t}' not found. Available: ${this.toolNames.join(", ")}`,retryable:!1};try{if(v(r?.signal),this.guardEngine){let a=this.guardEngine.guard(t,e);if(a&&!a.isSafe){let l=a.findings.map(c=>` - [${c.severity}] ${c.title}: ${c.description}`).join(`
145
+ `);return{kind:"error",content:`Security: Tool call blocked. The tool '${t}' was denied by the security guard.
150
146
 
151
147
  Findings:
152
- ${q}`,retryable:!1}}}let X=$.validateParams(_);if(X.length)return{kind:"error",content:`Error: Invalid parameters for tool '${J}': ${X.join("; ")}
148
+ ${l}`,retryable:!1}}}let o=n.validateParams(e);if(o.length)return{kind:"error",content:`Error: Invalid parameters for tool '${t}': ${o.join("; ")}
153
149
 
154
- [Analyze the error above and try a different approach.]`,retryable:!0};let A=await $.execute(_,y);if(v(y?.signal),A.startsWith("__TERMINAL__"))return{kind:"terminal",content:A.slice(12)};return{kind:"ok",content:A}}catch(X){if(k(X))throw X;return{kind:"error",content:`Error executing ${J}: ${String(X)}
150
+ [Analyze the error above and try a different approach.]`,retryable:!0};let i=await n.execute(e,r);return v(r?.signal),i.startsWith("__TERMINAL__")?{kind:"terminal",content:i.slice(12)}:{kind:"ok",content:i}}catch(o){if(k(o))throw o;return{kind:"error",content:`Error executing ${t}: ${String(o)}
155
151
 
156
- [Analyze the error above and try a different approach.]`,retryable:!0}}}}function WX(J){return J.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g,"").trim()}function C4(J){return J.replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
152
+ [Analyze the error above and try a different approach.]`,retryable:!0}}}};function er(s){return s.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g,"").trim()}function hn(s){return s.replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
157
153
 
158
- `).trim()}function w4(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 Ey extends O{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 y=String(J.query??""),$=Math.min(Math.max(Number(J.count??this.maxResults),1),10),X=this.apiKey||process.env.BRAVE_API_KEY||"";if(!X)return"Error: Brave Search API key not configured. Set tools.web.search.apiKey or BRAVE_API_KEY.";try{v(_?.signal);let A=new URL("https://api.search.brave.com/res/v1/web/search");A.searchParams.set("q",y),A.searchParams.set("count",String($));let L=await fetch(A,{headers:{Accept:"application/json","X-Subscription-Token":X},..._?.signal?{signal:_.signal}:{}});if(!L.ok)return`Error: ${L.status} ${L.statusText}`;let N=(await L.json()).web?.results??[];if(!N.length)return`No results for: ${y}`;let G=[`Results for: ${y}`,""];return N.slice(0,$).forEach((B,R)=>{if(G.push(`${R+1}. ${B.title??""}`),G.push(` ${B.url??""}`),B.description)G.push(` ${B.description}`)}),G.join(`
159
- `)}catch(A){if(k(A))throw A;return`Error: ${String(A)}`}}}class Vy extends O{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 y=String(J.url??""),$=String(J.extractMode??"markdown"),X=Number(J.maxChars??this.maxChars),[A,L]=w4(y);if(!A)return JSON.stringify({error:`URL validation failed: ${L}`,url:y});try{v(_?.signal);let q=await fetch(y,{redirect:"follow",headers:{"User-Agent":"Mozilla/5.0"},..._?.signal?{signal:_.signal}:{}}),N=q.headers.get("content-type")||"",G="",B="raw";if(N.includes("application/json"))G=JSON.stringify(await q.json(),null,2),B="json";else{let K=await q.text();if(N.includes("text/html")||/^\s*<!doctype|^\s*<html/i.test(K.slice(0,256)))G=$==="text"?WX(K):C4(WX(K)),B="html";else G=K}let R=G.length>X,Q=R?G.slice(0,X):G;return JSON.stringify({url:y,finalUrl:q.url,status:q.status,extractor:B,truncated:R,length:Q.length,text:Q})}catch(q){if(k(q))throw q;return JSON.stringify({error:String(q),url:y})}}}function BJ(J){return z4.resolve(J.workspace)}function L0(J){let _=BJ(J);return J.restrictToWorkspace?_:void 0}function O4(J){let _=[_J({name:"builtin-filesystem-tools",tools:[{name:"read_file",create:(y)=>new a0(BJ(y),L0(y))},{name:"write_file",create:(y)=>new t0(BJ(y),L0(y))},{name:"edit_file",create:(y)=>new e0(BJ(y),L0(y))},{name:"list_dir",create:(y)=>new Jy(BJ(y),L0(y))}]}),_J({name:"builtin-shell-tools",tools:[{name:"exec",create:(y)=>new Xy(y.execConfig?.timeout??60,BJ(y),!!y.restrictToWorkspace,y.execConfig?.pathAppend??"",new oJ,y.rtkService,y.rtkConfig?.ultraCompact??!1)}]}),_J({name:"builtin-web-tools",tools:[{name:"web_search",create:(y)=>new Ey(y.braveApiKey??null)},{name:"web_fetch",create:()=>new Vy}]})];if(J.bus)_.push(_J({name:"builtin-messaging-tools",tools:[{name:"message",create:(y)=>{if(!y.bus)throw new Error("Builtin message tool requires a message bus");let $=new _y(async(X)=>{if(y.turn?.isCurrent&&!y.turn.isCurrent())return;await y.bus.publishOutbound(X)});if(y.turn)$.setContext(y.turn.channel,y.turn.chatId,y.turn.messageId);return $}}]}));if(J.subagents)_.push(_J({name:"builtin-subagent-tools",tools:[{name:"spawn",create:(y)=>{if(!y.subagents)throw new Error("Builtin spawn tool requires a subagent manager");let $=new Ay(y.subagents);if(y.turn)$.setContext(y.turn.channel,y.turn.chatId,y.turn.sessionKey,y.turn.systemPrompt);return $}}]}));if(J.cronService)_.push(_J({name:"builtin-scheduler-tools",tools:[{name:"cron",create:(y)=>{if(!y.cronService)throw new Error("Builtin cron tool requires a cron service");let $=new s0(y.cronService);if(y.turn)$.setContext(y.turn.channel,y.turn.chatId);return $}}]}));if(J.sessionManager)_.push(_J({name:"builtin-session-tools",tools:[{name:"session.info",create:(y)=>{if(!y.sessionManager)throw new Error("Builtin session.info tool requires a session manager");let $=new Ny;if($.setSessionManager(y.sessionManager),y.turn)$.setContext(y.turn.sessionKey);return $}},{name:"session.anchor",create:(y)=>{if(!y.sessionManager)throw new Error("Builtin session.anchor tool requires a session manager");let $=new Gy;if($.setSessionManager(y.sessionManager),y.turn)$.setContext(y.turn.sessionKey);return $}},{name:"session.search",create:(y)=>{if(!y.sessionManager)throw new Error("Builtin session.search tool requires a session manager");let $=new Ly;if($.setSessionManager(y.sessionManager),y.turn)$.setContext(y.turn.sessionKey);return $}}]}));if(J.chromeSessionConfig?.enabled)_.push(_J({name:"builtin-chrome-session-tools",tools:[{name:"chrome_session",create:(y)=>new _0(y.chromeSessionConfig,BJ(y),!!y.restrictToWorkspace)}]}));if(J.browserRelay)_.push(_J({name:"builtin-browser-relay-tools",tools:[{name:"chrome_relay",create:(y)=>{if(!y.browserRelay)throw new Error("Builtin chrome_relay tool requires a browser relay server");return new y0(y.browserRelay)}}]}));return _.push(_J({name:"builtin-automation-tools",tools:[{name:"automation",create:(y)=>{let $=y.browserRelay?new y0(y.browserRelay):y.chromeSessionConfig?.enabled?new _0(y.chromeSessionConfig,BJ(y),!!y.restrictToWorkspace):void 0;return new Yy(BJ(y),$,y.chromeSessionConfig?.stealth)}}]})),_}function T4(J){return _X(O4(J))}function PX(J){let _=new M_,y=T4(J);for(let $ of y.tools.values())_.register($.contribution.create(J));return _}class by{tasks=new Map;order=[];register(J,_,y,$){let X=new Date().toISOString(),A={id:J,type:_,label:y,sessionKey:$,createdAt:X,status:"pending",startedAt:null,completedAt:null,result:null,error:null};return this.tasks.set(J,A),this.order.push(J),this.enforceLimit(),A}transition(J,_,y,$){let X=this.tasks.get(J);if(!X)return;let A=new Date().toISOString(),L={status:_};if(_==="running"&&X.startedAt===null)L.startedAt=A;if(this.isTerminal(_)){if(L.completedAt=A,y!==void 0)L.result=y;if($!==void 0)L.error=$}Object.assign(X,L)}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(),y=[];for(let $ of this.tasks.values())if(this.isTerminal($.status)&&$.completedAt){let X=new Date($.completedAt).getTime();if(_-X>J)y.push($.id)}for(let $ of y){this.tasks.delete($);let X=this.order.indexOf($);if(X!==-1)this.order.splice(X,1)}return y.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 IX="EVERCLAW_SUBAGENT_RESULT ";function xX(J,_){let y=new Date().toLocaleString(),$=_??"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}
154
+ `).trim()}function yn(s){try{let t=new URL(s);return["http:","https:"].includes(t.protocol)?t.hostname?[!0,""]:[!1,"Missing domain"]:[!1,`Only http/https allowed, got '${t.protocol.replace(":","")}'`]}catch(t){return[!1,String(t)]}}var qe=class extends g{constructor(e,r=5){super();this.apiKey=e;this.maxResults=r}apiKey;maxResults;name="web_search";description="Search the web. Returns titles, URLs, and snippets.";parameters={type:"object",properties:{query:{type:"string",description:"Search query"},count:{type:"integer",minimum:1,maximum:10,description:"Results (1-10)"}},required:["query"]};async execute(e,r){let n=String(e.query??""),o=Math.min(Math.max(Number(e.count??this.maxResults),1),10),i=this.apiKey||process.env.BRAVE_API_KEY||"";if(!i)return"Error: Brave Search API key not configured. Set tools.web.search.apiKey or BRAVE_API_KEY.";try{v(r?.signal);let a=new URL("https://api.search.brave.com/res/v1/web/search");a.searchParams.set("q",n),a.searchParams.set("count",String(o));let l=await fetch(a,{headers:{Accept:"application/json","X-Subscription-Token":i},...r?.signal?{signal:r.signal}:{}});if(!l.ok)return`Error: ${l.status} ${l.statusText}`;let u=(await l.json()).web?.results??[];if(!u.length)return`No results for: ${n}`;let d=[`Results for: ${n}`,""];return u.slice(0,o).forEach((m,p)=>{d.push(`${p+1}. ${m.title??""}`),d.push(` ${m.url??""}`),m.description&&d.push(` ${m.description}`)}),d.join(`
155
+ `)}catch(a){if(k(a))throw a;return`Error: ${String(a)}`}}},We=class extends g{constructor(e=5e4){super();this.maxChars=e}maxChars;name="web_fetch";description="Fetch URL and extract readable content (HTML to markdown/text).";parameters={type:"object",properties:{url:{type:"string",description:"URL to fetch"},extractMode:{type:"string",enum:["markdown","text"]},maxChars:{type:"integer",minimum:100}},required:["url"]};async execute(e,r){let n=String(e.url??""),o=String(e.extractMode??"markdown"),i=Number(e.maxChars??this.maxChars),[a,l]=yn(n);if(!a)return JSON.stringify({error:`URL validation failed: ${l}`,url:n});try{v(r?.signal);let c=await fetch(n,{redirect:"follow",headers:{"User-Agent":"Mozilla/5.0"},...r?.signal?{signal:r.signal}:{}}),u=c.headers.get("content-type")||"",d="",m="raw";if(u.includes("application/json"))d=JSON.stringify(await c.json(),null,2),m="json";else{let b=await c.text();u.includes("text/html")||/^\s*<!doctype|^\s*<html/i.test(b.slice(0,256))?(d=o==="text"?er(b):hn(er(b)),m="html"):d=b}let p=d.length>i,f=p?d.slice(0,i):d;return JSON.stringify({url:n,finalUrl:c.url,status:c.status,extractor:m,truncated:p,length:f.length,text:f})}catch(c){if(k(c))throw c;return JSON.stringify({error:String(c),url:n})}}};function O(s){return bn.resolve(s.workspace)}function Ge(s){let t=O(s);return s.restrictToWorkspace?t:void 0}function vn(s){let t=[R({name:"builtin-filesystem-tools",tools:[{name:"read_file",create:e=>new fe(O(e),Ge(e))},{name:"write_file",create:e=>new he(O(e),Ge(e))},{name:"edit_file",create:e=>new ye(O(e),Ge(e))},{name:"list_dir",create:e=>new be(O(e),Ge(e))}]}),R({name:"builtin-shell-tools",tools:[{name:"exec",create:e=>new we(e.execConfig?.timeout??60,O(e),!!e.restrictToWorkspace,e.execConfig?.pathAppend??"",new D,e.rtkService,e.rtkConfig?.ultraCompact??!1)}]}),R({name:"builtin-web-tools",tools:[{name:"web_search",create:e=>new qe(e.braveApiKey??null)},{name:"web_fetch",create:()=>new We}]})];return s.bus&&t.push(R({name:"builtin-messaging-tools",tools:[{name:"message",create:e=>{if(!e.bus)throw new Error("Builtin message tool requires a message bus");let r=new Se(async n=>{e.turn?.isCurrent&&!e.turn.isCurrent()||await e.bus.publishOutbound(n)});return e.turn&&r.setContext(e.turn.channel,e.turn.chatId,e.turn.messageId),r}}]})),s.subagents&&t.push(R({name:"builtin-subagent-tools",tools:[{name:"spawn",create:e=>{if(!e.subagents)throw new Error("Builtin spawn tool requires a subagent manager");let r=new xe(e.subagents);return e.turn&&r.setContext(e.turn.channel,e.turn.chatId,e.turn.sessionKey,e.turn.systemPrompt),r}}]})),s.cronService&&t.push(R({name:"builtin-scheduler-tools",tools:[{name:"cron",create:e=>{if(!e.cronService)throw new Error("Builtin cron tool requires a cron service");let r=new pe(e.cronService);return e.turn&&r.setContext(e.turn.channel,e.turn.chatId),r}}]})),s.sessionManager&&t.push(R({name:"builtin-session-tools",tools:[{name:"session.info",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.info tool requires a session manager");let r=new _e;return r.setSessionManager(e.sessionManager),e.turn&&r.setContext(e.turn.sessionKey),r}},{name:"session.anchor",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.anchor tool requires a session manager");let r=new Le;return r.setSessionManager(e.sessionManager),e.turn&&r.setContext(e.turn.sessionKey),r}},{name:"session.search",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.search tool requires a session manager");let r=new ke;return r.setSessionManager(e.sessionManager),e.turn&&r.setContext(e.turn.sessionKey),r}}]})),s.chromeSessionConfig?.enabled&&t.push(R({name:"builtin-chrome-session-tools",tools:[{name:"chrome_session",create:e=>new re(e.chromeSessionConfig,O(e),!!e.restrictToWorkspace)}]})),s.browserRelay&&t.push(R({name:"builtin-browser-relay-tools",tools:[{name:"chrome_relay",create:e=>{if(!e.browserRelay)throw new Error("Builtin chrome_relay tool requires a browser relay server");return new ne(e.browserRelay)}}]})),t.push(R({name:"builtin-automation-tools",tools:[{name:"automation",create:e=>{let r=e.browserRelay?new ne(e.browserRelay):e.chromeSessionConfig?.enabled?new re(e.chromeSessionConfig,O(e),!!e.restrictToWorkspace):void 0;return new Je(O(e),r,e.chromeSessionConfig?.stealth)}}]})),t}function Sn(s){return Et(vn(s))}function tr(s){let t=new Ue,e=Sn(s);for(let r of e.tools.values())t.register(r.contribution.create(s));return t}var nr="EVERCLAW_SUBAGENT_RESULT ";function rr(s,t){let e=new Date().toLocaleString(),r=t??"You are operating as a subagent spawned by the main agent to complete a specific task. Stay focused and concise. Complete the assigned task and report your findings.";return s?`${s}
160
156
 
161
157
  ---
162
158
 
163
159
  # Subagent Mode
164
160
 
165
- Current Time: ${y}
161
+ Current Time: ${e}
166
162
 
167
- ${$}`;return`# Subagent
163
+ ${r}`:`# Subagent
168
164
 
169
- Current Time: ${y}
165
+ Current Time: ${e}
170
166
 
171
- ${$}`}async function DX(J){let _=PX({workspace:J.workspace,restrictToWorkspace:J.restrictToWorkspace,braveApiKey:J.braveApiKey,execConfig:J.execConfig}),y=J.definition;if(y?.allowedTools&&y.allowedTools.length>0)_=_.filterByNames(y.allowedTools);else if(y?.deniedTools&&y.deniedTools.length>0)_=_.excludeByNames(y.deniedTools);let $=y?.systemPromptSuffix,X;if(J.contextMode==="fork"&&J.existingMessages?.length){let L=$?`# Subagent Mode
167
+ ${r}`}async function or(s){let t=tr({workspace:s.workspace,restrictToWorkspace:s.restrictToWorkspace,braveApiKey:s.braveApiKey,execConfig:s.execConfig}),e=s.definition;e?.allowedTools&&e.allowedTools.length>0?t=t.filterByNames(e.allowedTools):e?.deniedTools&&e.deniedTools.length>0&&(t=t.excludeByNames(e.deniedTools));let r=e?.systemPromptSuffix,n;if(s.contextMode==="fork"&&s.existingMessages?.length){let i=r?`# Subagent Mode
172
168
 
173
- ${$}`:`# Subagent Mode
169
+ ${r}`:`# Subagent Mode
174
170
 
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.`;X=J.existingMessages.map((q,N)=>{if(N===0&&q.role==="system"&&typeof q.content==="string")return{...q,content:`${q.content}
171
+ You are operating as a subagent spawned by the main agent to complete a specific task. Stay focused and concise. Complete the assigned task and report your findings.`;n=s.existingMessages.map((a,l)=>l===0&&a.role==="system"&&typeof a.content=="string"?{...a,content:`${a.content}
176
172
 
177
173
  ---
178
174
 
179
- ${L}`};return q}),X.push({role:"user",content:J.task})}else if(J.contextMode==="inherit-system"&&J.parentSystemPrompt)X=[{role:"system",content:xX(J.parentSystemPrompt,$)},{role:"user",content:J.task}];else X=J.existingMessages?[...J.existingMessages,{role:"user",content:J.task}]:[{role:"system",content:xX(void 0,$)},{role:"user",content:J.task}];let A="Task completed but no final response was generated.";for(let L=0;L<15;L++){v(J.signal);let q=await J.provider.chat({messages:X,tools:_.getDefinitions(),model:J.model,temperature:J.temperature,maxTokens:J.maxTokens,...J.signal?{signal:J.signal}:{}});if(v(J.signal),q.toolCalls.length){X.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){v(J.signal);let G=await _.execute(N.name,N.arguments,J.signal?{signal:J.signal}:{});v(J.signal);let B=typeof G==="object"&&"kind"in G?G.content??String(G):String(G);X.push({role:"tool",tool_call_id:N.id,name:N.name,content:B})}continue}A=q.content??A;break}return A}class j4{bus;processExecutor;inlineExecutor;settings;running=new Map;controllers=new Map;sessionTasks=new Map;sessionGenerations=new Map;taskTracker=new by;constructor(J,_,y,$){this.bus=J;this.processExecutor=_;this.inlineExecutor=y;this.settings=$}getTaskTracker(){return this.taskTracker}getTaskSnapshot(){return this.taskTracker.prune(),this.taskTracker.getAll()}async spawn(J){let _=F4().slice(0,8),y=J.label??(J.task.length>30?`${J.task.slice(0,30)}...`:J.task),$=this.getSessionGeneration(J.sessionKey),X=new AbortController;this.controllers.set(_,X),this.taskTracker.register(_,"subagent",y,J.sessionKey);let A=J.mode??"process",L=J.agentType?NX(J.agentType):void 0,q=this.runSubagent(_,J.task,y,{channel:J.originChannel,chatId:J.originChatId,sessionKey:J.sessionKey,generation:$},A,J.provider,J.model,J.providerName,J.contextMode,J.parentSystemPrompt,L).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 [${y}] started (id: ${_}). I'll notify you when it completes.`}async runSubagent(J,_,y,$,X="process",A,L,q,N,G,B){let R=this.controllers.get(J)?.signal,Q=X==="inline"?this.inlineExecutor:this.processExecutor;this.taskTracker.transition(J,"running");try{let K={...this.settings,task:_};if(R)K.signal=R;if(A)K.provider=A;if(L)K.model=L;if(q)K.providerName=q;if(N)K.contextMode=N;if(G)K.parentSystemPrompt=G;if(B)K.agentType=B.name;let Y=await Q.execute(K);if(Y.status==="aborted"){this.taskTracker.transition(J,"killed");return}if(!this.isSessionCurrent($.sessionKey,$.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($,_,y,Y,J)}catch(K){if(k(K)){this.taskTracker.transition(J,"killed");return}if(!this.isSessionCurrent($.sessionKey,$.generation)){this.taskTracker.transition(J,"killed");return}let Y=K instanceof Error?K.message:String(K);this.taskTracker.transition(J,"failed",void 0,Y);try{await this.publishOutcome($,_,y,{status:"failed",errorMessage:Y,failureAttribution:"exception"},J)}catch{}}}async publishOutcome(J,_,y,$,X){let A={kind:$.status==="completed"?"subagent_completed":"subagent_failed",taskId:X,label:y,status:$.status==="completed"?"completed":"failed",originalTask:_,...$.finalResult?{result:$.finalResult}:{},...$.errorMessage?{error:$.errorMessage}:{}},L=$.status==="completed"?$.finalResult??"Task completed.":$.errorMessage??"Subagent failed.",q={channel:"system",senderId:"subagent",chatId:`${J.channel}:${J.chatId}`,content:L,metadata:{_notification:A}};await this.bus.publishInbound(q)}async cancelBySession(J){this.sessionGenerations.set(J,this.getSessionGeneration(J)+1);let _=[...this.sessionTasks.get(J)??[]],y=0;for(let $ of _){let X=this.controllers.get($);if(!X||X.signal.aborted)continue;X.abort(),y+=1}return y}async cancelAll(){let J=[...this.sessionTasks.keys()],_=0;for(let y of J)_+=await this.cancelBySession(y);return _}getRunningCount(){return this.running.size}getSessionGeneration(J){return this.sessionGenerations.get(J)??0}isSessionCurrent(J,_){return this.getSessionGeneration(J)===_}}async function W4(){let J=[];for await(let _ of process.stdin)J.push(typeof _==="string"?_:_.toString("utf8"));return J.join("")}function My(J){process.stdout.write(`${IX}${JSON.stringify(J)}
180
- `)}async function P4(){let J=new AbortController,_=()=>J.abort();process.once("SIGTERM",_),process.once("SIGINT",_);try{let y=(await W4()).trim();if(!y)throw new Error("Missing subagent payload.");let $=JSON.parse(y),X=ey();if($.providerName)X.agents.defaults.provider=$.providerName;if($.model)X.agents.defaults.model=$.model;let A=X1(X),L=await DX({...$,provider:A,signal:J.signal});My({status:"completed",finalResult:L})}catch(y){if(J.signal.aborted||k(y)){My({status:"aborted",errorMessage:null,failureAttribution:"aborted"});return}let $=y instanceof Error?y.message:String(y);console.error(y instanceof Error&&y.stack?y.stack:$),My({status:"failed",errorMessage:$,failureAttribution:"exception"}),process.exitCode=1}finally{process.removeListener("SIGTERM",_),process.removeListener("SIGINT",_)}}P4();
175
+ ${i}`}:a),n.push({role:"user",content:s.task})}else s.contextMode==="inherit-system"&&s.parentSystemPrompt?n=[{role:"system",content:rr(s.parentSystemPrompt,r)},{role:"user",content:s.task}]:n=s.existingMessages?[...s.existingMessages,{role:"user",content:s.task}]:[{role:"system",content:rr(void 0,r)},{role:"user",content:s.task}];let o="Task completed but no final response was generated.";for(let i=0;i<15;i++){v(s.signal);let a=await s.provider.chat({messages:n,tools:t.getDefinitions(),model:s.model,temperature:s.temperature,maxTokens:s.maxTokens,...s.signal?{signal:s.signal}:{}});if(v(s.signal),a.toolCalls.length){n.push({role:"assistant",content:a.content??"",tool_calls:a.toolCalls.map(l=>({id:l.id,type:"function",function:{name:l.name,arguments:JSON.stringify(l.arguments)}}))});for(let l of a.toolCalls){v(s.signal);let c=await t.execute(l.name,l.arguments,s.signal?{signal:s.signal}:{});v(s.signal);let u=typeof c=="object"&&"kind"in c?c.content??String(c):String(c);n.push({role:"tool",tool_call_id:l.id,name:l.name,content:u})}continue}o=a.content??o;break}return o}async function wn(){let s=[];for await(let t of process.stdin)s.push(typeof t=="string"?t:t.toString("utf8"));return s.join("")}function it(s){process.stdout.write(`${nr}${JSON.stringify(s)}
176
+ `)}async function xn(){let s=new AbortController,t=()=>s.abort();process.once("SIGTERM",t),process.once("SIGINT",t);try{let e=(await wn()).trim();if(!e)throw new Error("Missing subagent payload.");let r=JSON.parse(e),n=kt();r.providerName&&(n.agents.defaults.provider=r.providerName),r.model&&(n.agents.defaults.model=r.model);let o=At(n),i=await or({...r,provider:o,signal:s.signal});it({status:"completed",finalResult:i})}catch(e){if(s.signal.aborted||k(e)){it({status:"aborted",errorMessage:null,failureAttribution:"aborted"});return}let r=e instanceof Error?e.message:String(e);console.error(e instanceof Error&&e.stack?e.stack:r),it({status:"failed",errorMessage:r,failureAttribution:"exception"}),process.exitCode=1}finally{process.removeListener("SIGTERM",t),process.removeListener("SIGINT",t)}}xn();