everclaw 0.3.2 → 0.3.3
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 +6 -6
- package/index.js +170 -118
- package/package.json +1 -1
package/agent/subagent-worker.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import"dotenv/config";import lt from"node:fs";import fn from"node:path";import Jt from"node:fs";import Ye from"node:os";import N from"node:path";import{fileURLToPath as qt}from"node:url";var De=".everclaw",J="~/.everclaw/config.json",Ze=N.join("~",De,"workspace");function Qe(s=Ye.homedir()){return N.join(s,De,"workspace")}function et(s=Ye.homedir()){return N.join(s,De,"config.json")}function Ut(){let s=qt(import.meta.url),t=N.dirname(s);return s.endsWith("/index.js")||s.endsWith("\\index.js")?t:N.resolve(t,"..")}var Wt=Ut();function tt(...s){let t=N.resolve(Wt,...s);if(!Jt.existsSync(t))throw new Error(`Runtime asset not found: ${t}`);return t}var Gt=[{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 je(){return Gt.map(s=>s.spec)}var q=je(),Kt=Object.fromEntries(je().map(s=>[s.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),ee="custom:",U={agents:{defaults:{workspace:Ze,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}},discord:{enabled:!1,token:"",allowFrom:[],gatewayUrl:"wss://gateway.discord.gg/?v=10&encoding=json",intents:37377,debounce:{enabled:!0,quietMs:500,maxWaitMs:3e3}}},providers:Kt,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},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}}};function D(s){return s.toLowerCase().replace(/[\s-]+/g,"_")}function rt(s){return`${ee}${D(s)}`}function nt(s,t){let e=D(t.startsWith(ee)?t.slice(ee.length):t);return s.customLlmProviders.find(n=>D(n.name)===e)??null}function Ht(s,t){if(!t.includes("/"))return null;let n=t.split("/",1)[0];return n?nt(s,n):null}function O(s){return!!s&&s.startsWith(ee)}function j(s,t,e){let n=(t??s.agents.defaults.provider).trim();if(n&&n!=="auto"&&!s.providers[n])return nt(s,n);let r=Ht(s,e??s.agents.defaults.model);if(r)return r;let o=s.customLlmProviders.filter(i=>i.name.trim()&&i.baseUrl.trim());return o.length===1?o[0]??null:null}function te(s,t){let e=s.agents.defaults.provider;if(e!=="auto"){if(s.providers[e])return e;let a=j(s,e,t);return a?rt(a.name):null}let n=(t??s.agents.defaults.model).toLowerCase(),r=D(n),o=n.includes("/")?n.split("/",1)[0]:"";for(let a of q){let l=s.providers[a.name];if(o&&D(o)===a.name&&(a.isOauth||l?.apiKey))return a.name}for(let a of q){let l=s.providers[a.name];if(a.keywords.some(c=>n.includes(c)||r.includes(D(c)))&&(a.isOauth||l?.apiKey))return a.name}for(let a of q){if(a.isOauth)continue;if(s.providers[a.name]?.apiKey)return a.name}let i=j(s,e,t);return i?rt(i.name):null}function ot(s,t){let e=te(s,t);if(e&&O(e)){let n=j(s,e,t);return n?{apiKey:n.apiKey,apiBase:n.baseUrl,extraHeaders:n.extraHeaders}:null}return e?s.providers[e]??null:null}function re(s,t){let e=te(s,t);if(!e)return null;if(O(e))return j(s,e,t)?.baseUrl??null;let n=s.providers[e];if(n?.apiBase)return n.apiBase;let r=q.find(o=>o.name===e);return r?.isGateway?r.defaultApiBase:null}import Vt from"node:fs";import zt from"node:path";import st from"node:os";function it(s){return Vt.mkdirSync(s,{recursive:!0}),s}function at(s){let t=s?s.replace(/^~(?=$|[\\/])/,st.homedir()):Qe(st.homedir());return it(zt.resolve(t))}function Yt(){return et()}function ct(s,t){if(!t||typeof t!="object")return s;let e=Array.isArray(s)?[...s]:{...s};for(let[n,r]of Object.entries(t))r&&typeof r=="object"&&!Array.isArray(r)&&e[n]&&typeof e[n]=="object"&&!Array.isArray(e[n])?e[n]=ct(e[n],r):e[n]=r;return e}function ut(s){let t=s??Yt();if(!lt.existsSync(t))return structuredClone(U);try{let e=lt.readFileSync(t,"utf8"),n=JSON.parse(e),r=ct(structuredClone(U),n),o=["advisor"];for(let i of o)if(!r.subagents.find(a=>a.id===i)){let a=U.subagents.find(l=>l.id===i);a&&r.subagents.push(structuredClone(a))}return r}catch(e){return console.warn(`Warning: Failed to load config from ${t}: ${String(e)}`),structuredClone(U)}}function W(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 n=e.filter(r=>!(typeof r=="object"&&r&&["text","input_text","output_text"].includes(r.type)&&!r.text));if(n.length!==e.length)return n.length>0?{...t,content:n}:t.role==="assistant"&&t.tool_calls?{...t,content:null}:{...t,content:"(empty)"}}return t})}function Be(){let s=new Error("Operation aborted");return s.name="AbortError",s}function x(s){return s instanceof Error&&s.name==="AbortError"}function b(s){if(s?.aborted)throw Be()}function dt(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_")}function mt(s){if(typeof s!="string")return s&&typeof s=="object"?s:{};try{return JSON.parse(s)}catch{return{}}}var ne=class{constructor(t,e,n,r={}){this.apiKey=t;this.apiBase=e;this.defaultModel=n;this.options=r}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 n=e.split("/",2),r=n[0],o=n[1];return!r||!o?e:new Set(["custom",dt(this.options.providerLabel??"")]).has(dt(r))?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:W(t.messages),tools:t.tools,tool_choice:t.tools?.length?"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}:{}}),n=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${n?.error?.message??JSON.stringify(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let r=n.choices?.[0];if(!r?.message)return{content:`Error calling LLM: ${JSON.stringify(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=(r.message.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:mt(i.function.arguments)}));return{content:r.message.content??null,toolCalls:o,finishReason:r.finish_reason??"stop",usage:{prompt_tokens:n.usage?.prompt_tokens??0,completion_tokens:n.usage?.completion_tokens??0,total_tokens:n.usage?.total_tokens??0},reasoningContent:r.message.reasoning_content??null}}toResponsesInput(t){let e=[];for(let n of W(t)){let r=String(n.role??"");if(r==="tool"){e.push({type:"function_call_output",call_id:String(n.tool_call_id??""),output:typeof n.content=="string"?n.content:JSON.stringify(n.content??null)});continue}if(r==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.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??{})});(r==="system"||r==="user"||r==="assistant")&&e.push({role:r,content:n.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?"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}:{}}),n=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${n?.error?.message??JSON.stringify(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let r=Array.isArray(n.output)?n.output:[],o=r.filter(a=>a?.type==="function_call").map(a=>({id:String(a.call_id??a.id??""),name:String(a.name??""),arguments:mt(a.arguments)}));return{content:r.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(`
|
|
2
|
+
import"dotenv/config";import lt from"node:fs";import fn from"node:path";import Jt from"node:fs";import Ye from"node:os";import N from"node:path";import{fileURLToPath as Ut}from"node:url";var De=".everclaw",J="~/.everclaw/config.json",Ze=N.join("~",De,"workspace");function Qe(s=Ye.homedir()){return N.join(s,De,"workspace")}function et(s=Ye.homedir()){return N.join(s,De,"config.json")}function qt(){let s=Ut(import.meta.url),t=N.dirname(s);return s.endsWith("/index.js")||s.endsWith("\\index.js")?t:N.resolve(t,"..")}var Wt=qt();function tt(...s){let t=N.resolve(Wt,...s);if(!Jt.existsSync(t))throw new Error(`Runtime asset not found: ${t}`);return t}var Gt=[{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 je(){return Gt.map(s=>s.spec)}var U=je(),Kt=Object.fromEntries(je().map(s=>[s.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),ee="custom:",q={agents:{defaults:{workspace:Ze,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}},discord:{enabled:!1,token:"",allowFrom:[],gatewayUrl:"wss://gateway.discord.gg/?v=10&encoding=json",intents:37377,debounce:{enabled:!0,quietMs:500,maxWaitMs:3e3}}},providers:Kt,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},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}}};function D(s){return s.toLowerCase().replace(/[\s-]+/g,"_")}function rt(s){return`${ee}${D(s)}`}function nt(s,t){let e=D(t.startsWith(ee)?t.slice(ee.length):t);return s.customLlmProviders.find(n=>D(n.name)===e)??null}function Ht(s,t){if(!t.includes("/"))return null;let n=t.split("/",1)[0];return n?nt(s,n):null}function O(s){return!!s&&s.startsWith(ee)}function j(s,t,e){let n=(t??s.agents.defaults.provider).trim();if(n&&n!=="auto"&&!s.providers[n])return nt(s,n);let r=Ht(s,e??s.agents.defaults.model);if(r)return r;let o=s.customLlmProviders.filter(i=>i.name.trim()&&i.baseUrl.trim());return o.length===1?o[0]??null:null}function te(s,t){let e=s.agents.defaults.provider;if(e!=="auto"){if(s.providers[e])return e;let a=j(s,e,t);return a?rt(a.name):null}let n=(t??s.agents.defaults.model).toLowerCase(),r=D(n),o=n.includes("/")?n.split("/",1)[0]:"";for(let a of U){let l=s.providers[a.name];if(o&&D(o)===a.name&&(a.isOauth||l?.apiKey))return a.name}for(let a of U){let l=s.providers[a.name];if(a.keywords.some(c=>n.includes(c)||r.includes(D(c)))&&(a.isOauth||l?.apiKey))return a.name}for(let a of U){if(a.isOauth)continue;if(s.providers[a.name]?.apiKey)return a.name}let i=j(s,e,t);return i?rt(i.name):null}function ot(s,t){let e=te(s,t);if(e&&O(e)){let n=j(s,e,t);return n?{apiKey:n.apiKey,apiBase:n.baseUrl,extraHeaders:n.extraHeaders}:null}return e?s.providers[e]??null:null}function re(s,t){let e=te(s,t);if(!e)return null;if(O(e))return j(s,e,t)?.baseUrl??null;let n=s.providers[e];if(n?.apiBase)return n.apiBase;let r=U.find(o=>o.name===e);return r?.isGateway?r.defaultApiBase:null}import Vt from"node:fs";import zt from"node:path";import st from"node:os";function it(s){return Vt.mkdirSync(s,{recursive:!0}),s}function at(s){let t=s?s.replace(/^~(?=$|[\\/])/,st.homedir()):Qe(st.homedir());return it(zt.resolve(t))}function Yt(){return et()}function ct(s,t){if(!t||typeof t!="object")return s;let e=Array.isArray(s)?[...s]:{...s};for(let[n,r]of Object.entries(t))r&&typeof r=="object"&&!Array.isArray(r)&&e[n]&&typeof e[n]=="object"&&!Array.isArray(e[n])?e[n]=ct(e[n],r):e[n]=r;return e}function ut(s){let t=s??Yt();if(!lt.existsSync(t))return structuredClone(q);try{let e=lt.readFileSync(t,"utf8"),n=JSON.parse(e),r=ct(structuredClone(q),n),o=["advisor"];for(let i of o)if(!r.subagents.find(a=>a.id===i)){let a=q.subagents.find(l=>l.id===i);a&&r.subagents.push(structuredClone(a))}return r}catch(e){return console.warn(`Warning: Failed to load config from ${t}: ${String(e)}`),structuredClone(q)}}function W(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 n=e.filter(r=>!(typeof r=="object"&&r&&["text","input_text","output_text"].includes(r.type)&&!r.text));if(n.length!==e.length)return n.length>0?{...t,content:n}:t.role==="assistant"&&t.tool_calls?{...t,content:null}:{...t,content:"(empty)"}}return t})}function Be(){let s=new Error("Operation aborted");return s.name="AbortError",s}function x(s){return s instanceof Error&&s.name==="AbortError"}function b(s){if(s?.aborted)throw Be()}function dt(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_")}function mt(s){if(typeof s!="string")return s&&typeof s=="object"?s:{};try{return JSON.parse(s)}catch{return{}}}var ne=class{constructor(t,e,n,r={}){this.apiKey=t;this.apiBase=e;this.defaultModel=n;this.options=r}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 n=e.split("/",2),r=n[0],o=n[1];return!r||!o?e:new Set(["custom",dt(this.options.providerLabel??"")]).has(dt(r))?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:W(t.messages),tools:t.tools,tool_choice:t.tools?.length?"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}:{}}),n=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${n?.error?.message??JSON.stringify(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let r=n.choices?.[0];if(!r?.message)return{content:`Error calling LLM: ${JSON.stringify(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=(r.message.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:mt(i.function.arguments)}));return{content:r.message.content??null,toolCalls:o,finishReason:r.finish_reason??"stop",usage:{prompt_tokens:n.usage?.prompt_tokens??0,completion_tokens:n.usage?.completion_tokens??0,total_tokens:n.usage?.total_tokens??0},reasoningContent:r.message.reasoning_content??null}}toResponsesInput(t){let e=[];for(let n of W(t)){let r=String(n.role??"");if(r==="tool"){e.push({type:"function_call_output",call_id:String(n.tool_call_id??""),output:typeof n.content=="string"?n.content:JSON.stringify(n.content??null)});continue}if(r==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.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??{})});(r==="system"||r==="user"||r==="assistant")&&e.push({role:r,content:n.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?"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}:{}}),n=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${n?.error?.message??JSON.stringify(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let r=Array.isArray(n.output)?n.output:[],o=r.filter(a=>a?.type==="function_call").map(a=>({id:String(a.call_id??a.id??""),name:String(a.name??""),arguments:mt(a.arguments)}));return{content:r.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
3
|
`).trim()||null,toolCalls:o,finishReason:o.length?"tool_calls":n.status??"stop",usage:{prompt_tokens:n.usage?.input_tokens??0,completion_tokens:n.usage?.output_tokens??0,total_tokens:n.usage?.total_tokens??0},reasoningContent:null}}async chat(t){try{return b(t.signal),this.requestFormat==="v1/responses"?await this.responses(t):await this.chatCompletions(t)}catch(e){if(x(e))throw e;return{content:`Error calling LLM: ${String(e)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};import{nanoid as Zt}from"nanoid";var oe=class s{constructor(t,e,n){this.apiKey=t;this.apiBase=e;this.defaultModel=n}static DEFAULT_BASE="https://generativelanguage.googleapis.com/v1beta";getDefaultModel(){return this.defaultModel}resolveModel(t){let e=t.trim();if(e.includes("/")){let n=e.split("/",2),r=n[0],o=n[1];if(!r||!o)return e;let i=r.toLowerCase();(i==="gemini"||i==="google")&&(e=o)}return e.startsWith("models/")?e.slice(7):e}asText(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)}catch{return String(t)}}parseToolArgs(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{}}toGemini(t){let e=[],n=[];for(let i of t.messages){let a=String(i.role??"");if(a==="system"){let l=this.asText(i.content).trim();l&&e.push(l);continue}if(a==="user"){let l=this.asText(i.content).trim();if(!l)continue;n.push({role:"user",parts:[{text:l}]});continue}if(a==="assistant"||a==="model"){let l=[],c=this.asText(i.content).trim();c&&l.push({text:c});let u=Array.isArray(i.tool_calls)?i.tool_calls:[];for(let d of u){let m=d.function;m?.name&&l.push({functionCall:{name:m.name,args:this.parseToolArgs(m.arguments)}})}l.length&&n.push({role:"model",parts:l});continue}if(a==="tool"){let l=typeof i.name=="string"?i.name:"";if(!l)continue;let c=this.asText(i.content);n.push({role:"user",parts:[{functionResponse:{name:l,response:{result:c}}}]})}}n.length||n.push({role:"user",parts:[{text:"Hello"}]});let r={contents:n,generationConfig:{temperature:t.temperature??.1,maxOutputTokens:Math.max(1,t.maxTokens??4096),...t.reasoning?{thinkingConfig:{thinkingBudget:Math.max(1,t.maxTokens??4096)}}:{}}};e.length&&(r.systemInstruction={parts:[{text:e.join(`
|
|
4
4
|
|
|
5
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&&(r.tools=[{functionDeclarations:o}],r.toolConfig={functionCallingConfig:{mode:"AUTO"}}),t.imageOutput&&(r.responseModalities=["TEXT","IMAGE"]),r}async chat(t){try{b(t.signal);let e=this.resolveModel(t.model??this.defaultModel),r=`${(this.apiBase??s.DEFAULT_BASE).replace(/\/$/,"")}/models/${encodeURIComponent(e)}:generateContent`,o=this.toGemini(t),i=await fetch(r,{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(p=>typeof p?.text=="string").map(p=>String(p.text)),d=c.filter(p=>p?.functionCall?.name).map(p=>({id:Zt(9),name:String(p.functionCall.name),arguments:this.parseToolArgs(p.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 h=String(l?.finishReason??"STOP").toLowerCase();return{content:u.length?u.join(`
|
|
6
6
|
`):null,toolCalls:d,finishReason:h,usage:m,reasoningContent:null}}catch(e){if(x(e))throw e;return{content:`Error calling LLM: ${String(e)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};import{nanoid as Qt}from"nanoid";var se=class s{constructor(t,e,n,r){this.apiKey=t;this.apiBase=e;this.defaultModel=n;this.providerName=r}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=n=>n.toLowerCase().replace(/-/g,"_");if(t.includes("/")){let n=t.split("/",2),r=n[0],o=n[1];if(!r||!o)return t;if(e(r)==="github_copilot")return`github_copilot/${o}`;if(e(r)==="openai_codex")return`openai_codex/${o}`;if(e(r)==="groq")return o==="compound"||o==="compound-mini"?`groq/${o}`:o;if(e(r)==="ollama")return o}return t}async chat(t){let n={model:this.resolveModel(t.model??this.defaultModel),messages:W(t.messages),max_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7};t.tools?.length&&(n.tools=t.tools,n.tool_choice="auto"),t.reasoning&&(n.reasoning_effort="medium"),t.imageOutput&&(n.include_image_output=!0);try{b(t.signal);let r=(this.providerName??"").trim();if(r&&s.UNSUPPORTED_PROVIDERS.has(r))return{content:`Error calling LLM: provider '${r}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=this.apiBase??(r?s.DEFAULT_BASE_BY_PROVIDER[r]: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 ${J} 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(n),...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
|
-
${r==="groq"?"Try a Groq-supported model like llama-3.3-70b-versatile or openai/gpt-oss-120b. You can run `everclaw doctor`.":"Check your model id and provider access. You can run `everclaw doctor`."}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}:{content:`Error calling LLM: ${m}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}let c=l.choices?.[0]?.message?l.choices[0]:null;if(!c)return{content:`Error calling LLM: ${JSON.stringify(l)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let u=(c.message.tool_calls??[]).map(d=>({id:Qt(9),name:d.function.name,arguments:typeof d.function.arguments=="string"?JSON.parse(d.function.arguments||"{}"):d.function.arguments}));return{content:c.message.content??null,toolCalls:u,finishReason:c.finish_reason??"stop",usage:l.usage??{},reasoningContent:c.message.reasoning_content??null}}catch(r){if(x(r))throw r;return{content:`Error calling LLM: ${String(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};function pt(s){let t=s.agents.defaults.model,e=te(s,t),n=ot(s,t),r=e&&O(e)?j(s,e,t):null,o=new Set(["openai_codex","github_copilot"]),i=new Set(["anthropic"]);if(!e)throw new Error("No provider could be resolved from config. Run `everclaw onboard` and set provider/model/API key.");if(O(e)&&!r)throw new Error(`Custom provider '${e}' could not be found. Check ${J}.`);if(i.has(e))throw new Error(`Provider '${e}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`);if(!o.has(e)&&e!=="vllm"&&e!=="custom"&&!O(e)&&!(n?.apiKey||"").trim())throw new Error(`No API key configured for provider '${e}'. Run 'everclaw onboard' or edit ${J}.`);return e==="custom"||O(e)?new ne(n?.apiKey||r?.apiKey||"no-key",re(s,t)||r?.baseUrl||"http://localhost:8000/v1",t,{providerLabel:r?.name??e,apiFormat:r?.apiFormat,extraHeaders:r?.extraHeaders??n?.extraHeaders??null}):e==="gemini"?new oe(n?.apiKey||"",re(s,t),t):new se(n?.apiKey??null,re(s,t),t,e)}import{randomUUID as ii}from"node:crypto";import Wr from"node:path";import{randomUUID as Zn}from"node:crypto";import eo from"cron-parser";function Je(s){return s??"builtin"}function er(){return{beforeAgentTurn:[],afterAgentTurn:[],beforeOutbound:[],afterOutbound:[],beforeScheduledJob:[],afterScheduledJob:[],shutdown:[]}}function ie(s,t,e,n){let r=Je(e.source),o=t.get(n.name);if(o)throw new Error(`${s} '${n.name}' from extension '${e.name}' conflicts with extension '${o.extension}'`);t.set(n.name,{extension:e.name,source:r,contribution:n})}function tr(s,t,e){let n=(r,o)=>{let i=r.find(a=>a.contribution.name===o.name);if(i)throw new Error(`lifecycle '${o.slot}:${o.name}' from extension '${t.name}' conflicts with extension '${i.extension}'`);r.push({extension:t.name,source:Je(t.source),contribution:o})};switch(e.slot){case"beforeAgentTurn":n(s.beforeAgentTurn,e);return;case"afterAgentTurn":n(s.afterAgentTurn,e);return;case"beforeOutbound":n(s.beforeOutbound,e);return;case"afterOutbound":n(s.afterOutbound,e);return;case"beforeScheduledJob":n(s.beforeScheduledJob,e);return;case"afterScheduledJob":n(s.afterScheduledJob,e);return;case"shutdown":n(s.shutdown,e);return}}function E(s){return{...s,source:"builtin"}}var Fe=class{extensions=new Map;register(t){if(this.extensions.has(t.name))throw new Error(`Extension '${t.name}' is already registered`);return this.extensions.set(t.name,{...t,source:Je(t.source)}),this}list(){return[...this.extensions.values()]}compose(){let t=new Map,e=new Map,n=new Map,r=new Map,o=er();for(let i of this.extensions.values()){for(let a of i.tools??[])ie("tool",t,i,a);for(let a of i.channels??[])ie("channel",e,i,a);for(let a of i.jobs??[])ie("job",n,i,a);for(let a of i.commands??[])ie("command",r,i,a);for(let a of i.lifecycle??[])tr(o,i,a)}return{extensions:this.list(),tools:t,channels:e,jobs:n,commands:r,lifecycle:{beforeAgentTurn:o.beforeAgentTurn,afterAgentTurn:o.afterAgentTurn,beforeOutbound:o.beforeOutbound,afterOutbound:o.afterOutbound,beforeScheduledJob:o.beforeScheduledJob,afterScheduledJob:o.afterScheduledJob,shutdown:o.shutdown}}}};function gt(s){let t=new Fe;for(let e of s)t.register(e);return t.compose()}import
|
|
7
|
+
${r==="groq"?"Try a Groq-supported model like llama-3.3-70b-versatile or openai/gpt-oss-120b. You can run `everclaw doctor`.":"Check your model id and provider access. You can run `everclaw doctor`."}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}:{content:`Error calling LLM: ${m}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}let c=l.choices?.[0]?.message?l.choices[0]:null;if(!c)return{content:`Error calling LLM: ${JSON.stringify(l)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let u=(c.message.tool_calls??[]).map(d=>({id:Qt(9),name:d.function.name,arguments:typeof d.function.arguments=="string"?JSON.parse(d.function.arguments||"{}"):d.function.arguments}));return{content:c.message.content??null,toolCalls:u,finishReason:c.finish_reason??"stop",usage:l.usage??{},reasoningContent:c.message.reasoning_content??null}}catch(r){if(x(r))throw r;return{content:`Error calling LLM: ${String(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};function pt(s){let t=s.agents.defaults.model,e=te(s,t),n=ot(s,t),r=e&&O(e)?j(s,e,t):null,o=new Set(["openai_codex","github_copilot"]),i=new Set(["anthropic"]);if(!e)throw new Error("No provider could be resolved from config. Run `everclaw onboard` and set provider/model/API key.");if(O(e)&&!r)throw new Error(`Custom provider '${e}' could not be found. Check ${J}.`);if(i.has(e))throw new Error(`Provider '${e}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`);if(!o.has(e)&&e!=="vllm"&&e!=="custom"&&!O(e)&&!(n?.apiKey||"").trim())throw new Error(`No API key configured for provider '${e}'. Run 'everclaw onboard' or edit ${J}.`);return e==="custom"||O(e)?new ne(n?.apiKey||r?.apiKey||"no-key",re(s,t)||r?.baseUrl||"http://localhost:8000/v1",t,{providerLabel:r?.name??e,apiFormat:r?.apiFormat,extraHeaders:r?.extraHeaders??n?.extraHeaders??null}):e==="gemini"?new oe(n?.apiKey||"",re(s,t),t):new se(n?.apiKey??null,re(s,t),t,e)}import{randomUUID as ii}from"node:crypto";import Wr from"node:path";import{randomUUID as Zn}from"node:crypto";import eo from"cron-parser";function Je(s){return s??"builtin"}function er(){return{beforeAgentTurn:[],afterAgentTurn:[],beforeOutbound:[],afterOutbound:[],beforeScheduledJob:[],afterScheduledJob:[],shutdown:[]}}function ie(s,t,e,n){let r=Je(e.source),o=t.get(n.name);if(o)throw new Error(`${s} '${n.name}' from extension '${e.name}' conflicts with extension '${o.extension}'`);t.set(n.name,{extension:e.name,source:r,contribution:n})}function tr(s,t,e){let n=(r,o)=>{let i=r.find(a=>a.contribution.name===o.name);if(i)throw new Error(`lifecycle '${o.slot}:${o.name}' from extension '${t.name}' conflicts with extension '${i.extension}'`);r.push({extension:t.name,source:Je(t.source),contribution:o})};switch(e.slot){case"beforeAgentTurn":n(s.beforeAgentTurn,e);return;case"afterAgentTurn":n(s.afterAgentTurn,e);return;case"beforeOutbound":n(s.beforeOutbound,e);return;case"afterOutbound":n(s.afterOutbound,e);return;case"beforeScheduledJob":n(s.beforeScheduledJob,e);return;case"afterScheduledJob":n(s.afterScheduledJob,e);return;case"shutdown":n(s.shutdown,e);return}}function E(s){return{...s,source:"builtin"}}var Fe=class{extensions=new Map;register(t){if(this.extensions.has(t.name))throw new Error(`Extension '${t.name}' is already registered`);return this.extensions.set(t.name,{...t,source:Je(t.source)}),this}list(){return[...this.extensions.values()]}compose(){let t=new Map,e=new Map,n=new Map,r=new Map,o=er();for(let i of this.extensions.values()){for(let a of i.tools??[])ie("tool",t,i,a);for(let a of i.channels??[])ie("channel",e,i,a);for(let a of i.jobs??[])ie("job",n,i,a);for(let a of i.commands??[])ie("command",r,i,a);for(let a of i.lifecycle??[])tr(o,i,a)}return{extensions:this.list(),tools:t,channels:e,jobs:n,commands:r,lifecycle:{beforeAgentTurn:o.beforeAgentTurn,afterAgentTurn:o.afterAgentTurn,beforeOutbound:o.beforeOutbound,afterOutbound:o.afterOutbound,beforeScheduledJob:o.beforeScheduledJob,afterScheduledJob:o.afterScheduledJob,shutdown:o.shutdown}}}};function gt(s){let t=new Fe;for(let e of s)t.register(e);return t.compose()}import qn from"node:path";import{createRequire as rr}from"node:module";var Hn=rr(import.meta.url);import io from"node:fs";import lo from"node:path";var g=class s{static typeMap={string:t=>typeof t=="string",integer:t=>Number.isInteger(t),number:t=>typeof t=="number"&&Number.isFinite(t),boolean:t=>typeof t=="boolean",array:t=>Array.isArray(t),object:t=>!!t&&typeof t=="object"&&!Array.isArray(t)};validateParams(t){let e=this.parameters??{};if(e.type!=="object")throw new Error(`Schema must be object type, got ${String(e.type)}`);return this.validateValue(t,{...e,type:"object"},"parameter")}validateValue(t,e,n){let r=e.type,o=[];if(r&&s.typeMap[r]&&!s.typeMap[r](t))return[`${n} should be ${r}`];if(e.enum&&!e.enum.includes(t)&&o.push(`${n} must be one of ${JSON.stringify(e.enum)}`),(r==="integer"||r==="number")&&typeof t=="number"&&(typeof e.minimum=="number"&&t<e.minimum&&o.push(`${n} must be >= ${e.minimum}`),typeof e.maximum=="number"&&t>e.maximum&&o.push(`${n} must be <= ${e.maximum}`)),r==="string"&&typeof t=="string"&&(typeof e.minLength=="number"&&t.length<e.minLength&&o.push(`${n} must be at least ${e.minLength} chars`),typeof e.maxLength=="number"&&t.length>e.maxLength&&o.push(`${n} must be at most ${e.maxLength} chars`)),r==="object"&&t&&typeof t=="object"&&!Array.isArray(t)){let i=t,a=e.properties??{};for(let l of e.required??[])l in i||o.push(`missing required ${n==="parameter"?l:`${n}.${l}`}`);for(let[l,c]of Object.entries(i))a[l]&&o.push(...this.validateValue(c,a[l],n==="parameter"?l:`${n}.${l}`))}return r==="array"&&Array.isArray(t)&&e.items&&typeof e.items=="object"&&t.forEach((i,a)=>o.push(...this.validateValue(i,e.items,`${n}[${a}]`))),o}toSchema(){return{type:"function",function:{name:this.name,description:this.description,parameters:this.parameters}}}};var ae=class extends g{constructor(e){super();this.cron=e}name="cron";description="Schedule reminders and recurring tasks. Actions: add, list, remove.";parameters={type:"object",properties:{action:{type:"string",enum:["add","list","remove"]},message:{type:"string"},every_seconds:{type:"integer"},cron_expr:{type:"string"},tz:{type:"string"},at:{type:"string"},job_id:{type:"string"}},required:["action"]};channel="";chatId="";setContext(e,n){this.channel=e,this.chatId=n}async execute(e,n){let r=String(e.action??"");return r==="add"?this.addJob(e):r==="list"?this.listJobs():r==="remove"?this.removeJob(String(e.job_id??"")):`Unknown action: ${r}`}addJob(e){let n=String(e.message??"");if(!n)return"Error: message is required for add";if(!this.channel||!this.chatId)return"Error: no session context (channel/chat_id)";let r=e.every_seconds!=null?Number(e.every_seconds):null,o=e.cron_expr!=null?String(e.cron_expr):null,i=e.tz!=null?String(e.tz):null,a=e.at!=null?String(e.at):null,l,c=!1;if(r)l={kind:"every",everyMs:r*1e3};else if(o){let u={kind:"cron",expr:o};i&&(u.tz=i),l=u}else if(a){let u=new Date(a);if(Number.isNaN(u.getTime()))return"Error: invalid ISO datetime in at";l={kind:"at",atMs:u.getTime()},c=!0}else return"Error: either every_seconds, cron_expr, or at is required";try{let u=this.cron.addJob({name:n.slice(0,30),schedule:l,message:n,deliver:!0,channel:this.channel,to:this.chatId,deleteAfterRun:c});return`Created job '${u.name}' (id: ${u.id})`}catch(u){return`Error: ${String(u).replace(/^Error:\s*/,"")}`}}listJobs(){let e=this.cron.listJobs();return e.length?`Scheduled jobs:
|
|
8
8
|
${e.map(n=>`- ${n.name} (id: ${n.id}, ${n.schedule.kind})`).join(`
|
|
9
9
|
`)}`:"No scheduled jobs."}removeJob(e){return e?this.cron.removeJob(e)?`Removed job ${e}`:`Job ${e} not found`:"Error: job_id is required for remove"}};import A from"node:fs";import B from"node:path";import R from"node:fs";import C from"node:path";function ft(s){let t=C.resolve(s);for(;t!=="/"&&t!==".";)try{return R.lstatSync(t),t}catch{let e=C.dirname(t);if(e===t)break;t=e}return t||"/"}function ht(s,t){let e=C.resolve(s),n=C.resolve(t),r=n.endsWith(C.sep)?n.slice(0,-1):n,o=e===r||e.startsWith(r+C.sep);if(!R.existsSync(r))return o;try{let i=r;try{i=R.realpathSync.native(r)}catch{}if(R.existsSync(e)){let c=R.realpathSync.native(e);return c===i||c.startsWith(i+C.sep)}let a=ft(e);if(a===i||a===r)return!0;if(a!=="/")try{let c=R.realpathSync.native(a);if(c===i||c.startsWith(i+C.sep))return!0;if(!o)return!1}catch{return o}let l=e;for(;l!=="/"&&l!==".";){let c=C.dirname(l);if(c===l)break;try{if(R.lstatSync(c).isSymbolicLink()){let d=R.realpathSync.native(c);if(d!==i&&!d.startsWith(i+C.sep))return!1}}catch{}l=c}return o}catch{return!1}}function yt(s,t){let e=C.resolve(s),n=C.resolve(t);if(!ht(s,t))throw new Error(`Path '${s}' is outside allowed workspace '${t}'`);let r=C.dirname(e),o=ft(r),i=n;try{R.existsSync(n)&&(i=R.realpathSync.native(n))}catch{}if(o!=="/"&&o!==i)try{let a=R.realpathSync.native(o);if(a!==i&&!a.startsWith(i+C.sep))throw new Error(`Path '${s}' would be created outside workspace via symlinked parent directory`)}catch(a){throw a instanceof Error&&a.message.includes("symlinked parent")?a:new Error(`Could not validate path '${s}' is within workspace`)}}function bt(s,t){if(!ht(s,t))throw new Error(`Path '${s}' is outside allowed workspace '${t}'`)}function me(s,t,e,n=!1){let r=s.startsWith("~")?B.join(process.env.USERPROFILE||process.env.HOME||"",s.slice(1)):s,o=B.isAbsolute(r)?r:t?B.join(t,r):r,i=B.resolve(o);if(e)try{n?yt(i,e):bt(i,e)}catch(a){throw new Error(a instanceof Error?a.message:`Path ${s} validation failed`)}return i}var le=class extends g{constructor(e,n){super();this.workspace=e;this.allowedDir=n}name="read_file";description="Read the contents of a file at the given path.";parameters={type:"object",properties:{path:{type:"string",description:"The file path to read"}},required:["path"]};async execute(e,n){try{let r=me(String(e.path),this.workspace,this.allowedDir);return A.existsSync(r)?A.statSync(r).isFile()?A.readFileSync(r,"utf8"):`Error: Not a file: ${String(e.path)}`:`Error: File not found: ${String(e.path)}`}catch(r){return`Error reading file: ${String(r)}`}}},ce=class extends g{constructor(e,n){super();this.workspace=e;this.allowedDir=n}name="write_file";description="Write content to a file at the given path. Creates parent directories if needed.";parameters={type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]};async execute(e,n){try{let r=me(String(e.path),this.workspace,this.allowedDir,!0);A.mkdirSync(B.dirname(r),{recursive:!0});let o=String(e.content??"");return A.writeFileSync(r,o,"utf8"),`Successfully wrote ${o.length} bytes to ${r}`}catch(r){return`Error writing file: ${String(r)}`}}},ue=class extends g{constructor(e,n){super();this.workspace=e;this.allowedDir=n}name="edit_file";description="Edit a file by replacing old_text with new_text. The old_text must exist exactly in the file.";parameters={type:"object",properties:{path:{type:"string"},old_text:{type:"string"},new_text:{type:"string"}},required:["path","old_text","new_text"]};async execute(e,n){try{let r=me(String(e.path),this.workspace,this.allowedDir,!0);if(!A.existsSync(r))return`Error: File not found: ${String(e.path)}`;let o=A.readFileSync(r,"utf8"),i=String(e.old_text??""),a=String(e.new_text??"");return o.includes(i)?o.split(i).length-1>1?`Warning: old_text appears ${o.split(i).length-1} times. Please provide more context to make it unique.`:(A.writeFileSync(r,o.replace(i,a),"utf8"),`Successfully edited ${r}`):`Error: old_text not found in ${String(e.path)}. Verify the file content.`}catch(r){return`Error editing file: ${String(r)}`}}},de=class extends g{constructor(e,n){super();this.workspace=e;this.allowedDir=n}name="list_dir";description="List the contents of a directory.";parameters={type:"object",properties:{path:{type:"string"}},required:["path"]};async execute(e,n){try{let r=me(String(e.path),this.workspace,this.allowedDir);if(!A.existsSync(r))return`Error: Directory not found: ${String(e.path)}`;if(!A.statSync(r).isDirectory())return`Error: Not a directory: ${String(e.path)}`;let o=A.readdirSync(r).sort().map(i=>{let a=B.join(r,i);return`${A.statSync(a).isDirectory()?"[DIR]":"[FILE]"} ${i}`});return o.length?o.join(`
|
|
10
|
-
`):`Directory ${String(e.path)} is empty`}catch(r){return`Error listing directory: ${String(r)}`}}};var pe=class extends g{constructor(e){super();this.sendCallback=e}name="message";description="Send a message to the user. Use this when you want to communicate something.";parameters={type:"object",properties:{content:{type:"string",description:"The message content to send"},channel:{type:"string",description:"Optional target channel"},chat_id:{type:"string",description:"Optional target chat/user ID"},media:{type:"array",items:{type:"string"},description:"Optional file attachments"}},required:["content"]};defaultChannel="";defaultChatId="";defaultMessageId=null;setContext(e,n,r){this.defaultChannel=e,this.defaultChatId=n,this.defaultMessageId=r??null}setSendCallback(e){this.sendCallback=e}async execute(e,n){let r=String(e.content??""),o=String(e.channel??this.defaultChannel),i=String(e.chat_id??this.defaultChatId),a=String(e.message_id??this.defaultMessageId??""),l=Array.isArray(e.media)?e.media:[];if(!o||!i)return"Error: No target channel/chat specified";if(!this.sendCallback)return"Error: Message sending not configured";try{await this.sendCallback({channel:o,chatId:i,content:r,media:l,metadata:{message_id:a}});let c=o===this.defaultChannel&&i===this.defaultChatId,u=`Message sent to ${o}:${i}${l.length?` with ${l.length} attachments`:""}`;return c?`__TERMINAL__${u}`:u}catch(c){return`Error sending message: ${String(c)}`}}};import
|
|
10
|
+
`):`Directory ${String(e.path)} is empty`}catch(r){return`Error listing directory: ${String(r)}`}}};var pe=class extends g{constructor(e){super();this.sendCallback=e}name="message";description="Send a message to the user. Use this when you want to communicate something.";parameters={type:"object",properties:{content:{type:"string",description:"The message content to send"},channel:{type:"string",description:"Optional target channel"},chat_id:{type:"string",description:"Optional target chat/user ID"},media:{type:"array",items:{type:"string"},description:"Optional file attachments"}},required:["content"]};defaultChannel="";defaultChatId="";defaultMessageId=null;setContext(e,n,r){this.defaultChannel=e,this.defaultChatId=n,this.defaultMessageId=r??null}setSendCallback(e){this.sendCallback=e}async execute(e,n){let r=String(e.content??""),o=String(e.channel??this.defaultChannel),i=String(e.chat_id??this.defaultChatId),a=String(e.message_id??this.defaultMessageId??""),l=Array.isArray(e.media)?e.media:[];if(!o||!i)return"Error: No target channel/chat specified";if(!this.sendCallback)return"Error: Message sending not configured";try{await this.sendCallback({channel:o,chatId:i,content:r,media:l,metadata:{message_id:a}});let c=o===this.defaultChannel&&i===this.defaultChatId,u=`Message sent to ${o}:${i}${l.length?` with ${l.length} attachments`:""}`;return c?`__TERMINAL__${u}`:u}catch(c){return`Error sending message: ${String(c)}`}}};import qe from"node:path";import{spawn as vt}from"node:child_process";var or={"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 Ue(s){return{...or[s]}}var $=class{async run(t){let e=Math.max(1,t.maxCaptureBytes??1048576),n=typeof t.timeoutMs=="number"&&Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:null,r=this.launch(t);if(r instanceof Error)return{status:"failed",pid:null,stdout:"",stderr:"",exitCode:null,signal:null,failureAttribution:"spawn_error",cleanupTriggered:!1,cleanupReason:null,errorMessage:r.message};let{child:o,spawnError:i}=r;t.stdinText!=null?o.stdin?.end(t.stdinText,"utf8"):o.stdin?.end();let a="",l="",c=!1,u=null,d=!1,m=(w,M)=>{let P=typeof w=="string"?w:w.toString("utf8"),T=e-Buffer.byteLength(M);return T<=0?M:M+P.slice(0,T)};o.stdout?.on("data",w=>{a=m(w,a)}),o.stderr?.on("data",w=>{l=m(w,l)});let h=null,p=w=>{c||(c=!0,u=w,d=w==="timeout",this.killChild(o,"SIGTERM"),h=setTimeout(()=>this.killChild(o,"SIGKILL"),250),h.unref?.())},y=()=>p("abort");t.signal?.aborted?y():t.signal?.addEventListener("abort",y,{once:!0});let k=n!=null?setTimeout(()=>p("timeout"),n):null;k?.unref?.();let v=await new Promise(w=>{let M=!1,P=T=>{M||(M=!0,w(T))};o.once("error",T=>{i.current=T,P({code:null,signal:null})}),o.once("close",(T,_)=>P({code:T,signal:_}))});return k&&clearTimeout(k),h&&clearTimeout(h),t.signal?.removeEventListener("abort",y),u==="abort"?{status:"aborted",pid:o.pid??null,stdout:a,stderr:l,exitCode:v.code,signal:v.signal,failureAttribution:"aborted",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:d?{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:v.code,signal:v.signal,failureAttribution:"timeout",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:i.current?{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:v.code,signal:v.signal,failureAttribution:"spawn_error",cleanupTriggered:c,cleanupReason:u,errorMessage:i.current.message}:v.code===0?{status:"ok",pid:o.pid??null,stdout:a,stderr:l,exitCode:0,signal:v.signal,failureAttribution:"none",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:v.code,signal:v.signal,failureAttribution:v.signal?"signal":"exit_code",cleanupTriggered:c,cleanupReason:u,errorMessage:null}}launch(t){try{return{child:t.command.kind==="shell"?vt(t.command.command,{cwd:t.cwd,env:t.env,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}):vt(t.command.file,t.command.args??[],{cwd:t.cwd,env:t.env,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),spawnError:{current:null}}}catch(e){return e instanceof Error?e:new Error(String(e))}}killChild(t,e){try{if(process.platform!=="win32"&&typeof t.pid=="number"){process.kill(-t.pid,e);return}}catch{}try{t.kill(e)}catch{}}};var ge=class extends g{constructor(e=60,n,r=!1,o="",i=new $,a,l=!1){super();this.timeout=e;this.workingDir=n;this.restrictToWorkspace=r;this.pathAppend=o;this.runner=i;this.rtkService=a;this.rtkUltraCompact=l}name="exec";description="Execute a shell command and return its output. Use with caution.";parameters={type:"object",properties:{command:{type:"string",description:"The shell command to execute"},working_dir:{type:"string",description:"Optional working directory for the command"}},required:["command"]};guard(e,n){let r=e.toLowerCase();if([/\brm\s+-[rf]{1,2}\b/,/\bdel\s+\/[fq]\b/,/\brmdir\s+\/s\b/,/(?:^|[;&|]\s*)format\b/,/\b(mkfs|diskpart)\b/,/\bdd\s+if=/,/>\s*\/dev\/sd/,/\b(shutdown|reboot|poweroff)\b/,/:\(\)\s*\{.*\};\s*:/].some(i=>i.test(r)))return"Error: Command blocked by safety guard (dangerous pattern detected)";if(this.restrictToWorkspace){if(e.includes("../")||e.includes("..\\"))return"Error: Command blocked by safety guard (path traversal detected)";let i=e.match(/[A-Za-z]:\\[^\s"']+/g)??[];for(let a of i){let l=qe.resolve(a),c=qe.resolve(n);if(!l.startsWith(c))return"Error: Command blocked by safety guard (path outside working dir)"}}return null}async execute(e,n){let r=String(e.command??""),o=String(e.working_dir??this.workingDir??process.cwd()),i=this.guard(r,o);if(i)return i;b(n?.signal);let a=Ue("tool.exec"),l={...process.env};if(this.pathAppend&&(l.PATH=`${l.PATH??""}${qe.delimiter}${this.pathAppend}`),a.mode!=="local-process")return"Error: exec tool requires local-process isolation";let c={command:{kind:"shell",command:r},cwd:o,env:l,timeoutMs:this.timeout*1e3,maxCaptureBytes:1024*1024};n?.signal&&(c.signal=n.signal);let u=await this.runner.run(c);if(u.status==="aborted")throw Be();if(u.failureAttribution==="timeout")return`Error: Command timed out after ${this.timeout} seconds`;let d=u.stdout?`${u.stdout}${u.status==="failed"?`
|
|
11
11
|
`:""}`:"";if(this.rtkService?.getRuntime().available&&d)try{let k=await this.rtkService.compress({command:r,stdout:d,stderr:u.stderr,exitCode:u.exitCode,ultraCompact:this.rtkUltraCompact});k.compressed&&(d=k.stdout)}catch{}let m=u.stderr.trim()?`STDERR:
|
|
12
12
|
${u.stderr}
|
|
13
13
|
`:"",h=u.status==="failed"&&typeof u.exitCode=="number"?`
|
|
@@ -139,10 +139,10 @@ ${l}`,retryable:!1}}}let o=r.validateParams(e);if(o.length)return{kind:"error",c
|
|
|
139
139
|
|
|
140
140
|
[Analyze the error above and try a different approach.]`,retryable:!0};let i=await r.execute(e,n);return b(n?.signal),i.startsWith("__TERMINAL__")?{kind:"terminal",content:i.slice(12)}:{kind:"ok",content:i}}catch(o){if(x(o))throw o;return{kind:"error",content:`Error executing ${t}: ${String(o)}
|
|
141
141
|
|
|
142
|
-
[Analyze the error above and try a different approach.]`,retryable:!0}}}};function Dt(s){return s.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g,"").trim()}function
|
|
142
|
+
[Analyze the error above and try a different approach.]`,retryable:!0}}}};function Dt(s){return s.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g,"").trim()}function Ur(s){return s.replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
143
143
|
|
|
144
|
-
`).trim()}function
|
|
145
|
-
`)}catch(a){if(x(a))throw a;return`Error: ${String(a)}`}}},Ie=class extends g{constructor(e=5e4){super();this.maxChars=e}name="web_fetch";description="Fetch URL and extract readable content (HTML to markdown/text).";parameters={type:"object",properties:{url:{type:"string",description:"URL to fetch"},extractMode:{type:"string",enum:["markdown","text"]},maxChars:{type:"integer",minimum:100}},required:["url"]};async execute(e,n){let r=String(e.url??""),o=String(e.extractMode??"markdown"),i=Number(e.maxChars??this.maxChars),[a,l]=
|
|
144
|
+
`).trim()}function qr(s){try{let t=new URL(s);return["http:","https:"].includes(t.protocol)?t.hostname?[!0,""]:[!1,"Missing domain"]:[!1,`Only http/https allowed, got '${t.protocol.replace(":","")}'`]}catch(t){return[!1,String(t)]}}var $e=class extends g{constructor(e,n=5){super();this.apiKey=e;this.maxResults=n}name="web_search";description="Search the web. Returns titles, URLs, and snippets.";parameters={type:"object",properties:{query:{type:"string",description:"Search query"},count:{type:"integer",minimum:1,maximum:10,description:"Results (1-10)"}},required:["query"]};async execute(e,n){let r=String(e.query??""),o=Math.min(Math.max(Number(e.count??this.maxResults),1),10),i=this.apiKey||process.env.BRAVE_API_KEY||"";if(!i)return"Error: Brave Search API key not configured. Set tools.web.search.apiKey or BRAVE_API_KEY.";try{b(n?.signal);let a=new URL("https://api.search.brave.com/res/v1/web/search");a.searchParams.set("q",r),a.searchParams.set("count",String(o));let l=await fetch(a,{headers:{Accept:"application/json","X-Subscription-Token":i},...n?.signal?{signal:n.signal}:{}});if(!l.ok)return`Error: ${l.status} ${l.statusText}`;let u=(await l.json()).web?.results??[];if(!u.length)return`No results for: ${r}`;let d=[`Results for: ${r}`,""];return u.slice(0,o).forEach((m,h)=>{d.push(`${h+1}. ${m.title??""}`),d.push(` ${m.url??""}`),m.description&&d.push(` ${m.description}`)}),d.join(`
|
|
145
|
+
`)}catch(a){if(x(a))throw a;return`Error: ${String(a)}`}}},Ie=class extends g{constructor(e=5e4){super();this.maxChars=e}name="web_fetch";description="Fetch URL and extract readable content (HTML to markdown/text).";parameters={type:"object",properties:{url:{type:"string",description:"URL to fetch"},extractMode:{type:"string",enum:["markdown","text"]},maxChars:{type:"integer",minimum:100}},required:["url"]};async execute(e,n){let r=String(e.url??""),o=String(e.extractMode??"markdown"),i=Number(e.maxChars??this.maxChars),[a,l]=qr(r);if(!a)return JSON.stringify({error:`URL validation failed: ${l}`,url:r});try{b(n?.signal);let c=await fetch(r,{redirect:"follow",headers:{"User-Agent":"Mozilla/5.0"},...n?.signal?{signal:n.signal}:{}}),u=c.headers.get("content-type")||"",d="",m="raw";if(u.includes("application/json"))d=JSON.stringify(await c.json(),null,2),m="json";else{let y=await c.text();u.includes("text/html")||/^\s*<!doctype|^\s*<html/i.test(y.slice(0,256))?(d=o==="text"?Dt(y):Ur(Dt(y)),m="html"):d=y}let h=d.length>i,p=h?d.slice(0,i):d;return JSON.stringify({url:r,finalUrl:c.url,status:c.status,extractor:m,truncated:h,length:p.length,text:p})}catch(c){if(x(c))throw c;return JSON.stringify({error:String(c),url:r})}}};function L(s){return Wr.resolve(s.workspace)}function Ne(s){let t=L(s);return s.restrictToWorkspace?t:void 0}function Gr(s){let t=[E({name:"builtin-filesystem-tools",tools:[{name:"read_file",create:e=>new le(L(e),Ne(e))},{name:"write_file",create:e=>new ce(L(e),Ne(e))},{name:"edit_file",create:e=>new ue(L(e),Ne(e))},{name:"list_dir",create:e=>new de(L(e),Ne(e))}]}),E({name:"builtin-shell-tools",tools:[{name:"exec",create:e=>new ge(e.execConfig?.timeout??60,L(e),!!e.restrictToWorkspace,e.execConfig?.pathAppend??"",new $,e.rtkService,e.rtkConfig?.ultraCompact??!1)}]}),E({name:"builtin-web-tools",tools:[{name:"web_search",create:e=>new $e(e.braveApiKey??null)},{name:"web_fetch",create:()=>new Ie}]})];return s.bus&&t.push(E({name:"builtin-messaging-tools",tools:[{name:"message",create:e=>{if(!e.bus)throw new Error("Builtin message tool requires a message bus");let n=new pe(async r=>{e.turn?.isCurrent&&!e.turn.isCurrent()||await e.bus.publishOutbound(r)});return e.turn&&n.setContext(e.turn.channel,e.turn.chatId,e.turn.messageId),n}}]})),s.subagents&&t.push(E({name:"builtin-subagent-tools",tools:[{name:"spawn",create:e=>{if(!e.subagents)throw new Error("Builtin spawn tool requires a subagent manager");let n=new fe(e.subagents);return e.turn&&n.setContext(e.turn.channel,e.turn.chatId,e.turn.sessionKey),n}}]})),s.cronService&&t.push(E({name:"builtin-scheduler-tools",tools:[{name:"cron",create:e=>{if(!e.cronService)throw new Error("Builtin cron tool requires a cron service");let n=new ae(e.cronService);return e.turn&&n.setContext(e.turn.channel,e.turn.chatId),n}}]})),s.sessionManager&&t.push(E({name:"builtin-session-tools",tools:[{name:"session.info",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.info tool requires a session manager");let n=new Se;return n.setSessionManager(e.sessionManager),e.turn&&n.setContext(e.turn.sessionKey),n}},{name:"session.anchor",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.anchor tool requires a session manager");let n=new xe;return n.setSessionManager(e.sessionManager),e.turn&&n.setContext(e.turn.sessionKey),n}},{name:"session.search",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.search tool requires a session manager");let n=new he;return n.setSessionManager(e.sessionManager),e.turn&&n.setContext(e.turn.sessionKey),n}}]})),s.chromeSessionConfig?.enabled&&t.push(E({name:"builtin-chrome-session-tools",tools:[{name:"chrome_session",create:e=>new Y(e.chromeSessionConfig,L(e),!!e.restrictToWorkspace)}]})),s.browserRelay&&t.push(E({name:"builtin-browser-relay-tools",tools:[{name:"chrome_relay",create:e=>{if(!e.browserRelay)throw new Error("Builtin chrome_relay tool requires a browser relay server");return new Z(e.browserRelay)}}]})),t.push(E({name:"builtin-automation-tools",tools:[{name:"automation",create:e=>{let n=e.browserRelay?new Z(e.browserRelay):e.chromeSessionConfig?.enabled?new Y(e.chromeSessionConfig,L(e),!!e.restrictToWorkspace):void 0;return new Pe(L(e),n)}}]})),t}function Kr(s){return gt(Gr(s))}function jt(s){let t=new Oe,e=Kr(s);for(let n of e.tools.values())t.register(n.contribution.create(s));return t}var Bt="EVERCLAW_SUBAGENT_RESULT ";function Hr(){return`# Subagent
|
|
146
146
|
|
|
147
147
|
Current Time: ${new Date().toLocaleString()}
|
|
148
148
|
|