everclaw 0.3.16 → 0.3.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent/subagent-worker.js +76 -72
- package/agent/tools/chrome-session/daemon-worker.js +49 -0
- package/index.js +397 -214
- package/package.json +1 -1
package/agent/subagent-worker.js
CHANGED
|
@@ -1,58 +1,62 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"dotenv/config";import St from"node:fs";import Fn from"node:path";import sr from"node:fs";import ct from"node:os";import F from"node:path";import{fileURLToPath as ir}from"node:url";var He=".everclaw",G="~/.everclaw/config.json",ut=F.join("~",He,"workspace");function dt(s=ct.homedir()){return F.join(s,He,"workspace")}function mt(s=ct.homedir()){return F.join(s,He,"config.json")}function ar(){let s=ir(import.meta.url),t=F.dirname(s);return s.endsWith("/index.js")||s.endsWith("\\index.js")?t:F.resolve(t,"..")}var lr=ar();function gt(...s){let t=F.resolve(lr,...s);if(!sr.existsSync(t))throw new Error(`Runtime asset not found: ${t}`);return t}var cr=[{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 cr.map(s=>s.spec)}var K=Ve(),ur=Object.fromEntries(Ve().map(s=>[s.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),ae="custom:",H={agents:{defaults:{workspace:ut,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:ur,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 J(s){return s.toLowerCase().replace(/[\s-]+/g,"_")}function pt(s){return`${ae}${J(s)}`}function ft(s,t){let e=J(t.startsWith(ae)?t.slice(ae.length):t);return s.customLlmProviders.find(r=>J(r.name)===e)??null}function dr(s,t){if(!t.includes("/"))return null;let r=t.split("/",1)[0];return r?ft(s,r):null}function N(s){return!!s&&s.startsWith(ae)}function U(s,t,e){let r=(t??s.agents.defaults.provider).trim();if(r&&r!=="auto"&&!s.providers[r])return ft(s,r);let n=dr(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=U(s,e,t);return a?pt(a.name):null}let r=(t??s.agents.defaults.model).toLowerCase(),n=J(r),o=r.includes("/")?r.split("/",1)[0]:"";for(let a of K){let l=s.providers[a.name];if(o&&J(o)===a.name&&(a.isOauth||l?.apiKey))return a.name}for(let a of K){let l=s.providers[a.name];if(a.keywords.some(c=>r.includes(c)||n.includes(J(c)))&&(a.isOauth||l?.apiKey))return a.name}for(let a of K){if(a.isOauth)continue;if(s.providers[a.name]?.apiKey)return a.name}let i=U(s,e,t);return i?pt(i.name):null}function ht(s,t){let e=le(s,t);if(e&&N(e)){let r=U(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 U(s,e,t)?.baseUrl??null;let r=s.providers[e];if(r?.apiBase)return r.apiBase;let n=K.find(o=>o.name===e);return n?.isGateway?n.defaultApiBase:null}import mr from"node:fs";import gr from"node:path";import yt from"node:os";function bt(s){return mr.mkdirSync(s,{recursive:!0}),s}function vt(s){let t=s?s.replace(/^~(?=$|[\\/])/,yt.homedir()):dt(yt.homedir());return bt(gr.resolve(t))}function fr(){return mt()}function wt(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]=wt(e[r],n):e[r]=n;return e}function xt(s){let t=s??fr();if(!St.existsSync(t))return structuredClone(H);try{let e=St.readFileSync(t,"utf8"),r=JSON.parse(e),n=wt(structuredClone(H),r),o=["advisor"];for(let i of o)if(!n.subagents.find(a=>a.id===i)){let a=H.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(H)}}function V(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 kt(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_")}function Ct(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}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",kt(this.options.providerLabel??"")]).has(kt(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:V(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:Ct(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 V(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:Ct(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
|
-
|
|
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:hr(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 yr}from"nanoid";var me=class s{constructor(t,e,r,n){this.apiKey=t;this.apiBase=e;this.defaultModel=r;this.providerName=n}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:V(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 ${G} 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
|
-
|
|
8
|
-
|
|
9
|
-
`)}
|
|
10
|
-
`)
|
|
11
|
-
|
|
12
|
-
${
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
`),
|
|
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.
|
|
23
27
|
|
|
24
28
|
## Current Long-term Memory
|
|
25
29
|
|
|
26
30
|
|
|
27
31
|
## Conversation to Process
|
|
28
|
-
`),
|
|
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":"..."}.
|
|
29
33
|
|
|
30
34
|
## Current Long-term Memory
|
|
31
|
-
${
|
|
35
|
+
${K}
|
|
32
36
|
|
|
33
|
-
${
|
|
34
|
-
${
|
|
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}
|
|
35
39
|
|
|
36
|
-
${this.stripFrontmatter(
|
|
40
|
+
${this.stripFrontmatter($.content)}`)}return _.join(`
|
|
37
41
|
|
|
38
42
|
---
|
|
39
43
|
|
|
40
|
-
`)}buildSkillsSummary(){let
|
|
41
|
-
`)}getAlwaysSkills(){return this.getResolvedSkills().filter(
|
|
42
|
-
`)||
|
|
43
|
-
`)))return{frontmatter:null,error:"missing YAML frontmatter"};let
|
|
44
|
+
`)}buildSkillsSummary(){let J=this.getResolvedSkills();if(!J.length)return"";let _=($)=>$.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"),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}
|
|
44
48
|
|
|
45
|
-
Error: ${
|
|
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
|
|
46
50
|
|
|
47
|
-
${
|
|
51
|
+
${A}`);let L=this.skills.getAlwaysSkills();if(L.length){let N=this.skills.loadSkillsForContext(L);if(N)y.push(`# Active Skills
|
|
48
52
|
|
|
49
|
-
${
|
|
53
|
+
${N}`)}if(J?.length){let N=this.skills.loadSkillsForContext(J);if(N)y.push(`# Requested Skills
|
|
50
54
|
|
|
51
|
-
${
|
|
55
|
+
${N}`)}let q=this.skills.buildSkillsSummary();if(q)y.push(`# Skills
|
|
52
56
|
|
|
53
57
|
The following skills extend your capabilities. To use one, read its SKILL.md with read_file.
|
|
54
58
|
|
|
55
|
-
${
|
|
59
|
+
${q}`);return y.join(`
|
|
56
60
|
|
|
57
61
|
---
|
|
58
62
|
|
|
@@ -61,29 +65,29 @@ ${l}`),r.join(`
|
|
|
61
65
|
You are everclaw, a helpful AI assistant.
|
|
62
66
|
|
|
63
67
|
## Runtime
|
|
64
|
-
${
|
|
68
|
+
${UX.platform()} ${UX.arch()}, Node ${process.version}
|
|
65
69
|
|
|
66
70
|
## Workspace
|
|
67
71
|
Your workspace is at: ${this.workspace}
|
|
68
|
-
- Long-term memory: ${
|
|
69
|
-
- History log: ${
|
|
70
|
-
- Custom skills: ${
|
|
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")}
|
|
71
75
|
|
|
72
76
|
## Guidelines
|
|
73
77
|
- State intent before tool calls, but never claim results before receiving them.
|
|
74
78
|
- Before modifying a file, read it first.
|
|
75
|
-
- Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let
|
|
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(`## ${_}
|
|
76
80
|
|
|
77
|
-
${
|
|
81
|
+
${HX.readFileSync(y,"utf8")}`)}return J.join(`
|
|
78
82
|
|
|
79
|
-
`)}static buildRuntimeContext(
|
|
80
|
-
${
|
|
81
|
-
`)}`}buildMessages(
|
|
82
|
-
`)}return`[${
|
|
83
|
-
Status: ${
|
|
84
|
-
`),
|
|
85
|
-
`)
|
|
86
|
-
`;return new Promise((
|
|
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).
|
|
87
91
|
|
|
88
92
|
Core Commands:
|
|
89
93
|
- status: Check Chrome connectivity, version, and remote debugging status
|
|
@@ -118,19 +122,19 @@ Examples:
|
|
|
118
122
|
- chrome_session clickxy --target "ABC123" --x 100 --y 200
|
|
119
123
|
- chrome_session type --target "ABC123" --text "Hello World"
|
|
120
124
|
- chrome_session loadall --target "ABC123" --selector "button.load-more" --interval 500
|
|
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 Ut();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 Q(t)}catch{e=await Q(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 qt(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 Q(e)}catch{r=await Q(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(un(),`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=cn(t);ln(r)||an(r,{recursive:!0});let n=Buffer.from(e,"base64");sn(t,n)}formatResult(t){return JSON.stringify(t,null,2)}formatError(t){return JSON.stringify({error:t},null,2)}};var re=class extends g{constructor(e){super();this.relay=e}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 ne from"node:path";import{randomUUID as dn}from"node:crypto";var mn="automations",gn="index.json";function pn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)}function rt(s){return ne.join(s,mn)}function Kt(s){return ne.join(rt(s),gn)}function je(s,t){return ne.join(rt(s),t)}function nt(s,t){return ne.join(je(s,t),"rule.json")}function ot(s,t){return ne.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=Kt(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=W(s,o.id);o.stepCount=i?.steps?.length||0,n=!0}if(o.toolType===void 0){let i=W(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=Kt(s),r=`${e}.tmp`;w.writeFileSync(r,JSON.stringify(t,null,2)),w.renameSync(r,e)}function Ht(s){return Be(s).rules}function W(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 Vt(s,t){st(s);let e=pn(t.name)||dn().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=Yt(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 zt(s,t,e){let r=W(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=Yt(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 Xt(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 Yt(s){let t=new Date().toISOString();return`// Automation: ${s.name}
|
|
122
|
-
// Tool: ${
|
|
123
|
-
// Generated: ${
|
|
124
|
-
// Description: ${
|
|
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}
|
|
125
129
|
//
|
|
126
130
|
// Steps:
|
|
127
|
-
${
|
|
131
|
+
${J.steps.map((y)=>`// ${y.order}. ${y.description}`).join(`
|
|
128
132
|
`)}
|
|
129
133
|
//
|
|
130
134
|
// Usage: node script.js [--port=6767]
|
|
131
135
|
|
|
132
136
|
const PORT = process.argv.find(a => a.startsWith('--port='))?.split('=')[1] ?? '6767';
|
|
133
|
-
const URL = \`http://127.0.0.1:\${PORT}/api/automations/${
|
|
137
|
+
const URL = \`http://127.0.0.1:\${PORT}/api/automations/${J.id}/run\`;
|
|
134
138
|
|
|
135
139
|
fetch(URL, { method: 'POST' })
|
|
136
140
|
.then(r => r.json())
|
|
@@ -139,38 +143,38 @@ fetch(URL, { method: 'POST' })
|
|
|
139
143
|
else console.error('Failed:', r.error);
|
|
140
144
|
})
|
|
141
145
|
.catch(e => console.error('Could not reach everclaw:', e.message));
|
|
142
|
-
`}var
|
|
143
|
-
`)}}return
|
|
144
|
-
`)}async resolveTabContext(){if(!this.browserTool)return{};let
|
|
145
|
-
`);return{kind:"error",content:`Security: Tool call blocked. The tool '${
|
|
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.
|
|
146
150
|
|
|
147
151
|
Findings:
|
|
148
|
-
${
|
|
152
|
+
${q}`,retryable:!1}}}let X=$.validateParams(_);if(X.length)return{kind:"error",content:`Error: Invalid parameters for tool '${J}': ${X.join("; ")}
|
|
149
153
|
|
|
150
|
-
[Analyze the error above and try a different approach.]`,retryable:!0};let
|
|
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)}
|
|
151
155
|
|
|
152
|
-
[Analyze the error above and try a different approach.]`,retryable:!0}}}}
|
|
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,`
|
|
153
157
|
|
|
154
|
-
`).trim()}function
|
|
155
|
-
`)}catch(
|
|
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}
|
|
156
160
|
|
|
157
161
|
---
|
|
158
162
|
|
|
159
163
|
# Subagent Mode
|
|
160
164
|
|
|
161
|
-
Current Time: ${
|
|
165
|
+
Current Time: ${y}
|
|
162
166
|
|
|
163
|
-
${
|
|
167
|
+
${$}`;return`# Subagent
|
|
164
168
|
|
|
165
|
-
Current Time: ${
|
|
169
|
+
Current Time: ${y}
|
|
166
170
|
|
|
167
|
-
${
|
|
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
|
|
168
172
|
|
|
169
|
-
${
|
|
173
|
+
${$}`:`# Subagent Mode
|
|
170
174
|
|
|
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.`;
|
|
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}
|
|
172
176
|
|
|
173
177
|
---
|
|
174
178
|
|
|
175
|
-
${
|
|
176
|
-
`)}async function
|
|
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();
|