@evolvingmachines/sdk 0.0.38 → 0.0.40

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/dist/index.cjs CHANGED
@@ -1,52 +1,52 @@
1
- 'use strict';var events=require('events'),Jo=require('ajv'),crypto=require('crypto'),zs=require('zod-to-json-schema'),A=require('fs'),re=require('path'),promises=require('fs/promises'),os$1=require('os'),core=require('@composio/core'),child_process=require('child_process'),util=require('util'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal'),stream=require('stream'),promises$1=require('stream/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Jo__default=/*#__PURE__*/_interopDefault(Jo);var zs__default=/*#__PURE__*/_interopDefault(zs);var A__namespace=/*#__PURE__*/_interopNamespace(A);var re__namespace=/*#__PURE__*/_interopNamespace(re);var us={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},je={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Ge={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-7",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-6",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"},{alias:"opus[1m]",modelId:"opus[1m]",description:"Complex reasoning with 1M context window"},{alias:"sonnet[1m]",modelId:"sonnet[1m]",description:"Daily coding with 1M context window"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.claude/skills"},buildCommand:({prompt:t,model:e,isResume:n})=>`echo "${t}" | claude -p ${n?"--continue ":""}--model ${e} --output-format stream-json --verbose --dangerously-skip-permissions`},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.4",models:[{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Newest frontier model"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Flagship for professional work"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Fast, efficient mini model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Previous general-purpose model"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:s})=>{let a=s?` -c model_reasoning_effort="${s}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${a} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.1-pro-preview",models:[{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"},{alias:"gemini-3.1-flash-lite-preview",modelId:"gemini-3.1-flash-lite-preview",description:"Cost-efficient, low latency"},{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest Flash model"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Frontier flash performance"},{alias:"gemini-2.5-pro",modelId:"gemini-2.5-pro",description:"Complex tasks, deep reasoning"},{alias:"gemini-2.5-flash",modelId:"gemini-2.5-flash",description:"Balance speed/reasoning"},{alias:"gemini-2.5-flash-lite",modelId:"gemini-2.5-flash-lite",description:"Simple tasks, fastest"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini "${t}" ${n?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3.6-plus",models:[{alias:"qwen3.6-plus",modelId:"qwen3.6-plus",description:"Latest flagship (Apr 2026)"},{alias:"qwen3.5-plus",modelId:"qwen3.5-plus",description:"Previous flagship, thinking-enabled"},{alias:"qwen3-max-2026-01-23",modelId:"qwen3-max-2026-01-23",description:"Max model with thinking"},{alias:"qwen3-coder-next",modelId:"qwen3-coder-next",description:"Recommended coder: balances quality/speed/cost"},{alias:"qwen3-coder-plus",modelId:"qwen3-coder-plus",description:"Max-quality coder for complex tasks"},{alias:"qwen3-coder-flash",modelId:"qwen3-coder-flash",description:"Fast coder with context cache"},{alias:"qwen3-vl-plus",modelId:"qwen3-vl-plus",description:"Vision + language, multimodal"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.6-plus":"dashscope/qwen3.6-plus","qwen3.5-plus":"dashscope/qwen3.5-plus","qwen3-max-2026-01-23":"dashscope/qwen3-max-2026-01-23","qwen3-coder-next":"dashscope/qwen3-coder-next","qwen3-coder-plus":"dashscope/qwen3-coder-plus","qwen3-coder-flash":"dashscope/qwen3-coder-flash","qwen3-vl-plus":"dashscope/qwen3-vl-plus"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:s})=>{let a=n?"--continue ":"",i=s||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${a}--auth-type openai --model ${i} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k2.6",models:[{alias:"kimi-k2.6",modelId:"moonshot/kimi-k2.6",description:"Latest: long-horizon coding, swarm orchestration"},{alias:"kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Previous multimodal flagship"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:s})=>`printf '%s' "${t}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${s?"":"--config-file /home/user/.kimi/evolve-config.toml "}${n?"--continue ":""}`},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-sonnet-4.6",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-sonnet-4.6",modelId:"openrouter/anthropic/claude-sonnet-4.6",description:"Anthropic Sonnet via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-4.7",modelId:"openrouter/anthropic/claude-opus-4.7",description:"Anthropic Opus via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-5.5",modelId:"openrouter/openai/gpt-5.5",description:"OpenAI GPT-5.5 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4",modelId:"openrouter/openai/gpt-5.4",description:"OpenAI GPT-5.4 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4-mini",modelId:"openrouter/openai/gpt-5.4-mini",description:"OpenAI GPT-5.4 Mini via OpenRouter"},{alias:"openrouter/openai/gpt-5.3-codex",modelId:"openrouter/openai/gpt-5.3-codex",description:"OpenAI Codex via OpenRouter"},{alias:"openrouter/openai/gpt-5.2",modelId:"openrouter/openai/gpt-5.2",description:"OpenAI GPT-5.2 via OpenRouter"},{alias:"openrouter/google/gemini-3.1-pro-preview",modelId:"openrouter/google/gemini-3.1-pro-preview",description:"Gemini 3.1 Pro via OpenRouter"},{alias:"openrouter/google/gemini-3.5-flash",modelId:"openrouter/google/gemini-3.5-flash",description:"Gemini 3.5 Flash via OpenRouter"},{alias:"openrouter/google/gemini-3-flash-preview",modelId:"openrouter/google/gemini-3-flash-preview",description:"Gemini 3 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-next",modelId:"openrouter/qwen/qwen3-coder-next",description:"Qwen Coder Next via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-plus",modelId:"openrouter/qwen/qwen3-coder-plus",description:"Qwen Coder via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.6",modelId:"openrouter/moonshotai/kimi-k2.6",description:"Kimi K2.6 via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.5",modelId:"openrouter/moonshotai/kimi-k2.5",description:"Kimi K2.5 via OpenRouter"},{alias:"openrouter/z-ai/glm-5",modelId:"openrouter/z-ai/glm-5",description:"Zhipu GLM-5 via OpenRouter"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:s})=>{let a=n?"--continue ":"",i=e.startsWith("openrouter/")?e:`openrouter/${e}`;return s?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${a}--model ${i} --format json "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${a}--model litellm/${i} --format json "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",defaultModel:"gpt-5.5",models:[{alias:"claude-opus-4-7",modelId:"claude-opus-4-7",description:"Factory-managed Claude Opus 4.7"},{alias:"claude-opus-4-7-fast",modelId:"claude-opus-4-7-fast",description:"Factory-managed Claude Opus 4.7 Fast Mode"},{alias:"claude-sonnet-4-6",modelId:"claude-sonnet-4-6",description:"Factory-managed Claude Sonnet 4.6"},{alias:"claude-opus-4-6",modelId:"claude-opus-4-6",description:"Factory-managed Claude Opus 4.6"},{alias:"claude-opus-4-6-fast",modelId:"claude-opus-4-6-fast",description:"Factory-managed Claude Opus 4.6 Fast Mode"},{alias:"claude-opus-4-5",modelId:"claude-opus-4-5-20251101",description:"Factory-managed Claude Opus 4.5"},{alias:"claude-sonnet-4-5",modelId:"claude-sonnet-4-5-20250929",description:"Factory-managed Claude Sonnet 4.5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Factory-managed GPT-5.5"},{alias:"gpt-5.5-fast",modelId:"gpt-5.5-fast",description:"Factory-managed GPT-5.5 Fast Mode"},{alias:"gpt-5.5-pro",modelId:"gpt-5.5-pro",description:"Factory-managed GPT-5.5 Pro"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Factory-managed GPT-5.4"},{alias:"gpt-5.4-fast",modelId:"gpt-5.4-fast",description:"Factory-managed GPT-5.4 Fast Mode"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Factory-managed GPT-5.4 Mini"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Factory-managed GPT-5.3-Codex"},{alias:"gpt-5.3-codex-fast",modelId:"gpt-5.3-codex-fast",description:"Factory-managed GPT-5.3-Codex Fast"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Factory-managed GPT-5.2"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Factory-managed GPT-5.2-Codex"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Factory-managed Gemini 3.1 Pro"},{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Factory-managed Gemini 3 Pro"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Factory-managed Gemini 3 Flash"},{alias:"kimi-k2.6",modelId:"kimi-k2.6",description:"Factory-managed Droid Core Kimi K2.6"},{alias:"kimi-k2.5",modelId:"kimi-k2.5",description:"Factory-managed Droid Core Kimi K2.5"},{alias:"deepseek-v4-pro",modelId:"deepseek-v4-pro",description:"Factory-managed Droid Core DeepSeek V4 Pro"},{alias:"minimax-m2.7",modelId:"minimax-m2.7",description:"Factory-managed Droid Core MiniMax M2.7"},{alias:"minimax-m2.5",modelId:"minimax-m2.5",description:"Factory-managed Droid Core MiniMax M2.5"},{alias:"glm-5.1",modelId:"glm-5.1",description:"Factory-managed Droid Core GLM-5.1"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5","deepseek-v4-pro":"deepseek/deepseek-v4-pro","minimax-m2.7":"minimax/minimax-m2.7","minimax-m2.5":"minimax/minimax-m2.5","glm-5.1":"openrouter/z-ai/glm-5.1"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:t,model:e,isResume:n,sessionId:s,reasoningEffort:a,isDirectMode:i})=>{let l=i?"":"--settings /home/user/.factory/evolve-settings.json ",r=i?e:"custom:Evolve-Gateway-0",c=a&&i?` --reasoning-effort ${a}`:"",d=n&&s?`--session-id ${Ve(s)} `:"";return `printf '%s' ${Ve(t)} | droid ${l}exec ${d}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${Ve(r)}${c}`}}};function $(t){let e=Ge[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function gs(t){return t in Ge}function V(t){return t.replace(/^~/,"/home/user")}function Ve(t){return `'${t.replace(/'/g,"'\\''")}'`}function N(t){let e=$(t);return `${V(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function K(t){let e=$(t);return V(e.mcpConfig.settingsDir)}function D(t){if(t instanceof Error){let e=t.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function We(t,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${t}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${t}" cannot specify both command and url`)}function ne(t){for(let[e,n]of Object.entries(t))We(e,n);}function se(t){return t.type?t.type:t.command?"stdio":"sse"}function ms(t){let e=se(t);return {...t,type:e}}function fs(t){let{type:e,url:n,...s}=t;return se(t)==="http"&&n?{httpUrl:n,...s}:n?{url:n,...s}:s}function hs(t){return {type:se(t),...t}}function ys(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function ws(t){let e=se(t),{type:n,httpHeaders:s,envHttpHeaders:a,bearerTokenEnvVar:i,envVars:l,...r}=t;if(e==="stdio"&&t.command)return {type:"stdio",...r};if(t.url){let c={...r,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??s;return d&&Object.keys(d).length>0&&(c.headers=d),c}return {type:e==="stdio"?"stdio":"http",...r}}async function ze(t,e,n,s){ne(n);let a=K(e),i=N(e);await t.files.makeDir(a);let l={};try{let c=await t.files.read(i);typeof c=="string"&&(l=JSON.parse(c));}catch(c){if(!D(c))throw c}let r=Object.fromEntries(Object.entries(n).map(([c,d])=>[c,s(d)]));await t.files.write(i,JSON.stringify({...l,mcpServers:r},null,2));}async function me(t,e,n){ne(n);let s=K("claude"),a=N("claude"),i=Object.fromEntries(Object.entries(n).map(([r,c])=>[r,hs(c)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:i},null,2)),await t.files.makeDir(s);let l={};try{let r=await t.files.read(a);typeof r=="string"&&(l=JSON.parse(r));}catch(r){if(!D(r))throw r}l.enableAllProjectMcpServers=true,await t.files.write(a,JSON.stringify(l,null,2));}async function fe(t,e){await ze(t,"gemini",e,ms);}async function he(t,e){await ze(t,"qwen",e,fs);}async function ye(t,e,n,s){let a=K(e),i=N(e);await t.files.makeDir(a);let l={};try{let p=await t.files.read(i);typeof p=="string"&&(l=JSON.parse(p));}catch(p){if(!D(p))throw p}let r=n.split("."),c=l;for(let p=0;p<r.length-1;p++){let u=r[p];(typeof c[u]!="object"||c[u]===null)&&(c[u]={}),c=c[u];}let d=r[r.length-1],o=typeof c[d]=="object"&&c[d]!==null?c[d]:{};c[d]={...o,...s},await t.files.write(i,JSON.stringify(l,null,2));}async function Je(t,e){await ze(t,"kimi",e,ys);}async function we(t,e,n){ne(n);let s=`${e}/.factory`,a=`${s}/mcp.json`;await t.files.makeDir(s);let i={};try{let r=await t.files.read(a);typeof r=="string"&&(i=JSON.parse(r));}catch(r){if(!D(r))throw r}let l=Object.fromEntries(Object.entries(n).map(([r,c])=>[r,ws(c)]));await t.files.write(a,JSON.stringify({...i,mcpServers:l},null,2));}async function ve(t,e,n){let s=V(e.settingsPath),a=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(a);let i={cloudSessionSync:false,customModels:[{model:e.model,displayName:e.displayName,baseUrl:e.baseUrl,apiKey:`\${${e.apiKeyEnv}}`,provider:e.provider,...e.maxOutputTokens!==void 0&&{maxOutputTokens:e.maxOutputTokens},extraHeaders:n}]};await t.files.write(s,JSON.stringify(i,null,2));}async function qe(t,e,n){ne(n);let s=`${e}/opencode.json`,a={};try{let l=await t.files.read(s);typeof l=="string"&&(a=JSON.parse(l));}catch(l){if(!D(l))throw l}let i=Object.fromEntries(Object.entries(n).map(([l,r])=>[l,vs(r)]));await t.files.write(s,JSON.stringify({...a,mcp:i},null,2));}function vs(t){let e=se(t);if(e==="stdio"&&t.command){let s={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(s.environment=t.env),s}if(t.url){let n={type:"remote",url:t.url};return t.headers&&Object.keys(t.headers).length>0&&(n.headers=t.headers),n}return {type:e==="stdio"?"local":"remote",...t}}function q(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Se(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||R;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function He(){return Se("/api/managed/e2b")}function Ot(t){return {"browser-use":{type:"http",url:q("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var O="EVOLVE_API_KEY",xe="E2B_API_KEY",ke="DAYTONA_API_KEY",Ce="MODAL_TOKEN_ID",Ye="MODAL_TOKEN_SECRET",Mt="claude",oe=36e5,At=4,Ze=100,$t="/home/user/workspace",R=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",I="x-litellm-customer-id",U="x-litellm-tags",G="run:",Dt=".evolve-sdk/observability/sessions",Ut=100,Bt=5e3,be=3,Qe=1e3;function E(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>E(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,s])=>`${n} = ${E(s)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function _e(t,e){for(let[c,d]of Object.entries(e))We(c,d);let n=K("codex"),s=N("codex");await t.files.makeDir(n);let a="";try{let c=await t.files.read(s);typeof c=="string"&&(a=c);}catch(c){if(!D(c))throw c}let i=[],l=[];a.includes("experimental_use_rmcp_client")||(i.push("# Enable improved RMCP client (recommended)"),i.push("experimental_use_rmcp_client = true")),a.includes("[mcp_servers]")||l.push("[mcp_servers]","");for(let[c,d]of Object.entries(e)){if(a.includes(`[mcp_servers.${c}]`))continue;l.push(`[mcp_servers.${c}]`);let o=d.type??(d.command?"stdio":"http");if(o==="http"||o==="sse"||!!d.url){if(!d.url)throw new Error(`MCP server "${c}" is missing url for ${o} transport`);l.push(`url = ${E(d.url)}`),d.bearerTokenEnvVar&&l.push(`bearer_token_env_var = ${E(d.bearerTokenEnvVar)}`);let u=d.httpHeaders??d.headers;u&&Object.keys(u).length>0&&l.push(`http_headers = ${E(u)}`),d.envHttpHeaders&&Object.keys(d.envHttpHeaders).length>0&&l.push(`env_http_headers = ${E(d.envHttpHeaders)}`);}else l.push(`command = ${E(d.command)}`),d.args&&d.args.length>0&&l.push(`args = ${E(d.args)}`),d.cwd&&l.push(`cwd = ${E(d.cwd)}`);d.env&&Object.keys(d.env).length>0&&l.push(`env = ${E(d.env)}`),d.envVars&&d.envVars.length>0&&l.push(`env_vars = ${E(d.envVars)}`),l.push("");}let r=[a.trim(),i.join(`
1
+ 'use strict';var events=require('events'),ri=require('ajv'),crypto=require('crypto'),Zs=require('zod-to-json-schema'),A=require('fs'),re=require('path'),promises=require('fs/promises'),os$1=require('os'),core=require('@composio/core'),child_process=require('child_process'),util=require('util'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal'),stream=require('stream'),promises$1=require('stream/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ri__default=/*#__PURE__*/_interopDefault(ri);var Zs__default=/*#__PURE__*/_interopDefault(Zs);var A__namespace=/*#__PURE__*/_interopNamespace(A);var re__namespace=/*#__PURE__*/_interopNamespace(re);var ys={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},Ge={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var ze={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-7",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-6",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"},{alias:"opus[1m]",modelId:"opus[1m]",description:"Complex reasoning with 1M context window"},{alias:"sonnet[1m]",modelId:"sonnet[1m]",description:"Daily coding with 1M context window"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.claude/skills"},buildCommand:({prompt:t,model:e,isResume:n})=>`echo "${t}" | claude -p ${n?"--continue ":""}--model ${e} --output-format stream-json --verbose --dangerously-skip-permissions`},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.4",models:[{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Newest frontier model"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Flagship for professional work"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Fast, efficient mini model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Previous general-purpose model"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:s})=>{let i=s?` -c model_reasoning_effort="${s}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${i} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.1-pro-preview",models:[{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"},{alias:"gemini-3.1-flash-lite-preview",modelId:"gemini-3.1-flash-lite-preview",description:"Cost-efficient, low latency"},{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest Flash model"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Frontier flash performance"},{alias:"gemini-2.5-pro",modelId:"gemini-2.5-pro",description:"Complex tasks, deep reasoning"},{alias:"gemini-2.5-flash",modelId:"gemini-2.5-flash",description:"Balance speed/reasoning"},{alias:"gemini-2.5-flash-lite",modelId:"gemini-2.5-flash-lite",description:"Simple tasks, fastest"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini "${t}" ${n?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3.6-plus",models:[{alias:"qwen3.6-plus",modelId:"qwen3.6-plus",description:"Latest flagship (Apr 2026)"},{alias:"qwen3.5-plus",modelId:"qwen3.5-plus",description:"Previous flagship, thinking-enabled"},{alias:"qwen3-max-2026-01-23",modelId:"qwen3-max-2026-01-23",description:"Max model with thinking"},{alias:"qwen3-coder-next",modelId:"qwen3-coder-next",description:"Recommended coder: balances quality/speed/cost"},{alias:"qwen3-coder-plus",modelId:"qwen3-coder-plus",description:"Max-quality coder for complex tasks"},{alias:"qwen3-coder-flash",modelId:"qwen3-coder-flash",description:"Fast coder with context cache"},{alias:"qwen3-vl-plus",modelId:"qwen3-vl-plus",description:"Vision + language, multimodal"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.6-plus":"dashscope/qwen3.6-plus","qwen3.5-plus":"dashscope/qwen3.5-plus","qwen3-max-2026-01-23":"dashscope/qwen3-max-2026-01-23","qwen3-coder-next":"dashscope/qwen3-coder-next","qwen3-coder-plus":"dashscope/qwen3-coder-plus","qwen3-coder-flash":"dashscope/qwen3-coder-flash","qwen3-vl-plus":"dashscope/qwen3-vl-plus"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:s})=>{let i=n?"--continue ":"",r=s||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${i}--auth-type openai --model ${r} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k2.6",models:[{alias:"kimi-k2.6",modelId:"moonshot/kimi-k2.6",description:"Latest: long-horizon coding, swarm orchestration"},{alias:"kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Previous multimodal flagship"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:s})=>`printf '%s' "${t}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${s?"":"--config-file /home/user/.kimi/evolve-config.toml "}${n?"--continue ":""}`},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-sonnet-4.6",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-sonnet-4.6",modelId:"openrouter/anthropic/claude-sonnet-4.6",description:"Anthropic Sonnet via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-4.7",modelId:"openrouter/anthropic/claude-opus-4.7",description:"Anthropic Opus via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-5.5",modelId:"openrouter/openai/gpt-5.5",description:"OpenAI GPT-5.5 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4",modelId:"openrouter/openai/gpt-5.4",description:"OpenAI GPT-5.4 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4-mini",modelId:"openrouter/openai/gpt-5.4-mini",description:"OpenAI GPT-5.4 Mini via OpenRouter"},{alias:"openrouter/openai/gpt-5.3-codex",modelId:"openrouter/openai/gpt-5.3-codex",description:"OpenAI Codex via OpenRouter"},{alias:"openrouter/openai/gpt-5.2",modelId:"openrouter/openai/gpt-5.2",description:"OpenAI GPT-5.2 via OpenRouter"},{alias:"openrouter/google/gemini-3.1-pro-preview",modelId:"openrouter/google/gemini-3.1-pro-preview",description:"Gemini 3.1 Pro via OpenRouter"},{alias:"openrouter/google/gemini-3.5-flash",modelId:"openrouter/google/gemini-3.5-flash",description:"Gemini 3.5 Flash via OpenRouter"},{alias:"openrouter/google/gemini-3-flash-preview",modelId:"openrouter/google/gemini-3-flash-preview",description:"Gemini 3 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-next",modelId:"openrouter/qwen/qwen3-coder-next",description:"Qwen Coder Next via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-plus",modelId:"openrouter/qwen/qwen3-coder-plus",description:"Qwen Coder via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.6",modelId:"openrouter/moonshotai/kimi-k2.6",description:"Kimi K2.6 via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.5",modelId:"openrouter/moonshotai/kimi-k2.5",description:"Kimi K2.5 via OpenRouter"},{alias:"openrouter/z-ai/glm-5",modelId:"openrouter/z-ai/glm-5",description:"Zhipu GLM-5 via OpenRouter"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:s})=>{let i=n?"--continue ":"",r=e.startsWith("openrouter/")?e:`openrouter/${e}`;return s?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${i}--model ${r} --format json "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${i}--model litellm/${r} --format json "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",defaultModel:"gpt-5.5",models:[{alias:"claude-opus-4-7",modelId:"claude-opus-4-7",description:"Factory-managed Claude Opus 4.7"},{alias:"claude-opus-4-7-fast",modelId:"claude-opus-4-7-fast",description:"Factory-managed Claude Opus 4.7 Fast Mode"},{alias:"claude-sonnet-4-6",modelId:"claude-sonnet-4-6",description:"Factory-managed Claude Sonnet 4.6"},{alias:"claude-opus-4-6",modelId:"claude-opus-4-6",description:"Factory-managed Claude Opus 4.6"},{alias:"claude-opus-4-6-fast",modelId:"claude-opus-4-6-fast",description:"Factory-managed Claude Opus 4.6 Fast Mode"},{alias:"claude-opus-4-5",modelId:"claude-opus-4-5-20251101",description:"Factory-managed Claude Opus 4.5"},{alias:"claude-sonnet-4-5",modelId:"claude-sonnet-4-5-20250929",description:"Factory-managed Claude Sonnet 4.5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Factory-managed GPT-5.5"},{alias:"gpt-5.5-fast",modelId:"gpt-5.5-fast",description:"Factory-managed GPT-5.5 Fast Mode"},{alias:"gpt-5.5-pro",modelId:"gpt-5.5-pro",description:"Factory-managed GPT-5.5 Pro"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Factory-managed GPT-5.4"},{alias:"gpt-5.4-fast",modelId:"gpt-5.4-fast",description:"Factory-managed GPT-5.4 Fast Mode"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Factory-managed GPT-5.4 Mini"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Factory-managed GPT-5.3-Codex"},{alias:"gpt-5.3-codex-fast",modelId:"gpt-5.3-codex-fast",description:"Factory-managed GPT-5.3-Codex Fast"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Factory-managed GPT-5.2"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Factory-managed GPT-5.2-Codex"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Factory-managed Gemini 3.1 Pro"},{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Factory-managed Gemini 3 Pro"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Factory-managed Gemini 3 Flash"},{alias:"kimi-k2.6",modelId:"kimi-k2.6",description:"Factory-managed Droid Core Kimi K2.6"},{alias:"kimi-k2.5",modelId:"kimi-k2.5",description:"Factory-managed Droid Core Kimi K2.5"},{alias:"deepseek-v4-pro",modelId:"deepseek-v4-pro",description:"Factory-managed Droid Core DeepSeek V4 Pro"},{alias:"minimax-m2.7",modelId:"minimax-m2.7",description:"Factory-managed Droid Core MiniMax M2.7"},{alias:"minimax-m2.5",modelId:"minimax-m2.5",description:"Factory-managed Droid Core MiniMax M2.5"},{alias:"glm-5.1",modelId:"glm-5.1",description:"Factory-managed Droid Core GLM-5.1"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5","deepseek-v4-pro":"deepseek/deepseek-v4-pro","minimax-m2.7":"minimax/minimax-m2.7","minimax-m2.5":"minimax/minimax-m2.5","glm-5.1":"openrouter/z-ai/glm-5.1"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:t,model:e,isResume:n,sessionId:s,reasoningEffort:i,isDirectMode:r})=>{let l=r?"":"--settings /home/user/.factory/evolve-settings.json ",a=r?e:"custom:Evolve-Gateway-0",c=i&&r?` --reasoning-effort ${i}`:"",d=n&&s?`--session-id ${We(s)} `:"";return `printf '%s' ${We(t)} | droid ${l}exec ${d}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${We(a)}${c}`}}};function $(t){let e=ze[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function ws(t){return t in ze}function V(t){return t.replace(/^~/,"/home/user")}function We(t){return `'${t.replace(/'/g,"'\\''")}'`}function N(t){let e=$(t);return `${V(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function K(t){let e=$(t);return V(e.mcpConfig.settingsDir)}function D(t){if(t instanceof Error){let e=t.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function Je(t,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${t}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${t}" cannot specify both command and url`)}function ne(t){for(let[e,n]of Object.entries(t))Je(e,n);}function se(t){return t.type?t.type:t.command?"stdio":"sse"}function vs(t){let e=se(t);return {...t,type:e}}function bs(t){let{type:e,url:n,...s}=t;return se(t)==="http"&&n?{httpUrl:n,...s}:n?{url:n,...s}:s}function Cs(t){return {type:se(t),...t}}function Ss(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function xs(t){let e=se(t),{type:n,httpHeaders:s,envHttpHeaders:i,bearerTokenEnvVar:r,envVars:l,...a}=t;if(e==="stdio"&&t.command)return {type:"stdio",...a};if(t.url){let c={...a,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??s;return d&&Object.keys(d).length>0&&(c.headers=d),c}return {type:e==="stdio"?"stdio":"http",...a}}async function qe(t,e,n,s){ne(n);let i=K(e),r=N(e);await t.files.makeDir(i);let l={};try{let c=await t.files.read(r);typeof c=="string"&&(l=JSON.parse(c));}catch(c){if(!D(c))throw c}let a=Object.fromEntries(Object.entries(n).map(([c,d])=>[c,s(d)]));await t.files.write(r,JSON.stringify({...l,mcpServers:a},null,2));}async function fe(t,e,n){ne(n);let s=K("claude"),i=N("claude"),r=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,Cs(c)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:r},null,2)),await t.files.makeDir(s);let l={};try{let a=await t.files.read(i);typeof a=="string"&&(l=JSON.parse(a));}catch(a){if(!D(a))throw a}l.enableAllProjectMcpServers=true,await t.files.write(i,JSON.stringify(l,null,2));}async function he(t,e){await qe(t,"gemini",e,vs);}async function ye(t,e){await qe(t,"qwen",e,bs);}async function we(t,e,n,s){let i=K(e),r=N(e);await t.files.makeDir(i);let l={};try{let p=await t.files.read(r);typeof p=="string"&&(l=JSON.parse(p));}catch(p){if(!D(p))throw p}let a=n.split("."),c=l;for(let p=0;p<a.length-1;p++){let u=a[p];(typeof c[u]!="object"||c[u]===null)&&(c[u]={}),c=c[u];}let d=a[a.length-1],o=typeof c[d]=="object"&&c[d]!==null?c[d]:{};c[d]={...o,...s},await t.files.write(r,JSON.stringify(l,null,2));}async function He(t,e){await qe(t,"kimi",e,Ss);}async function ve(t,e,n){ne(n);let s=`${e}/.factory`,i=`${s}/mcp.json`;await t.files.makeDir(s);let r={};try{let a=await t.files.read(i);typeof a=="string"&&(r=JSON.parse(a));}catch(a){if(!D(a))throw a}let l=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,xs(c)]));await t.files.write(i,JSON.stringify({...r,mcpServers:l},null,2));}async function be(t,e,n){let s=V(e.settingsPath),i=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(i);let r={cloudSessionSync:false,customModels:[{model:e.model,displayName:e.displayName,baseUrl:e.baseUrl,apiKey:`\${${e.apiKeyEnv}}`,provider:e.provider,...e.maxOutputTokens!==void 0&&{maxOutputTokens:e.maxOutputTokens},extraHeaders:n}]};await t.files.write(s,JSON.stringify(r,null,2));}async function Ye(t,e,n){ne(n);let s=`${e}/opencode.json`,i={};try{let l=await t.files.read(s);typeof l=="string"&&(i=JSON.parse(l));}catch(l){if(!D(l))throw l}let r=Object.fromEntries(Object.entries(n).map(([l,a])=>[l,ks(a)]));await t.files.write(s,JSON.stringify({...i,mcp:r},null,2));}function ks(t){let e=se(t);if(e==="stdio"&&t.command){let s={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(s.environment=t.env),s}if(t.url){let n={type:"remote",url:t.url};return t.headers&&Object.keys(t.headers).length>0&&(n.headers=t.headers),n}return {type:e==="stdio"?"local":"remote",...t}}function q(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Ce(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||E;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function Ze(){return Ce("/api/managed/e2b")}function Dt(t){return {"browser-use":{type:"http",url:q("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var O="EVOLVE_API_KEY",Se="E2B_API_KEY",xe="DAYTONA_API_KEY",ke="MODAL_TOKEN_ID",Qe="MODAL_TOKEN_SECRET",Bt="claude",oe=36e5,Ut=4,Xe=100,Ft="/home/user/workspace",E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",I="x-litellm-customer-id",B="x-litellm-tags",G="run:",Lt=".evolve-sdk/observability/sessions",Nt=100,Kt=5e3,_e=3,et=1e3;function T(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>T(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,s])=>`${n} = ${T(s)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function Ee(t,e){for(let[c,d]of Object.entries(e))Je(c,d);let n=K("codex"),s=N("codex");await t.files.makeDir(n);let i="";try{let c=await t.files.read(s);typeof c=="string"&&(i=c);}catch(c){if(!D(c))throw c}let r=[],l=[];i.includes("experimental_use_rmcp_client")||(r.push("# Enable improved RMCP client (recommended)"),r.push("experimental_use_rmcp_client = true")),i.includes("[mcp_servers]")||l.push("[mcp_servers]","");for(let[c,d]of Object.entries(e)){if(i.includes(`[mcp_servers.${c}]`))continue;l.push(`[mcp_servers.${c}]`);let o=d.type??(d.command?"stdio":"http");if(o==="http"||o==="sse"||!!d.url){if(!d.url)throw new Error(`MCP server "${c}" is missing url for ${o} transport`);l.push(`url = ${T(d.url)}`),d.bearerTokenEnvVar&&l.push(`bearer_token_env_var = ${T(d.bearerTokenEnvVar)}`);let u=d.httpHeaders??d.headers;u&&Object.keys(u).length>0&&l.push(`http_headers = ${T(u)}`),d.envHttpHeaders&&Object.keys(d.envHttpHeaders).length>0&&l.push(`env_http_headers = ${T(d.envHttpHeaders)}`);}else l.push(`command = ${T(d.command)}`),d.args&&d.args.length>0&&l.push(`args = ${T(d.args)}`),d.cwd&&l.push(`cwd = ${T(d.cwd)}`);d.env&&Object.keys(d.env).length>0&&l.push(`env = ${T(d.env)}`),d.envVars&&d.envVars.length>0&&l.push(`env_vars = ${T(d.envVars)}`),l.push("");}let a=[i.trim(),r.join(`
2
2
  `),l.join(`
3
- `)].filter(c=>c.length>0);await t.files.write(s,r.join(`
3
+ `)].filter(c=>c.length>0);await t.files.write(s,a.join(`
4
4
 
5
5
  `)+`
6
- `);}async function Xe(t,e,n){let s=K("codex"),a=N("codex");await t.files.makeDir(s);let i="";try{let f=await t.files.read(a);typeof f=="string"&&(i=f);}catch(f){if(!D(f))throw f}let l=i.search(/^\[/m),r=l>=0?i.slice(0,l):i,c=l>=0?i.slice(l):"",d=i.includes("[model_providers.evolve-gateway]"),o=/^model_provider\s*=\s*"evolve-gateway"/m.test(r);if(d&&o)return;i=(r.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
6
+ `);}async function tt(t,e,n){let s=K("codex"),i=N("codex");await t.files.makeDir(s);let r="";try{let f=await t.files.read(i);typeof f=="string"&&(r=f);}catch(f){if(!D(f))throw f}let l=r.search(/^\[/m),a=l>=0?r.slice(0,l):r,c=l>=0?r.slice(l):"",d=r.includes("[model_providers.evolve-gateway]"),o=/^model_provider\s*=\s*"evolve-gateway"/m.test(a);if(d&&o)return;r=(a.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
7
7
 
8
- `)+c).replace(/^\n+/,"");let u='model_provider = "evolve-gateway"',g=d?"":["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${E(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${E({[I]:n.sessionTagEnv,[U]:n.runTagEnv})}`].join(`
9
- `),m;if(!i.trim())m=g?`${u}
8
+ `)+c).replace(/^\n+/,"");let u='model_provider = "evolve-gateway"',g=d?"":["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${T(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${T({[I]:n.sessionTagEnv,[B]:n.runTagEnv})}`].join(`
9
+ `),m;if(!r.trim())m=g?`${u}
10
10
 
11
11
  ${g}
12
12
  `:`${u}
13
- `;else {let f=i.search(/^\[/m);f>0?m=i.slice(0,f)+u+`
13
+ `;else {let f=r.search(/^\[/m);f>0?m=r.slice(0,f)+u+`
14
14
 
15
- `+i.slice(f).trimEnd():f===0?m=u+`
15
+ `+r.slice(f).trimEnd():f===0?m=u+`
16
16
 
17
- `+i.trimEnd():m=i.trimEnd()+`
17
+ `+r.trimEnd():m=r.trimEnd()+`
18
18
 
19
19
  `+u,g&&(m=m.trimEnd()+`
20
20
 
21
21
  `+g),m+=`
22
- `;}await t.files.write(a,m);}async function et(t,e,n){let s=V(e.configPath),a=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(a);let i=[`default_model = ${E(e.modelName)}`,"",`[providers.${e.providerName}]`,'type = "kimi"','base_url = ""','api_key = ""',`custom_headers = ${E(n)}`,"",`[models.${e.modelName}]`,`provider = ${E(e.providerName)}`,'model = ""',`max_context_size = ${e.maxContextSize}`].join(`
22
+ `;}await t.files.write(i,m);}async function nt(t,e,n){let s=V(e.configPath),i=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(i);let r=[`default_model = ${T(e.modelName)}`,"",`[providers.${e.providerName}]`,'type = "kimi"','base_url = ""','api_key = ""',`custom_headers = ${T(n)}`,"",`[models.${e.modelName}]`,`provider = ${T(e.providerName)}`,'model = ""',`max_context_size = ${e.maxContextSize}`].join(`
23
23
  `)+`
24
- `;await t.files.write(s,i);}async function tt(t,e,n,s){if(!(!s||Object.keys(s).length===0))switch(t){case "claude":await me(e,n,s);break;case "codex":await _e(e,s);break;case "gemini":await fe(e,s);break;case "qwen":await he(e,s);break;case "kimi":await Je(e,s);break;case "opencode":await qe(e,n,s);break;case "droid":await we(e,n,s);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Ee(){let t={};return function(d){let o;try{o=JSON.parse(d);}catch{return null}if(o._meta||o._prompt)return null;let p=o.session_id;switch(o.type){case "system":return null;case "assistant":return e(o.message?.content,"assistant",p);case "user":{let u=o.message?.content;return typeof u=="string"||Array.isArray(u)&&u.length===1&&u[0].type==="text"?null:e(u,"user",p)}case "result":return null;default:return null}};function e(c,d,o){if(typeof c=="string")return d==="user"?null:[{sessionId:o,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let p=[];for(let u of c){let g=null;switch(u.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:u.source?.type==="base64"?u.source.data:"",mimeType:u.source?.type==="base64"?u.source.media_type:"",uri:u.source?.type==="url"?u.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[u.id]=u,u.name==="TodoWrite")Array.isArray(u.input?.todos)&&(g={sessionUpdate:"plan",entries:l(u.input)});else {let m=n(u);g={sessionUpdate:"tool_call",toolCallId:u.id,status:"pending",...m};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let m=t[u.tool_use_id];if(!m||(delete t[u.tool_use_id],m.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:u.tool_use_id,status:"is_error"in u&&u.is_error?"failed":"completed",...s(u,m)};break}}g&&p.push({sessionId:o,update:g});}return p.length>0?p:null}function n(c){let d=c.name,o=c.input||{};switch(d){case "Task":return {title:o.description||"Task",kind:"think",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "NotebookRead":return {title:o.notebook_path?`Read Notebook ${o.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "NotebookEdit":return {title:o.notebook_path?`Edit Notebook ${o.notebook_path}`:"Edit Notebook",kind:"edit",content:o.new_source?[{type:"content",content:{type:"text",text:o.new_source}}]:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "Bash":return {title:o.command?"`"+o.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:o.description?[{type:"content",content:{type:"text",text:o.description}}]:[],rawInput:o};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:o};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:o};case "Read":{let p="";return o.limit?p=" ("+((o.offset??0)+1)+" - "+((o.offset??0)+o.limit)+")":o.offset&&(p=" (from line "+(o.offset+1)+")"),{title:"Read "+(o.file_path??"File")+p,kind:"read",content:[],locations:o.file_path?[{path:o.file_path,line:o.offset??0}]:[],rawInput:o}}case "LS":return {title:o.path?`List \`${o.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:o};case "Edit":{let p=o.file_path;return {title:p?`Edit \`${p}\``:"Edit",kind:"edit",content:p?[{type:"diff",path:p,oldText:o.old_string??null,newText:o.new_string??""}]:[],locations:p?[{path:p}]:[],rawInput:o}}case "Write":return {title:o.file_path?`Write ${o.file_path}`:"Write",kind:"edit",content:o.file_path?[{type:"diff",path:o.file_path,oldText:null,newText:o.content??""}]:[],locations:o.file_path?[{path:o.file_path}]:[],rawInput:o};case "Glob":{let p="Find";return o.path&&(p+=` \`${o.path}\``),o.pattern&&(p+=` \`${o.pattern}\``),{title:p,kind:"search",content:[],locations:o.path?[{path:o.path}]:[],rawInput:o}}case "Grep":{let p="grep";return o["-i"]&&(p+=" -i"),o["-n"]&&(p+=" -n"),o["-A"]!==void 0&&(p+=` -A ${o["-A"]}`),o["-B"]!==void 0&&(p+=` -B ${o["-B"]}`),o["-C"]!==void 0&&(p+=` -C ${o["-C"]}`),o.output_mode==="files_with_matches"?p+=" -l":o.output_mode==="count"&&(p+=" -c"),o.head_limit!==void 0&&(p+=` | head -${o.head_limit}`),o.glob&&(p+=` --include="${o.glob}"`),o.type&&(p+=` --type=${o.type}`),o.multiline&&(p+=" -P"),p+=` "${o.pattern??""}"`,o.path&&(p+=` ${o.path}`),{title:p,kind:"search",content:[],rawInput:o}}case "WebFetch":return {title:o.url?`Fetch ${o.url}`:"Fetch",kind:"fetch",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "WebSearch":{let p=`"${o.query??""}"`;return o.allowed_domains?.length>0&&(p+=` (allowed: ${o.allowed_domains.join(", ")})`),o.blocked_domains?.length>0&&(p+=` (blocked: ${o.blocked_domains.join(", ")})`),{title:p,kind:"fetch",content:[],rawInput:o}}case "TodoWrite":return {title:Array.isArray(o.todos)?`Update TODOs: ${o.todos.map(p=>p.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:o};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:o.plan?[{type:"content",content:{type:"text",text:o.plan}}]:[],rawInput:o};default:if(d?.startsWith("mcp__")){let p=d.split("__"),u=p[1]||"mcp",g=p.slice(2).join("__")||d;return {title:`${u}: ${g}`,kind:"other",content:[],rawInput:o}}return {title:d||"Unknown Tool",kind:"other",content:[],rawInput:o}}}function s(c,d){let o=c.content;switch(d?.name){case "Read":return Array.isArray(o)&&o.length>0?{content:o.map(p=>({type:"content",content:p.type==="text"?{type:"text",text:r(p.text)}:i(p,false)}))}:typeof o=="string"&&o.length>0?{content:[{type:"content",content:{type:"text",text:r(o)}}]}:{};case "Edit":case "Write":case "Bash":return a(o,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return a(o,"is_error"in c?c.is_error:false)}}function a(c,d=false){return Array.isArray(c)&&c.length>0?{content:c.map(o=>({type:"content",content:i(o,d)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+c+"\n```":c}}]}:{}}function i(c,d){if(c.type==="text")return d?{type:"text",text:"```\n"+c.text+"\n```"}:{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return {type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return {type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function l(c){return c.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function r(c){let d="```",o=Array.from(c.matchAll(/^```+/gm));for(let[p]of o)for(;p.length>=d.length;)d+="`";return d+`
24
+ `;await t.files.write(s,r);}async function st(t,e,n,s){if(!(!s||Object.keys(s).length===0))switch(t){case "claude":await fe(e,n,s);break;case "codex":await Ee(e,s);break;case "gemini":await he(e,s);break;case "qwen":await ye(e,s);break;case "kimi":await He(e,s);break;case "opencode":await Ye(e,n,s);break;case "droid":await ve(e,n,s);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Te(){let t={};return function(d){let o;try{o=JSON.parse(d);}catch{return null}if(o._meta||o._prompt)return null;let p=o.session_id;switch(o.type){case "system":return null;case "assistant":return e(o.message?.content,"assistant",p);case "user":{let u=o.message?.content;return typeof u=="string"||Array.isArray(u)&&u.length===1&&u[0].type==="text"?null:e(u,"user",p)}case "result":return null;default:return null}};function e(c,d,o){if(typeof c=="string")return d==="user"?null:[{sessionId:o,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let p=[];for(let u of c){let g=null;switch(u.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:u.source?.type==="base64"?u.source.data:"",mimeType:u.source?.type==="base64"?u.source.media_type:"",uri:u.source?.type==="url"?u.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[u.id]=u,u.name==="TodoWrite")Array.isArray(u.input?.todos)&&(g={sessionUpdate:"plan",entries:l(u.input)});else {let m=n(u);g={sessionUpdate:"tool_call",toolCallId:u.id,status:"pending",...m};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let m=t[u.tool_use_id];if(!m||(delete t[u.tool_use_id],m.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:u.tool_use_id,status:"is_error"in u&&u.is_error?"failed":"completed",...s(u,m)};break}}g&&p.push({sessionId:o,update:g});}return p.length>0?p:null}function n(c){let d=c.name,o=c.input||{};switch(d){case "Task":return {title:o.description||"Task",kind:"think",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "NotebookRead":return {title:o.notebook_path?`Read Notebook ${o.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "NotebookEdit":return {title:o.notebook_path?`Edit Notebook ${o.notebook_path}`:"Edit Notebook",kind:"edit",content:o.new_source?[{type:"content",content:{type:"text",text:o.new_source}}]:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "Bash":return {title:o.command?"`"+o.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:o.description?[{type:"content",content:{type:"text",text:o.description}}]:[],rawInput:o};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:o};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:o};case "Read":{let p="";return o.limit?p=" ("+((o.offset??0)+1)+" - "+((o.offset??0)+o.limit)+")":o.offset&&(p=" (from line "+(o.offset+1)+")"),{title:"Read "+(o.file_path??"File")+p,kind:"read",content:[],locations:o.file_path?[{path:o.file_path,line:o.offset??0}]:[],rawInput:o}}case "LS":return {title:o.path?`List \`${o.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:o};case "Edit":{let p=o.file_path;return {title:p?`Edit \`${p}\``:"Edit",kind:"edit",content:p?[{type:"diff",path:p,oldText:o.old_string??null,newText:o.new_string??""}]:[],locations:p?[{path:p}]:[],rawInput:o}}case "Write":return {title:o.file_path?`Write ${o.file_path}`:"Write",kind:"edit",content:o.file_path?[{type:"diff",path:o.file_path,oldText:null,newText:o.content??""}]:[],locations:o.file_path?[{path:o.file_path}]:[],rawInput:o};case "Glob":{let p="Find";return o.path&&(p+=` \`${o.path}\``),o.pattern&&(p+=` \`${o.pattern}\``),{title:p,kind:"search",content:[],locations:o.path?[{path:o.path}]:[],rawInput:o}}case "Grep":{let p="grep";return o["-i"]&&(p+=" -i"),o["-n"]&&(p+=" -n"),o["-A"]!==void 0&&(p+=` -A ${o["-A"]}`),o["-B"]!==void 0&&(p+=` -B ${o["-B"]}`),o["-C"]!==void 0&&(p+=` -C ${o["-C"]}`),o.output_mode==="files_with_matches"?p+=" -l":o.output_mode==="count"&&(p+=" -c"),o.head_limit!==void 0&&(p+=` | head -${o.head_limit}`),o.glob&&(p+=` --include="${o.glob}"`),o.type&&(p+=` --type=${o.type}`),o.multiline&&(p+=" -P"),p+=` "${o.pattern??""}"`,o.path&&(p+=` ${o.path}`),{title:p,kind:"search",content:[],rawInput:o}}case "WebFetch":return {title:o.url?`Fetch ${o.url}`:"Fetch",kind:"fetch",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "WebSearch":{let p=`"${o.query??""}"`;return o.allowed_domains?.length>0&&(p+=` (allowed: ${o.allowed_domains.join(", ")})`),o.blocked_domains?.length>0&&(p+=` (blocked: ${o.blocked_domains.join(", ")})`),{title:p,kind:"fetch",content:[],rawInput:o}}case "TodoWrite":return {title:Array.isArray(o.todos)?`Update TODOs: ${o.todos.map(p=>p.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:o};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:o.plan?[{type:"content",content:{type:"text",text:o.plan}}]:[],rawInput:o};default:if(d?.startsWith("mcp__")){let p=d.split("__"),u=p[1]||"mcp",g=p.slice(2).join("__")||d;return {title:`${u}: ${g}`,kind:"other",content:[],rawInput:o}}return {title:d||"Unknown Tool",kind:"other",content:[],rawInput:o}}}function s(c,d){let o=c.content;switch(d?.name){case "Read":return Array.isArray(o)&&o.length>0?{content:o.map(p=>({type:"content",content:p.type==="text"?{type:"text",text:a(p.text)}:r(p,false)}))}:typeof o=="string"&&o.length>0?{content:[{type:"content",content:{type:"text",text:a(o)}}]}:{};case "Edit":case "Write":case "Bash":return i(o,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return i(o,"is_error"in c?c.is_error:false)}}function i(c,d=false){return Array.isArray(c)&&c.length>0?{content:c.map(o=>({type:"content",content:r(o,d)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+c+"\n```":c}}]}:{}}function r(c,d){if(c.type==="text")return d?{type:"text",text:"```\n"+c.text+"\n```"}:{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return {type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return {type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function l(c){return c.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function a(c){let d="```",o=Array.from(c.matchAll(/^```+/gm));for(let[p]of o)for(;p.length>=d.length;)d+="`";return d+`
25
25
  `+c+(c.endsWith(`
26
26
  `)?"":`
27
- `)+d}}function Te(){return function(c){let d;try{d=JSON.parse(c);}catch{return null}if(d._meta||d._prompt)return null;let o=[];switch(d.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let p=d.item;if(!p)return null;let u=e(p);u&&o.push({update:u});break}case "item.updated":{let p=d.item;if(!p)return null;let u=n(p);u&&o.push({update:u});break}case "item.completed":{let p=d.item;if(!p)return null;let u=s(p);u&&o.push({update:u});break}default:return null}return o.length>0?o:null};function e(r){let c=r.id;switch(r.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${r.server}:${r.tool}`},{sessionUpdate:"tool_call",toolCallId:c,title:`${r.server}: ${r.tool}`,kind:"other",status:"in_progress",rawInput:r.arguments,content:[]};case "command_execution":return {type:"command_execution",name:r.command},{sessionUpdate:"tool_call",toolCallId:c,title:r.command?`\`${r.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:r.command},content:[]};case "web_search":return {type:"web_search",name:r.query},{sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${r.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(r.items)};default:return null}}function n(r){return r.type==="todo_list"?{sessionUpdate:"plan",entries:l(r.items)}:null}function s(r){let c=r.id;switch(r.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:r.text??r.summary?.join(`
28
- `)??r.content?.join(`
29
- `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:r.text??""}};case "mcp_tool_call":{let o=a(r.result),p=r.status==="failed"||r.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:o}}case "command_execution":{let o=r.aggregated_output?[{type:"content",content:{type:"text",text:r.aggregated_output}}]:[],p=r.status==="completed"||r.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:o}}case "file_change":{let o=r.changes??[],p=o.map(g=>({path:g.path})),u=o.length===1?`${o[0].kind==="add"?"Create":"Edit"} ${o[0].path}`:`Edit ${o.length} files`;return {sessionUpdate:"tool_call",toolCallId:c,title:u,kind:"edit",status:r.status==="completed"?"completed":"failed",content:o.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:p}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${r.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(r.items)};default:return null}}function a(r){return r?.content?Array.isArray(r.content)?r.content.map(c=>({type:"content",content:i(c)})):typeof r.content=="string"?[{type:"content",content:{type:"text",text:r.content}}]:[]:[]}function i(r){return r.type==="text"?{type:"text",text:r.text??""}:r.type==="image"?{type:"image",data:r.data??"",mimeType:r.mime_type??r.mimeType??"",uri:r.uri}:r}function l(r){if(!Array.isArray(r))return [];let c=false;return r.map(d=>{let o;return d.completed?o="completed":c?o="pending":(o="in_progress",c=true),{content:d.text??"",status:o,priority:"medium"}})}}var Ss={applypatch:"edit",apply_patch:"edit",create:"edit",edit:"edit",grep:"search",glob:"search",ls:"search",read:"read",write:"edit",execute:"execute",execute_cli:"execute",fetchurl:"fetch",fetch_url:"fetch",webfetch:"fetch",web_fetch:"fetch",websearch:"fetch",web_search:"fetch",skill:"execute",task:"think",todowrite:"other",todo_write:"other"},xs=new Set(["assistant_text_complete","thinking_text_complete","droid_working_state_changed","permission_resolved","settings_updated","session_title_updated","mcp_status_changed","session_token_usage_changed","mission_state_changed","mission_features_changed","mission_progress_entry","mission_heartbeat","mission_worker_started","mission_worker_completed","mcp_auth_required","mcp_auth_completed","structured_output"]);function Re(){let t=new Map,e,n=false,s="";return function(i){let l;try{l=JSON.parse(i);}catch{return null}if(!Nt(l))return null;let r=ks(l);if(r.sessionId&&(e=r.sessionId),r.errorText)return [j(e,r.errorText)];if(r.resultText)return s=r.resultText,n=true,[j(e,r.resultText)];if(r.handled)return null;let d=Cs(l)??l,o=Lt(d);o&&(e=o);let p=[],u=C(d,"type");switch(u){case "system":return null;case "message":{let g=C(d,"role"),m=C(d,"text")||nt(d.content);if(!m)break;g==="assistant"&&(n=true,s=m,p.push(j(e,m)));break}case "completion":{let g=C(d,"finalText")||C(d,"result");g&&(!n||g!==s)&&(n=true,s=g,p.push(j(e,g)));break}case "assistant_text_delta":{let g=C(d,"textDelta")||C(d,"text");g&&(n=true,s+=g,p.push(j(e,g)));break}case "thinking_text_delta":{let g=C(d,"textDelta")||C(d,"text");g&&p.push({sessionId:e,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g}}});break}case "assistant":{let g=C(d,"text")||nt(T(d.message)?.content);g&&(n=true,s=g,p.push(j(e,g)));break}case "tool_call":case "tool_call_delta":{let g=T(d.toolUse)??T(d.tool_use)??d,m=Ft(g,t);m&&p.push({sessionId:e,update:m});break}case "tool_result":{let g=_s(d,t);g&&p.push({sessionId:e,update:g});break}case "tool_progress_update":case "tool_progress":{let g=Es(d);g&&p.push({sessionId:e,update:g});break}case "create_message":{for(let g of bs(d,t)){if(g.sessionUpdate==="agent_message_chunk"){let m=g.content.type==="text"?g.content.text:"";if(n&&m===s)continue;n=true,s=m;}p.push({sessionId:e,update:g});}break}case "result":{let g=ie(d.result??d.text??d.error);g&&(n=true,s=g,p.push(j(e,g)));break}case "error":{let g=ie(d.message??d.error??d);g&&p.push(j(e,g));break}default:if(u&&!xs.has(u))return null}return p.length>0?p:null}}function ks(t){if(t.type!=="response")return {handled:false};let e=T(t.result),n=T(t.error),s=Lt(e??t);if(n)return {handled:true,sessionId:s,errorText:ie(n.message??n)};let a=e?C(e,"finalText")||C(e,"result"):"";return {handled:true,sessionId:s,resultText:a}}function Cs(t){return t.method!=="droid.session_notification"?null:T(T(t.params)?.notification)}function bs(t,e){let n=T(t.message);if(!n)return [];let s=[],a=n.content;if(Array.isArray(a))for(let i of a){let l=T(i);if(l&&l.type==="tool_use"){let r=Ft(l,e);r&&s.push(r);}}if(n.role==="assistant"){let i=nt(a);i&&s.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}});}return s}function Ft(t,e){let n=C(t,"id")||C(t,"toolUseId")||C(t,"tool_use_id"),s=C(t,"name")||C(t,"toolName")||C(t,"tool_name")||"Tool";if(!n)return null;e.set(n,s);let a=T(t.input)??T(t.toolInput)??T(t.arguments)??{};if(Kt(s)==="todowrite"){let d=Ts(a);if(d)return d}let{title:i,kind:l,content:r,locations:c}=Rs(s,a);return {sessionUpdate:"tool_call",toolCallId:n,title:i,kind:l,status:"pending",rawInput:a,content:r,locations:c}}function _s(t,e){let n=C(t,"toolUseId")||C(t,"tool_use_id")||C(t,"tool_id");if(!n)return null;let s=C(t,"toolName")||C(t,"tool_name")||e.get(n);return e.delete(n),{sessionUpdate:"tool_call_update",toolCallId:n,status:t.isError===true||t.is_error===true?"failed":"completed",title:s,content:st(t.content??t.result??t.error)}}function Es(t){let e=C(t,"toolUseId")||C(t,"tool_use_id")||C(t,"tool_id");if(!e)return null;let n=T(t.update),s=ie(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:s?st(s):void 0}}function Ts(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(s=>{let a=T(s);if(!a)return [];let i=C(a,"content"),l=Ps(C(a,"status")),r=Is(C(a,"priority"));return i?[{content:i,status:l,priority:r}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function Rs(t,e){let n=Ss[Kt(t)]||"other",s=C(e,"path")||C(e,"filePath")||C(e,"file_path")||C(e,"absolute_path"),a=C(e,"command"),i=C(e,"url"),l=s||a||i;return {title:l?`${t} ${l}`:t,kind:n,content:Object.keys(e).length>0?st(e):[],locations:s?[{path:s}]:[]}}function Lt(t){if(t)return C(t,"session_id")||C(t,"sessionId")}function j(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function nt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=T(e);return n?C(n,"text")||C(n,"content"):""}).filter(Boolean).join(""):""}function st(t){let e=ie(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function ie(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function T(t){return Nt(t)?t:null}function C(t,e){let n=t[e];return typeof n=="string"?n:""}function Kt(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Ps(t){return t==="in_progress"||t==="completed"?t:"pending"}function Is(t){return t==="high"||t==="low"?t:"medium"}var Os={read_file:"read",read_many_files:"read",write_file:"edit",replace:"edit",edit_file:"edit",run_shell_command:"execute",shell:"execute",glob:"search",grep:"search",search_file_content:"search",list_directory:"search",brave_web_search:"fetch",web_search:"fetch",google_web_search:"fetch",web_fetch:"fetch",delegate_to_agent:"think",write_todos:"other",save_memory:"other",activate_skill:"other"};function Pe(){return function(l){let r;try{r=JSON.parse(l);}catch{return null}if(r._meta||r._prompt)return null;let c=r.session_id,d=[];switch(r.type){case "init":case "result":return null;case "message":{let o=t(r);o&&d.push({sessionId:c,update:o});break}case "tool_use":{let o=e(r);o&&d.push({sessionId:c,update:o});break}case "tool_result":{let o=n(r);o&&d.push({sessionId:c,update:o});break}case "error":{let o=s(r);o&&d.push({sessionId:c,update:o});break}default:return null}return d.length>0?d:null};function t(i){let l=i.role,r=i.content;return r?l==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}:l==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:r}}:null:null}function e(i){let l=i.tool_id,r=i.tool_name,c=i.parameters||{},{title:d,kind:o,content:p,locations:u}=a(r,c);return {sessionUpdate:"tool_call",toolCallId:l,title:d,kind:o,status:"pending",rawInput:c,content:p,locations:u}}function n(i){let l=i.tool_id,r=i.status,c=i.output,d=i.error,o=[];return c&&typeof c=="string"&&c.length>0&&o.push({type:"content",content:{type:"text",text:r==="error"?`\`\`\`
27
+ `)+d}}function Re(){return function(c){let d;try{d=JSON.parse(c);}catch{return null}if(d._meta||d._prompt)return null;let o=[];switch(d.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let p=d.item;if(!p)return null;let u=e(p);u&&o.push({update:u});break}case "item.updated":{let p=d.item;if(!p)return null;let u=n(p);u&&o.push({update:u});break}case "item.completed":{let p=d.item;if(!p)return null;let u=s(p);u&&o.push({update:u});break}default:return null}return o.length>0?o:null};function e(a){let c=a.id;switch(a.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${a.server}:${a.tool}`},{sessionUpdate:"tool_call",toolCallId:c,title:`${a.server}: ${a.tool}`,kind:"other",status:"in_progress",rawInput:a.arguments,content:[]};case "command_execution":return {type:"command_execution",name:a.command},{sessionUpdate:"tool_call",toolCallId:c,title:a.command?`\`${a.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:a.command},content:[]};case "web_search":return {type:"web_search",name:a.query},{sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${a.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(a.items)};default:return null}}function n(a){return a.type==="todo_list"?{sessionUpdate:"plan",entries:l(a.items)}:null}function s(a){let c=a.id;switch(a.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a.text??a.summary?.join(`
28
+ `)??a.content?.join(`
29
+ `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:a.text??""}};case "mcp_tool_call":{let o=i(a.result),p=a.status==="failed"||a.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:o}}case "command_execution":{let o=a.aggregated_output?[{type:"content",content:{type:"text",text:a.aggregated_output}}]:[],p=a.status==="completed"||a.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:o}}case "file_change":{let o=a.changes??[],p=o.map(g=>({path:g.path})),u=o.length===1?`${o[0].kind==="add"?"Create":"Edit"} ${o[0].path}`:`Edit ${o.length} files`;return {sessionUpdate:"tool_call",toolCallId:c,title:u,kind:"edit",status:a.status==="completed"?"completed":"failed",content:o.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:p}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${a.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(a.items)};default:return null}}function i(a){return a?.content?Array.isArray(a.content)?a.content.map(c=>({type:"content",content:r(c)})):typeof a.content=="string"?[{type:"content",content:{type:"text",text:a.content}}]:[]:[]}function r(a){return a.type==="text"?{type:"text",text:a.text??""}:a.type==="image"?{type:"image",data:a.data??"",mimeType:a.mime_type??a.mimeType??"",uri:a.uri}:a}function l(a){if(!Array.isArray(a))return [];let c=false;return a.map(d=>{let o;return d.completed?o="completed":c?o="pending":(o="in_progress",c=true),{content:d.text??"",status:o,priority:"medium"}})}}var _s={applypatch:"edit",apply_patch:"edit",create:"edit",edit:"edit",grep:"search",glob:"search",ls:"search",read:"read",write:"edit",execute:"execute",execute_cli:"execute",fetchurl:"fetch",fetch_url:"fetch",webfetch:"fetch",web_fetch:"fetch",websearch:"fetch",web_search:"fetch",skill:"execute",task:"think",todowrite:"other",todo_write:"other"},Es=new Set(["assistant_text_complete","thinking_text_complete","droid_working_state_changed","permission_resolved","settings_updated","session_title_updated","mcp_status_changed","session_token_usage_changed","mission_state_changed","mission_features_changed","mission_progress_entry","mission_heartbeat","mission_worker_started","mission_worker_completed","mcp_auth_required","mcp_auth_completed","structured_output"]);function Pe(){let t=new Map,e,n=false,s="";return function(r){let l;try{l=JSON.parse(r);}catch{return null}if(!Gt(l))return null;let a=Ts(l);if(a.sessionId&&(e=a.sessionId),a.errorText)return [j(e,a.errorText)];if(a.resultText)return s=a.resultText,n=true,[j(e,a.resultText)];if(a.handled)return null;let d=Rs(l)??l,o=Vt(d);o&&(e=o);let p=[],u=x(d,"type");switch(u){case "system":return null;case "message":{let g=x(d,"role"),m=x(d,"text")||ot(d.content);if(!m)break;g==="assistant"&&(n=true,s=m,p.push(j(e,m)));break}case "completion":{let g=x(d,"finalText")||x(d,"result");g&&(!n||g!==s)&&(n=true,s=g,p.push(j(e,g)));break}case "assistant_text_delta":{let g=x(d,"textDelta")||x(d,"text");g&&(n=true,s+=g,p.push(j(e,g)));break}case "thinking_text_delta":{let g=x(d,"textDelta")||x(d,"text");g&&p.push({sessionId:e,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g}}});break}case "assistant":{let g=x(d,"text")||ot(R(d.message)?.content);g&&(n=true,s=g,p.push(j(e,g)));break}case "tool_call":case "tool_call_delta":{let g=R(d.toolUse)??R(d.tool_use)??d,m=jt(g,t);m&&p.push({sessionId:e,update:m});break}case "tool_result":{let g=Is(d,t);g&&p.push({sessionId:e,update:g});break}case "tool_progress_update":case "tool_progress":{let g=Os(d);g&&p.push({sessionId:e,update:g});break}case "create_message":{for(let g of Ps(d,t)){if(g.sessionUpdate==="agent_message_chunk"){let m=g.content.type==="text"?g.content.text:"";if(n&&m===s)continue;n=true,s=m;}p.push({sessionId:e,update:g});}break}case "result":{let g=ie(d.result??d.text??d.error);g&&(n=true,s=g,p.push(j(e,g)));break}case "error":{let g=ie(d.message??d.error??d);g&&p.push(j(e,g));break}default:if(u&&!Es.has(u))return null}return p.length>0?p:null}}function Ts(t){if(t.type!=="response")return {handled:false};let e=R(t.result),n=R(t.error),s=Vt(e??t);if(n)return {handled:true,sessionId:s,errorText:ie(n.message??n)};let i=e?x(e,"finalText")||x(e,"result"):"";return {handled:true,sessionId:s,resultText:i}}function Rs(t){return t.method!=="droid.session_notification"?null:R(R(t.params)?.notification)}function Ps(t,e){let n=R(t.message);if(!n)return [];let s=[],i=n.content;if(Array.isArray(i))for(let r of i){let l=R(r);if(l&&l.type==="tool_use"){let a=jt(l,e);a&&s.push(a);}}if(n.role==="assistant"){let r=ot(i);r&&s.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}});}return s}function jt(t,e){let n=x(t,"id")||x(t,"toolUseId")||x(t,"tool_use_id"),s=x(t,"name")||x(t,"toolName")||x(t,"tool_name")||"Tool";if(!n)return null;e.set(n,s);let i=R(t.input)??R(t.toolInput)??R(t.arguments)??{};if(Wt(s)==="todowrite"){let d=Ms(i);if(d)return d}let{title:r,kind:l,content:a,locations:c}=As(s,i);return {sessionUpdate:"tool_call",toolCallId:n,title:r,kind:l,status:"pending",rawInput:i,content:a,locations:c}}function Is(t,e){let n=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id");if(!n)return null;let s=x(t,"toolName")||x(t,"tool_name")||e.get(n);return e.delete(n),{sessionUpdate:"tool_call_update",toolCallId:n,status:t.isError===true||t.is_error===true?"failed":"completed",title:s,content:it(t.content??t.result??t.error)}}function Os(t){let e=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id");if(!e)return null;let n=R(t.update),s=ie(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:s?it(s):void 0}}function Ms(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(s=>{let i=R(s);if(!i)return [];let r=x(i,"content"),l=$s(x(i,"status")),a=Ds(x(i,"priority"));return r?[{content:r,status:l,priority:a}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function As(t,e){let n=_s[Wt(t)]||"other",s=x(e,"path")||x(e,"filePath")||x(e,"file_path")||x(e,"absolute_path"),i=x(e,"command"),r=x(e,"url"),l=s||i||r;return {title:l?`${t} ${l}`:t,kind:n,content:Object.keys(e).length>0?it(e):[],locations:s?[{path:s}]:[]}}function Vt(t){if(t)return x(t,"session_id")||x(t,"sessionId")}function j(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function ot(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=R(e);return n?x(n,"text")||x(n,"content"):""}).filter(Boolean).join(""):""}function it(t){let e=ie(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function ie(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function Gt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function R(t){return Gt(t)?t:null}function x(t,e){let n=t[e];return typeof n=="string"?n:""}function Wt(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function $s(t){return t==="in_progress"||t==="completed"?t:"pending"}function Ds(t){return t==="high"||t==="low"?t:"medium"}var Bs={read_file:"read",read_many_files:"read",write_file:"edit",replace:"edit",edit_file:"edit",run_shell_command:"execute",shell:"execute",glob:"search",grep:"search",search_file_content:"search",list_directory:"search",brave_web_search:"fetch",web_search:"fetch",google_web_search:"fetch",web_fetch:"fetch",delegate_to_agent:"think",write_todos:"other",save_memory:"other",activate_skill:"other"};function Ie(){return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(a._meta||a._prompt)return null;let c=a.session_id,d=[];switch(a.type){case "init":case "result":return null;case "message":{let o=t(a);o&&d.push({sessionId:c,update:o});break}case "tool_use":{let o=e(a);o&&d.push({sessionId:c,update:o});break}case "tool_result":{let o=n(a);o&&d.push({sessionId:c,update:o});break}case "error":{let o=s(a);o&&d.push({sessionId:c,update:o});break}default:return null}return d.length>0?d:null};function t(r){let l=r.role,a=r.content;return a?l==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}:l==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:a}}:null:null}function e(r){let l=r.tool_id,a=r.tool_name,c=r.parameters||{},{title:d,kind:o,content:p,locations:u}=i(a,c);return {sessionUpdate:"tool_call",toolCallId:l,title:d,kind:o,status:"pending",rawInput:c,content:p,locations:u}}function n(r){let l=r.tool_id,a=r.status,c=r.output,d=r.error,o=[];return c&&typeof c=="string"&&c.length>0&&o.push({type:"content",content:{type:"text",text:a==="error"?`\`\`\`
30
30
  ${c}
31
31
  \`\`\``:c}}),d?.message&&!c&&o.push({type:"content",content:{type:"text",text:`\`\`\`
32
32
  ${d.message}
33
- \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:l,status:r==="success"?"completed":"failed",content:o}}function s(i){let l=i.severity,r=i.message;return r?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${l==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${r}`}}:null}function a(i,l){let r=Os[i]||"other",c=[],d=[],o=i;switch(i){case "read_file":o=`Read ${l.absolute_path||l.file_path||"file"}`,(l.absolute_path||l.file_path)&&d.push({path:l.absolute_path||l.file_path});break;case "write_file":o=`Write ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),c.push({type:"diff",path:l.file_path,oldText:null,newText:l.content||""}));break;case "edit_file":o=`Edit ${l.file_path||"file"}`,l.file_path&&d.push({path:l.file_path});break;case "replace":o=`Edit ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),(l.old_string!==void 0||l.new_string!==void 0)&&c.push({type:"diff",path:l.file_path,oldText:l.old_string||"",newText:l.new_string||""}));break;case "run_shell_command":case "shell":o=l.command?`\`${l.command}\``:"Run command",l.description&&c.push({type:"content",content:{type:"text",text:l.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=l.query?`"${l.query}"`:"Web search";break;case "web_fetch":o=l.prompt?`Fetch: ${l.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${l.pattern||"files"}`,l.dir_path&&d.push({path:l.dir_path});break;case "grep":case "search_file_content":o=`grep "${l.pattern||l.query||""}"`;break;case "list_directory":o=`List ${l.dir_path||l.path||"directory"}`,(l.dir_path||l.path)&&d.push({path:l.dir_path||l.path});break;case "read_many_files":o=`Read ${l.include?.length||"multiple"} files`,Array.isArray(l.include)&&l.include.forEach(p=>d.push({path:p}));break;case "delegate_to_agent":o=l.agent_name?`Agent: ${l.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=l.fact?`Remember: "${l.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=l.name?`Activate skill: ${l.name}`:"Activate skill";break;default:o=i;}return {title:o,kind:r,content:c,locations:d}}}var Ms={ReadFile:"read",ReadMediaFile:"read",WriteFile:"edit",StrReplaceFile:"edit",Shell:"execute",Glob:"search",Grep:"search",SearchWeb:"fetch",FetchURL:"fetch",Task:"think",Think:"think",CreateSubagent:"think",SetTodoList:"other"};function it(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function Vt(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",s=e[2]||"",a=e[3]||"";return /;base64/i.test(s)?{mimeType:n,data:a}:null}function rt(t){if(!t||typeof t!="object")return null;if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {type:"content",content:{type:"text",text:t.text}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=Vt(e);return n?{type:"content",content:{type:"image",data:n.data,mimeType:n.mimeType}}:{type:"content",content:{type:"image",data:"",mimeType:"",uri:e}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{type:"content",content:{type:"text",text:`[video] ${t.video_url.url}`}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{type:"content",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}:null}function ot(t){let e=[];if(typeof t=="string")return t.length>0&&e.push({type:"content",content:{type:"text",text:t}}),e;if(Array.isArray(t)){for(let n of t){if(typeof n=="string"&&n.length>0){e.push({type:"content",content:{type:"text",text:n}});continue}let s=rt(n);s&&e.push(s);}return e}if(t&&typeof t=="object"){let n=rt(t);n&&e.push(n);}return e}function As(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&it(e.content.text))}function $s(t){if(!t||typeof t!="object")return null;if(t.type==="think"&&typeof t.think=="string"&&t.think.length>0)return {update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t.think}}};if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.text}}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=Vt(e);return n?{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:n.data,mimeType:n.mimeType}}}:{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:"",mimeType:"",uri:e}}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[video] ${t.video_url.url}`}}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}}:null}function Ds(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function jt(t){if(!t||typeof t!="object")return [];let e=t.todos;return Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object")return null;let s=n.title;if(typeof s!="string"||s.length===0)return null;let a=n.status;return {content:s,status:Ds(a),priority:"medium"}}).filter(n=>n!==null):[]}function at(){let t=new Set,e=0;function n(r,c){return typeof r=="string"&&r.length>0?r:(e+=1,`kimi_${c.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(c){let d;try{d=JSON.parse(c);}catch{return null}if(!d||typeof d!="object"||"_meta"in d||"_prompt"in d)return null;let o=d.role;return o==="assistant"?s(d):o==="tool"?a(d):typeof d.type=="string"&&"payload"in d?i(d):null};function s(r){let c=[],d=r.content,o=r.tool_calls;if(typeof d=="string"&&d.length>0)c.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let p of d){let u=$s(p);u&&c.push(u);}if(Array.isArray(o))for(let p of o){if(!p||typeof p!="object")continue;let u=p.function;if(!u)continue;let g=u.name??"",m=n(p.id,g),f;try{f=u.arguments?JSON.parse(u.arguments):{};}catch{f=u.arguments;}if(g==="SetTodoList"){let x=jt(f);x.length>0&&c.push({update:{sessionUpdate:"plan",entries:x}}),t.add(m);continue}let{title:h,kind:y,toolContent:w,locations:k}=l(g,typeof f=="object"&&f!==null?f:{});c.push({update:{sessionUpdate:"tool_call",toolCallId:m,title:h,kind:y,status:"pending",rawInput:f,content:w,locations:k}});}return c.length>0?c:null}function a(r){let c=r.tool_call_id;if(typeof c!="string"||c.length===0)return null;if(t.has(c))return t.delete(c),null;let d=r.content,o=[],p=false;if(typeof d=="string")p=it(d),d.length>0&&o.push({type:"content",content:{type:"text",text:d}});else if(Array.isArray(d))for(let u of d){let g=rt(u);g&&(g.type==="content"&&g.content.type==="text"&&it(g.content.text)&&(p=true),o.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:c,status:p?"failed":"completed",content:o}}]}function i(r){let c=r.type,d=r.payload??{},o=[];switch(c){case "TextPart":{let p=d.text;typeof p=="string"&&p.length>0&&o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});break}case "ThinkPart":{let p=d.think;typeof p=="string"&&p.length>0&&o.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p}}});break}case "ToolCall":{let p=d.function?.name??"",u=n(d.id,p),g=d.function;if(!g)break;let m;try{m=g.arguments?JSON.parse(g.arguments):{};}catch{m=g.arguments;}if(p==="SetTodoList"){let k=jt(m);k.length>0&&o.push({update:{sessionUpdate:"plan",entries:k}}),t.add(u);break}let{title:f,kind:h,toolContent:y,locations:w}=l(p,typeof m=="object"&&m!==null?m:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:u,title:f,kind:h,status:"pending",rawInput:m,content:y,locations:w}});break}case "ToolResult":{let p=d.tool_call_id;if(typeof p!="string"||p.length===0)break;if(t.has(p)){t.delete(p);break}let u=d.return_value??d.content,g=[],m=d.is_error===true;if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u;m=m||f.type==="ToolError"||f.is_error===true,g.push(...ot(f.output)),g.length===0&&typeof f.message=="string"&&f.message.length>0&&g.push({type:"content",content:{type:"text",text:f.message}}),g.length===0&&g.push(...ot(u));}else g.push(...ot(u));m=m||As(g),o.push({update:{sessionUpdate:"tool_call_update",toolCallId:p,status:m?"failed":"completed",content:g}});break}default:return null}return o.length>0?o:null}function l(r,c){let d=Ms[r]||"other",o=[],p=[],u=r;switch(r){case "ReadFile":{let g=c.path??c.file_path;u=`Read ${g||"file"}`,g&&p.push({path:g});break}case "ReadMediaFile":{let g=c.path??c.file_path;u=`Read media ${g||"file"}`,g&&p.push({path:g});break}case "WriteFile":{let g=c.path??c.file_path;u=`Write ${g||"file"}`,g&&(p.push({path:g}),typeof c.content=="string"&&o.push({type:"diff",path:g,oldText:null,newText:c.content}));break}case "StrReplaceFile":{let g=c.path??c.file_path;u=`Edit ${g||"file"}`,g&&p.push({path:g});break}case "Shell":u=c.command?`\`${c.command}\``:"Run command";break;case "Glob":u=`Find ${c.pattern||"files"}`,c.path&&p.push({path:c.path});break;case "Grep":u=`grep "${c.pattern||""}"`,c.path&&p.push({path:c.path});break;case "SearchWeb":u=c.query?`"${c.query}"`:"Web search";break;case "FetchURL":u=c.url?`Fetch ${c.url}`:"Web fetch";break;case "Task":u=c.description||"Subagent task";break;case "Think":u=c.thought||"Thinking";break;case "CreateSubagent":u=c.name?`Subagent: ${c.name}`:"Create subagent";break;case "SetTodoList":u="Update todos";break;default:u=r;}return {title:u,kind:d,toolContent:o,locations:p}}}var Us={read:"read",write:"edit",edit:"edit",multiedit:"edit",apply_patch:"edit",bash:"execute",glob:"search",grep:"search",list:"search",codesearch:"search",lsp:"search",webfetch:"fetch",websearch:"fetch",task:"think",batch:"think",plan_enter:"switch_mode",plan_exit:"switch_mode",todoread:"other",todowrite:"other",skill:"other",question:"other"};function Bs(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",s=e[2]||"",a=e[3]||"";return /;base64/i.test(s)?{mimeType:n,data:a}:null}function Fs(t){if(typeof t!="string")return "pending";switch(t.toLowerCase()){case "in_progress":case "in-progress":case "running":return "in_progress";case "completed":case "done":case "cancelled":return "completed";default:return "pending"}}function Ls(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function Gt(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return null;let n=e.content;return typeof n!="string"||n.length===0?null:{content:n,status:Fs(e.status),priority:Ls(e.priority)}}).filter(e=>e!==null):[]}function Ns(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",s=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(s.length>0){let r=Bs(s);return r?{type:"content",content:{type:"image",data:r.data,mimeType:r.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:s}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function Ks(t,e){if(t==="error")return typeof e.error=="string"?e.error:null;if(typeof e.output=="string")return e.output;if(e.output===void 0||e.output===null)return null;try{return JSON.stringify(e.output)}catch{return String(e.output)}}function js(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function ct(){return function(l){let r;try{r=JSON.parse(l);}catch{return null}if(!r||typeof r!="object")return null;let c=r.sessionID,d=[];switch(r.type){case "step_start":case "step_finish":return null;case "text":{let o=t(r);o&&d.push({sessionId:c,update:o});break}case "reasoning":{let o=e(r);o&&d.push({sessionId:c,update:o});break}case "tool_use":{let o=n(r);for(let p of o)d.push({sessionId:c,update:p});break}case "error":{let o=s(r);o&&d.push({sessionId:c,update:o});break}default:return null}return d.length>0?d:null};function t(i){let l=i.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}function e(i){let l=i.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l}}}function n(i){let l=i.part;if(!l)return [];let r=typeof l.callID=="string"?l.callID:"";if(r.length===0)return [];let c=typeof l.tool=="string"?l.tool.toLowerCase():"",d=typeof l.state=="object"&&l.state?l.state:{},o=typeof d.input=="object"&&d.input?d.input:{},p=d.status,u=d.title??d.metadata?.description??c,g=d.metadata?.exit,{kind:m,content:f,locations:h}=a(c,o),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:r,title:u,kind:m,status:"pending",rawInput:o,content:f,locations:h}),c==="todowrite"){let v=Gt(o.todos);if(v.length===0&&typeof d.output=="string")try{v=Gt(JSON.parse(d.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=js(p,g);if(w==="pending")return y;let k=Ks(p,d),x=[];if(typeof k=="string"&&k.length>0&&x.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
34
- ${k}
35
- \`\`\``:k}}),Array.isArray(d.attachments))for(let v of d.attachments){let S=Ns(v);S&&x.push(S);}return y.push({sessionUpdate:"tool_call_update",toolCallId:r,status:w,content:x}),y}function s(i){let l=i.error?.name??"Error",r=i.error?.data?.message??i.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${l}: ${r}`}}}function a(i,l){let r=Us[i]||"other",c=[],d=[];switch(i){case "read":{let o=l.filePath??l.path;if(o){let p=l.offset;d.push({path:o,line:typeof p=="number"&&Number.isFinite(p)?Math.max(0,p-1):void 0});}break}case "write":{let o=l.filePath??l.path;o&&(d.push({path:o}),typeof l.content=="string"&&c.push({type:"diff",path:o,oldText:null,newText:l.content}));break}case "edit":case "multiedit":{let o=l.filePath??l.path;o&&(d.push({path:o}),i==="edit"&&(l.oldString!==void 0||l.newString!==void 0)&&c.push({type:"diff",path:o,oldText:l.oldString??"",newText:l.newString??""}));break}case "apply_patch":break;case "bash":{let o=l.command;o&&l.description?c.push({type:"content",content:{type:"text",text:l.description}}):o&&c.push({type:"content",content:{type:"text",text:o}});break}case "glob":case "list":{let o=l.path;o&&d.push({path:o});break}case "grep":{let o=l.path;o&&d.push({path:o});break}case "codesearch":case "websearch":{let o=l.query;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "webfetch":{let o=l.url;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "task":{let o=l.description;o&&c.push({type:"content",content:{type:"text",text:o}});break}}return {kind:r,content:c,locations:d}}}var Vs={Read:"read",read_file:"read",Write:"edit",Edit:"edit",write_file:"edit",edit_file:"edit",Bash:"execute",BashOutput:"execute",KillShell:"execute",shell:"execute",run_shell_command:"execute",WebFetch:"fetch",WebSearch:"fetch",brave_web_search:"fetch",Glob:"search",Grep:"search",LS:"search",list_directory:"search",Task:"think",TodoWrite:"other",ExitPlanMode:"switch_mode"};function Ie(){let t=new Map,e=new Map;return function(o){let p;try{p=JSON.parse(o);}catch{return null}if(!p||typeof p!="object")return null;let u=p;if("_meta"in u||"_prompt"in u)return null;let g=u.session_id||void 0,m=[];switch(u.type){case "assistant":{let f=n(u);for(let h of f)m.push({sessionId:g,update:h});break}case "stream_event":{let f=s(u);for(let h of f)m.push({sessionId:g,update:h});break}case "user":{let f=a(u);for(let h of f)m.push({sessionId:g,update:h});break}case "system":case "result":return null;default:return null}return m.length>0?m:null};function n(d){let o=[],p=d.message?.content;if(!Array.isArray(p))return o;for(let u of p){let g=i(u);o.push(...g);}return o}function s(d){let o=[],p=d.event;if(!p)return o;switch(p.type){case "content_block_start":{let u=p.index??0,g=p.content_block;g&&(t.set(u,g),g.type==="tool_use"&&e.set(u,""));break}case "content_block_delta":{let u=p.index??0,g=p.delta,m=t.get(u);if(g?.type==="text_delta"&&g.text)o.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:g.text}});else if(g?.type==="thinking_delta"&&g.thinking)o.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g.thinking}});else if(g?.type==="input_json_delta"&&g.partial_json&&m?.type==="tool_use"){let f=e.get(u)||"";e.set(u,f+g.partial_json);}break}case "content_block_stop":{let u=p.index??0,g=t.get(u);if(g&&!(g.type==="text"&&g.text)){if(!(g.type==="thinking"&&g.thinking)){if(g.type==="tool_use"){let m=g,f=e.get(u)||"";e.delete(u);let h=m.input;if(f)try{h=JSON.parse(f);}catch{}let y={...m,input:h},w=l(y);w&&o.push(w);}else if(g.type==="tool_result"){let m=r(g);m&&o.push(m);}}}t.delete(u);break}}return o}function a(d){let o=d.message?.content,p=[];if(typeof o=="string")return p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:o}}),p;if(Array.isArray(o)){for(let u of o)if(u.type==="text")p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:u.text}});else if(u.type==="tool_result"){let g=r(u);g&&p.push(g);}}return p}function i(d){switch(d.type){case "text":return d.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d.text}}]:[];case "thinking":return d.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:d.thinking}}]:[];case "tool_use":{let o=l(d);return o?[o]:[]}case "tool_result":{let o=r(d);return o?[o]:[]}}}function l(d){let o=d.id,p=d.name,u=d.input;if(p==="TodoWrite"&&Array.isArray(u?.todos))return {sessionUpdate:"plan",entries:u.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:g,kind:m,content:f,locations:h}=c(p,u||{});return {sessionUpdate:"tool_call",toolCallId:o,title:g,kind:m,status:"pending",rawInput:u,content:f,locations:h}}function r(d){let o=d.tool_use_id,p=d.is_error??false,u=d.content,g=[];if(typeof u=="string"&&u.length>0)g.push({type:"content",content:{type:"text",text:p?`\`\`\`
33
+ \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:l,status:a==="success"?"completed":"failed",content:o}}function s(r){let l=r.severity,a=r.message;return a?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${l==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${a}`}}:null}function i(r,l){let a=Bs[r]||"other",c=[],d=[],o=r;switch(r){case "read_file":o=`Read ${l.absolute_path||l.file_path||"file"}`,(l.absolute_path||l.file_path)&&d.push({path:l.absolute_path||l.file_path});break;case "write_file":o=`Write ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),c.push({type:"diff",path:l.file_path,oldText:null,newText:l.content||""}));break;case "edit_file":o=`Edit ${l.file_path||"file"}`,l.file_path&&d.push({path:l.file_path});break;case "replace":o=`Edit ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),(l.old_string!==void 0||l.new_string!==void 0)&&c.push({type:"diff",path:l.file_path,oldText:l.old_string||"",newText:l.new_string||""}));break;case "run_shell_command":case "shell":o=l.command?`\`${l.command}\``:"Run command",l.description&&c.push({type:"content",content:{type:"text",text:l.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=l.query?`"${l.query}"`:"Web search";break;case "web_fetch":o=l.prompt?`Fetch: ${l.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${l.pattern||"files"}`,l.dir_path&&d.push({path:l.dir_path});break;case "grep":case "search_file_content":o=`grep "${l.pattern||l.query||""}"`;break;case "list_directory":o=`List ${l.dir_path||l.path||"directory"}`,(l.dir_path||l.path)&&d.push({path:l.dir_path||l.path});break;case "read_many_files":o=`Read ${l.include?.length||"multiple"} files`,Array.isArray(l.include)&&l.include.forEach(p=>d.push({path:p}));break;case "delegate_to_agent":o=l.agent_name?`Agent: ${l.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=l.fact?`Remember: "${l.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=l.name?`Activate skill: ${l.name}`:"Activate skill";break;default:o=r;}return {title:o,kind:a,content:c,locations:d}}}var Us={ReadFile:"read",ReadMediaFile:"read",WriteFile:"edit",StrReplaceFile:"edit",Shell:"execute",Glob:"search",Grep:"search",SearchWeb:"fetch",FetchURL:"fetch",Task:"think",Think:"think",CreateSubagent:"think",SetTodoList:"other"};function at(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function Jt(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",s=e[2]||"",i=e[3]||"";return /;base64/i.test(s)?{mimeType:n,data:i}:null}function ct(t){if(!t||typeof t!="object")return null;if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {type:"content",content:{type:"text",text:t.text}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=Jt(e);return n?{type:"content",content:{type:"image",data:n.data,mimeType:n.mimeType}}:{type:"content",content:{type:"image",data:"",mimeType:"",uri:e}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{type:"content",content:{type:"text",text:`[video] ${t.video_url.url}`}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{type:"content",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}:null}function rt(t){let e=[];if(typeof t=="string")return t.length>0&&e.push({type:"content",content:{type:"text",text:t}}),e;if(Array.isArray(t)){for(let n of t){if(typeof n=="string"&&n.length>0){e.push({type:"content",content:{type:"text",text:n}});continue}let s=ct(n);s&&e.push(s);}return e}if(t&&typeof t=="object"){let n=ct(t);n&&e.push(n);}return e}function Fs(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&at(e.content.text))}function Ls(t){if(!t||typeof t!="object")return null;if(t.type==="think"&&typeof t.think=="string"&&t.think.length>0)return {update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t.think}}};if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.text}}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=Jt(e);return n?{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:n.data,mimeType:n.mimeType}}}:{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:"",mimeType:"",uri:e}}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[video] ${t.video_url.url}`}}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}}:null}function Ns(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function zt(t){if(!t||typeof t!="object")return [];let e=t.todos;return Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object")return null;let s=n.title;if(typeof s!="string"||s.length===0)return null;let i=n.status;return {content:s,status:Ns(i),priority:"medium"}}).filter(n=>n!==null):[]}function lt(){let t=new Set,e=0;function n(a,c){return typeof a=="string"&&a.length>0?a:(e+=1,`kimi_${c.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(c){let d;try{d=JSON.parse(c);}catch{return null}if(!d||typeof d!="object"||"_meta"in d||"_prompt"in d)return null;let o=d.role;return o==="assistant"?s(d):o==="tool"?i(d):typeof d.type=="string"&&"payload"in d?r(d):null};function s(a){let c=[],d=a.content,o=a.tool_calls;if(typeof d=="string"&&d.length>0)c.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let p of d){let u=Ls(p);u&&c.push(u);}if(Array.isArray(o))for(let p of o){if(!p||typeof p!="object")continue;let u=p.function;if(!u)continue;let g=u.name??"",m=n(p.id,g),f;try{f=u.arguments?JSON.parse(u.arguments):{};}catch{f=u.arguments;}if(g==="SetTodoList"){let C=zt(f);C.length>0&&c.push({update:{sessionUpdate:"plan",entries:C}}),t.add(m);continue}let{title:h,kind:y,toolContent:w,locations:S}=l(g,typeof f=="object"&&f!==null?f:{});c.push({update:{sessionUpdate:"tool_call",toolCallId:m,title:h,kind:y,status:"pending",rawInput:f,content:w,locations:S}});}return c.length>0?c:null}function i(a){let c=a.tool_call_id;if(typeof c!="string"||c.length===0)return null;if(t.has(c))return t.delete(c),null;let d=a.content,o=[],p=false;if(typeof d=="string")p=at(d),d.length>0&&o.push({type:"content",content:{type:"text",text:d}});else if(Array.isArray(d))for(let u of d){let g=ct(u);g&&(g.type==="content"&&g.content.type==="text"&&at(g.content.text)&&(p=true),o.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:c,status:p?"failed":"completed",content:o}}]}function r(a){let c=a.type,d=a.payload??{},o=[];switch(c){case "TextPart":{let p=d.text;typeof p=="string"&&p.length>0&&o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});break}case "ThinkPart":{let p=d.think;typeof p=="string"&&p.length>0&&o.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p}}});break}case "ToolCall":{let p=d.function?.name??"",u=n(d.id,p),g=d.function;if(!g)break;let m;try{m=g.arguments?JSON.parse(g.arguments):{};}catch{m=g.arguments;}if(p==="SetTodoList"){let S=zt(m);S.length>0&&o.push({update:{sessionUpdate:"plan",entries:S}}),t.add(u);break}let{title:f,kind:h,toolContent:y,locations:w}=l(p,typeof m=="object"&&m!==null?m:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:u,title:f,kind:h,status:"pending",rawInput:m,content:y,locations:w}});break}case "ToolResult":{let p=d.tool_call_id;if(typeof p!="string"||p.length===0)break;if(t.has(p)){t.delete(p);break}let u=d.return_value??d.content,g=[],m=d.is_error===true;if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u;m=m||f.type==="ToolError"||f.is_error===true,g.push(...rt(f.output)),g.length===0&&typeof f.message=="string"&&f.message.length>0&&g.push({type:"content",content:{type:"text",text:f.message}}),g.length===0&&g.push(...rt(u));}else g.push(...rt(u));m=m||Fs(g),o.push({update:{sessionUpdate:"tool_call_update",toolCallId:p,status:m?"failed":"completed",content:g}});break}default:return null}return o.length>0?o:null}function l(a,c){let d=Us[a]||"other",o=[],p=[],u=a;switch(a){case "ReadFile":{let g=c.path??c.file_path;u=`Read ${g||"file"}`,g&&p.push({path:g});break}case "ReadMediaFile":{let g=c.path??c.file_path;u=`Read media ${g||"file"}`,g&&p.push({path:g});break}case "WriteFile":{let g=c.path??c.file_path;u=`Write ${g||"file"}`,g&&(p.push({path:g}),typeof c.content=="string"&&o.push({type:"diff",path:g,oldText:null,newText:c.content}));break}case "StrReplaceFile":{let g=c.path??c.file_path;u=`Edit ${g||"file"}`,g&&p.push({path:g});break}case "Shell":u=c.command?`\`${c.command}\``:"Run command";break;case "Glob":u=`Find ${c.pattern||"files"}`,c.path&&p.push({path:c.path});break;case "Grep":u=`grep "${c.pattern||""}"`,c.path&&p.push({path:c.path});break;case "SearchWeb":u=c.query?`"${c.query}"`:"Web search";break;case "FetchURL":u=c.url?`Fetch ${c.url}`:"Web fetch";break;case "Task":u=c.description||"Subagent task";break;case "Think":u=c.thought||"Thinking";break;case "CreateSubagent":u=c.name?`Subagent: ${c.name}`:"Create subagent";break;case "SetTodoList":u="Update todos";break;default:u=a;}return {title:u,kind:d,toolContent:o,locations:p}}}var Ks={read:"read",write:"edit",edit:"edit",multiedit:"edit",apply_patch:"edit",bash:"execute",glob:"search",grep:"search",list:"search",codesearch:"search",lsp:"search",webfetch:"fetch",websearch:"fetch",task:"think",batch:"think",plan_enter:"switch_mode",plan_exit:"switch_mode",todoread:"other",todowrite:"other",skill:"other",question:"other"};function js(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",s=e[2]||"",i=e[3]||"";return /;base64/i.test(s)?{mimeType:n,data:i}:null}function Vs(t){if(typeof t!="string")return "pending";switch(t.toLowerCase()){case "in_progress":case "in-progress":case "running":return "in_progress";case "completed":case "done":case "cancelled":return "completed";default:return "pending"}}function Gs(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function qt(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return null;let n=e.content;return typeof n!="string"||n.length===0?null:{content:n,status:Vs(e.status),priority:Gs(e.priority)}}).filter(e=>e!==null):[]}function Ws(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",s=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(s.length>0){let a=js(s);return a?{type:"content",content:{type:"image",data:a.data,mimeType:a.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:s}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function zs(t,e){if(t==="error")return typeof e.error=="string"?e.error:null;if(typeof e.output=="string")return e.output;if(e.output===void 0||e.output===null)return null;try{return JSON.stringify(e.output)}catch{return String(e.output)}}function Js(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function dt(){return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(!a||typeof a!="object")return null;let c=a.sessionID,d=[];switch(a.type){case "step_start":case "step_finish":return null;case "text":{let o=t(a);o&&d.push({sessionId:c,update:o});break}case "reasoning":{let o=e(a);o&&d.push({sessionId:c,update:o});break}case "tool_use":{let o=n(a);for(let p of o)d.push({sessionId:c,update:p});break}case "error":{let o=s(a);o&&d.push({sessionId:c,update:o});break}default:return null}return d.length>0?d:null};function t(r){let l=r.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}function e(r){let l=r.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l}}}function n(r){let l=r.part;if(!l)return [];let a=typeof l.callID=="string"?l.callID:"";if(a.length===0)return [];let c=typeof l.tool=="string"?l.tool.toLowerCase():"",d=typeof l.state=="object"&&l.state?l.state:{},o=typeof d.input=="object"&&d.input?d.input:{},p=d.status,u=d.title??d.metadata?.description??c,g=d.metadata?.exit,{kind:m,content:f,locations:h}=i(c,o),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:a,title:u,kind:m,status:"pending",rawInput:o,content:f,locations:h}),c==="todowrite"){let v=qt(o.todos);if(v.length===0&&typeof d.output=="string")try{v=qt(JSON.parse(d.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=Js(p,g);if(w==="pending")return y;let S=zs(p,d),C=[];if(typeof S=="string"&&S.length>0&&C.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
34
+ ${S}
35
+ \`\`\``:S}}),Array.isArray(d.attachments))for(let v of d.attachments){let b=Ws(v);b&&C.push(b);}return y.push({sessionUpdate:"tool_call_update",toolCallId:a,status:w,content:C}),y}function s(r){let l=r.error?.name??"Error",a=r.error?.data?.message??r.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${l}: ${a}`}}}function i(r,l){let a=Ks[r]||"other",c=[],d=[];switch(r){case "read":{let o=l.filePath??l.path;if(o){let p=l.offset;d.push({path:o,line:typeof p=="number"&&Number.isFinite(p)?Math.max(0,p-1):void 0});}break}case "write":{let o=l.filePath??l.path;o&&(d.push({path:o}),typeof l.content=="string"&&c.push({type:"diff",path:o,oldText:null,newText:l.content}));break}case "edit":case "multiedit":{let o=l.filePath??l.path;o&&(d.push({path:o}),r==="edit"&&(l.oldString!==void 0||l.newString!==void 0)&&c.push({type:"diff",path:o,oldText:l.oldString??"",newText:l.newString??""}));break}case "apply_patch":break;case "bash":{let o=l.command;o&&l.description?c.push({type:"content",content:{type:"text",text:l.description}}):o&&c.push({type:"content",content:{type:"text",text:o}});break}case "glob":case "list":{let o=l.path;o&&d.push({path:o});break}case "grep":{let o=l.path;o&&d.push({path:o});break}case "codesearch":case "websearch":{let o=l.query;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "webfetch":{let o=l.url;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "task":{let o=l.description;o&&c.push({type:"content",content:{type:"text",text:o}});break}}return {kind:a,content:c,locations:d}}}var qs={Read:"read",read_file:"read",Write:"edit",Edit:"edit",write_file:"edit",edit_file:"edit",Bash:"execute",BashOutput:"execute",KillShell:"execute",shell:"execute",run_shell_command:"execute",WebFetch:"fetch",WebSearch:"fetch",brave_web_search:"fetch",Glob:"search",Grep:"search",LS:"search",list_directory:"search",Task:"think",TodoWrite:"other",ExitPlanMode:"switch_mode"};function Oe(){let t=new Map,e=new Map;return function(o){let p;try{p=JSON.parse(o);}catch{return null}if(!p||typeof p!="object")return null;let u=p;if("_meta"in u||"_prompt"in u)return null;let g=u.session_id||void 0,m=[];switch(u.type){case "assistant":{let f=n(u);for(let h of f)m.push({sessionId:g,update:h});break}case "stream_event":{let f=s(u);for(let h of f)m.push({sessionId:g,update:h});break}case "user":{let f=i(u);for(let h of f)m.push({sessionId:g,update:h});break}case "system":case "result":return null;default:return null}return m.length>0?m:null};function n(d){let o=[],p=d.message?.content;if(!Array.isArray(p))return o;for(let u of p){let g=r(u);o.push(...g);}return o}function s(d){let o=[],p=d.event;if(!p)return o;switch(p.type){case "content_block_start":{let u=p.index??0,g=p.content_block;g&&(t.set(u,g),g.type==="tool_use"&&e.set(u,""));break}case "content_block_delta":{let u=p.index??0,g=p.delta,m=t.get(u);if(g?.type==="text_delta"&&g.text)o.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:g.text}});else if(g?.type==="thinking_delta"&&g.thinking)o.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g.thinking}});else if(g?.type==="input_json_delta"&&g.partial_json&&m?.type==="tool_use"){let f=e.get(u)||"";e.set(u,f+g.partial_json);}break}case "content_block_stop":{let u=p.index??0,g=t.get(u);if(g&&!(g.type==="text"&&g.text)){if(!(g.type==="thinking"&&g.thinking)){if(g.type==="tool_use"){let m=g,f=e.get(u)||"";e.delete(u);let h=m.input;if(f)try{h=JSON.parse(f);}catch{}let y={...m,input:h},w=l(y);w&&o.push(w);}else if(g.type==="tool_result"){let m=a(g);m&&o.push(m);}}}t.delete(u);break}}return o}function i(d){let o=d.message?.content,p=[];if(typeof o=="string")return p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:o}}),p;if(Array.isArray(o)){for(let u of o)if(u.type==="text")p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:u.text}});else if(u.type==="tool_result"){let g=a(u);g&&p.push(g);}}return p}function r(d){switch(d.type){case "text":return d.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d.text}}]:[];case "thinking":return d.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:d.thinking}}]:[];case "tool_use":{let o=l(d);return o?[o]:[]}case "tool_result":{let o=a(d);return o?[o]:[]}}}function l(d){let o=d.id,p=d.name,u=d.input;if(p==="TodoWrite"&&Array.isArray(u?.todos))return {sessionUpdate:"plan",entries:u.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:g,kind:m,content:f,locations:h}=c(p,u||{});return {sessionUpdate:"tool_call",toolCallId:o,title:g,kind:m,status:"pending",rawInput:u,content:f,locations:h}}function a(d){let o=d.tool_use_id,p=d.is_error??false,u=d.content,g=[];if(typeof u=="string"&&u.length>0)g.push({type:"content",content:{type:"text",text:p?`\`\`\`
36
36
  ${u}
37
37
  \`\`\``:u}});else if(Array.isArray(u)){for(let m of u)if(m.type==="text"){let f=m.text;g.push({type:"content",content:{type:"text",text:p?`\`\`\`
38
38
  ${f}
39
- \`\`\``:f}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:p?"failed":"completed",content:g}}function c(d,o){let p=Vs[d]||"other",u=[],g=[],m=d;switch(d){case "Read":case "read_file":m=`Read ${o.file_path||o.absolute_path||"file"}`,(o.file_path||o.absolute_path)&&g.push({path:o.file_path||o.absolute_path});break;case "Write":case "write_file":m=`Write ${o.file_path||"file"}`,o.file_path&&(g.push({path:o.file_path}),u.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":m=`Edit ${o.file_path||"file"}`,o.file_path&&g.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":m=o.command?`\`${o.command}\``:"Run command",o.description&&u.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":m=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":m=o.query?`"${o.query}"`:"Web search";break;case "Glob":m=`Find ${o.pattern||"files"}`,o.path&&g.push({path:o.path});break;case "Grep":m=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":m=`List ${o.path||"directory"}`,o.path&&g.push({path:o.path});break;case "Task":m=o.description||"Subagent task";break;case "TodoWrite":m="Update todos";break;case "ExitPlanMode":m="Exit plan mode";break;default:m=d;}return {title:m,kind:p,content:u,locations:g}}}function Wt(t){return Ie()(t)}function W(t){switch(t){case "claude":return Ee();case "codex":return Te();case "gemini":return Pe();case "qwen":return Ie();case "kimi":return at();case "opencode":return ct();case "droid":return Re();default:return ()=>null}}function Gs(t,e){let n=e.trim();return n?W(t)(n):null}function Ws(t,e){let n=[],s=e.split(`
40
- `),a=W(t);for(let i of s){let l=i.trim();if(!l)continue;let r=a(l);r&&n.push(...r);}return n}function M(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function H(t){return JSON.stringify(zs__default.default(t,{target:"jsonSchema7"}),null,2)}function Y(t){return JSON.stringify(t,null,2)}function zt(t,e=false){let n={};function s(a,i){for(let l of A__namespace.readdirSync(a)){let r=re__namespace.join(a,l),c=i?`${i}/${l}`:l;A__namespace.statSync(r).isDirectory()?e&&s(r,c):n[c]=A__namespace.readFileSync(r);}}return s(t,""),n}function Jt(t,e){for(let[n,s]of Object.entries(e)){let a=re__namespace.join(t,n),i=re__namespace.dirname(a);A__namespace.mkdirSync(i,{recursive:true});let l;s instanceof ArrayBuffer||s instanceof Uint8Array?l=Buffer.from(s):l=s,A__namespace.writeFileSync(a,l);}}function Js(t){let e=t.replace(/^~/,process.env.HOME||"");if(!A__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return A__namespace.readFileSync(e,"utf-8")}function Me(t){let e=t?.type??Mt,n=$(e);if(t?.oauthToken){if(e!=="claude")throw new Error(`oauthToken is only supported for claude agent (Claude Max subscription), not ${e}. Use providerApiKey for ${e} instead.`);return {type:e,apiKey:t.oauthToken,isDirectMode:true,isOAuth:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.providerApiKey){let l=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,r=t.providerBaseUrl??l??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:r,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort};let s=process.env[O];if(s)return {type:e,apiKey:s,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let r=(t?.model??n.defaultModel)?.split("/")[0],c=r?n.providerEnvMap[r]:void 0,d=c?process.env[c.keyEnv]:void 0;if(d){let p=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:p,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let a=process.env[n.apiKeyEnv];if(a){let r=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:a,baseUrl:r,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let l=process.env[n.oauthEnv];if(l){if(n.oauthFileName){let r=Js(l);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:r,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:l,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let i=n.oauthEnv?n.oauthFileName?`, or ${n.oauthEnv}`:`, oauthToken, or ${n.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${i}, or ${O} / ${n.apiKeyEnv} env var.`)}async function lt(){let t=process.env[xe];if(t)try{let{createE2BProvider:i}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===He()&&delete process.env.E2B_API_URL,i({apiKey:t})}catch(i){let l=i;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${xe} is set but @evolvingmachines/e2b failed to load.
41
- Try reinstalling: npm install @evolvingmachines/sdk`):l}let e=process.env[ke];if(e)try{let{createDaytonaProvider:i}=await import('@evolvingmachines/daytona');return i({apiKey:e})}catch(i){let l=i;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${ke} is set but @evolvingmachines/daytona failed to load.
42
- Try installing: npm install @evolvingmachines/daytona`):l}let n=process.env[Ce],s=process.env[Ye];if(n&&s)try{let{createModalProvider:i}=await import('@evolvingmachines/modal');return i({tokenId:n,tokenSecret:s})}catch(i){let l=i;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ce} is set but @evolvingmachines/modal failed to load.
43
- Try installing: npm install @evolvingmachines/modal`):l}let a=process.env[O];if(a)try{let{createE2BProvider:i}=await import('@evolvingmachines/e2b');return i({apiKey:a,apiUrl:He()})}catch(i){let l=i;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${O} is set but @evolvingmachines/e2b failed to load.
39
+ \`\`\``:f}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:p?"failed":"completed",content:g}}function c(d,o){let p=qs[d]||"other",u=[],g=[],m=d;switch(d){case "Read":case "read_file":m=`Read ${o.file_path||o.absolute_path||"file"}`,(o.file_path||o.absolute_path)&&g.push({path:o.file_path||o.absolute_path});break;case "Write":case "write_file":m=`Write ${o.file_path||"file"}`,o.file_path&&(g.push({path:o.file_path}),u.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":m=`Edit ${o.file_path||"file"}`,o.file_path&&g.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":m=o.command?`\`${o.command}\``:"Run command",o.description&&u.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":m=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":m=o.query?`"${o.query}"`:"Web search";break;case "Glob":m=`Find ${o.pattern||"files"}`,o.path&&g.push({path:o.path});break;case "Grep":m=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":m=`List ${o.path||"directory"}`,o.path&&g.push({path:o.path});break;case "Task":m=o.description||"Subagent task";break;case "TodoWrite":m="Update todos";break;case "ExitPlanMode":m="Exit plan mode";break;default:m=d;}return {title:m,kind:p,content:u,locations:g}}}function Ht(t){return Oe()(t)}function W(t){switch(t){case "claude":return Te();case "codex":return Re();case "gemini":return Ie();case "qwen":return Oe();case "kimi":return lt();case "opencode":return dt();case "droid":return Pe();default:return ()=>null}}function Hs(t,e){let n=e.trim();return n?W(t)(n):null}function Ys(t,e){let n=[],s=e.split(`
40
+ `),i=W(t);for(let r of s){let l=r.trim();if(!l)continue;let a=i(l);a&&n.push(...a);}return n}function M(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function H(t){return JSON.stringify(Zs__default.default(t,{target:"jsonSchema7"}),null,2)}function Y(t){return JSON.stringify(t,null,2)}function Yt(t,e=false){let n={};function s(i,r){for(let l of A__namespace.readdirSync(i)){let a=re__namespace.join(i,l),c=r?`${r}/${l}`:l;A__namespace.statSync(a).isDirectory()?e&&s(a,c):n[c]=A__namespace.readFileSync(a);}}return s(t,""),n}function Zt(t,e){for(let[n,s]of Object.entries(e)){let i=re__namespace.join(t,n),r=re__namespace.dirname(i);A__namespace.mkdirSync(r,{recursive:true});let l;s instanceof ArrayBuffer||s instanceof Uint8Array?l=Buffer.from(s):l=s,A__namespace.writeFileSync(i,l);}}function Qs(t){let e=t.replace(/^~/,process.env.HOME||"");if(!A__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return A__namespace.readFileSync(e,"utf-8")}function Ae(t){let e=t?.type??Bt,n=$(e);if(t?.oauthToken){if(e!=="claude")throw new Error(`oauthToken is only supported for claude agent (Claude Max subscription), not ${e}. Use providerApiKey for ${e} instead.`);return {type:e,apiKey:t.oauthToken,isDirectMode:true,isOAuth:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.providerApiKey){let l=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,a=t.providerBaseUrl??l??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:a,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort};let s=process.env[O];if(s)return {type:e,apiKey:s,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let a=(t?.model??n.defaultModel)?.split("/")[0],c=a?n.providerEnvMap[a]:void 0,d=c?process.env[c.keyEnv]:void 0;if(d){let p=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:p,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let i=process.env[n.apiKeyEnv];if(i){let a=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:i,baseUrl:a,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let l=process.env[n.oauthEnv];if(l){if(n.oauthFileName){let a=Qs(l);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:a,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:l,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let r=n.oauthEnv?n.oauthFileName?`, or ${n.oauthEnv}`:`, oauthToken, or ${n.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${r}, or ${O} / ${n.apiKeyEnv} env var.`)}async function pt(){let t=process.env[Se];if(t)try{let{createE2BProvider:r}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===Ze()&&delete process.env.E2B_API_URL,r({apiKey:t})}catch(r){let l=r;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${Se} is set but @evolvingmachines/e2b failed to load.
41
+ Try reinstalling: npm install @evolvingmachines/sdk`):l}let e=process.env[xe];if(e)try{let{createDaytonaProvider:r}=await import('@evolvingmachines/daytona');return r({apiKey:e})}catch(r){let l=r;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${xe} is set but @evolvingmachines/daytona failed to load.
42
+ Try installing: npm install @evolvingmachines/daytona`):l}let n=process.env[ke],s=process.env[Qe];if(n&&s)try{let{createModalProvider:r}=await import('@evolvingmachines/modal');return r({tokenId:n,tokenSecret:s})}catch(r){let l=r;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${ke} is set but @evolvingmachines/modal failed to load.
43
+ Try installing: npm install @evolvingmachines/modal`):l}let i=process.env[O];if(i)try{let{createE2BProvider:r}=await import('@evolvingmachines/e2b');return r({apiKey:i,apiUrl:Ze()})}catch(r){let l=r;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${O} is set but @evolvingmachines/e2b failed to load.
44
44
  Try reinstalling: npm install @evolvingmachines/sdk`):l}throw new Error(`No sandbox provider configured. Either:
45
45
  1. Set ${O} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
46
- 2. Set ${xe} environment variable (direct E2B access, get key at https://e2b.dev)
47
- 3. Set ${ke} environment variable (direct Daytona access, get key at https://app.daytona.io)
48
- 4. Set ${Ce} and ${Ye} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
49
- 5. Pass sandbox explicitly: .withSandbox(provider)`)}function qs(t){return new Promise(e=>setTimeout(e,t))}async function P(t,e,n=0){let s=Hs(e),a=e?.onItemRetry,i=null,l=0,r=s.backoffMs;for(;l<s.maxAttempts;){if(l++,i=await t(l),!s.retryOn(i))return i;if(l>=s.maxAttempts)break;if(a){let c=i.error??"Unknown error";a(n,l,c);}await qs(r),r*=s.backoffMultiplier;}return i}function Hs(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var qt=`## FILESYSTEM INSTRUCTIONS:
46
+ 2. Set ${Se} environment variable (direct E2B access, get key at https://e2b.dev)
47
+ 3. Set ${xe} environment variable (direct Daytona access, get key at https://app.daytona.io)
48
+ 4. Set ${ke} and ${Qe} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
49
+ 5. Pass sandbox explicitly: .withSandbox(provider)`)}function Xs(t){return new Promise(e=>setTimeout(e,t))}async function P(t,e,n=0){let s=eo(e),i=e?.onItemRetry,r=null,l=0,a=s.backoffMs;for(;l<s.maxAttempts;){if(l++,r=await t(l),!s.retryOn(r))return r;if(l>=s.maxAttempts)break;if(i){let c=r.error??"Unknown error";i(n,l,c);}await Xs(a),a*=s.backoffMultiplier;}return r}function eo(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var Qt=`## FILESYSTEM INSTRUCTIONS:
50
50
 
51
51
  You are running in a sandbox environment.
52
52
 
@@ -79,7 +79,7 @@ Examples:
79
79
  - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
80
80
  - "Write a Python script" \u2192 \`output/parser.py\`
81
81
  - "Convert this to JSON" \u2192 \`output/data.json\`
82
- `;var Ht=`## FILESYSTEM INSTRUCTIONS:
82
+ `;var Xt=`## FILESYSTEM INSTRUCTIONS:
83
83
 
84
84
  You are running in a sandbox environment.
85
85
 
@@ -113,9 +113,9 @@ Examples:
113
113
  - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
114
114
  - "Write a Python script" \u2192 \`output/parser.py\`
115
115
  - "Convert this to JSON" \u2192 \`output/data.json\`
116
- `;var Yt=`## SYSTEM PROMPT
116
+ `;var en=`## SYSTEM PROMPT
117
117
 
118
- {{systemPrompt}}`;var Zt=`## STRUCTURED OUTPUT
118
+ {{systemPrompt}}`;var tn=`## STRUCTURED OUTPUT
119
119
 
120
120
  Your final result MUST be saved to \`output/result.json\` following this schema:
121
121
 
@@ -133,13 +133,13 @@ You are free to:
133
133
  But your final \`output/result.json\` MUST conform to the schema above.
134
134
 
135
135
  ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
136
- ### Never just state results as text.`;var Qt=`## BROWSER AUTOMATION
136
+ ### Never just state results as text.`;var nn=`## BROWSER AUTOMATION
137
137
 
138
138
  Actionbook is preconfigured for remote browser automation in this environment. When browser automation is needed, start sessions with \`actionbook browser start --session s1\`, then use normal Actionbook browser commands. Do not override the configured browser mode or browser endpoint unless the user explicitly asks.
139
- `;var Xt=`## Browser Automation
139
+ `;var sn=`## Browser Automation
140
140
 
141
141
  The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
142
- `;var en=`### 1. YOUR ROLE: BEST OF N JUDGE
142
+ `;var on=`### 1. YOUR ROLE: BEST OF N JUDGE
143
143
 
144
144
  You are a judge. {{candidateCount}} AI workers attempted the same task independently. Your job is to analyze their solution attempts and pick the best one based on the evaluation criteria below.
145
145
 
@@ -169,7 +169,7 @@ You must judge their work based on:
169
169
  5. Pick the best candidate (0-indexed)
170
170
 
171
171
  **IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
172
- `;var tn=`### 1. YOUR ROLE: OUTPUT VERIFIER
172
+ `;var rn=`### 1. YOUR ROLE: OUTPUT VERIFIER
173
173
 
174
174
  You are a quality verifier. An AI worker produced output for a task. Your job is to verify whether the output meets the specified quality criteria.
175
175
 
@@ -202,14 +202,14 @@ The output must satisfy:
202
202
  **IMPORTANT:** Be thorough and fair. Cite specific evidence. If the output generally achieves the goal with minor issues, consider passing. Only fail if there are significant problems that violate the criteria.
203
203
 
204
204
  If failing, provide specific, actionable feedback explaining what needs to be fixed.
205
- `;var nn=`### CONTEXT STRUCTURE
205
+ `;var an=`### CONTEXT STRUCTURE
206
206
 
207
207
  \`\`\`
208
208
  {{fileTree}}
209
209
  \`\`\`
210
210
 
211
211
  Examine all files within each item folder before producing your output.
212
- `;var sn="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var on="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var rn=`{{originalPrompt}}
212
+ `;var cn="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var ln="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var dn=`{{originalPrompt}}
213
213
 
214
214
  ## IMPORTANT: Previous Attempt Failed Verification
215
215
 
@@ -218,38 +218,38 @@ Your previous attempt did not pass quality verification. Please address this fee
218
218
  {{feedback}}
219
219
 
220
220
  Make sure your output addresses all the feedback points above.
221
- `;var an=qt,cn=Ht,ln=Yt,dn=Zt,dt=Qt,pn=Xt,pt=en,un=sn,ut=tn,gn=on,mn=nn,gt=rn;function B(t,e){let n=t;for(let[s,a]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),a);return n}function mt(t){let e=t.mode==="swe"?cn:an,n=B(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
221
+ `;var pn=Qt,un=Xt,gn=en,mn=tn,ut=nn,fn=sn,gt=on,hn=cn,mt=rn,yn=ln,wn=an,ft=dn;function U(t,e){let n=t;for(let[s,i]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),i);return n}function ht(t){let e=t.mode==="swe"?un:pn,n=U(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
222
222
 
223
223
 
224
224
  ${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
225
225
 
226
226
 
227
- ${B(ln,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let s=M(t.schema)?H(t.schema):Y(t.schema);n+=`
227
+ ${U(gn,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let s=M(t.schema)?H(t.schema):Y(t.schema);n+=`
228
228
 
229
229
 
230
- ${B(dn,{schema:s}).trim()}`;}return n}function Ae(t){let e=[...new Set(Object.keys(t).map(c=>c.split("/")[0]))].sort((c,d)=>c==="worker_task"?-1:d==="worker_task"?1:c.localeCompare(d));if(!e.length)return `context/
231
- (empty)`;let n="worker_task/system_prompt.txt"in t,s="worker_task/schema.json"in t,a=Object.keys(t).some(c=>c.startsWith("worker_task/input/")),i=[];e.forEach((c,d)=>{let o=d===e.length-1,p=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=o?" ":"\u2502 ";if(c==="worker_task"){i.push({line:`${p}${c}/`,comment:"task given to worker"});let g=[];n&&g.push({name:"system_prompt.txt",comment:"worker system prompt"}),g.push({name:"user_prompt.txt",comment:"worker task prompt"}),s&&g.push({name:"schema.json",comment:"expected output schema"}),a&&g.push({name:"input/",comment:"worker input files"}),g.forEach((m,f)=>{let y=f===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";i.push({line:`${u}${y}${m.name}`,comment:m.comment});});}else if(c.startsWith("candidate_")){let g=c.replace("candidate_","");i.push({line:`${p}${c}/`,comment:`worker ${g} solution`});}else if(c==="worker_output")i.push({line:`${p}${c}/`,comment:"output to verify"});else if(c.startsWith("item_")){let g=c.replace("item_","");i.push({line:`${p}${c}/`,comment:`input ${g}`});}else i.push({line:`${p}${c}/`,comment:""});});let l=Math.max(...i.map(c=>c.line.length)),r=["context/"];for(let c of i)if(c.comment){let d=" ".repeat(l-c.line.length+3);r.push(`${c.line}${d}# ${c.comment}`);}else r.push(c.line);return r.join(`
232
- `)}var fn=re.join(os$1.homedir(),Dt),ae=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(fn,{recursive:true}).catch(()=>{});eventBuffer=[];dashboardQueue=Promise.resolve();flushTimer;constructor(e){this.validateConfig(e),this.provider=e.provider,this.agent=e.agent,this.model=e.model,this.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=Se(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),s=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=re.join(fn,s),this.parser=W(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let s of n)this.bufferForDashboard(s);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let s of n)this.bufferForDashboard(s);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.isClosed=true,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
230
+ ${U(mn,{schema:s}).trim()}`;}return n}function $e(t){let e=[...new Set(Object.keys(t).map(c=>c.split("/")[0]))].sort((c,d)=>c==="worker_task"?-1:d==="worker_task"?1:c.localeCompare(d));if(!e.length)return `context/
231
+ (empty)`;let n="worker_task/system_prompt.txt"in t,s="worker_task/schema.json"in t,i=Object.keys(t).some(c=>c.startsWith("worker_task/input/")),r=[];e.forEach((c,d)=>{let o=d===e.length-1,p=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=o?" ":"\u2502 ";if(c==="worker_task"){r.push({line:`${p}${c}/`,comment:"task given to worker"});let g=[];n&&g.push({name:"system_prompt.txt",comment:"worker system prompt"}),g.push({name:"user_prompt.txt",comment:"worker task prompt"}),s&&g.push({name:"schema.json",comment:"expected output schema"}),i&&g.push({name:"input/",comment:"worker input files"}),g.forEach((m,f)=>{let y=f===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";r.push({line:`${u}${y}${m.name}`,comment:m.comment});});}else if(c.startsWith("candidate_")){let g=c.replace("candidate_","");r.push({line:`${p}${c}/`,comment:`worker ${g} solution`});}else if(c==="worker_output")r.push({line:`${p}${c}/`,comment:"output to verify"});else if(c.startsWith("item_")){let g=c.replace("item_","");r.push({line:`${p}${c}/`,comment:`input ${g}`});}else r.push({line:`${p}${c}/`,comment:""});});let l=Math.max(...r.map(c=>c.line.length)),a=["context/"];for(let c of r)if(c.comment){let d=" ".repeat(l-c.line.length+3);a.push(`${c.line}${d}# ${c.comment}`);}else a.push(c.line);return a.join(`
232
+ `)}var vn=re.join(os$1.homedir(),Lt),ae=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(vn,{recursive:true}).catch(()=>{});eventBuffer=[];dashboardQueue=Promise.resolve();flushTimer;constructor(e){this.validateConfig(e),this.provider=e.provider,this.agent=e.agent,this.model=e.model,this.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=Ce(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),s=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=re.join(vn,s),this.parser=W(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let s of n)this.bufferForDashboard(s);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let s of n)this.bufferForDashboard(s);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.isClosed=true,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
233
233
  `)?e:e+`
234
234
  `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let n=JSON.stringify(e)+`
235
235
  `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&(this.eventBuffer.push(e),this.scheduleFlush());}writeMeta(){let e={_meta:{tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandbox_id:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability)}},n=JSON.stringify(e)+`
236
- `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=Ut){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Bt));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let s=1;s<=be;s++)try{let a=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(a.ok)return;if(a.status===429||a.status===401||a.status>=500){if(s===be){console.debug(`[SessionLogger] Dashboard ${a.status} after ${s} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Qe*s);continue}console.debug(`[SessionLogger] Dashboard ${a.status}, dropping events`);return}catch(a){s===be?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",a),this.requeueEvents(e)):await this.delay(Qe*s);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Se();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var $e="COMPOSIO_API_KEY";function yn(t){return new core.Composio({apiKey:process.env[$e]})}function ft(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function De(t,e,n){ft(t);let s=yn(),a={};return e?.toolkits&&(a.toolkits=e.toolkits),e?.tools&&(a.tools=e.tools),e?.authConfigs&&(a.authConfigs=e.authConfigs),e?.connectedAccounts&&(a.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(a.manageConnections=e.manageConnections),await s.create(t,Object.keys(a).length>0?a:void 0)}async function wn(t,e,n,s){ft(t);let a=yn(),r=(await a.toolkits.get(e)).authConfigDetails?.find(c=>c.mode==="API_KEY");if(!r)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await a.connectedAccounts.initiate(t,r.name,{config:core.AuthScheme.APIKey({api_key:n})});}async function ht(t,e){if(ft(t),e?.keys)for(let[s,a]of Object.entries(e.keys))try{await wn(t,s,a);}catch(i){throw new Error(`Failed to create API key connection for "${s}": ${i.message}`)}let n=await De(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function vn(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function ho(){return new core.Composio({apiKey:process.env[$e]})}async function Sn(t,e){vn(t);let s=await(await De(t,{manageConnections:false})).authorize(e);return {url:s.redirectUrl,connectionId:s.id}}async function xn(t,e){let n=await yt(t),s={};for(let a of n)s[a.toolkit]=a.connected;return e?s[e]??false:s}async function yt(t){return vn(t),(await ho().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(s=>({toolkit:s.toolkit.slug,connected:s.status==="ACTIVE",accountId:s.id}))}var wt={auth:Sn,status:xn,connections:yt};util.promisify(child_process.exec);var kt=util.promisify(child_process.execFile),bn=Symbol.for("evolve:awsSdkCache"),_n=Symbol.for("evolve:s3ClientCache");var To=3600,Ro=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Po(t){if(t.startsWith("s3://")){let a=t.slice(5),i=a.indexOf("/");return i===-1?{bucket:a,prefix:""}:{bucket:a.slice(0,i),prefix:a.slice(i+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,s=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:s.join("/")};if(s.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:s[0],prefix:s.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function Fe(t,e,n,s){if(!t?.url&&!t?.bucket){if(!e)throw new Error("Storage requires either a URL (BYOK mode) or gateway API key. Use .withStorage({ url: 's3://bucket/prefix' }) or configure EVOLVE_API_KEY for gateway mode.");return {bucket:"",prefix:"",region:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:s}}let a=t?.bucket||"",i=t?.prefix||"",l=t?.endpoint;if(t?.url){let r=Po(t.url);a=a||r.bucket,i=i||r.prefix,l=l||r.endpoint;}if(!a)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:a,prefix:i,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:l,credentials:t?.credentials,mode:"byok"}}function En(t){if(t.includes(".."))throw new Error(`settingsDir must not contain '..': ${t}`);let e;if(t.startsWith("~/"))e=t.slice(2);else if(t.startsWith("/home/user/"))e=t.slice(11);else if(t.startsWith("."))e=t;else throw new Error(`Unexpected settingsDir: ${t}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${t}`);return e}function Io(t){if(t.includes(".."))throw new Error(`workingDir must not contain '..': ${t}`);if(!t.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${t}. Must start with /home/user/.`);let e=t.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${t}`);return e}function Ue(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Oo(t,e){let n=$(t),s=Io(e),a=n.checkpointDirs?.length?n.checkpointDirs.map(r=>En(r)):[En(n.mcpConfig.settingsDir)],i=[...Ro.map(r=>`--exclude=${Ue(r)}`),`--exclude=${Ue(s+"/temp")}`].join(" "),l=[Ue(s+"/"),...a.map(r=>Ue(r+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${i} ${l}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Q(){let t=globalThis[bn];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[s,a]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[bn]={s3:s,presigner:a},{s3:s,presigner:a}}catch{throw new Error("Storage requires @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner. Install: npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner")}}async function le(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,s=globalThis[_n];if(s?.key===n)return s.client;let{s3:a}=await Q(),i=new a.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[_n]={client:i,key:n},i}async function Dn(t,e,n){let{s3:s,presigner:a}=await Q(),i=await le(t),l=n==="put"?new s.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new s.GetObjectCommand({Bucket:t.bucket,Key:e});return a.getSignedUrl(i,l,{expiresIn:To})}async function Tn(t,e){let{s3:n}=await Q(),s=await le(t);try{return await s.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(a){let i=a?.name||a?.message||"";if(a?.$metadata?.httpStatusCode===404||i==="NotFound"||i==="NoSuchKey")return false;throw a}}async function Un(t,e){let{s3:n}=await Q(),i=await(await(await le(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!i)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(i)}async function Mo(t,e,n){let{s3:s}=await Q();await(await le(t)).send(new s.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Bn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function Fn(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Ao(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Ln(t,e,n,s){let a=await fetch(`${t.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:n,action:s})});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Gateway presign failed (${a.status}): ${i}`)}return a.json()}async function $o(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify(e)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${s}`)}return n.json()}async function Do(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let s=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${s}`)}return n.json()}async function Ct(t,e,n,s,a){let i=new Date().toISOString(),l=Oo(n,s),r=await t.commands.run(l,{timeoutMs:12e4});if(r.exitCode!==0)throw new Error(`Checkpoint tar failed: ${r.stderr}`);let c=r.stdout.trim().split(`
237
- `).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);let d=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(d.stdout.trim(),10),p=Number.isNaN(o)?void 0:o,u;try{if(e.mode==="byok"){let g=Bn(e,c);if(!await Tn(e,g)){let h=await Dn(e,g,"put"),y=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(y.exitCode!==0)throw new Error(`Checkpoint upload failed: ${y.stderr}`);if(!await Tn(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=Ao();let f={id:u,hash:c,tag:a.tag,timestamp:i,sizeBytes:p,agentType:n,model:a.model,workspaceMode:a.workspaceMode,parentId:a.parentId,comment:a.comment,sandboxId:t.sandboxId};await Mo(e,Fn(e,u),f);}else {let g=await Ln(e,a.tag,c,"put");if(!g.alreadyExists){let f=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${g.url}"`,{timeoutMs:3e5});if(f.exitCode!==0)throw new Error(`Checkpoint upload failed: ${f.stderr}`)}u=(await $o(e,{tag:a.tag,hash:c,sizeBytes:p??0,agentType:n,model:a.model,workspaceMode:a.workspaceMode,parentId:a.parentId,comment:a.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:u,hash:c,tag:a.tag,timestamp:i,sizeBytes:p,agentType:n,model:a.model,workspaceMode:a.workspaceMode,parentId:a.parentId,comment:a.comment}}async function Nn(t,e,n){let s=await _t(e,n),a=s.hash,i={agentType:s.agentType,workspaceMode:s.workspaceMode},l=await Gn(e,s),r=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${l}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(r.exitCode!==0)throw new Error(`Checkpoint download failed: ${r.stderr}`);let c=r.stdout.trim().split(`
238
- `).pop()?.trim();if(c!==a)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${a}, got ${c})`);let d=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(d.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${d.stderr}`);return i}function Kn(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,s=e?.gatewayUrl||R,a=!t.url&&!t.bucket&&!!n;return Fe(t,a,s,n)}async function jn(t,e){let{s3:n}=await Q(),s=await le(t),i=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,l=[],r;do{let u={Bucket:t.bucket,Prefix:i,...r&&{ContinuationToken:r}},g=await s.send(new n.ListObjectsV2Command(u));if(g.Contents)for(let m of g.Contents)m.Key?.endsWith(".json")&&m.LastModified&&l.push({key:m.Key,lastModified:m.LastModified});r=g.IsTruncated?g.NextContinuationToken:void 0;}while(r);if(l.length===0)return [];l.sort((u,g)=>{let m=g.lastModified.getTime()-u.lastModified.getTime();return m!==0?m:g.key<u.key?-1:g.key>u.key?1:0});let d=!!e?.tag?l:e?.limit?l.slice(0,e.limit):l,p=(await Promise.all(d.map(async u=>{try{return await Un(t,u.key)}catch{return null}}))).filter(u=>u!==null);return e?.tag&&(p=p.filter(u=>u.tag===e.tag)),e?.limit&&p.length>e.limit&&(p=p.slice(0,e.limit)),p}async function Vn(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let s=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,a=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${a.status}): ${i}`)}return a.json()}function Uo(t){return t&&t>0?Math.min(t,500):100}async function bt(t,e){return t.mode==="byok"?(await jn(t,{limit:1,tag:e?.tag}))[0]??null:(await Vn(t,{limit:1,tag:e?.tag}))[0]??null}async function _t(t,e){if(t.mode==="byok"){let n=Fn(t,e);try{return await Un(t,n)}catch(s){throw Bo(s)?new Error(`Checkpoint ${e} not found`):s}}else return await Do(t,e)}async function Rn(t,e,n){if(e==="latest"){let s=await bt(t,{tag:n});if(!s)throw new Error("No checkpoints found");return s.id}return e}async function Gn(t,e){if(t.mode==="byok")return Dn(t,Bn(t,e.hash),"get");{let n=await Ln(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function Wn(t){return !(!t||re.isAbsolute(t)||t.startsWith("-")||re.normalize(t).startsWith("..")||t.includes("\0"))}function Pn(t,e){let n=re.resolve(t,e),s=re.resolve(t),a=re.relative(s,n);if(a.startsWith("..")||re.isAbsolute(a))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Bo(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function vt(t){let e=t.filter(n=>!Wn(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var zn=10*1024*1024,In=false;async function Jn(){if(!In)try{await kt("tar",["--version"]),In=!0;}catch{throw new Error("The 'tar' command is not available on this system. Storage download/extract requires tar (available on macOS, Linux, and Windows with Git Bash or WSL).")}}async function On(t,e){let n=await _t(t,e),s=await Gn(t,n),a=e.replace(/[^a-zA-Z0-9_-]/g,"_"),i=re.join(os$1.tmpdir(),`evolve-dl-${a}-${Date.now()}.tar.gz`),l=await fetch(s);if(!l.ok)throw new Error(`Checkpoint download failed (${l.status})`);if(!l.body)throw new Error("Checkpoint download returned empty body");let r=crypto.createHash("sha256"),c=A.createWriteStream(i);try{let o=l.body.getReader();await new Promise((p,u)=>{c.on("error",u),c.on("finish",p);async function g(){for(;;){let{done:m,value:f}=await o.read();if(m){c.end();break}r.update(f),c.write(f)||await new Promise(h=>c.once("drain",h));}}g().catch(u);});}catch(o){throw c.destroy(),await promises.unlink(i).catch(()=>{}),o}let d=r.digest("hex");if(d!==n.hash)throw await promises.unlink(i).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:i,metadata:n}}async function Mn(t){await Jn();let{stdout:e}=await kt("tar",["-tvzf",t],{maxBuffer:zn}),n=new Set,s=[],a=[];for(let i of e.trim().split(`
239
- `)){if(!i||i.startsWith("total "))continue;let l=i[0];if(l!=="-"&&l!=="d"&&l!=="l")throw new Error(`Archive contains unsupported entry type: "${l}"`);let r=i.match(/\d{2}:\d{2}\s+(.+)/)??i.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!r)continue;let c=r[1];if(l==="l"){let d=c.indexOf(" -> ");d!==-1&&(c=c.slice(0,d)),n.add(c);}else l==="d"?s.push(c.replace(/\/$/,"")):a.push(c);}return vt(s),vt([...n]),vt(a)}async function St(t,e,n){await Jn(),await promises.mkdir(e,{recursive:true});let s=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&s.push("--",...n),await kt("tar",s,{maxBuffer:zn});}function Fo(t){let e="^",n=0;for(;n<t.length;){let s=t[n];s==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):s==="*"?(e+="[^/]*",n++):s==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,n++):(e+=s,n++);}return e+="$",new RegExp(e)}function Et(t,e){let n=Kn(t,e);return qn(n)}function Lo(t){let e=Kn(t||{});return qn(e)}function qn(t){return {async listCheckpoints(e){let n=Uo(e?.limit);return t.mode==="byok"?jn(t,{limit:n,tag:e?.tag}):Vn(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return _t(t,e)},async downloadCheckpoint(e,n){let s=n?.extract!==false,a=n?.to||process.cwd(),i=await Rn(t,e),{tmpPath:l,metadata:r}=await On(t,i);try{if(s)return await promises.mkdir(a,{recursive:!0}),await Mn(l),await St(l,a),a;{await promises.mkdir(a,{recursive:!0});let c=re.join(a,`checkpoint-${r.id}.tar.gz`);return await promises.copyFile(l,c),c}}finally{await promises.unlink(l).catch(()=>{});}},async downloadFiles(e,n){let s=await Rn(t,e),{tmpPath:a}=await On(t,s),i;try{let l=await Mn(a),r;if(n?.files){let d=n.files.filter(p=>!Wn(p));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let o=new Set(n.files);r=l.filter(p=>o.has(p));}else if(n?.glob){let d=n.glob.map(Fo);r=l.filter(o=>d.some(p=>p.test(o)));}else r=l;if(r.length===0)return {};i=re.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`);try{await St(a,i,r);}catch(d){let o=d?.message??"";if(!o.includes("E2BIG")&&!o.includes("Argument list too long")&&!o.includes("ENAMETOOLONG"))throw d;await promises.rm(i,{recursive:!0,force:!0}).catch(()=>{}),i=re.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`),await St(a,i);}let c={};return await Promise.all(r.map(async d=>{Pn(i,d),c[d]=await promises.readFile(re.join(i,d));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(c).map(async([d,o])=>{Pn(n.to,d);let p=re.join(n.to,d);await promises.mkdir(re.dirname(p),{recursive:!0}),await promises.writeFile(p,o);}))),c}finally{i&&await promises.rm(i,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(a).catch(()=>{});}}}}function F(t){return `'${t.replace(/'/g,"'\\''")}'`}function Le(t){return typeof t=="string"&&t.length>0}function X(t,e,n){let s=t[e];if(!Le(s))throw new Error(`withPlugins() for ${n} requires ${e}`);return s}function No(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
240
- ${n}`)}function Ko(t,e){switch(t){case "droid":{let n=X(e,"marketplace",t),s=X(e,"plugin",t);return [`droid plugin marketplace add ${F(n)}`,`droid plugin install ${F(s)} --scope user`]}case "claude":{let n=X(e,"marketplace",t),s=X(e,"plugin",t);return [`claude plugin marketplace add ${F(n)} --scope user`,`claude plugin install ${F(s)} --scope user`]}case "gemini":{let n=X(e,"source",t),s=e,a=[`gemini extensions install ${F(n)}`];return Le(s.ref)&&a.push(`--ref ${F(s.ref)}`),s.autoUpdate===true&&a.push("--auto-update"),s.preRelease===true&&a.push("--pre-release"),a.push("--consent"),s.skipSettings===true&&a.push("--skip-settings"),[a.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=X(e,"marketplace",t),s=e,a=[`codex plugin marketplace add ${F(n)}`];if(Le(s.ref)&&a.push(`--ref ${F(s.ref)}`),Array.isArray(s.sparse))for(let i of s.sparse){if(!Le(i))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");a.push(`--sparse ${F(i)}`);}return [a.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function Hn(t,e,n){if(n?.length)for(let s of n){let a=Ko(t,s);for(let i of a){let l=await e.commands.run(i,{timeoutMs:12e4});if(l.exitCode!==0)throw No(i,l)}}}var jo=["actionbook","active-research","extract"],Vo=["agent-browser"],Go={actionbook:jo,"agent-browser":Vo},Qn="/home/user/.agent-browser",Yn=`${Qn}/config.json`,Xn="/home/user/.actionbook",Wo=`${Xn}/config.toml`;function Zn(t){return t==="actionbook"||t==="agent-browser"}function zo(t){return t.remote===true}function es(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(Zn(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(Zn(t.provider))return {provider:t.provider,managed:zo(t)};throw new Error("Unsupported browser configuration")}function ts(t,e){return Array.from(new Set([...e??[],...Go[t]]))}function Tt(t,e){return t==="actionbook"?{envs:{},files:[{path:Wo,data:`version = 1
236
+ `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=Nt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Kt));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let s=1;s<=_e;s++)try{let i=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(i.ok)return;if(i.status===429||i.status===401||i.status>=500){if(s===_e){console.debug(`[SessionLogger] Dashboard ${i.status} after ${s} retries, requeueing`),this.requeueEvents(e);return}await this.delay(et*s);continue}console.debug(`[SessionLogger] Dashboard ${i.status}, dropping events`);return}catch(i){s===_e?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",i),this.requeueEvents(e)):await this.delay(et*s);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Ce();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var De="COMPOSIO_API_KEY";function Cn(t){return new core.Composio({apiKey:process.env[De]})}function yt(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function Be(t,e,n){yt(t);let s=Cn(),i={};return e?.toolkits&&(i.toolkits=e.toolkits),e?.tools&&(i.tools=e.tools),e?.authConfigs&&(i.authConfigs=e.authConfigs),e?.connectedAccounts&&(i.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(i.manageConnections=e.manageConnections),await s.create(t,Object.keys(i).length>0?i:void 0)}async function Sn(t,e,n,s){yt(t);let i=Cn(),a=(await i.toolkits.get(e)).authConfigDetails?.find(c=>c.mode==="API_KEY");if(!a)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await i.connectedAccounts.initiate(t,a.name,{config:core.AuthScheme.APIKey({api_key:n})});}async function wt(t,e){if(yt(t),e?.keys)for(let[s,i]of Object.entries(e.keys))try{await Sn(t,s,i);}catch(r){throw new Error(`Failed to create API key connection for "${s}": ${r.message}`)}let n=await Be(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function xn(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function Co(){return new core.Composio({apiKey:process.env[De]})}async function kn(t,e){xn(t);let s=await(await Be(t,{manageConnections:false})).authorize(e);return {url:s.redirectUrl,connectionId:s.id}}async function _n(t,e){let n=await vt(t),s={};for(let i of n)s[i.toolkit]=i.connected;return e?s[e]??false:s}async function vt(t){return xn(t),(await Co().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(s=>({toolkit:s.toolkit.slug,connected:s.status==="ACTIVE",accountId:s.id}))}var bt={auth:kn,status:_n,connections:vt};util.promisify(child_process.exec);var kt=util.promisify(child_process.execFile),Rn=Symbol.for("evolve:awsSdkCache"),Pn=Symbol.for("evolve:s3ClientCache");var Mo=3600,Ao=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function $o(t){if(t.startsWith("s3://")){let i=t.slice(5),r=i.indexOf("/");return r===-1?{bucket:i,prefix:""}:{bucket:i.slice(0,r),prefix:i.slice(r+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,s=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:s.join("/")};if(s.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:s[0],prefix:s.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function Le(t,e,n,s){if(!t?.url&&!t?.bucket){if(!e)throw new Error("Storage requires either a URL (BYOK mode) or gateway API key. Use .withStorage({ url: 's3://bucket/prefix' }) or configure EVOLVE_API_KEY for gateway mode.");return {bucket:"",prefix:"",region:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:s}}let i=t?.bucket||"",r=t?.prefix||"",l=t?.endpoint;if(t?.url){let a=$o(t.url);i=i||a.bucket,r=r||a.prefix,l=l||a.endpoint;}if(!i)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:i,prefix:r,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:l,credentials:t?.credentials,mode:"byok"}}function In(t){if(t.includes(".."))throw new Error(`settingsDir must not contain '..': ${t}`);let e;if(t.startsWith("~/"))e=t.slice(2);else if(t.startsWith("/home/user/"))e=t.slice(11);else if(t.startsWith("."))e=t;else throw new Error(`Unexpected settingsDir: ${t}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${t}`);return e}function Do(t){if(t.includes(".."))throw new Error(`workingDir must not contain '..': ${t}`);if(!t.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${t}. Must start with /home/user/.`);let e=t.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${t}`);return e}function Ue(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Bo(t,e){let n=$(t),s=Do(e),i=n.checkpointDirs?.length?n.checkpointDirs.map(a=>In(a)):[In(n.mcpConfig.settingsDir)],r=[...Ao.map(a=>`--exclude=${Ue(a)}`),`--exclude=${Ue(s+"/temp")}`].join(" "),l=[Ue(s+"/"),...i.map(a=>Ue(a+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${r} ${l}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Q(){let t=globalThis[Rn];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[s,i]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[Rn]={s3:s,presigner:i},{s3:s,presigner:i}}catch{throw new Error("Storage requires @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner. Install: npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner")}}async function le(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,s=globalThis[Pn];if(s?.key===n)return s.client;let{s3:i}=await Q(),r=new i.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Pn]={client:r,key:n},r}async function Ln(t,e,n){let{s3:s,presigner:i}=await Q(),r=await le(t),l=n==="put"?new s.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new s.GetObjectCommand({Bucket:t.bucket,Key:e});return i.getSignedUrl(r,l,{expiresIn:Mo})}async function On(t,e){let{s3:n}=await Q(),s=await le(t);try{return await s.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(i){let r=i?.name||i?.message||"";if(i?.$metadata?.httpStatusCode===404||r==="NotFound"||r==="NoSuchKey")return false;throw i}}async function Nn(t,e){let{s3:n}=await Q(),r=await(await(await le(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!r)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(r)}async function Uo(t,e,n){let{s3:s}=await Q();await(await le(t)).send(new s.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Kn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function jn(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Fo(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Vn(t,e,n,s){let i=await fetch(`${t.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:n,action:s})});if(!i.ok){let r=await i.text().catch(()=>"");throw new Error(`Gateway presign failed (${i.status}): ${r}`)}return i.json()}async function Lo(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify(e)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${s}`)}return n.json()}async function No(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let s=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${s}`)}return n.json()}async function _t(t,e,n,s,i){let r=new Date().toISOString(),l=Bo(n,s),a=await t.commands.run(l,{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint tar failed: ${a.stderr}`);let c=a.stdout.trim().split(`
237
+ `).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);let d=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(d.stdout.trim(),10),p=Number.isNaN(o)?void 0:o,u;try{if(e.mode==="byok"){let g=Kn(e,c);if(!await On(e,g)){let h=await Ln(e,g,"put"),y=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(y.exitCode!==0)throw new Error(`Checkpoint upload failed: ${y.stderr}`);if(!await On(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=Fo();let f={id:u,hash:c,tag:i.tag,timestamp:r,sizeBytes:p,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment,sandboxId:t.sandboxId};await Uo(e,jn(e,u),f);}else {let g=await Vn(e,i.tag,c,"put");if(!g.alreadyExists){let f=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${g.url}"`,{timeoutMs:3e5});if(f.exitCode!==0)throw new Error(`Checkpoint upload failed: ${f.stderr}`)}u=(await Lo(e,{tag:i.tag,hash:c,sizeBytes:p??0,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:u,hash:c,tag:i.tag,timestamp:r,sizeBytes:p,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment}}async function Gn(t,e,n){let s=await Tt(e,n),i=s.hash,r={agentType:s.agentType,workspaceMode:s.workspaceMode},l=await qn(e,s),a=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${l}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(a.exitCode!==0)throw new Error(`Checkpoint download failed: ${a.stderr}`);let c=a.stdout.trim().split(`
238
+ `).pop()?.trim();if(c!==i)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${i}, got ${c})`);let d=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(d.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${d.stderr}`);return r}function Wn(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,s=e?.gatewayUrl||E,i=!t.url&&!t.bucket&&!!n;return Le(t,i,s,n)}async function zn(t,e){let{s3:n}=await Q(),s=await le(t),r=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,l=[],a;do{let u={Bucket:t.bucket,Prefix:r,...a&&{ContinuationToken:a}},g=await s.send(new n.ListObjectsV2Command(u));if(g.Contents)for(let m of g.Contents)m.Key?.endsWith(".json")&&m.LastModified&&l.push({key:m.Key,lastModified:m.LastModified});a=g.IsTruncated?g.NextContinuationToken:void 0;}while(a);if(l.length===0)return [];l.sort((u,g)=>{let m=g.lastModified.getTime()-u.lastModified.getTime();return m!==0?m:g.key<u.key?-1:g.key>u.key?1:0});let d=!!e?.tag?l:e?.limit?l.slice(0,e.limit):l,p=(await Promise.all(d.map(async u=>{try{return await Nn(t,u.key)}catch{return null}}))).filter(u=>u!==null);return e?.tag&&(p=p.filter(u=>u.tag===e.tag)),e?.limit&&p.length>e.limit&&(p=p.slice(0,e.limit)),p}async function Jn(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let s=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,i=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!i.ok){let r=await i.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${i.status}): ${r}`)}return i.json()}function Ko(t){return t&&t>0?Math.min(t,500):100}async function Et(t,e){return t.mode==="byok"?(await zn(t,{limit:1,tag:e?.tag}))[0]??null:(await Jn(t,{limit:1,tag:e?.tag}))[0]??null}async function Tt(t,e){if(t.mode==="byok"){let n=jn(t,e);try{return await Nn(t,n)}catch(s){throw jo(s)?new Error(`Checkpoint ${e} not found`):s}}else return await No(t,e)}async function Mn(t,e,n){if(e==="latest"){let s=await Et(t,{tag:n});if(!s)throw new Error("No checkpoints found");return s.id}return e}async function qn(t,e){if(t.mode==="byok")return Ln(t,Kn(t,e.hash),"get");{let n=await Vn(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function Hn(t){return !(!t||re.isAbsolute(t)||t.startsWith("-")||re.normalize(t).startsWith("..")||t.includes("\0"))}function An(t,e){let n=re.resolve(t,e),s=re.resolve(t),i=re.relative(s,n);if(i.startsWith("..")||re.isAbsolute(i))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function jo(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Ct(t){let e=t.filter(n=>!Hn(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var Yn=10*1024*1024,$n=false;async function Zn(){if(!$n)try{await kt("tar",["--version"]),$n=!0;}catch{throw new Error("The 'tar' command is not available on this system. Storage download/extract requires tar (available on macOS, Linux, and Windows with Git Bash or WSL).")}}async function Dn(t,e){let n=await Tt(t,e),s=await qn(t,n),i=e.replace(/[^a-zA-Z0-9_-]/g,"_"),r=re.join(os$1.tmpdir(),`evolve-dl-${i}-${Date.now()}.tar.gz`),l=await fetch(s);if(!l.ok)throw new Error(`Checkpoint download failed (${l.status})`);if(!l.body)throw new Error("Checkpoint download returned empty body");let a=crypto.createHash("sha256"),c=A.createWriteStream(r);try{let o=l.body.getReader();await new Promise((p,u)=>{c.on("error",u),c.on("finish",p);async function g(){for(;;){let{done:m,value:f}=await o.read();if(m){c.end();break}a.update(f),c.write(f)||await new Promise(h=>c.once("drain",h));}}g().catch(u);});}catch(o){throw c.destroy(),await promises.unlink(r).catch(()=>{}),o}let d=a.digest("hex");if(d!==n.hash)throw await promises.unlink(r).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:r,metadata:n}}async function Bn(t){await Zn();let{stdout:e}=await kt("tar",["-tvzf",t],{maxBuffer:Yn}),n=new Set,s=[],i=[];for(let r of e.trim().split(`
239
+ `)){if(!r||r.startsWith("total "))continue;let l=r[0];if(l!=="-"&&l!=="d"&&l!=="l")throw new Error(`Archive contains unsupported entry type: "${l}"`);let a=r.match(/\d{2}:\d{2}\s+(.+)/)??r.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!a)continue;let c=a[1];if(l==="l"){let d=c.indexOf(" -> ");d!==-1&&(c=c.slice(0,d)),n.add(c);}else l==="d"?s.push(c.replace(/\/$/,"")):i.push(c);}return Ct(s),Ct([...n]),Ct(i)}async function St(t,e,n){await Zn(),await promises.mkdir(e,{recursive:true});let s=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&s.push("--",...n),await kt("tar",s,{maxBuffer:Yn});}function Vo(t){let e="^",n=0;for(;n<t.length;){let s=t[n];s==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):s==="*"?(e+="[^/]*",n++):s==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,n++):(e+=s,n++);}return e+="$",new RegExp(e)}function Rt(t,e){let n=Wn(t,e);return Qn(n)}function Go(t){let e=Wn(t||{});return Qn(e)}function Qn(t){return {async listCheckpoints(e){let n=Ko(e?.limit);return t.mode==="byok"?zn(t,{limit:n,tag:e?.tag}):Jn(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return Tt(t,e)},async downloadCheckpoint(e,n){let s=n?.extract!==false,i=n?.to||process.cwd(),r=await Mn(t,e),{tmpPath:l,metadata:a}=await Dn(t,r);try{if(s)return await promises.mkdir(i,{recursive:!0}),await Bn(l),await St(l,i),i;{await promises.mkdir(i,{recursive:!0});let c=re.join(i,`checkpoint-${a.id}.tar.gz`);return await promises.copyFile(l,c),c}}finally{await promises.unlink(l).catch(()=>{});}},async downloadFiles(e,n){let s=await Mn(t,e),{tmpPath:i}=await Dn(t,s),r;try{let l=await Bn(i),a;if(n?.files){let d=n.files.filter(p=>!Hn(p));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let o=new Set(n.files);a=l.filter(p=>o.has(p));}else if(n?.glob){let d=n.glob.map(Vo);a=l.filter(o=>d.some(p=>p.test(o)));}else a=l;if(a.length===0)return {};r=re.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`);try{await St(i,r,a);}catch(d){let o=d?.message??"";if(!o.includes("E2BIG")&&!o.includes("Argument list too long")&&!o.includes("ENAMETOOLONG"))throw d;await promises.rm(r,{recursive:!0,force:!0}).catch(()=>{}),r=re.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`),await St(i,r);}let c={};return await Promise.all(a.map(async d=>{An(r,d),c[d]=await promises.readFile(re.join(r,d));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(c).map(async([d,o])=>{An(n.to,d);let p=re.join(n.to,d);await promises.mkdir(re.dirname(p),{recursive:!0}),await promises.writeFile(p,o);}))),c}finally{r&&await promises.rm(r,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(i).catch(()=>{});}}}}function F(t){return `'${t.replace(/'/g,"'\\''")}'`}function Ne(t){return typeof t=="string"&&t.length>0}function X(t,e,n){let s=t[e];if(!Ne(s))throw new Error(`withPlugins() for ${n} requires ${e}`);return s}function Wo(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
240
+ ${n}`)}function zo(t,e){switch(t){case "droid":{let n=X(e,"marketplace",t),s=X(e,"plugin",t);return [`droid plugin marketplace add ${F(n)}`,`droid plugin install ${F(s)} --scope user`]}case "claude":{let n=X(e,"marketplace",t),s=X(e,"plugin",t);return [`claude plugin marketplace add ${F(n)} --scope user`,`claude plugin install ${F(s)} --scope user`]}case "gemini":{let n=X(e,"source",t),s=e,i=[`gemini extensions install ${F(n)}`];return Ne(s.ref)&&i.push(`--ref ${F(s.ref)}`),s.autoUpdate===true&&i.push("--auto-update"),s.preRelease===true&&i.push("--pre-release"),i.push("--consent"),s.skipSettings===true&&i.push("--skip-settings"),[i.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=X(e,"marketplace",t),s=e,i=[`codex plugin marketplace add ${F(n)}`];if(Ne(s.ref)&&i.push(`--ref ${F(s.ref)}`),Array.isArray(s.sparse))for(let r of s.sparse){if(!Ne(r))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");i.push(`--sparse ${F(r)}`);}return [i.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function Xn(t,e,n){if(n?.length)for(let s of n){let i=zo(t,s);for(let r of i){let l=await e.commands.run(r,{timeoutMs:12e4});if(l.exitCode!==0)throw Wo(r,l)}}}var Jo=["actionbook","active-research","extract"],qo=["agent-browser"],Ho={actionbook:Jo,"agent-browser":qo},ns="/home/user/.agent-browser",es=`${ns}/config.json`,ss="/home/user/.actionbook",Yo=`${ss}/config.toml`;function ts(t){return t==="actionbook"||t==="agent-browser"}function Zo(t){return t.remote===true}function os(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(ts(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(ts(t.provider))return {provider:t.provider,managed:Zo(t)};throw new Error("Unsupported browser configuration")}function is(t,e){return Array.from(new Set([...e??[],...Ho[t]]))}function Pt(t,e){return t==="actionbook"?{envs:{},files:[{path:Yo,data:`version = 1
241
241
 
242
242
  [browser]
243
243
  mode = "cloud"
244
244
  cdp_endpoint = ${JSON.stringify(e.cdpUrl)}
245
- `}],directories:[Xn]}:{envs:{AGENT_BROWSER_CONFIG:Yn},files:[{path:Yn,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
246
- `}],directories:[Qn]}}function ns(t){return (t?.dashboardUrl||R).replace(/\/$/,"")}async function ss(t){return await t.text().catch(()=>"")}async function os(t,e){let n=await fetch(`${ns(t)}/api/browser-sessions`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({sessionTag:e,options:{remote:true}}),signal:AbortSignal.timeout(3e4)});if(!n.ok)throw new Error(`Managed browser session create failed (${n.status}): ${await ss(n)}`);let s=await n.json();if(!s.id||!s.sessionId||!s.cdpUrl||!s.liveUrl)throw new Error("Managed browser session response missing id, sessionId, cdpUrl, or liveUrl");return {id:s.id,sessionId:s.sessionId,sessionTag:s.sessionTag,cdpUrl:s.cdpUrl,liveUrl:s.liveUrl}}async function is(t,e){let n=await fetch(`${ns(t)}/api/browser-sessions/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!n.ok&&n.status!==404)throw new Error(`Managed browser session stop failed (${n.status}): ${await ss(n)}`)}var rs="/home/user/.factory/evolve-session.json";function Yo(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function as(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function cs(t,e,n="newline"){let s=new Map;if(t){let a=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let i of a){let l=i.trim();if(!l)continue;let r=l.indexOf(":");if(r<=0)continue;let c=l.slice(0,r).trim(),d=l.slice(r+1).trim();s.set(c.toLowerCase(),`${c}: ${d}`);}}for(let[a,i]of Object.entries(e)){let l=a.toLowerCase();if(l===U&&s.has(l)&&n==="newline"){let r=s.get(l),c=r.slice(r.indexOf(":")+1).trim();s.set(l,`${a}: ${c},${i}`);}else s.set(l,`${a}: ${i}`);}return Array.from(s.values()).join(n==="comma"?", ":`
247
- `)}var de=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||$t,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,this.storage=n.storage,n.schema)if(M(n.schema))this.zodSchema=n.schema,n.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=n.schema,this.schemaOptions=n.schemaOptions;try{let s=this.createAjvValidator();this.compiledValidator=s.compile(this.jsonSchema);}catch(s){throw new Error(`Invalid JSON Schema: ${s.message}`)}}this.registry=$(e.type),this.sessionTag=as(n.sessionTagPrefix||"evolve");}browserRuntimeInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl,sessionId:this.managedBrowserSession.sessionId,sessionTag:this.managedBrowserSession.sessionTag}}browserResponseInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl}}emitLifecycle(e,n){let s=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...s?{browser:s}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,s,a){let i=++this.nextOperationId;return this.activeOperationId=i,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(s,a),i}finalizeOperation(e,n,s,a="idle",i="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=i,this.agentState=a,this.emitLifecycle(n,s),true)}watchBackgroundOperation(e,n,s,a,i){let l=n==="run"?"run_background_complete":"command_background_complete",r=n==="run"?"run_background_failed":"command_background_failed",c=n==="run"?"run_interrupted":"command_interrupted";s.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,a,c,"interrupted");return}n==="run"&&i&&await this.writeDroidSessionState(i);let p=d.exitCode===0?l:r,u=d.exitCode===0?"idle":"error";this.finalizeOperation(e,a,p,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,a,r,"error");});}createAjvValidator(){let n={...je[this.schemaOptions?.mode||"loose"],...this.schemaOptions?.coerceTypes!==void 0&&{coerceTypes:this.schemaOptions.coerceTypes},...this.schemaOptions?.removeAdditional!==void 0&&{removeAdditional:this.schemaOptions.removeAdditional},...this.schemaOptions?.useDefaults!==void 0&&{useDefaults:this.schemaOptions.useDefaults},...this.schemaOptions?.allErrors!==void 0&&{allErrors:this.schemaOptions.allErrors}};return new Jo__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, plugins, context, files, systemPrompt, and managed browser setup"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,await this.loadDroidSessionState(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {await this.ensureManagedBrowserSession(e);let s=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:s,workingDirectory:this.workingDir}),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(s){throw await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let n of Object.values(this.registry.providerEnvMap))e[n.keyEnv]=this.agentConfig.apiKey;else {let n=this.agentConfig.model?.split("/")[0],s=n?this.registry.providerEnvMap?.[n]:void 0,a=s?s.keyEnv:this.registry.apiKeyEnv,i=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:a;e[i]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=q(this.registry.gatewayPath);this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[I]:this.sessionTag}):this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=n),e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Tt(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.options.secrets&&Object.assign(e,this.options.secrets),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let n=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";e[n]=cs(e[n],{[I]:this.sessionTag},s);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await os(this.options.managedBrowser,this.sessionTag),this.emitLifecycle(e,"browser_ready"));}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Tt(this.options.managedBrowser.provider,this.managedBrowserSession);for(let s of n.directories)await e.files.makeDir(s);for(let s of n.files)await e.files.write(s.path,s.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await is(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}buildGatewayConfigJson(e){let n=q(this.registry.gatewayPath),s=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),a={},i=this.options.secrets?.[this.registry.gatewayConfigEnv];if(i)try{a=JSON.parse(i);}catch{}let l=a.provider??{},r=l.litellm??{},c=r.options??{},d=r.models??{},o=d[s]??{},p=o.headers??{};return a.provider={...l,litellm:{...r,npm:"@ai-sdk/openai-compatible",options:{...c,baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{...d,[s]:{...o,name:s,headers:{...p,...e}}}}},JSON.stringify(a)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.registry.customHeadersEnv;if(n){let a=this.options.secrets?.[n],i=this.registry.customHeadersFormat||"newline";return {[n]:cs(a,{[I]:this.sessionTag,[U]:`${G}${e}`},i)}}let s=this.registry.spendTrackingEnvs;if(s)return {[s.sessionTagEnv]:this.sessionTag,[s.runTagEnv]:`${G}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[I]:this.sessionTag,[U]:`${G}${e}`})}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let s=n?.find(i=>typeof i.sessionId=="string"&&i.sessionId.length>0)?.sessionId;if(s){this.droidSessionId=s;return}let a=this.extractDroidSessionId(e);a&&(this.droidSessionId=a);}extractDroidSessionId(e){try{return this.findDroidSessionId(JSON.parse(e))}catch{return}}findDroidSessionId(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,s=n.sessionId??n.session_id;return typeof s=="string"&&s.length>0?s:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(rs);if(typeof n!="string")return;let s=JSON.parse(n);typeof s.sessionId=="string"&&s.sessionId.length>0&&(this.droidSessionId=s.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir("/home/user/.factory"),await e.files.write(rs,JSON.stringify({sessionId:this.droidSessionId},null,2)));}resolveGatewayModel(e){return this.agentConfig.isDirectMode?e:this.registry.gatewayModelAliases?.[e]??e}resolveCommandModel(e){return (this.agentConfig.isDirectMode?this.registry.directModelAliases:this.registry.gatewayModelAliases)?.[e]??e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupAgentPlugins(e){await Hn(this.agentConfig.type,e,this.options.plugins);}async setupWorkspace(e,n){let s=this.options.workspaceMode||"knowledge",a=s==="swe"?`${this.workingDir}/repo ${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`:`${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`;if(await e.commands.run(`mkdir -p ${a}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let l=mt({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:s}),r=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(r,l);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let i={...this.options.mcpServers};if(this.options.composio){let l=await ht(this.options.composio.userId,this.options.composio.config);i={...i,composio:{type:"http",url:l.url,headers:l.headers}};}Object.keys(i).length>0&&await tt(this.agentConfig.type,e,this.workingDir,i),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await Xe(e,this.agentConfig.baseUrl||q(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ye(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[I]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:s,targetDir:a}=n;await e.files.makeDir(a);for(let i of this.skills){let l=`cp -r ${s}/${i} ${a}/ 2>/dev/null || true`;await e.commands.run(l,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let s=Object.entries(n).map(([i,l])=>({path:`${this.workingDir}/context/${i}`,data:l}));if(s.length===0)return;let a=new Set(s.map(i=>i.path.substring(0,i.path.lastIndexOf("/"))).filter(Boolean));a.size>0&&await e.commands.run(`mkdir -p ${Array.from(a).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}async uploadWorkspaceFiles(e,n){let s=Object.entries(n).map(([i,l])=>({path:i.startsWith("/")?i:`${this.workingDir}/${i}`,data:l}));if(s.length===0)return;let a=new Set(s.map(i=>i.path.substring(0,i.path.lastIndexOf("/"))).filter(Boolean));a.size>0&&await e.commands.run(`mkdir -p ${Array.from(a).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:Yo(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.agentConfig.reasoningEffort,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,n){let{prompt:s,timeoutMs:a=oe,background:i=false,checkpointComment:l}=e,{from:r}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(r&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(r==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await bt(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');r=v.id;}if(r){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");await this.ensureManagedBrowserSession(n);let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir});let S=await Nn(this.sandbox,this.storage,r);if(await this.setupManagedBrowser(this.sandbox),S.agentType&&S.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${S.agentType}, current: ${this.agentConfig.type})`);let b=this.options.workspaceMode||"knowledge";if(S.workspaceMode&&S.workspaceMode!==b)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${S.workspaceMode}, current: ${b})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let _=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!_}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=r,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(S){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),S}}let c=await this.getSandbox(n);if(await this.loadDroidSessionState(c),this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new ae({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:c.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}this.sessionLogger.writePrompt(s);let d=this.buildCommand(s),o=crypto.randomUUID(),p=this.buildRunEnvs(o);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ye(c,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[I]:this.sessionTag,[U]:`${G}${o}`}),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await et(c,this.registry.spendTrackingTomlProvider,{[I]:this.sessionTag,[U]:`${G}${o}`}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await ve(c,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${q()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[I]:this.sessionTag,[U]:`${G}${o}`});let u="",g=W(this.agentConfig.type),m=v=>{u+=v;let S=u.split(`
248
- `);u=S.pop()??"";for(let b of S){if(!b.trim())continue;let _=g(b);if(this.captureDroidSession(b,_),this.sessionLogger?.writeEventParsed(b,_),n?.onStdout?.(b+`
249
- `),_&&n?.onContent)for(let L of _)n.onContent(L);}},f=v=>{n?.onStderr?.(v);},h=await c.commands.spawn(d,{cwd:this.workingDir,timeoutMs:a,envs:p,onStdout:m,onStderr:f}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,i)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:0,stdout:`Background process started with ID ${h.processId}`,stderr:""};let w;try{w=await h.wait();}catch(v){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n,"run_failed","error"),v}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,n,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,n,"run_complete","idle"):this.finalizeOperation(y,n,"run_failed","error"),u.trim()){let v=g(u);if(this.captureDroidSession(u,v),this.sessionLogger?.writeEventParsed(u,v),n?.onStdout?.(u+`
250
- `),v&&n?.onContent)for(let S of v)n.onContent(S);}await this.writeDroidSessionState(c),this.sessionLogger&&!i&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let x;if(this.storage&&!i&&w.exitCode===0)try{x=await Ct(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:l,parentId:this.lastCheckpointId}),this.lastCheckpointId=x.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:x}}async executeCommand(e,n={},s){let{timeoutMs:a=oe,background:i=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let l=await this.getSandbox(s);this.lastRunTimestamp=Date.now();let r="",c="",d=f=>{r+=f,s?.onStdout?.(f);},o=f=>{c+=f,s?.onStderr?.(f);},p=await l.commands.spawn(e,{cwd:this.workingDir,timeoutMs:a,onStdout:d,onStderr:o}),u=this.beginOperation("command",p,s,"command_start");if(i)return this.watchBackgroundOperation(u,"command",p,s),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let g;try{g=await p.wait();}catch(f){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,s,"command_failed","error"),f}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,s,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,s,"command_complete","idle"):this.finalizeOperation(u,s,"command_failed","error"),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:g.exitCode,stdout:r||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),s=`${this.workingDir}/output`,a=e?"":"-maxdepth 1",l=(await n.commands.run(`find ${s} ${a} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
251
- `).filter(Boolean),r=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${s}/`;for(let m of l){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);r>0&&y<r||c.push(f);}let o={},p=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(d)?m.slice(d.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of p)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await Ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=n.id,n}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,s=this.activeOperationKind,a=false;try{this.activeCommand?a=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(a=await this.sandbox.commands.kill(this.activeProcessId));}catch{a=false;}if(!a)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let i=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,i),a}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(s){n=s;}finally{await this.closeManagedBrowserSession();}if(n)throw n;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=false,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed");}async getHost(e){return (await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return !this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=as(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let n=this.agentConfig.apiKey;if(!n)throw new Error("Cost tracking requires an API key.");let s=process.env.EVOLVE_DASHBOARD_URL||R,a=await fetch(`${s}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Spend query failed (${a.status}): ${i}`)}return a}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,n){return {...e,asOf:e.asOf??n.asOf,isComplete:e.isComplete??n.isComplete,truncated:e.truncated??n.truncated}}normalizeSessionCost(e){let n={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(s=>this.normalizeRunCost(s,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),a=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(a)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let s=await this.getSessionCost(),a=e.index>0?e.index-1:s.runs.length+e.index,i=s.runs[a];if(!i)throw new Error(`Run index ${e.index} out of range. Session has ${s.runs.length} run(s).`);return i}};var pe=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"actionbook",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}withStorage(e){return this.config.storage=e||{},this}static composio=wt;async initializeAgent(){let e=Me(this.config.agent),n=this.config.sandbox??await lt(),s={},a,i,l=this.config.skills;if(this.config.browser){let d=es(this.config.browser);if(d.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');s=Ot(e.apiKey);}if((d.provider==="actionbook"||d.provider==="agent-browser")&&(l=ts(d.provider,l),d.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);a=d.provider==="actionbook"?dt:pn,i={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||R};}}let r=this.config.storage!==void 0?Fe(this.config.storage,!e.isDirectMode,R,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s,...this.config.mcpServers},browserPrompt:a,managedBrowser:i,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:r};this.agent=new de(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,a=this.listenerCount("lifecycle")>0;return {onStdout:e?i=>this.emit("stdout",i):void 0,onStderr:n?i=>this.emit("stderr",i):void 0,onContent:s?i=>this.emit("content",i):void 0,onLifecycle:a?i=>this.emit("lifecycle",i):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let n=this.status();this.emit("lifecycle",{sandboxId:n.sandboxId,sandbox:n.sandbox,agent:n.agent,timestamp:new Date().toISOString(),reason:e,...n.browser?{browser:n.browser}:{}});}async run({prompt:e,timeoutMs:n,background:s,from:a,checkpointComment:i}){if(a&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s,from:a,checkpointComment:i},l)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Me(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:R,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Et(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Et(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var ee=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e;}async use(e){await this.acquire();try{return await e()}finally{this.release();}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++;}};var z=Symbol.for("evolve.SwarmResult"),te=class t extends Array{get success(){return this.filter(e=>e.status==="success")}get filtered(){return this.filter(e=>e.status==="filtered")}get error(){return this.filter(e=>e.status==="error")}static from(e){let n=new t;return n.push(...e),n}};var Rt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??At;if(n>Ze)throw new Error(`concurrency=${n} exceeds max ${Ze}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:n,timeoutMs:e.timeoutMs??oe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,p)=>a?this.executeMapItemWithBestOf(o,s,p,r,e,c,l):i?this.executeMapItemWithVerify(o,s,p,r,e,c,l):l?P(u=>this.executeMapItem(o,s,p,r,e,c,u),l,p):this.executeMapItem(o,s,p,r,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:s,condition:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>i?this.executeFilterItemWithVerify(p,s,u,r,e,c,l):l?P(g=>this.executeFilterItem(p,s,u,r,e,c,g),l,u):this.executeFilterItem(p,s,u,r,e,c))),o=[];for(let p of d)if(p.status==="error")o.push(p);else if(p.data!==null)try{a(p.data)?o.push(p):o.push({...p,status:"filtered"});}catch(u){o.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:s,verify:a}=e,i=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((x,v)=>{c.push(this.getFiles(x)),d.push(this.getIndex(x,v));});let o={};c.forEach((x,v)=>{Object.entries(x).forEach(([S,b])=>{o[`item_${d[v]}/${S}`]=b;});});let p=Ae(o),u=B(mn,{fileTree:p}),g=e.systemPrompt?`${u}
245
+ `}],directories:[ss]}:{envs:{AGENT_BROWSER_CONFIG:es},files:[{path:es,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
246
+ `}],directories:[ns]}}function rs(t){return (t?.dashboardUrl||E).replace(/\/$/,"")}async function as(t){return await t.text().catch(()=>"")}async function cs(t,e,n={}){let s=await fetch(`${rs(t)}/api/browser-sessions`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({sessionTag:e,options:{remote:true},browserAuth:n.browserCredentials===true}),signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Managed browser session create failed (${s.status}): ${await as(s)}`);let i=await s.json();if(!i.id||!i.sessionId||!i.cdpUrl||!i.liveUrl)throw new Error("Managed browser session response missing id, sessionId, cdpUrl, or liveUrl");return {id:i.id,sessionId:i.sessionId,sessionTag:i.sessionTag,cdpUrl:i.cdpUrl,liveUrl:i.liveUrl,browserAuthGrantToken:i.browserAuthGrantToken}}async function ls(t,e){let n=await fetch(`${rs(t)}/api/browser-sessions/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!n.ok&&n.status!==404)throw new Error(`Managed browser session stop failed (${n.status}): ${await as(n)}`)}var ei="RSA-OAEP-256",It="browser-login";function ti(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function ni(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser credentials require EVOLVE_API_KEY or an explicit apiKey");return e}async function si(t){return await t.text().catch(()=>"")}async function de(t,e,n={}){let s=await fetch(`${ti(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${ni(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!s.ok)throw new Error(`Browser credentials request failed (${s.status}): ${await si(s)}`);return await s.json()}async function oi(t,e){let n=await de(t,"/api/browser-credentials/public-key"),s=crypto.publicEncrypt({key:n.publicKey,padding:crypto.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"utf8"));return {algorithm:ei,keyId:n.id,ciphertext:s.toString("base64url")}}var Ke=class{constructor(e={}){this.config=e;}toMetadata(e){let{account_label:n,...s}=e;return {...s,accountLabel:n}}async list(e={}){let n=new URLSearchParams;e.website&&n.set("website",e.website),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let s=n.toString()?`?${n.toString()}`:"",i=await de(this.config,`/api/browser-credentials${s}`);return {credentials:i.credentials.map(r=>this.toMetadata(r)),total:i.total,count:i.count,offset:i.offset,hasMore:i.has_more??i.offset+i.count<i.total}}async create(e){let n=await oi(this.config,e.password),s=await de(this.config,"/api/browser-credentials",{method:"POST",body:JSON.stringify({website:e.website,account_label:e.accountLabel,email:e.email,encryptedPassword:n})});return {status:s.status,credential:this.toMetadata(s.credential)}}async delete(e){let n="id"in e?e:{website:e.website,account_label:e.accountLabel};return await de(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function Ot(t={}){return new Ke(t)}async function ds(t){return (await de({apiKey:t.apiKey,dashboardUrl:t.dashboardUrl},"/api/browser-login/mcp-config",{method:"POST",body:JSON.stringify({browserSessionId:t.browserSessionId,sessionTag:t.sessionTag,grantToken:t.grantToken,allow:ii(t.config)})})).server}function ii(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var ps="/home/user/.factory/evolve-session.json";function li(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function us(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function gs(t,e,n="newline"){let s=new Map;if(t){let i=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let r of i){let l=r.trim();if(!l)continue;let a=l.indexOf(":");if(a<=0)continue;let c=l.slice(0,a).trim(),d=l.slice(a+1).trim();s.set(c.toLowerCase(),`${c}: ${d}`);}}for(let[i,r]of Object.entries(e)){let l=i.toLowerCase();if(l===B&&s.has(l)&&n==="newline"){let a=s.get(l),c=a.slice(a.indexOf(":")+1).trim();s.set(l,`${i}: ${c},${r}`);}else s.set(l,`${i}: ${r}`);}return Array.from(s.values()).join(n==="comma"?", ":`
247
+ `)}var pe=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||Ft,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,this.storage=n.storage,n.schema)if(M(n.schema))this.zodSchema=n.schema,n.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=n.schema,this.schemaOptions=n.schemaOptions;try{let s=this.createAjvValidator();this.compiledValidator=s.compile(this.jsonSchema);}catch(s){throw new Error(`Invalid JSON Schema: ${s.message}`)}}this.registry=$(e.type),this.sessionTag=us(n.sessionTagPrefix||"evolve");}browserRuntimeInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl,sessionId:this.managedBrowserSession.sessionId,sessionTag:this.managedBrowserSession.sessionTag}}browserResponseInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl}}emitLifecycle(e,n){let s=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...s?{browser:s}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,s,i){let r=++this.nextOperationId;return this.activeOperationId=r,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(s,i),r}finalizeOperation(e,n,s,i="idle",r="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=r,this.agentState=i,this.emitLifecycle(n,s),true)}watchBackgroundOperation(e,n,s,i,r){let l=n==="run"?"run_background_complete":"command_background_complete",a=n==="run"?"run_background_failed":"command_background_failed",c=n==="run"?"run_interrupted":"command_interrupted";s.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,i,c,"interrupted");return}n==="run"&&r&&await this.writeDroidSessionState(r);let p=d.exitCode===0?l:a,u=d.exitCode===0?"idle":"error";this.finalizeOperation(e,i,p,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,i,a,"error");});}createAjvValidator(){let n={...Ge[this.schemaOptions?.mode||"loose"],...this.schemaOptions?.coerceTypes!==void 0&&{coerceTypes:this.schemaOptions.coerceTypes},...this.schemaOptions?.removeAdditional!==void 0&&{removeAdditional:this.schemaOptions.removeAdditional},...this.schemaOptions?.useDefaults!==void 0&&{useDefaults:this.schemaOptions.useDefaults},...this.schemaOptions?.allErrors!==void 0&&{allErrors:this.schemaOptions.allErrors}};return new ri__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser||this.options.browserCredentials)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, plugins, context, files, systemPrompt, managed browser setup, and browser credentials"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,await this.loadDroidSessionState(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {await this.ensureManagedBrowserSession(e);let s=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:s,workingDirectory:this.workingDir}),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(s){throw await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let n of Object.values(this.registry.providerEnvMap))e[n.keyEnv]=this.agentConfig.apiKey;else {let n=this.agentConfig.model?.split("/")[0],s=n?this.registry.providerEnvMap?.[n]:void 0,i=s?s.keyEnv:this.registry.apiKeyEnv,r=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:i;e[r]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=q(this.registry.gatewayPath);this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[I]:this.sessionTag}):this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=n),e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Pt(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.options.secrets&&Object.assign(e,this.options.secrets),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let n=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";e[n]=gs(e[n],{[I]:this.sessionTag},s);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await cs(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Pt(this.options.managedBrowser.provider,this.managedBrowserSession);for(let s of n.directories)await e.files.makeDir(s);for(let s of n.files)await e.files.write(s.path,s.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await ls(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}buildGatewayConfigJson(e){let n=q(this.registry.gatewayPath),s=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),i={},r=this.options.secrets?.[this.registry.gatewayConfigEnv];if(r)try{i=JSON.parse(r);}catch{}let l=i.provider??{},a=l.litellm??{},c=a.options??{},d=a.models??{},o=d[s]??{},p=o.headers??{};return i.provider={...l,litellm:{...a,npm:"@ai-sdk/openai-compatible",options:{...c,baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{...d,[s]:{...o,name:s,headers:{...p,...e}}}}},JSON.stringify(i)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.registry.customHeadersEnv;if(n){let i=this.options.secrets?.[n],r=this.registry.customHeadersFormat||"newline";return {[n]:gs(i,{[I]:this.sessionTag,[B]:`${G}${e}`},r)}}let s=this.registry.spendTrackingEnvs;if(s)return {[s.sessionTagEnv]:this.sessionTag,[s.runTagEnv]:`${G}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[I]:this.sessionTag,[B]:`${G}${e}`})}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let s=n?.find(r=>typeof r.sessionId=="string"&&r.sessionId.length>0)?.sessionId;if(s){this.droidSessionId=s;return}let i=this.extractDroidSessionId(e);i&&(this.droidSessionId=i);}extractDroidSessionId(e){try{return this.findDroidSessionId(JSON.parse(e))}catch{return}}findDroidSessionId(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,s=n.sessionId??n.session_id;return typeof s=="string"&&s.length>0?s:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(ps);if(typeof n!="string")return;let s=JSON.parse(n);typeof s.sessionId=="string"&&s.sessionId.length>0&&(this.droidSessionId=s.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir("/home/user/.factory"),await e.files.write(ps,JSON.stringify({sessionId:this.droidSessionId},null,2)));}resolveGatewayModel(e){return this.agentConfig.isDirectMode?e:this.registry.gatewayModelAliases?.[e]??e}resolveCommandModel(e){return (this.agentConfig.isDirectMode?this.registry.directModelAliases:this.registry.gatewayModelAliases)?.[e]??e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupAgentPlugins(e){await Xn(this.agentConfig.type,e,this.options.plugins);}async setupWorkspace(e,n){let s=this.options.workspaceMode||"knowledge",i=s==="swe"?`${this.workingDir}/repo ${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`:`${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`;if(await e.commands.run(`mkdir -p ${i}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let l=ht({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:s}),a=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(a,l);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let r={...this.options.mcpServers};if(this.options.composio){let l=await wt(this.options.composio.userId,this.options.composio.config);r={...r,composio:{type:"http",url:l.url,headers:l.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let l=await ds({apiKey:this.options.browserCredentials.apiKey,dashboardUrl:this.options.browserCredentials.dashboardUrl,browserSessionId:this.managedBrowserSession.id,sessionTag:this.managedBrowserSession.sessionTag,grantToken:this.managedBrowserSession.browserAuthGrantToken,config:this.options.browserCredentials.config});r={...r,[It]:l};}Object.keys(r).length>0&&await st(this.agentConfig.type,e,this.workingDir,r),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await tt(e,this.agentConfig.baseUrl||q(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await we(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[I]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:s,targetDir:i}=n;await e.files.makeDir(i);for(let r of this.skills){let l=`cp -r ${s}/${r} ${i}/ 2>/dev/null || true`;await e.commands.run(l,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let s=Object.entries(n).map(([r,l])=>({path:`${this.workingDir}/context/${r}`,data:l}));if(s.length===0)return;let i=new Set(s.map(r=>r.path.substring(0,r.path.lastIndexOf("/"))).filter(Boolean));i.size>0&&await e.commands.run(`mkdir -p ${Array.from(i).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}async uploadWorkspaceFiles(e,n){let s=Object.entries(n).map(([r,l])=>({path:r.startsWith("/")?r:`${this.workingDir}/${r}`,data:l}));if(s.length===0)return;let i=new Set(s.map(r=>r.path.substring(0,r.path.lastIndexOf("/"))).filter(Boolean));i.size>0&&await e.commands.run(`mkdir -p ${Array.from(i).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:li(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.agentConfig.reasoningEffort,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,n){let{prompt:s,timeoutMs:i=oe,background:r=false,checkpointComment:l}=e,{from:a}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(a&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(a==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await Et(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');a=v.id;}if(a){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");await this.ensureManagedBrowserSession(n);let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir});let b=await Gn(this.sandbox,this.storage,a);if(await this.setupManagedBrowser(this.sandbox),b.agentType&&b.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${b.agentType}, current: ${this.agentConfig.type})`);let k=this.options.workspaceMode||"knowledge";if(b.workspaceMode&&b.workspaceMode!==k)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${b.workspaceMode}, current: ${k})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let _=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!_}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=a,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(b){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),b}}let c=await this.getSandbox(n);if(await this.loadDroidSessionState(c),this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new ae({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:c.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}this.sessionLogger.writePrompt(s);let d=this.buildCommand(s),o=crypto.randomUUID(),p=this.buildRunEnvs(o);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await we(c,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[I]:this.sessionTag,[B]:`${G}${o}`}),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await nt(c,this.registry.spendTrackingTomlProvider,{[I]:this.sessionTag,[B]:`${G}${o}`}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await be(c,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${q()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[I]:this.sessionTag,[B]:`${G}${o}`});let u="",g=W(this.agentConfig.type),m=v=>{u+=v;let b=u.split(`
248
+ `);u=b.pop()??"";for(let k of b){if(!k.trim())continue;let _=g(k);if(this.captureDroidSession(k,_),this.sessionLogger?.writeEventParsed(k,_),n?.onStdout?.(k+`
249
+ `),_&&n?.onContent)for(let L of _)n.onContent(L);}},f=v=>{n?.onStderr?.(v);},h=await c.commands.spawn(d,{cwd:this.workingDir,timeoutMs:i,envs:p,onStdout:m,onStderr:f}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,r)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:0,stdout:`Background process started with ID ${h.processId}`,stderr:""};let w;try{w=await h.wait();}catch(v){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n,"run_failed","error"),v}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,n,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,n,"run_complete","idle"):this.finalizeOperation(y,n,"run_failed","error"),u.trim()){let v=g(u);if(this.captureDroidSession(u,v),this.sessionLogger?.writeEventParsed(u,v),n?.onStdout?.(u+`
250
+ `),v&&n?.onContent)for(let b of v)n.onContent(b);}await this.writeDroidSessionState(c),this.sessionLogger&&!r&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let C;if(this.storage&&!r&&w.exitCode===0)try{C=await _t(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:l,parentId:this.lastCheckpointId}),this.lastCheckpointId=C.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:C}}async executeCommand(e,n={},s){let{timeoutMs:i=oe,background:r=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let l=await this.getSandbox(s);this.lastRunTimestamp=Date.now();let a="",c="",d=f=>{a+=f,s?.onStdout?.(f);},o=f=>{c+=f,s?.onStderr?.(f);},p=await l.commands.spawn(e,{cwd:this.workingDir,timeoutMs:i,onStdout:d,onStderr:o}),u=this.beginOperation("command",p,s,"command_start");if(r)return this.watchBackgroundOperation(u,"command",p,s),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let g;try{g=await p.wait();}catch(f){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,s,"command_failed","error"),f}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,s,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,s,"command_complete","idle"):this.finalizeOperation(u,s,"command_failed","error"),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:g.exitCode,stdout:a||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),s=`${this.workingDir}/output`,i=e?"":"-maxdepth 1",l=(await n.commands.run(`find ${s} ${i} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
251
+ `).filter(Boolean),a=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${s}/`;for(let m of l){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);a>0&&y<a||c.push(f);}let o={},p=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(d)?m.slice(d.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of p)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await _t(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=n.id,n}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,s=this.activeOperationKind,i=false;try{this.activeCommand?i=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(i=await this.sandbox.commands.kill(this.activeProcessId));}catch{i=false;}if(!i)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let r=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,r),i}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(s){n=s;}finally{await this.closeManagedBrowserSession();}if(n)throw n;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=false,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed");}async getHost(e){return (await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return !this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=us(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let n=this.agentConfig.apiKey;if(!n)throw new Error("Cost tracking requires an API key.");let s=process.env.EVOLVE_DASHBOARD_URL||E,i=await fetch(`${s}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!i.ok){let r=await i.text().catch(()=>"");throw new Error(`Spend query failed (${i.status}): ${r}`)}return i}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,n){return {...e,asOf:e.asOf??n.asOf,isComplete:e.isComplete??n.isComplete,truncated:e.truncated??n.truncated}}normalizeSessionCost(e){let n={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(s=>this.normalizeRunCost(s,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),i=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(i)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let s=await this.getSessionCost(),i=e.index>0?e.index-1:s.runs.length+e.index,r=s.runs[i];if(!r)throw new Error(`Run index ${e.index} out of range. Session has ${s.runs.length} run(s).`);return r}};var ue=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}withStorage(e){return this.config.storage=e||{},this}static composio=bt;static browserCredentials=Ot;async initializeAgent(){let e=Ae(this.config.agent),n=this.config.sandbox??await pt(),s={},i,r,l=this.config.skills,a;if(this.config.browser){let o=os(this.config.browser);if(a=o,o.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');s=Dt(e.apiKey);}if((o.provider==="actionbook"||o.provider==="agent-browser")&&(l=is(o.provider,l),o.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${o.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);i=o.provider==="actionbook"?ut:fn,r={provider:o.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E};}}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!a||a.provider!=="agent-browser"||!a.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let c=this.config.storage!==void 0?Le(this.config.storage,!e.isDirectMode,E,e.isDirectMode?void 0:e.apiKey):void 0,d={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s,...this.config.mcpServers},browserPrompt:i,managedBrowser:r,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:c};this.agent=new pe(e,d);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,i=this.listenerCount("lifecycle")>0;return {onStdout:e?r=>this.emit("stdout",r):void 0,onStderr:n?r=>this.emit("stderr",r):void 0,onContent:s?r=>this.emit("content",r):void 0,onLifecycle:i?r=>this.emit("lifecycle",r):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let n=this.status();this.emit("lifecycle",{sandboxId:n.sandboxId,sandbox:n.sandbox,agent:n.agent,timestamp:new Date().toISOString(),reason:e,...n.browser?{browser:n.browser}:{}});}async run({prompt:e,timeoutMs:n,background:s,from:i,checkpointComment:r}){if(i&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s,from:i,checkpointComment:r},l)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Ae(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:E,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Rt(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Rt(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var ee=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e;}async use(e){await this.acquire();try{return await e()}finally{this.release();}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++;}};var z=Symbol.for("evolve.SwarmResult"),te=class t extends Array{get success(){return this.filter(e=>e.status==="success")}get filtered(){return this.filter(e=>e.status==="filtered")}get error(){return this.filter(e=>e.status==="error")}static from(e){let n=new t;return n.push(...e),n}};var Mt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Ut;if(n>Xe)throw new Error(`concurrency=${n} exceeds max ${Xe}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:n,timeoutMs:e.timeoutMs??oe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:i,verify:r}=e,l=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(i&&r)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,p)=>i?this.executeMapItemWithBestOf(o,s,p,a,e,c,l):r?this.executeMapItemWithVerify(o,s,p,a,e,c,l):l?P(u=>this.executeMapItem(o,s,p,a,e,c,u),l,p):this.executeMapItem(o,s,p,a,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:s,condition:i,verify:r}=e,l=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>r?this.executeFilterItemWithVerify(p,s,u,a,e,c,l):l?P(g=>this.executeFilterItem(p,s,u,a,e,c,g),l,u):this.executeFilterItem(p,s,u,a,e,c))),o=[];for(let p of d)if(p.status==="error")o.push(p);else if(p.data!==null)try{i(p.data)?o.push(p):o.push({...p,status:"filtered"});}catch(u){o.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:s,verify:i}=e,r=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((C,v)=>{c.push(this.getFiles(C)),d.push(this.getIndex(C,v));});let o={};c.forEach((C,v)=>{Object.entries(C).forEach(([b,k])=>{o[`item_${d[v]}/${b}`]=k;});});let p=$e(o),u=U(wn,{fileTree:p}),g=e.systemPrompt?`${u}
252
252
 
253
- ${e.systemPrompt}`:u,m=(x,v,S)=>({operationId:l,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:v,verifyRetry:S,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(x,v,S,b)=>{let _=await this.semaphore.use(()=>this.execute(o,x,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:e.name,operationId:l,operation:"reduce",role:"worker",errorRetry:S,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),L=m(_,S,b&&b>1?b-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:L,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:L}},k=`${this.config.tag}-reduce`;return a?this.runWithVerification((x,v,S)=>w(x,v,void 0,S),{originalPrompt:s,inputFiles:o,verifyConfig:a,timeoutMs:r,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:l,baseTag:k,retry:i,operation:"reduce",_pipelineContext:e._pipelineContext}):i?P(x=>{let v=x>1?x-1:void 0,S=v?`${k}-er${v}`:k;return w(s,S,v)},i):w(s,k)}async bestOf(e){let{item:n,prompt:s,config:a}=e,i=e.retry??this.config.retry,l=a.n??a.taskAgents?.length;if(l===void 0)throw new Error("bestOf requires n or taskAgents");if(l<2)throw new Error("bestOf requires n >= 2");let r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),o=a.mcpServers??this.config.mcpServers,p=a.judgeMcpServers??a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,g=a.judgeSkills??a.skills??this.config.skills,m=a.composio??this.config.composio,f=a.judgeComposio??a.composio??this.config.composio,h=await Promise.all(Array.from({length:l},async(v,S)=>{let b=i?await P(_=>this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:S,operationId:r,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c,attempt:_}),i,S):await this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:S,operationId:r,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c});return a.onCandidateComplete?.(0,S,b.status==="success"?"success":"error"),b})),y=i?await P(v=>this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:a,timeoutMs:c,operationId:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f,attempt:v}),{...i,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:a,timeoutMs:c,operationId:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);a.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:r,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:l};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:h}}async execute(e,n,s){let a=null,i="",l=s.tagPrefix,r={},c=null,d,o,p={...this.config.agent,...s.agent};try{a=new pe().withAgent(p).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(s.tagPrefix),s.schema&&a.withSchema(s.schema,s.schemaOptions),s.systemPrompt&&a.withSystemPrompt(s.systemPrompt),s.mcpServers&&a.withMcpServers(s.mcpServers),s.skills?.length&&a.withSkills(s.skills),s.composio&&a.withComposio(s.composio.userId,s.composio.config),s.observability&&a.withObservability(s.observability),Object.keys(e).length>0&&a.withContext(e);let u=await a.run({prompt:n,timeoutMs:s.timeoutMs});i=u.sandboxId,l=a.getSessionTag()??s.tagPrefix;let g=null;try{g=await a.getOutputFiles(!0),r=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:s.schema?g?(c=g.data,g.error&&(d=g.error),g.rawData&&(o=g.rawData)):d="Failed to read output files from sandbox":c=r;}catch(u){if(d=u.message,a){l=a.getSessionTag()??s.tagPrefix;try{r=(await a.getOutputFiles(!0)).files;}catch{}}}finally{a&&await a.kill().catch(()=>{});}return {files:r,data:c,tag:l,sandboxId:i,error:d,rawData:o}}async executeMapItem(e,n,s,a,i,l,r=1){let c=this.getFiles(e),d=r>1?`${this.config.tag}-map-${s}-er${r-1}`:`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(c,o,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:s,role:"worker",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),f={operationId:a,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,errorRetry:r>1?r-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=i.verify,p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=this.evaluatePrompt(n,c,s);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let f=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:y,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:s,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),x={operationId:a,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(k,x)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:p,skills:u,composio:g,operationId:a,baseTag:d,retry:r,itemIndex:s,operation:"map",_pipelineContext:i._pipelineContext})}async executeMapItemWithBestOf(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=i.bestOf,u=p.n??p.taskAgents?.length;if(u===void 0||u<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let g=i.mcpServers??this.config.mcpServers,m=p.mcpServers??g,f=p.judgeMcpServers??p.mcpServers??g,h=i.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,k=i.composio??this.config.composio,x=p.composio??k,v=p.judgeComposio??p.composio??k,S=await Promise.all(Array.from({length:u},async(ue,ge)=>{let It=r?await P(ps=>this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:a,config:p,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:y,composio:x,timeoutMs:l,parentIndex:s,attempt:ps,_pipelineContext:i._pipelineContext}),r,ge):await this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:a,config:p,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:y,composio:x,timeoutMs:l,parentIndex:s,_pipelineContext:i._pipelineContext});return p.onCandidateComplete?.(s,ge,It.status==="success"?"success":"error"),It})),b=r?await P(ue=>this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:S,config:p,timeoutMs:l,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,attempt:ue,_pipelineContext:i._pipelineContext}),{...r,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:S,config:p,timeoutMs:l,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,_pipelineContext:i._pipelineContext}),_=S.findIndex(ue=>ue.status==="success"),L=b.decision?.winner??(_>=0?_:0),Pt=S[L]??S[0];p.onJudgeComplete?.(s,L,b.decision?.reasoning??"Judge failed to provide reasoning");let ds={operationId:a,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:i.name,candidateCount:u,...this.pipelineContextToMeta(i._pipelineContext)};return {...Pt,meta:{...Pt.meta,operation:"map",swarmName:this.config.tag,operationName:i.name,itemIndex:s,...this.pipelineContextToMeta(i._pipelineContext)},bestOf:{winnerIndex:L,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:ds,candidates:S}}}async executeFilterItem(e,n,s,a,i,l,r=1){let c=this.getFiles(e),d=r>1?`${this.config.tag}-filter-${s}-er${r-1}`:`${this.config.tag}-filter-${s}`,o=i.mcpServers??this.config.mcpServers,p=i.skills??this.config.skills,u=i.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:o,skills:p,composio:u,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:s,role:"worker",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),m={operationId:a,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,errorRetry:r>1?r-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(g,m,c)}async executeFilterItemWithVerify(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-filter-${s}`,o=i.verify,p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,f,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:h,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:s,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),k={operationId:a,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(w,k,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:p,skills:u,composio:g,operationId:a,baseTag:d,retry:r,itemIndex:s,operation:"filter",_pipelineContext:i._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:s,candidateIndex:a,operationId:i,config:l,timeoutMs:r,parentIndex:c,attempt:d=1,_pipelineContext:o}=e,p=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,u=d>1?`${p}-er${d-1}`:p,g=await this.semaphore.use(()=>this.execute(n,s,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:l.taskAgents?.[a],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:u,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:c,role:"candidate",candidateIndex:a,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(o)}})),m={operationId:i,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:d>1?d-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(o)};return this.buildResult(g,m)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((s,a)=>{s.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
253
+ ${e.systemPrompt}`:u,m=(C,v,b)=>({operationId:l,operation:"reduce",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:v,verifyRetry:b,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(C,v,b,k)=>{let _=await this.semaphore.use(()=>this.execute(o,C,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:e.name,operationId:l,operation:"reduce",role:"worker",errorRetry:b,verifyRetry:k&&k>1?k-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),L=m(_,b,k&&k>1?k-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:L,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:L}},S=`${this.config.tag}-reduce`;return i?this.runWithVerification((C,v,b)=>w(C,v,void 0,b),{originalPrompt:s,inputFiles:o,verifyConfig:i,timeoutMs:a,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:l,baseTag:S,retry:r,operation:"reduce",_pipelineContext:e._pipelineContext}):r?P(C=>{let v=C>1?C-1:void 0,b=v?`${S}-er${v}`:S;return w(s,b,v)},r):w(s,S)}async bestOf(e){let{item:n,prompt:s,config:i}=e,r=e.retry??this.config.retry,l=i.n??i.taskAgents?.length;if(l===void 0)throw new Error("bestOf requires n or taskAgents");if(l<2)throw new Error("bestOf requires n >= 2");let a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),o=i.mcpServers??this.config.mcpServers,p=i.judgeMcpServers??i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.judgeSkills??i.skills??this.config.skills,m=i.composio??this.config.composio,f=i.judgeComposio??i.composio??this.config.composio,h=await Promise.all(Array.from({length:l},async(v,b)=>{let k=r?await P(_=>this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:b,operationId:a,config:i,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c,attempt:_}),r,b):await this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:b,operationId:a,config:i,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c});return i.onCandidateComplete?.(0,b,k.status==="success"?"success":"error"),k})),y=r?await P(v=>this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:i,timeoutMs:c,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f,attempt:v}),{...r,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:i,timeoutMs:c,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f}),w=h.findIndex(v=>v.status==="success"),S=y.decision?.winner??(w>=0?w:0);i.onJudgeComplete?.(0,S,y.decision?.reasoning??"Judge failed to provide reasoning");let C={operationId:a,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:l};return {winner:h[S]??h[0],winnerIndex:S,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:C,candidates:h}}async execute(e,n,s){let i=null,r="",l=s.tagPrefix,a={},c=null,d,o,p={...this.config.agent,...s.agent};try{i=new ue().withAgent(p).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(s.tagPrefix),s.schema&&i.withSchema(s.schema,s.schemaOptions),s.systemPrompt&&i.withSystemPrompt(s.systemPrompt),s.mcpServers&&i.withMcpServers(s.mcpServers),s.skills?.length&&i.withSkills(s.skills),s.composio&&i.withComposio(s.composio.userId,s.composio.config),s.observability&&i.withObservability(s.observability),Object.keys(e).length>0&&i.withContext(e);let u=await i.run({prompt:n,timeoutMs:s.timeoutMs});r=u.sandboxId,l=i.getSessionTag()??s.tagPrefix;let g=null;try{g=await i.getOutputFiles(!0),a=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:s.schema?g?(c=g.data,g.error&&(d=g.error),g.rawData&&(o=g.rawData)):d="Failed to read output files from sandbox":c=a;}catch(u){if(d=u.message,i){l=i.getSessionTag()??s.tagPrefix;try{a=(await i.getOutputFiles(!0)).files;}catch{}}}finally{i&&await i.kill().catch(()=>{});}return {files:a,data:c,tag:l,sandboxId:r,error:d,rawData:o}}async executeMapItem(e,n,s,i,r,l,a=1){let c=this.getFiles(e),d=a>1?`${this.config.tag}-map-${s}-er${a-1}`:`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=r.mcpServers??this.config.mcpServers,u=r.skills??this.config.skills,g=r.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(c,o,{systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,agent:r.agent,mcpServers:p,skills:u,composio:g,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:r.name,operationId:i,operation:"map",itemIndex:s,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(r._pipelineContext)}})),f={operationId:i,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:r.name,itemIndex:s,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(r._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,s,i,r,l,a){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=r.verify,p=r.mcpServers??this.config.mcpServers,u=r.skills??this.config.skills,g=r.composio??this.config.composio,m=this.evaluatePrompt(n,c,s);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:s});let f=async(h,y,w)=>{let S=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,agent:r.agent,mcpServers:p,skills:u,composio:g,tagPrefix:y,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:r.name,operationId:i,operation:"map",itemIndex:s,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(r._pipelineContext)}})),C={operationId:i,operation:"map",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:r.name,itemIndex:s,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(r._pipelineContext)};return this.buildResult(S,C)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:r.systemPrompt,schema:r.schema,mcpServers:p,skills:u,composio:g,operationId:i,baseTag:d,retry:a,itemIndex:s,operation:"map",_pipelineContext:r._pipelineContext})}async executeMapItemWithBestOf(e,n,s,i,r,l,a){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=r.bestOf,u=p.n??p.taskAgents?.length;if(u===void 0||u<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:s});let g=r.mcpServers??this.config.mcpServers,m=p.mcpServers??g,f=p.judgeMcpServers??p.mcpServers??g,h=r.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,S=r.composio??this.config.composio,C=p.composio??S,v=p.judgeComposio??p.composio??S,b=await Promise.all(Array.from({length:u},async(ge,me)=>{let $t=a?await P(hs=>this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:me,operationId:i,config:p,systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,mcpServers:m,skills:y,composio:C,timeoutMs:l,parentIndex:s,attempt:hs,_pipelineContext:r._pipelineContext}),a,me):await this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:me,operationId:i,config:p,systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,mcpServers:m,skills:y,composio:C,timeoutMs:l,parentIndex:s,_pipelineContext:r._pipelineContext});return p.onCandidateComplete?.(s,me,$t.status==="success"?"success":"error"),$t})),k=a?await P(ge=>this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:b,config:p,timeoutMs:l,operationId:i,systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,attempt:ge,_pipelineContext:r._pipelineContext}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:b,config:p,timeoutMs:l,operationId:i,systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,_pipelineContext:r._pipelineContext}),_=b.findIndex(ge=>ge.status==="success"),L=k.decision?.winner??(_>=0?_:0),At=b[L]??b[0];p.onJudgeComplete?.(s,L,k.decision?.reasoning??"Judge failed to provide reasoning");let fs={operationId:i,operation:"bestof-judge",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:r.name,candidateCount:u,...this.pipelineContextToMeta(r._pipelineContext)};return {...At,meta:{...At.meta,operation:"map",swarmName:this.config.tag,operationName:r.name,itemIndex:s,...this.pipelineContextToMeta(r._pipelineContext)},bestOf:{winnerIndex:L,judgeReasoning:k.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:fs,candidates:b}}}async executeFilterItem(e,n,s,i,r,l,a=1){let c=this.getFiles(e),d=a>1?`${this.config.tag}-filter-${s}-er${a-1}`:`${this.config.tag}-filter-${s}`,o=r.mcpServers??this.config.mcpServers,p=r.skills??this.config.skills,u=r.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,agent:r.agent,mcpServers:o,skills:p,composio:u,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:r.name,operationId:i,operation:"filter",itemIndex:s,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(r._pipelineContext)}})),m={operationId:i,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:r.name,itemIndex:s,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(r._pipelineContext)};return this.buildResult(g,m,c)}async executeFilterItemWithVerify(e,n,s,i,r,l,a){let c=this.getFiles(e),d=`${this.config.tag}-filter-${s}`,o=r.verify,p=r.mcpServers??this.config.mcpServers,u=r.skills??this.config.skills,g=r.composio??this.config.composio,m=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,f,{systemPrompt:r.systemPrompt,schema:r.schema,schemaOptions:r.schemaOptions,agent:r.agent,mcpServers:p,skills:u,composio:g,tagPrefix:h,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:r.name,operationId:i,operation:"filter",itemIndex:s,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(r._pipelineContext)}})),S={operationId:i,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:r.name,itemIndex:s,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(r._pipelineContext)};return this.buildResult(w,S,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:r.systemPrompt,schema:r.schema,mcpServers:p,skills:u,composio:g,operationId:i,baseTag:d,retry:a,itemIndex:s,operation:"filter",_pipelineContext:r._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:s,candidateIndex:i,operationId:r,config:l,timeoutMs:a,parentIndex:c,attempt:d=1,_pipelineContext:o}=e,p=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${i}`:`${this.config.tag}-bestof-cand-${i}`,u=d>1?`${p}-er${d-1}`:p,g=await this.semaphore.use(()=>this.execute(n,s,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:l.taskAgents?.[i],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:u,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:r,operation:"map",itemIndex:c,role:"candidate",candidateIndex:i,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(o)}})),m={operationId:r,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:i,errorRetry:d>1?d-1:void 0,candidateIndex:i,...this.pipelineContextToMeta(o)};return this.buildResult(g,m)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((s,i)=>{s.status==="error"&&(n[`candidate_${i}/_failed.txt`]=`STATUS: FAILED
254
254
 
255
- Error: ${s.error??"Unknown error"}`),Object.entries(s.files).forEach(([i,l])=>{n[`candidate_${a}/${i}`]=l;});}),n}async executeBestOfJudge(e){let{candidates:n,config:s,timeoutMs:a,operationId:i,parentIndex:l,attempt:r=1,_pipelineContext:c}=e,d=l!==void 0?`${this.config.tag}-map-${l}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=r>1?`${d}-er${r-1}`:d,p=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=Ae(p),g=B(pt,{candidateCount:String(n.length),criteria:s.judgeCriteria,fileTree:u}),m=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),f=await this.semaphore.use(()=>this.execute(p,un,{systemPrompt:g,schema:m,agent:s.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:l,role:"judge",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(c)}})),h=null;if(f.data&&!f.error)h=f.data;else if(f.rawData)try{let y=JSON.parse(f.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${f.error}`);}return {status:h?"success":"error",decision:h,tag:f.tag,sandboxId:f.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([s,a])=>{n[`worker_output/${s}`]=a;}),n}async executeVerify(e){let{config:n,timeoutMs:s,operationId:a,workerTag:i,retryAttempt:l=1,operation:r,itemIndex:c,attemptIndex:d,_pipelineContext:o}=e,p=l>1?`${i}-verifier-er${l-1}`:`${i}-verifier`,u=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,m=n.verifierComposio??e.composio,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=Ae(f),y=B(ut,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(f,gn,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:u,skills:g,composio:m,tagPrefix:p,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:a,operation:r,itemIndex:c,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let x=JSON.parse(w.rawData);k={passed:!!x.passed,reasoning:x.reasoning??"Verification completed",feedback:x.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:k?"success":"error",decision:k,tag:w.tag,sandboxId:w.sandboxId,error:k?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return B(gt,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:s,inputFiles:a,verifyConfig:i,timeoutMs:l,operationId:r,baseTag:c,retry:d,itemIndex:o=0,operation:p,_pipelineContext:u}=n,g=i.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,m=s,f=null,h=0;for(;h<g;){h++;let w=h>1?`${c}-vr${h-1}`:c,k=d?await P(S=>e(m,S>1?`${w}-er${S-1}`:w,h),d,o):await e(m,w,h);if(i.onWorkerComplete?.(o,h,k.status==="error"?"error":"success"),k.status==="error")return k;f=k;let x=d?await P(S=>this.executeVerify({inputFiles:a,outputFiles:k.files,taskPrompt:m,config:i,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:r,workerTag:w,retryAttempt:S,operation:p,itemIndex:o,attemptIndex:h,_pipelineContext:u}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:a,outputFiles:k.files,taskPrompt:m,config:i,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:r,workerTag:w,operation:p,itemIndex:o,attemptIndex:h,_pipelineContext:u}),v={operationId:r,operation:"verify",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(i.onVerifierComplete?.(o,h,x.decision?.passed??false,x.decision?.feedback),x.decision?.passed)return {...k,verify:{passed:true,reasoning:x.decision.reasoning,verifyMeta:v,attempts:h}};if(h<g){let S=x.decision?.feedback??x.decision?.reasoning??"Output did not meet criteria";m=t.buildRetryPromptWithFeedback(s,S);}}let y=h>1?`${c}-vr${h-1}`:c;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:r,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,s){if(typeof e=="string")return e;try{return e(n,s)}catch(a){return a}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=M(e.schema)?H(e.schema):Y(e.schema)),Object.entries(e.inputFiles).forEach(([s,a])=>{n[`worker_task/input/${s}`]=a;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&z in e&&e[z]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,s){let a=s??e.files;return e.error?{[z]:true,status:"error",data:null,files:a,meta:n,error:e.error,rawData:e.rawData}:{[z]:true,status:"success",data:e.data,files:a,meta:n}}buildErrorResult(e,n){return {[z]:true,status:"error",data:null,files:{},meta:n,error:e}}};var Ne=class t{swarm;steps;events;constructor(e,n=[],s={}){this.swarm=e,this.steps=n,this.events=s;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new Ke(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[s]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),s=[],a=e,i=Date.now();for(let r=0;r<this.steps.length;r++){let c=this.steps[r],d=c.config.name,o=Date.now();this.events.onStepStart?.({type:c.type,index:r,name:d,itemCount:a.length});let p={pipelineRunId:n,pipelineStepIndex:r};try{let u=await this.executeStep(c,a,r,d,p),g=Date.now()-o;if(s.push({type:c.type,index:r,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:c.type,index:r,name:d,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),c.type==="reduce")return {pipelineRunId:n,steps:s,output:u.output,totalDurationMs:Date.now()-i};a=u.nextItems;}catch(u){throw this.events.onStepError?.({type:c.type,index:r,name:d,error:u instanceof Error?u:new Error(String(u))}),u}}let l=s[s.length-1];return {pipelineRunId:n,steps:s,output:l?.results??[],totalDurationMs:Date.now()-i}}async executeStep(e,n,s,a,i){if(e.type==="map"){let c=e.config,d=await this.swarm.map({items:n,...c,_pipelineContext:i,retry:this.wrapRetry(c.retry,s,a),verify:this.wrapVerify(c.verify,s,a),bestOf:this.wrapBestOf(c.bestOf,s,a)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,d=await this.swarm.filter({items:n,...c,_pipelineContext:i,retry:this.wrapRetry(c.retry,s,a),verify:this.wrapVerify(c.verify,s,a)}),o=c.emit??"success",p=o==="success"?d.success:o==="filtered"?d.filtered:[...d.success,...d.filtered];return {output:[...d],nextItems:p,successCount:d.success.length,errorCount:d.error.length,filteredCount:d.filtered.length}}let l=e.config,r=await this.swarm.reduce({items:n,...l,_pipelineContext:i,retry:this.wrapRetry(l.retry,s,a),verify:this.wrapVerify(l.verify,s,a)});return {output:r,nextItems:[],successCount:r.status==="success"?1:0,errorCount:r.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,s){if(e)return {...e,onItemRetry:(a,i,l)=>{e.onItemRetry?.(a,i,l),this.events.onItemRetry?.({stepIndex:n,stepName:s,itemIndex:a,attempt:i,error:l});}}}wrapVerify(e,n,s){if(e)return {...e,onWorkerComplete:(a,i,l)=>{e.onWorkerComplete?.(a,i,l),this.events.onWorkerComplete?.({stepIndex:n,stepName:s,itemIndex:a,attempt:i,status:l});},onVerifierComplete:(a,i,l,r)=>{e.onVerifierComplete?.(a,i,l,r),this.events.onVerifierComplete?.({stepIndex:n,stepName:s,itemIndex:a,attempt:i,passed:l,feedback:r});}}}wrapBestOf(e,n,s){if(e)return {...e,onCandidateComplete:(a,i,l)=>{e.onCandidateComplete?.(a,i,l),this.events.onCandidateComplete?.({stepIndex:n,stepName:s,itemIndex:a,candidateIndex:i,status:l});},onJudgeComplete:(a,i,l)=>{e.onJudgeComplete?.(a,i,l),this.events.onJudgeComplete?.({stepIndex:n,stepName:s,itemIndex:a,winnerIndex:i,reasoning:l});}}}},Ke=class t extends Ne{constructor(e,n,s){super(e,n,s);}on(e,n){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[s]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}map(){throw new Error("Cannot add steps after reduce")}filter(){throw new Error("Cannot add steps after reduce")}reduce(){throw new Error("Cannot add steps after reduce")}};var ii=6e5,ri=5e3;function ls(t,e,n){let s=e??n;if(!Number.isFinite(s)||s<=0)throw new Error(`${t} must be a positive number`);return s}function ai(t){let e=t?.apiKey||process.env[O];if(!e)throw new Error(`sessions() requires an API key. Set ${O} or pass { apiKey } in config.`);let n=t?.dashboardUrl||R;async function s(r,c){let d=await fetch(`${n}${r}`,{...c,headers:{Authorization:`Bearer ${e}`,...c?.headers}});if(!d.ok){let o=await d.text().catch(()=>"");throw new Error(`Dashboard API error (${d.status}): ${o||d.statusText}`)}return d}function a(r){return {id:r.id,tag:r.tag,agent:r.agent,model:r.model||null,provider:r.provider,sandboxId:r.sandboxId||null,state:r.isEnded?"ended":"live",runtimeStatus:r.runtimeStatus||"unknown",cost:typeof r.cost=="number"?r.cost:null,createdAt:r.createdAt,endedAt:r.endedAt||null,stepCount:r.stepCount||0,toolStats:r.toolStats||null}}function i(r,c){if(r.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(r.status||"unknown")})`);if(typeof r.replayUrl!="string"||typeof r.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:r.sessionId||c,status:"ready",replayUrl:r.replayUrl,downloadUrl:r.downloadUrl,suggestedStartSeconds:typeof r.suggestedStartSeconds=="number"?r.suggestedStartSeconds:void 0,sizeBytes:typeof r.sizeBytes=="number"?r.sizeBytes:void 0,readyAt:typeof r.readyAt=="string"?r.readyAt:void 0}}let l=r=>new Promise(c=>setTimeout(c,r));return {async list(r){let c=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(r?.limit??20,200)),paginated:"true"});if(r?.cursor&&c.set("cursor",r.cursor),r?.state&&r.state!=="all"&&c.set("state",r.state),r?.agent&&c.set("agent",r.agent),r?.tagPrefix&&c.set("tagPrefix",r.tagPrefix),r?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};c.set("sortDirection",p[r.sort]),r.sort==="cost"?c.set("sortField","cost"):c.set("sortField","timestamp");}let o=await(await s(`/api/sessions?${c}`)).json();return {items:(o.items||[]).map(a),nextCursor:o.nextCursor||null,hasMore:!!o.hasMore}},async get(r){let d=await(await s(`/api/sessions/${encodeURIComponent(r)}`)).json();return a(d)},async events(r,c){let d=new URLSearchParams;c?.since!=null&&d.set("since",String(c.since));let o=d.toString();return (await(await s(`/api/sessions/${encodeURIComponent(r)}/events${o?`?${o}`:""}`)).json()).events||[]},async download(r,c){let p=(await(await s(`/api/sessions/${encodeURIComponent(r)}`)).json()).tag||r,u=await fetch(`${n}/api/sessions/${encodeURIComponent(r)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!u.ok){let h=await u.text().catch(()=>"");throw new Error(`Download failed (${u.status}): ${h||u.statusText}`)}let g=c?.to||process.cwd();await promises.mkdir(g,{recursive:true});let m=re.join(g,`${p}.jsonl`);if(!u.body)throw new Error("Download response has no body");let f=stream.Readable.fromWeb(u.body);return await promises$1.pipeline(f,A.createWriteStream(m)),m},async browserReplay(r,c){let d=ls("timeoutMs",c?.timeoutMs,ii),o=ls("intervalMs",c?.intervalMs,ri),p=Date.now()+d,u=`/api/sessions/${encodeURIComponent(r)}/browser-replay`;for(;;){let g=p-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let m;try{m=await fetch(`${n}${u}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,g))});}catch(h){let y=h.name;throw y==="AbortError"||y==="TimeoutError"?new Error(`Browser replay timed out after ${d}ms`):h}let f={};if(m.ok)f=await m.json();else {let h=await m.text().catch(()=>"");throw new Error(`Dashboard API error (${m.status}): ${h||m.statusText}`)}if(f.status==="ready")return i(f,r);if(f.status==="failed"){let h=typeof f.error=="string"?f.error:"unknown error";throw new Error(`Browser replay failed: ${h}`)}if(Date.now()>=p)throw new Error(`Browser replay timed out after ${d}ms`);await l(Math.min(o,Math.max(0,p-Date.now())));}}}}Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Ge;exports.AGENT_TYPES=us;exports.Agent=de;exports.BROWSER_ACTIONBOOK_PROMPT=dt;exports.Evolve=pe;exports.JUDGE_PROMPT=pt;exports.Pipeline=Ne;exports.RETRY_FEEDBACK_PROMPT=gt;exports.SCHEMA_PROMPT=dn;exports.SWARM_RESULT_BRAND=z;exports.SYSTEM_PROMPT=ln;exports.Semaphore=ee;exports.Swarm=Rt;exports.SwarmResultList=te;exports.TerminalPipeline=Ke;exports.VALIDATION_PRESETS=je;exports.VERIFY_PROMPT=ut;exports.WORKSPACE_PROMPT=an;exports.WORKSPACE_SWE_PROMPT=cn;exports.applyTemplate=B;exports.buildWorkerSystemPrompt=mt;exports.createAgentParser=W;exports.createClaudeParser=Ee;exports.createCodexParser=Te;exports.createDroidParser=Re;exports.createGeminiParser=Pe;exports.executeWithRetry=P;exports.expandPath=V;exports.getAgentConfig=$;exports.getMcpSettingsDir=K;exports.getMcpSettingsPath=N;exports.isValidAgentType=gs;exports.isZodSchema=M;exports.jsonSchemaToString=Y;exports.parseNdjsonLine=Gs;exports.parseNdjsonOutput=Ws;exports.parseQwenOutput=Wt;exports.readLocalDir=zt;exports.resolveStorageConfig=Fe;exports.saveLocalDir=Jt;exports.sessions=ai;exports.storage=Lo;exports.writeClaudeMcpConfig=me;exports.writeCodexMcpConfig=_e;exports.writeDroidGatewaySettings=ve;exports.writeDroidMcpConfig=we;exports.writeGeminiMcpConfig=fe;exports.writeMcpConfig=tt;exports.writeQwenMcpConfig=he;exports.zodSchemaToJson=H;
255
+ Error: ${s.error??"Unknown error"}`),Object.entries(s.files).forEach(([r,l])=>{n[`candidate_${i}/${r}`]=l;});}),n}async executeBestOfJudge(e){let{candidates:n,config:s,timeoutMs:i,operationId:r,parentIndex:l,attempt:a=1,_pipelineContext:c}=e,d=l!==void 0?`${this.config.tag}-map-${l}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=a>1?`${d}-er${a-1}`:d,p=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=$e(p),g=U(gt,{candidateCount:String(n.length),criteria:s.judgeCriteria,fileTree:u}),m=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),f=await this.semaphore.use(()=>this.execute(p,hn,{systemPrompt:g,schema:m,agent:s.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:r,operation:"map",itemIndex:l,role:"judge",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(c)}})),h=null;if(f.data&&!f.error)h=f.data;else if(f.rawData)try{let y=JSON.parse(f.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${f.error}`);}return {status:h?"success":"error",decision:h,tag:f.tag,sandboxId:f.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([s,i])=>{n[`worker_output/${s}`]=i;}),n}async executeVerify(e){let{config:n,timeoutMs:s,operationId:i,workerTag:r,retryAttempt:l=1,operation:a,itemIndex:c,attemptIndex:d,_pipelineContext:o}=e,p=l>1?`${r}-verifier-er${l-1}`:`${r}-verifier`,u=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,m=n.verifierComposio??e.composio,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=$e(f),y=U(mt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(f,yn,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:u,skills:g,composio:m,tagPrefix:p,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:i,operation:a,itemIndex:c,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o)}})),S=null;if(w.data&&!w.error)S=w.data;else if(w.rawData)try{let C=JSON.parse(w.rawData);S={passed:!!C.passed,reasoning:C.reasoning??"Verification completed",feedback:C.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:S?"success":"error",decision:S,tag:w.tag,sandboxId:w.sandboxId,error:S?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return U(ft,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:s,inputFiles:i,verifyConfig:r,timeoutMs:l,operationId:a,baseTag:c,retry:d,itemIndex:o=0,operation:p,_pipelineContext:u}=n,g=r.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,m=s,f=null,h=0;for(;h<g;){h++;let w=h>1?`${c}-vr${h-1}`:c,S=d?await P(b=>e(m,b>1?`${w}-er${b-1}`:w,h),d,o):await e(m,w,h);if(r.onWorkerComplete?.(o,h,S.status==="error"?"error":"success"),S.status==="error")return S;f=S;let C=d?await P(b=>this.executeVerify({inputFiles:i,outputFiles:S.files,taskPrompt:m,config:r,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:a,workerTag:w,retryAttempt:b,operation:p,itemIndex:o,attemptIndex:h,_pipelineContext:u}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:i,outputFiles:S.files,taskPrompt:m,config:r,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:a,workerTag:w,operation:p,itemIndex:o,attemptIndex:h,_pipelineContext:u}),v={operationId:a,operation:"verify",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(r.onVerifierComplete?.(o,h,C.decision?.passed??false,C.decision?.feedback),C.decision?.passed)return {...S,verify:{passed:true,reasoning:C.decision.reasoning,verifyMeta:v,attempts:h}};if(h<g){let b=C.decision?.feedback??C.decision?.reasoning??"Output did not meet criteria";m=t.buildRetryPromptWithFeedback(s,b);}}let y=h>1?`${c}-vr${h-1}`:c;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:a,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,s){if(typeof e=="string")return e;try{return e(n,s)}catch(i){return i}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=M(e.schema)?H(e.schema):Y(e.schema)),Object.entries(e.inputFiles).forEach(([s,i])=>{n[`worker_task/input/${s}`]=i;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&z in e&&e[z]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,s){let i=s??e.files;return e.error?{[z]:true,status:"error",data:null,files:i,meta:n,error:e.error,rawData:e.rawData}:{[z]:true,status:"success",data:e.data,files:i,meta:n}}buildErrorResult(e,n){return {[z]:true,status:"error",data:null,files:{},meta:n,error:e}}};var je=class t{swarm;steps;events;constructor(e,n=[],s={}){this.swarm=e,this.steps=n,this.events=s;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new Ve(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[s]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),s=[],i=e,r=Date.now();for(let a=0;a<this.steps.length;a++){let c=this.steps[a],d=c.config.name,o=Date.now();this.events.onStepStart?.({type:c.type,index:a,name:d,itemCount:i.length});let p={pipelineRunId:n,pipelineStepIndex:a};try{let u=await this.executeStep(c,i,a,d,p),g=Date.now()-o;if(s.push({type:c.type,index:a,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:c.type,index:a,name:d,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),c.type==="reduce")return {pipelineRunId:n,steps:s,output:u.output,totalDurationMs:Date.now()-r};i=u.nextItems;}catch(u){throw this.events.onStepError?.({type:c.type,index:a,name:d,error:u instanceof Error?u:new Error(String(u))}),u}}let l=s[s.length-1];return {pipelineRunId:n,steps:s,output:l?.results??[],totalDurationMs:Date.now()-r}}async executeStep(e,n,s,i,r){if(e.type==="map"){let c=e.config,d=await this.swarm.map({items:n,...c,_pipelineContext:r,retry:this.wrapRetry(c.retry,s,i),verify:this.wrapVerify(c.verify,s,i),bestOf:this.wrapBestOf(c.bestOf,s,i)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,d=await this.swarm.filter({items:n,...c,_pipelineContext:r,retry:this.wrapRetry(c.retry,s,i),verify:this.wrapVerify(c.verify,s,i)}),o=c.emit??"success",p=o==="success"?d.success:o==="filtered"?d.filtered:[...d.success,...d.filtered];return {output:[...d],nextItems:p,successCount:d.success.length,errorCount:d.error.length,filteredCount:d.filtered.length}}let l=e.config,a=await this.swarm.reduce({items:n,...l,_pipelineContext:r,retry:this.wrapRetry(l.retry,s,i),verify:this.wrapVerify(l.verify,s,i)});return {output:a,nextItems:[],successCount:a.status==="success"?1:0,errorCount:a.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,s){if(e)return {...e,onItemRetry:(i,r,l)=>{e.onItemRetry?.(i,r,l),this.events.onItemRetry?.({stepIndex:n,stepName:s,itemIndex:i,attempt:r,error:l});}}}wrapVerify(e,n,s){if(e)return {...e,onWorkerComplete:(i,r,l)=>{e.onWorkerComplete?.(i,r,l),this.events.onWorkerComplete?.({stepIndex:n,stepName:s,itemIndex:i,attempt:r,status:l});},onVerifierComplete:(i,r,l,a)=>{e.onVerifierComplete?.(i,r,l,a),this.events.onVerifierComplete?.({stepIndex:n,stepName:s,itemIndex:i,attempt:r,passed:l,feedback:a});}}}wrapBestOf(e,n,s){if(e)return {...e,onCandidateComplete:(i,r,l)=>{e.onCandidateComplete?.(i,r,l),this.events.onCandidateComplete?.({stepIndex:n,stepName:s,itemIndex:i,candidateIndex:r,status:l});},onJudgeComplete:(i,r,l)=>{e.onJudgeComplete?.(i,r,l),this.events.onJudgeComplete?.({stepIndex:n,stepName:s,itemIndex:i,winnerIndex:r,reasoning:l});}}}},Ve=class t extends je{constructor(e,n,s){super(e,n,s);}on(e,n){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[s]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}map(){throw new Error("Cannot add steps after reduce")}filter(){throw new Error("Cannot add steps after reduce")}reduce(){throw new Error("Cannot add steps after reduce")}};var wi=6e5,vi=5e3;function ms(t,e,n){let s=e??n;if(!Number.isFinite(s)||s<=0)throw new Error(`${t} must be a positive number`);return s}function bi(t){let e=t?.apiKey||process.env[O];if(!e)throw new Error(`sessions() requires an API key. Set ${O} or pass { apiKey } in config.`);let n=t?.dashboardUrl||E;async function s(a,c){let d=await fetch(`${n}${a}`,{...c,headers:{Authorization:`Bearer ${e}`,...c?.headers}});if(!d.ok){let o=await d.text().catch(()=>"");throw new Error(`Dashboard API error (${d.status}): ${o||d.statusText}`)}return d}function i(a){return {id:a.id,tag:a.tag,agent:a.agent,model:a.model||null,provider:a.provider,sandboxId:a.sandboxId||null,state:a.isEnded?"ended":"live",runtimeStatus:a.runtimeStatus||"unknown",cost:typeof a.cost=="number"?a.cost:null,createdAt:a.createdAt,endedAt:a.endedAt||null,stepCount:a.stepCount||0,toolStats:a.toolStats||null}}function r(a,c){if(a.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(a.status||"unknown")})`);if(typeof a.replayUrl!="string"||typeof a.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:a.sessionId||c,status:"ready",replayUrl:a.replayUrl,downloadUrl:a.downloadUrl,suggestedStartSeconds:typeof a.suggestedStartSeconds=="number"?a.suggestedStartSeconds:void 0,sizeBytes:typeof a.sizeBytes=="number"?a.sizeBytes:void 0,readyAt:typeof a.readyAt=="string"?a.readyAt:void 0}}let l=a=>new Promise(c=>setTimeout(c,a));return {async list(a){let c=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(a?.limit??20,200)),paginated:"true"});if(a?.cursor&&c.set("cursor",a.cursor),a?.state&&a.state!=="all"&&c.set("state",a.state),a?.agent&&c.set("agent",a.agent),a?.tagPrefix&&c.set("tagPrefix",a.tagPrefix),a?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};c.set("sortDirection",p[a.sort]),a.sort==="cost"?c.set("sortField","cost"):c.set("sortField","timestamp");}let o=await(await s(`/api/sessions?${c}`)).json();return {items:(o.items||[]).map(i),nextCursor:o.nextCursor||null,hasMore:!!o.hasMore}},async get(a){let d=await(await s(`/api/sessions/${encodeURIComponent(a)}`)).json();return i(d)},async events(a,c){let d=new URLSearchParams;c?.since!=null&&d.set("since",String(c.since));let o=d.toString();return (await(await s(`/api/sessions/${encodeURIComponent(a)}/events${o?`?${o}`:""}`)).json()).events||[]},async download(a,c){let p=(await(await s(`/api/sessions/${encodeURIComponent(a)}`)).json()).tag||a,u=await fetch(`${n}/api/sessions/${encodeURIComponent(a)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!u.ok){let h=await u.text().catch(()=>"");throw new Error(`Download failed (${u.status}): ${h||u.statusText}`)}let g=c?.to||process.cwd();await promises.mkdir(g,{recursive:true});let m=re.join(g,`${p}.jsonl`);if(!u.body)throw new Error("Download response has no body");let f=stream.Readable.fromWeb(u.body);return await promises$1.pipeline(f,A.createWriteStream(m)),m},async browserReplay(a,c){let d=ms("timeoutMs",c?.timeoutMs,wi),o=ms("intervalMs",c?.intervalMs,vi),p=Date.now()+d,u=`/api/sessions/${encodeURIComponent(a)}/browser-replay`;for(;;){let g=p-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let m;try{m=await fetch(`${n}${u}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,g))});}catch(h){let y=h.name;throw y==="AbortError"||y==="TimeoutError"?new Error(`Browser replay timed out after ${d}ms`):h}let f={};if(m.ok)f=await m.json();else {let h=await m.text().catch(()=>"");throw new Error(`Dashboard API error (${m.status}): ${h||m.statusText}`)}if(f.status==="ready")return r(f,a);if(f.status==="failed"){let h=typeof f.error=="string"?f.error:"unknown error";throw new Error(`Browser replay failed: ${h}`)}if(Date.now()>=p)throw new Error(`Browser replay timed out after ${d}ms`);await l(Math.min(o,Math.max(0,p-Date.now())));}}}}Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=ze;exports.AGENT_TYPES=ys;exports.Agent=pe;exports.BROWSER_ACTIONBOOK_PROMPT=ut;exports.BROWSER_LOGIN_MCP_SERVER_NAME=It;exports.BrowserCredentialsClient=Ke;exports.Evolve=ue;exports.JUDGE_PROMPT=gt;exports.Pipeline=je;exports.RETRY_FEEDBACK_PROMPT=ft;exports.SCHEMA_PROMPT=mn;exports.SWARM_RESULT_BRAND=z;exports.SYSTEM_PROMPT=gn;exports.Semaphore=ee;exports.Swarm=Mt;exports.SwarmResultList=te;exports.TerminalPipeline=Ve;exports.VALIDATION_PRESETS=Ge;exports.VERIFY_PROMPT=mt;exports.WORKSPACE_PROMPT=pn;exports.WORKSPACE_SWE_PROMPT=un;exports.applyTemplate=U;exports.browserCredentials=Ot;exports.buildWorkerSystemPrompt=ht;exports.createAgentParser=W;exports.createClaudeParser=Te;exports.createCodexParser=Re;exports.createDroidParser=Pe;exports.createGeminiParser=Ie;exports.executeWithRetry=P;exports.expandPath=V;exports.getAgentConfig=$;exports.getMcpSettingsDir=K;exports.getMcpSettingsPath=N;exports.isValidAgentType=ws;exports.isZodSchema=M;exports.jsonSchemaToString=Y;exports.parseNdjsonLine=Hs;exports.parseNdjsonOutput=Ys;exports.parseQwenOutput=Ht;exports.readLocalDir=Yt;exports.resolveStorageConfig=Le;exports.saveLocalDir=Zt;exports.sessions=bi;exports.storage=Go;exports.writeClaudeMcpConfig=fe;exports.writeCodexMcpConfig=Ee;exports.writeDroidGatewaySettings=be;exports.writeDroidMcpConfig=ve;exports.writeGeminiMcpConfig=he;exports.writeMcpConfig=st;exports.writeQwenMcpConfig=ye;exports.zodSchemaToJson=H;