@evolvingmachines/sdk 0.0.51 → 0.0.52-launch-round-1.20260803.cb1be5b

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,33 @@
1
- 'use strict';var events=require('events'),Es=require('ajv'),crypto=require('crypto'),gi=require('zod-to-json-schema'),$=require('fs'),ae=require('path'),promises=require('fs/promises'),os$1=require('os'),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 Es__default=/*#__PURE__*/_interopDefault(Es);var gi__default=/*#__PURE__*/_interopDefault(gi);var $__namespace=/*#__PURE__*/_interopNamespace($);var ae__namespace=/*#__PURE__*/_interopNamespace(ae);var Ar={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},qe={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};function ne(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function Ye(t){if(!(t==="off"||t==="none"||t==="no-thinking"))return !t||t==="thinking"||t==="medium"?"medium":t==="low"||t==="minimal"?"minimal":t==="xhigh"?"max":t}function Mr(t){let e=Ye(t);return e?` --variant ${e} --thinking`:""}var Qe={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:"fable",modelId:"claude-fable-5",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-4-8",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,reasoningEffort:r})=>{let s=n?"--continue ":"",a=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${s}--model ${e}${a} --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:r})=>{let s=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${s} --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.7-max",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"},{alias:"qwen3.6-plus",modelId:"qwen3.6-plus",description:"Compatibility model used in Qwen Code examples"}],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.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash","qwen3.6-plus":"dashscope/qwen3.6-plus"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r})=>{let s=n?"--continue ":"",a=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${a} --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-k2p6-raptor",modelId:"kimi-k2p6-raptor",description:"Evolve-managed Kimi K2.6 Raptor route for latency-sensitive agent runs"},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"},{alias:"kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Previous multimodal flagship"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2p6-raptor":"kimi-k2p6-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n})=>{let r=e?"--continue ":"",s=ke(t),a="--config-file /home/user/.kimi-code/config.toml",o="$(if [ -f /home/user/.kimi-code/mcp.json ]; then printf ' --mcp-config-file /home/user/.kimi-code/mcp.json'; fi)",c=ne(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${r}${a}${o}${c} -p ${s} --output-format stream-json; else kimi ${r}-p ${s} --output-format stream-json; fi`}},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-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{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.8",modelId:"openrouter/anthropic/claude-opus-4.8",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:r,reasoningEffort:s})=>{let a=n?"--continue ":"",o=e.startsWith("openrouter/")?e:`openrouter/${e}`,c=Mr(s);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${a}--model ${o} --format json${c} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${a}--model litellm/${o} --format json${c} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",defaultModel:"gpt-5.5",models:[{alias:"claude-opus-4-8",modelId:"claude-opus-4-8",description:"Factory-managed Claude Opus 4.8"},{alias:"claude-opus-4-8-fast",modelId:"claude-opus-4-8-fast",description:"Factory-managed Claude Opus 4.8 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:r,reasoningEffort:s,isDirectMode:a})=>{let o=a?"":"--settings /home/user/.factory/evolve-settings.json ",c=a?e:"custom:Evolve-Gateway-0",l=s?` --reasoning-effort ${s}`:"",d=n&&r?`--session-id ${ke(r)} `:"";return `printf '%s' ${ke(t)} | droid ${o}exec ${d}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${ke(c)}${l}`}}};function D(t){let e=Qe[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function $r(t){return t in Qe}function V(t){return t.replace(/^~/,"/home/user")}function ke(t){return `'${t.replace(/'/g,"'\\''")}'`}function U(t){let e=D(t);return `${V(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function B(t){let e=D(t);return V(e.mcpConfig.settingsDir)}function A(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 Ze(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 re(t){for(let[e,n]of Object.entries(t))Ze(e,n);}function ie(t){return t.type?t.type:t.command?"stdio":"sse"}function Dr(t){let e=ie(t);return {...t,type:e}}function Ur(t){let{type:e,url:n,...r}=t;return ie(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function Br(t){return {type:ie(t),...t}}function Lr(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function Fr(t){let e=ie(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:a,envVars:o,...c}=t;if(e==="stdio"&&t.command)return {type:"stdio",...c};if(t.url){let l={...c,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??r;return d&&Object.keys(d).length>0&&(l.headers=d),l}return {type:e==="stdio"?"stdio":"http",...c}}async function Xe(t,e,n,r){re(n);let s=B(e),a=U(e);await t.files.makeDir(s);let o={};try{let l=await t.files.read(a);typeof l=="string"&&(o=JSON.parse(l));}catch(l){if(!A(l))throw l}let c=Object.fromEntries(Object.entries(n).map(([l,d])=>[l,r(d)]));await t.files.write(a,JSON.stringify({...o,mcpServers:c},null,2));}async function Se(t,e,n){re(n);let r=B("claude"),s=U("claude"),a=Object.fromEntries(Object.entries(n).map(([c,l])=>[c,Br(l)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:a},null,2)),await t.files.makeDir(r);let o={};try{let c=await t.files.read(s);typeof c=="string"&&(o=JSON.parse(c));}catch(c){if(!A(c))throw c}o.enableAllProjectMcpServers=true,await t.files.write(s,JSON.stringify(o,null,2));}async function xe(t,e){await Xe(t,"gemini",e,Dr);}async function Ce(t,e){await Xe(t,"qwen",e,Ur);}async function _e(t,e,n,r){let s=B(e),a=U(e);await t.files.makeDir(s);let o={};try{let p=await t.files.read(a);typeof p=="string"&&(o=JSON.parse(p));}catch(p){if(!A(p))throw p}let c=n.split("."),l=o;for(let p=0;p<c.length-1;p++){let u=c[p];(typeof l[u]!="object"||l[u]===null)&&(l[u]={}),l=l[u];}let d=c[c.length-1],i=typeof l[d]=="object"&&l[d]!==null?l[d]:{};l[d]={...i,...r},await t.files.write(a,JSON.stringify(o,null,2));}async function et(t,e){let n=B("qwen"),r=U("qwen");await t.files.makeDir(n);let s={};try{let l=await t.files.read(r);typeof l=="string"&&(s=JSON.parse(l));}catch(l){if(!A(l))throw l}let a=s.model??{},o=a.generationConfig??{},c=o.extra_body??{};s.model={...a,generationConfig:{...o,extra_body:{...c,enable_thinking:e}}},await t.files.write(r,JSON.stringify(s,null,2));}async function tt(t,e){await Xe(t,"kimi",e,Lr);}async function Ee(t,e,n){re(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let a={};try{let c=await t.files.read(s);typeof c=="string"&&(a=JSON.parse(c));}catch(c){if(!A(c))throw c}let o=Object.fromEntries(Object.entries(n).map(([c,l])=>[c,Fr(l)]));await t.files.write(s,JSON.stringify({...a,mcpServers:o},null,2));}async function Re(t,e,n){let r=V(e.settingsPath),s=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(s);let a={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(r,JSON.stringify(a,null,2));}async function nt(t,e,n){re(n);let r=`${e}/opencode.json`,s={};try{let o=await t.files.read(r);typeof o=="string"&&(s=JSON.parse(o));}catch(o){if(!A(o))throw o}let a=Object.fromEntries(Object.entries(n).map(([o,c])=>[o,Nr(c)]));await t.files.write(r,JSON.stringify({...s,mcp:a},null,2));}function Nr(t){let e=ie(t);if(e==="stdio"&&t.command){let r={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(r.environment=t.env),r}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 G(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 Te(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||_;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function rt(){return Te("/api/managed/e2b")}function zt(t){return {"browser-use":{type:"http",url:G("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var T="EVOLVE_API_KEY",Pe="E2B_API_KEY",Ie="DAYTONA_API_KEY",Oe="MODAL_TOKEN_ID",it="MODAL_TOKEN_SECRET",Jt="claude",se=36e5,Ht=4,st=100,qt="/home/user/workspace",_=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",O="x-litellm-customer-id",L="x-litellm-tags",W="run:",Yt=".evolve-sdk/observability/sessions",Qt=100,Zt=5e3,Ae=3,ot=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,r])=>`${n} = ${E(r)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function Me(t,e){for(let[l,d]of Object.entries(e))Ze(l,d);let n=B("codex"),r=U("codex");await t.files.makeDir(n);let s="";try{let l=await t.files.read(r);typeof l=="string"&&(s=l);}catch(l){if(!A(l))throw l}let a=[],o=[];s.includes("experimental_use_rmcp_client")||(a.push("# Enable improved RMCP client (recommended)"),a.push("experimental_use_rmcp_client = true")),s.includes("[mcp_servers]")||o.push("[mcp_servers]","");for(let[l,d]of Object.entries(e)){if(s.includes(`[mcp_servers.${l}]`))continue;o.push(`[mcp_servers.${l}]`);let i=d.type??(d.command?"stdio":"http");if(i==="http"||i==="sse"||!!d.url){if(!d.url)throw new Error(`MCP server "${l}" is missing url for ${i} transport`);o.push(`url = ${E(d.url)}`),d.bearerTokenEnvVar&&o.push(`bearer_token_env_var = ${E(d.bearerTokenEnvVar)}`);let u=d.httpHeaders??d.headers;u&&Object.keys(u).length>0&&o.push(`http_headers = ${E(u)}`),d.envHttpHeaders&&Object.keys(d.envHttpHeaders).length>0&&o.push(`env_http_headers = ${E(d.envHttpHeaders)}`);}else o.push(`command = ${E(d.command)}`),d.args&&d.args.length>0&&o.push(`args = ${E(d.args)}`),d.cwd&&o.push(`cwd = ${E(d.cwd)}`);d.env&&Object.keys(d.env).length>0&&o.push(`env = ${E(d.env)}`),d.envVars&&d.envVars.length>0&&o.push(`env_vars = ${E(d.envVars)}`),o.push("");}let c=[s.trim(),a.join(`
2
- `),o.join(`
3
- `)].filter(l=>l.length>0);await t.files.write(r,c.join(`
4
-
5
- `)+`
6
- `);}async function at(t,e,n,r={}){let s=B("codex"),a=U("codex");await t.files.makeDir(s);let o="";try{let w=await t.files.read(a);typeof w=="string"&&(o=w);}catch(w){if(!A(w))throw w}let c=o.search(/^\[/m),l=c>=0?o.slice(0,c):o,d=c>=0?o.slice(c):"",i=o.includes("[model_providers.evolve-gateway]"),p=/^model_provider\s*=\s*"evolve-gateway"/m.test(l),u={[O]:n.sessionTagEnv,[L]:n.runTagEnv,...r},g=["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${E(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${E(u)}`].join(`
7
- `);if(i&&p&&o.includes(g))return;o=(l.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
8
-
9
- `)+d).replace(/\n?\[model_providers\.evolve-gateway\][\s\S]*?(?=\n\[|\s*$)/,"").replace(/^\n+/,"");let m='model_provider = "evolve-gateway"',h=g,y;if(!o.trim())y=h?`${m}
10
-
11
- ${h}
12
- `:`${m}
13
- `;else {let w=o.search(/^\[/m);w>0?y=o.slice(0,w)+m+`
14
-
15
- `+o.slice(w).trimEnd():w===0?y=m+`
16
-
17
- `+o.trimEnd():y=o.trimEnd()+`
18
-
19
- `+m,h&&(y=y.trimEnd()+`
20
-
21
- `+h),y+=`
22
- `;}await t.files.write(a,y);}async function ct(t,e,n,r){let s=V(e.configPath),a=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(a);let o=[`default_model = ${E(e.modelName)}`,`default_thinking = ${E(r.defaultThinking)}`,'default_permission_mode = "auto"',"","[thinking]",`mode = ${E(r.defaultThinking?"on":"off")}`];r.defaultThinking&&r.thinkingEffort&&o.push(`effort = ${E(r.thinkingEffort)}`),o.push("",`[providers.${e.providerName}]`,'type = "kimi"',`base_url = ${E(r.baseUrl)}`,`api_key = ${E(r.apiKey)}`,`custom_headers = ${E(n)}`,"",`[models.${e.modelName}]`,`provider = ${E(e.providerName)}`,`model = ${E(r.model)}`,`max_context_size = ${e.maxContextSize}`,`capabilities = ${E(["image_in","thinking"])}`);let c=o.join(`
23
- `)+`
24
- `;await t.files.write(s,c);}async function lt(t,e,n,r){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await Se(e,n,r);break;case "codex":await Me(e,r);break;case "gemini":await xe(e,r);break;case "qwen":await Ce(e,r);break;case "kimi":await tt(e,r);break;case "opencode":await nt(e,n,r);break;case "droid":await Ee(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function $e(){let t={};return function(d){let i;try{i=JSON.parse(d);}catch{return null}if(i._meta||i._prompt)return null;let p=i.session_id;switch(i.type){case "system":return null;case "assistant":return e(i.message?.content,"assistant",p);case "user":{let u=i.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(l,d,i){if(typeof l=="string")return d==="user"?null:[{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}];if(!l||!Array.isArray(l))return null;let p=[];for(let u of l){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:o(u.input)});else {let f=n(u);g={sessionUpdate:"tool_call",toolCallId:u.id,status:"pending",...f};}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 f=t[u.tool_use_id];if(!f||(delete t[u.tool_use_id],f.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:u.tool_use_id,status:"is_error"in u&&u.is_error?"failed":"completed",...r(u,f)};break}}g&&p.push({sessionId:i,update:g});}return p.length>0?p:null}function n(l){let d=l.name,i=l.input||{};switch(d){case "Task":return {title:i.description||"Task",kind:"think",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "NotebookRead":return {title:i.notebook_path?`Read Notebook ${i.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "NotebookEdit":return {title:i.notebook_path?`Edit Notebook ${i.notebook_path}`:"Edit Notebook",kind:"edit",content:i.new_source?[{type:"content",content:{type:"text",text:i.new_source}}]:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "Bash":return {title:i.command?"`"+i.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:i.description?[{type:"content",content:{type:"text",text:i.description}}]:[],rawInput:i};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:i};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:i};case "Read":{let p="";return i.limit?p=" ("+((i.offset??0)+1)+" - "+((i.offset??0)+i.limit)+")":i.offset&&(p=" (from line "+(i.offset+1)+")"),{title:"Read "+(i.file_path??"File")+p,kind:"read",content:[],locations:i.file_path?[{path:i.file_path,line:i.offset??0}]:[],rawInput:i}}case "LS":return {title:i.path?`List \`${i.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:i};case "Edit":{let p=i.file_path;return {title:p?`Edit \`${p}\``:"Edit",kind:"edit",content:p?[{type:"diff",path:p,oldText:i.old_string??null,newText:i.new_string??""}]:[],locations:p?[{path:p}]:[],rawInput:i}}case "Write":return {title:i.file_path?`Write ${i.file_path}`:"Write",kind:"edit",content:i.file_path?[{type:"diff",path:i.file_path,oldText:null,newText:i.content??""}]:[],locations:i.file_path?[{path:i.file_path}]:[],rawInput:i};case "Glob":{let p="Find";return i.path&&(p+=` \`${i.path}\``),i.pattern&&(p+=` \`${i.pattern}\``),{title:p,kind:"search",content:[],locations:i.path?[{path:i.path}]:[],rawInput:i}}case "Grep":{let p="grep";return i["-i"]&&(p+=" -i"),i["-n"]&&(p+=" -n"),i["-A"]!==void 0&&(p+=` -A ${i["-A"]}`),i["-B"]!==void 0&&(p+=` -B ${i["-B"]}`),i["-C"]!==void 0&&(p+=` -C ${i["-C"]}`),i.output_mode==="files_with_matches"?p+=" -l":i.output_mode==="count"&&(p+=" -c"),i.head_limit!==void 0&&(p+=` | head -${i.head_limit}`),i.glob&&(p+=` --include="${i.glob}"`),i.type&&(p+=` --type=${i.type}`),i.multiline&&(p+=" -P"),p+=` "${i.pattern??""}"`,i.path&&(p+=` ${i.path}`),{title:p,kind:"search",content:[],rawInput:i}}case "WebFetch":return {title:i.url?`Fetch ${i.url}`:"Fetch",kind:"fetch",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "WebSearch":{let p=`"${i.query??""}"`;return i.allowed_domains?.length>0&&(p+=` (allowed: ${i.allowed_domains.join(", ")})`),i.blocked_domains?.length>0&&(p+=` (blocked: ${i.blocked_domains.join(", ")})`),{title:p,kind:"fetch",content:[],rawInput:i}}case "TodoWrite":return {title:Array.isArray(i.todos)?`Update TODOs: ${i.todos.map(p=>p.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:i};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:i.plan?[{type:"content",content:{type:"text",text:i.plan}}]:[],rawInput:i};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:i}}return {title:d||"Unknown Tool",kind:"other",content:[],rawInput:i}}}function r(l,d){let i=l.content;switch(d?.name){case "Read":return Array.isArray(i)&&i.length>0?{content:i.map(p=>({type:"content",content:p.type==="text"?{type:"text",text:c(p.text)}:a(p,false)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:c(i)}}]}:{};case "Edit":case "Write":case "Bash":return s(i,l.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return s(i,"is_error"in l?l.is_error:false)}}function s(l,d=false){return Array.isArray(l)&&l.length>0?{content:l.map(i=>({type:"content",content:a(i,d)}))}:typeof l=="string"&&l.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+l+"\n```":l}}]}:{}}function a(l,d){if(l.type==="text")return d?{type:"text",text:"```\n"+l.text+"\n```"}:{type:"text",text:l.text};if(l.type==="image"){if(l.data&&l.mimeType)return {type:"image",data:l.data,mimeType:l.mimeType};if(l.source?.type==="base64")return {type:"image",data:l.source.data||"",mimeType:l.source.media_type||""};if(l.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:l.source.url}}return l}function o(l){return l.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function c(l){let d="```",i=Array.from(l.matchAll(/^```+/gm));for(let[p]of i)for(;p.length>=d.length;)d+="`";return d+`
25
- `+l+(l.endsWith(`
1
+ 'use strict';var zlib=require('zlib'),j=require('fs'),promises=require('fs/promises'),F=require('path'),promises$1=require('stream/promises'),tarStream=require('tar-stream'),events=require('events'),Ya=require('ajv'),crypto=require('crypto'),smolToml=require('smol-toml'),Co=require('zod-to-json-schema'),os=require('os'),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');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 j__namespace=/*#__PURE__*/_interopNamespace(j);var F__namespace=/*#__PURE__*/_interopNamespace(F);var Ya__default=/*#__PURE__*/_interopDefault(Ya);var Co__default=/*#__PURE__*/_interopDefault(Co);var Ni=Object.defineProperty;var er=(t,e)=>()=>(t&&(e=t(t=0)),e);var tr=(t,e)=>{for(var n in e)Ni(t,n,{get:e[n],enumerable:true});};var Ir={};tr(Ir,{ManagedModalProvider:()=>wn,ManagedModalWriteLimitError:()=>yt,_testManagedModalSandbox:()=>To});function Ro(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return new Uint8Array(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new Error(`Unsupported data type: ${typeof t}`)}function Pr(t){return {sandboxId:t.sandboxId,image:t.image??"",metadata:t.metadata??{},startedAt:t.startedAt??""}}var yt,wt,hn,yn,Ee,wn,To,Ar=er(()=>{yt=class extends Error{bytes;constructor(e,n){super(`Managed Modal ${e} body is ${n} bytes; the managed door caps every request at 1048576 bytes (1 MiB) of wire bytes, base64 inflation included. Split the payload into smaller writes.`),this.name="ManagedModalWriteLimitError",this.bytes=n;}};wt=class{constructor(e){this.config=e;}async request(e,n,r){let s=await fetch(`${this.config.baseUrl}${n}`,{...r,headers:{authorization:`Bearer ${this.config.apiKey}`,...r.headers??{}}});if(!s.ok){let a="";try{a=(await s.json())?.error??"";}catch{}throw new Error(`Managed Modal ${e} failed (${s.status})${a?`: ${a}`:""}`)}return s}json(e){return {method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}}},hn=class{constructor(e,n){this.door=e;this.sandboxId=n;}async run(e,n){let r=await this.door.request("exec",`/sandboxes/${encodeURIComponent(this.sandboxId)}/exec`,this.door.json({command:e,...n?.cwd?{cwd:n.cwd}:{},...n?.envs?{envs:n.envs}:{},...n?.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}})),s="",a="",c,l=o=>{if(!o.trim())return;let d;try{d=JSON.parse(o);}catch{throw new Error(`Managed Modal exec stream carried a garbled record: ${o}`)}d.stream==="stdout"&&typeof d.data=="string"?(s+=d.data,n?.onStdout?.(d.data)):d.stream==="stderr"&&typeof d.data=="string"?(a+=d.data,n?.onStderr?.(d.data)):c=d;};if(r.body){let o=r.body.getReader(),d=new TextDecoder,i="";for(;;){let{done:u,value:p}=await o.read();if(u)break;i+=d.decode(p,{stream:true});let g;for(;(g=i.indexOf(`
2
+ `))!==-1;)l(i.slice(0,g)),i=i.slice(g+1);}i+=d.decode(),l(i);}else for(let o of (await r.text()).split(`
3
+ `))l(o);if(c?.error!==void 0)throw new Error(`Managed Modal exec failed: ${c.error}`);if(typeof c?.exitCode!="number")throw new Error("Managed Modal exec stream ended without a terminal record \u2014 the connection died mid-run.");return {exitCode:c.exitCode,stdout:s,stderr:a}}async spawn(e,n){let r=this.run(e,n);return r.catch(()=>{}),{processId:`managed-modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:()=>r,kill:async()=>false}}async list(){return (await this.run("ps -eo pid,comm,args")).stdout.trim().split(`
4
+ `).slice(1).filter(r=>r.trim()).map(r=>{let s=r.trim().split(/\s+/);return {processId:s[0],cmd:s[1]||"",args:s.slice(2),envs:{}}})}async kill(e){return /^\d+$/.test(e)?(await this.run(`kill -9 ${e}`)).exitCode===0:false}},yn=class{constructor(e,n){this.door=e;this.sandboxId=n;}filesPath(e){return `/sandboxes/${encodeURIComponent(this.sandboxId)}/files/${e}`}encodeContent(e){return typeof e=="string"?{content:e}:{content:Buffer.from(Ro(e)).toString("base64"),encoding:"base64"}}boundedJson(e,n){let r=this.door.json(n),s=Buffer.byteLength(r.body,"utf8");if(s>1048576)throw new yt(e,s);return r}async read(e){let r=await(await this.door.request("file read",this.filesPath("read"),this.door.json({path:e}))).json();return r.encoding==="base64"?new Uint8Array(Buffer.from(r.content??"","base64")):r.content??""}async write(e,n){await this.door.request("file write",this.filesPath("write"),this.boundedJson("file write",{path:e,...this.encodeContent(n)}));}async writeBatch(e){e.length!==0&&await this.door.request("file writeBatch",this.filesPath("writeBatch"),this.boundedJson("file writeBatch",{files:e.map(n=>({path:n.path,...this.encodeContent(n.data)}))}));}async makeDir(e){await this.door.request("makeDir",this.filesPath("makeDir"),this.door.json({path:e}));}};Ee=class{constructor(e,n){this.door=e;this.sandboxId=n;this.commands=new hn(e,n),this.files=new yn(e,n);}commands;files;async getHost(e){throw new Error("Managed Modal sandboxes expose no tunnels, so getHost() is unavailable through the managed door.")}async kill(){try{await this.door.request("kill",`/sandboxes/${encodeURIComponent(this.sandboxId)}`,{method:"DELETE"});}catch(e){if(e instanceof Error&&e.message.includes("(404)"))return;throw e}}async pause(){throw new Error("Modal does not support pause/resume. Persist progress with Evolve checkpoints and resume in a fresh sandbox, or use kill() to terminate.")}async isRunning(){try{return await this.getInfo(),!0}catch(e){if(e instanceof Error&&e.message.includes("(404)"))return false;throw e}}async getInfo(){let e=await this.door.request("get",`/sandboxes/${encodeURIComponent(this.sandboxId)}`,{method:"GET"});return Pr(await e.json())}},wn=class{providerType="modal";name="Managed Modal";door;constructor(e){this.door=new wt(e);}async create(e){if(e.resources!==void 0)throw new Error("Managed Modal sandboxes are platform-sized; `resources` cannot be enforced through the managed door.");if(e.network!==void 0)throw new Error("Managed Modal sandboxes run the platform's network policy; `network` cannot be enforced through the managed door.");if(e.user!==void 0)throw new Error("Managed Modal sandboxes run as the platform's sandbox user; `user` cannot be enforced through the managed door.");if(e.idleTimeoutMs!==void 0)throw new Error("The managed Modal door takes no idle timeout; bound the sandbox with `timeoutMs` instead.");let r=await(await this.door.request("create","/sandboxes",this.door.json({...e.image?{image:e.image}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.workingDirectory?{workingDirectory:e.workingDirectory}:{},...e.envs?{envs:e.envs}:{},...e.metadata?{metadata:e.metadata}:{}}))).json();return new Ee(this.door,r.sandboxId)}async connect(e,n){let r=new Ee(this.door,e);return await r.getInfo(),r}async list(e){if(e?.state&&!e.state.includes("running"))return [];let s=((await(await this.door.request("list","/sandboxes",{method:"GET"})).json()).sandboxes??[]).map(Pr);if(e?.metadata){let a=Object.entries(e.metadata);s=s.filter(c=>a.every(([l,o])=>c.metadata[l]===o));}return e?.limit!==void 0&&(s=s.slice(0,e.limit)),s}async listAll(e){if(e?.state&&!e.state.includes("running"))return {sandboxes:[],complete:true,pagesFetched:0};let n;try{n=await this.list({...e,limit:void 0});}catch(a){return {sandboxes:[],complete:false,pagesFetched:0,error:`sandbox list failed: ${a instanceof Error?a.message:String(a)}`}}let r=e?.limit!==void 0?n.slice(0,e.limit):n,s=r.length<n.length;return {sandboxes:r,complete:!s,pagesFetched:1,...s?{error:`stopped at the requested limit of ${e?.limit} with more sandboxes available`}:{}}}},To=(t,e)=>new Ee(new wt(t),e);});var zn={};tr(zn,{tarGzipDirectory:()=>kl});async function xl(t){let e=[],n=async r=>{let s=r===""?t:F.join(t,r),a=await promises.readdir(s,{withFileTypes:true});a.sort((c,l)=>c.name<l.name?-1:c.name>l.name?1:0);for(let c of a){if(_l.has(c.name))continue;let l=r===""?c.name:`${r}/${c.name}`,o=F.join(s,c.name),d=await promises.lstat(o);d.isSymbolicLink()||(d.isDirectory()?await n(l):d.isFile()&&e.push({rel:l,abs:o,mode:d.mode&73?493:420,size:d.size}));}};return await n(""),e.sort((r,s)=>r.rel<s.rel?-1:r.rel>s.rel?1:0)}async function kl(t){let e=await xl(t),n=tarStream.pack(),r=zlib.createGzip({level:9}),s=[],a=(async()=>{for await(let l of r)s.push(Buffer.from(l));})(),c=(async()=>{for(let{rel:l,abs:o,mode:d,size:i}of e){let u=n.entry({name:l,size:i,mode:d,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"});await promises$1.pipeline(j.createReadStream(o),u);}n.finalize();})();return await Promise.all([promises$1.pipeline(n,r),c,a]),Buffer.concat(s)}var _l,Wn=er(()=>{_l=new Set([".git",".DS_Store",".venv"]);});var Fi={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},Ft={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};function L(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 We(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||E;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}var Ye=["e2b","daytona","modal"];function ye(t){return We(`/api/managed/${t}`)}function nr(){return `${ye("daytona")}/toolbox`}function jt(){return ye("e2b")}function rr(t){return {"browser-use":{type:"http",url:L("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var P="EVOLVE_API_KEY",Xe="E2B_API_KEY",Qe="DAYTONA_API_KEY",Ze="MODAL_TOKEN_ID",Kt="MODAL_TOKEN_SECRET",Jt="claude",we=36e5,sr=4,Vt=100,B="/home/user";function ir(t,e){return e?e.replace(/\/+$/,"")||"/":t?t==="root"?"/root":`/home/${t}`:B}var E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",U="x-litellm-customer-id",K="x-litellm-tags",X="run:",or=".evolve-sdk/observability/sessions",be=["tag","provider","agent","model","sandboxId","sandbox_id","timestamp","event","events"],ar=100,lr=5e3,et=3,Gt=1e3;var cr=["off","minimal","low","medium","high","xhigh","max","thinking"],dr=["off","minimal","medium","thinking"],ur="medium";function ji(t){return t==="none"?{efforts:[],defaultEffort:null}:{efforts:t==="binary"?dr:cr,defaultEffort:ur}}function pr(t,e){return e??ie[t]?.defaultReasoningEffort}function Se(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function qt(t){if(!(t==="off"||t==="none"||t==="no-thinking"))return !t||t==="thinking"||t==="medium"?"medium":t==="low"||t==="minimal"?"minimal":t==="xhigh"?"max":t}function Ki(t){let e=qt(t);return e?` --variant ${e} --thinking`:""}var ie={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",effortSupport:"level",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",defaultReasoningEffort:"high",models:[{alias:"fable",modelId:"claude-fable-5",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-5",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-5",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:"~/.evolve/skills",targetDir:"~/.claude/skills"},buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:r})=>{let s=n?"--continue ":"",a=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${s}--model ${e}${a} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",effortSupport:"level",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.6-sol",defaultReasoningEffort:"high",models:[{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Newest frontier flagship"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Balances intelligence and cost"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"High-volume, cost-sensitive tier"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Previous frontier model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.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:r})=>{let s=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${s} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",effortSupport:"none",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.6-flash",models:[{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Newest stable workhorse: coding + agentic planning"},{alias:"gemini-3.5-flash-lite",modelId:"gemini-3.5-flash-lite",description:"Most cost-effective 3.5-class model"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${ve(t)} --model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",effortSupport:"binary",defaultModel:"qwen3.7-max",defaultReasoningEffort:"thinking",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r})=>{let s=n?"--continue ":"",a=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${a} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",effortSupport:"level",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k3",defaultReasoningEffort:"max",models:[{alias:"kimi-k3",modelId:"moonshot/kimi-k3",description:"Latest flagship: 1M context, always-on thinking",maxContextSize:1048576},{alias:"kimi-k2.7-code",modelId:"moonshot/kimi-k2.7-code",description:"Latest coding-specialized standard model"},{alias:"kimi-k3-raptor",modelId:"kimi-k3-raptor",description:"Evolve-managed Kimi K3 Raptor route for latency-sensitive agent runs",maxContextSize:1048576},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","kimi-k2.7-code":"moonshot/kimi-k2.7-code","kimi-k3-raptor":"kimi-k3-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n,homeDir:r=B})=>{let s=e?"--continue ":"",a=ve(t),c=`--config-file ${r}/.kimi-code/config.toml`,l=`$(if [ -f ${r}/.kimi-code/mcp.json ]; then printf ' --mcp-config-file ${r}/.kimi-code/mcp.json'; fi)`,o=Se(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${s}${c}${l}${o} -p ${a} --output-format stream-json; else kimi ${s}-p ${a} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",effortSupport:"level",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-opus-5",defaultReasoningEffort:"high",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-5",modelId:"openrouter/anthropic/claude-opus-5",description:"Anthropic Opus 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-5",modelId:"openrouter/anthropic/claude-sonnet-5",description:"Anthropic Sonnet 5 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.6-sol",modelId:"openrouter/openai/gpt-5.6-sol",description:"OpenAI GPT-5.6 Sol via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-terra",modelId:"openrouter/openai/gpt-5.6-terra",description:"OpenAI GPT-5.6 Terra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-luna",modelId:"openrouter/openai/gpt-5.6-luna",description:"OpenAI GPT-5.6 Luna via OpenRouter"},{alias:"openrouter/google/gemini-3.6-flash",modelId:"openrouter/google/gemini-3.6-flash",description:"Gemini 3.6 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3.7-max",modelId:"openrouter/qwen/qwen3.7-max",description:"Qwen 3.7 Max via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k3",modelId:"openrouter/moonshotai/kimi-k3",description:"Kimi K3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.2",modelId:"openrouter/z-ai/glm-5.2",description:"Zhipu GLM-5.2 via OpenRouter"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,isExternalGateway:s,reasoningEffort:a})=>{let c=n?"--continue ":"",l=Ki(a);if(s)return `OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model litellm/${e} --format json${l} "${t}" < /dev/null`;let o=e.startsWith("openrouter/")?e:`openrouter/${e}`;return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model ${o} --format json${l} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model litellm/${o} --format json${l} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",effortSupport:"level",defaultModel:"claude-opus-5",defaultReasoningEffort:"high",models:[{alias:"claude-fable-5",modelId:"claude-fable-5",description:"Factory-managed Claude Fable 5"},{alias:"claude-opus-5",modelId:"claude-opus-5",description:"Factory-managed Claude Opus 5"},{alias:"claude-sonnet-5",modelId:"claude-sonnet-5",description:"Factory-managed Claude Sonnet 5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Factory-managed GPT-5.6 Sol"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Factory-managed GPT-5.6 Terra"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"Factory-managed GPT-5.6 Luna"},{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Factory-managed Gemini 3.6 Flash"},{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Qwen 3.7 Max via the Evolve gateway"},{alias:"kimi-k3",modelId:"kimi-k3",description:"Factory-managed Droid Core Kimi K3"},{alias:"glm-5.2",modelId:"glm-5.2",description:"Factory-managed Droid Core GLM-5.2"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","glm-5.2":"openrouter/z-ai/glm-5.2","qwen3.7-max":"dashscope/qwen3.7-max"},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:r,reasoningEffort:s,isDirectMode:a,isExternalGateway:c,homeDir:l=B})=>{let o=!a||c,d=o?`--settings ${l}/.factory/evolve-settings.json `:"",i=o?"custom:Evolve-Gateway-0":e,u=s?` --reasoning-effort ${s}`:"",p=n&&r?`--session-id ${ve(r)} `:"";return `printf '%s' ${ve(t)} | droid ${d}exec ${p}--skip-permissions-unsafe --cwd ${l}/workspace --output-format stream-json --model ${ve(i)}${u}`}}};function O(t){let e=ie[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function Ht(t){return t in ie}function M(t,e=B){return t.replace(/^~/,e)}function ve(t){return `'${t.replace(/'/g,"'\\''")}'`}function J(t,e=B){let n=O(t);return `${M(n.mcpConfig.settingsDir,e)}/${n.mcpConfig.filename}`}function V(t,e=B){let n=O(t);return M(n.mcpConfig.settingsDir,e)}function G(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 zt(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 _e(t){for(let[e,n]of Object.entries(t))zt(e,n);}function xe(t){return t.type?t.type:t.command?"stdio":"sse"}function Ji(t){let e=xe(t);return {...t,type:e}}function Vi(t){let{type:e,url:n,...r}=t;return xe(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function Gi(t){return {type:xe(t),...t}}function qi(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function Hi(t){let e=xe(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:a,envVars:c,...l}=t;if(e==="stdio"&&t.command)return {type:"stdio",...l};if(t.url){let o={...l,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??r;return d&&Object.keys(d).length>0&&(o.headers=d),o}return {type:e==="stdio"?"stdio":"http",...l}}async function Wt(t,e,n,r,s){_e(n);let a=V(e,s),c=J(e,s);await t.files.makeDir(a);let l={};try{let d=await t.files.read(c);typeof d=="string"&&(l=JSON.parse(d));}catch(d){if(!G(d))throw d}let o=Object.fromEntries(Object.entries(n).map(([d,i])=>[d,r(i)]));await t.files.write(c,JSON.stringify({...l,mcpServers:o},null,2));}async function tt(t,e,n,r){_e(n);let s=V("claude",r),a=J("claude",r),c=Object.fromEntries(Object.entries(n).map(([o,d])=>[o,Gi(d)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:c},null,2)),await t.files.makeDir(s);let l={};try{let o=await t.files.read(a);typeof o=="string"&&(l=JSON.parse(o));}catch(o){if(!G(o))throw o}l.enableAllProjectMcpServers=true,await t.files.write(a,JSON.stringify(l,null,2));}async function nt(t,e,n){await Wt(t,"gemini",e,Ji,n);}async function rt(t,e,n){await Wt(t,"qwen",e,Vi,n);}async function st(t,e,n,r,s){let a=V(e,s),c=J(e,s);await t.files.makeDir(a);let l={};try{let p=await t.files.read(c);typeof p=="string"&&(l=JSON.parse(p));}catch(p){if(!G(p))throw p}let o=n.split("."),d=l;for(let p=0;p<o.length-1;p++){let g=o[p];(typeof d[g]!="object"||d[g]===null)&&(d[g]={}),d=d[g];}let i=o[o.length-1],u=typeof d[i]=="object"&&d[i]!==null?d[i]:{};d[i]={...u,...r},await t.files.write(c,JSON.stringify(l,null,2));}async function Yt(t,e,n){let r=V("qwen",n),s=J("qwen",n);await t.files.makeDir(r);let a={};try{let d=await t.files.read(s);typeof d=="string"&&(a=JSON.parse(d));}catch(d){if(!G(d))throw d}let c=a.model??{},l=c.generationConfig??{},o=l.extra_body??{};a.model={...c,generationConfig:{...l,extra_body:{...o,enable_thinking:e}}},await t.files.write(s,JSON.stringify(a,null,2));}async function Xt(t,e,n){await Wt(t,"kimi",e,qi,n);}async function it(t,e,n){_e(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let a={};try{let l=await t.files.read(s);typeof l=="string"&&(a=JSON.parse(l));}catch(l){if(!G(l))throw l}let c=Object.fromEntries(Object.entries(n).map(([l,o])=>[l,Hi(o)]));await t.files.write(s,JSON.stringify({...a,mcpServers:c},null,2));}async function ot(t,e,n,r){let s=M(e.settingsPath,r),a=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(a);let c={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(c,null,2));}async function Qt(t,e,n){_e(n);let r=`${e}/opencode.json`,s={};try{let c=await t.files.read(r);typeof c=="string"&&(s=JSON.parse(c));}catch(c){if(!G(c))throw c}let a=Object.fromEntries(Object.entries(n).map(([c,l])=>[c,zi(l)]));await t.files.write(r,JSON.stringify({...s,mcp:a},null,2));}function zi(t){let e=xe(t);if(e==="stdio"&&t.command){let r={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(r.environment=t.env),r}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 Zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function gr(t,e,n){let r=t[e];if(r===void 0)return {};let s=Zt(r);if(!s){let a=Array.isArray(r)?"an array":`a ${typeof r}`;throw new Error(`Refusing to rewrite "${e}" in ${n}: expected a TOML table, found ${a}`)}return s}function en(t,e){if(t===e)return true;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((a,c)=>en(a,e[c]));let n=Zt(t),r=Zt(e);if(!n||!r)return false;let s=Object.keys(n);return s.length===Object.keys(r).length&&s.every(a=>a in r&&en(n[a],r[a]))}async function mr(t,e){let n="";try{let r=await t.files.read(e);typeof r=="string"&&(n=r);}catch(r){if(!G(r))throw r;return {}}if(!n.trim())return {};try{return smolToml.parse(n)}catch(r){throw new Error(`Failed to parse TOML at ${e}: ${r.message}`)}}async function tn(t,e,n){await t.files.write(e,smolToml.stringify(n).trimEnd()+`
5
+ `);}function Xi(t,e){let n={},r=e.type??(e.command?"stdio":"http");if(r==="http"||r==="sse"||!!e.url){if(!e.url)throw new Error(`MCP server "${t}" is missing url for ${r} transport`);n.url=e.url,e.bearerTokenEnvVar&&(n.bearer_token_env_var=e.bearerTokenEnvVar);let a=e.httpHeaders??e.headers;a&&Object.keys(a).length>0&&(n.http_headers=a),e.envHttpHeaders&&Object.keys(e.envHttpHeaders).length>0&&(n.env_http_headers=e.envHttpHeaders);}else n.command=e.command,e.args&&e.args.length>0&&(n.args=e.args),e.cwd&&(n.cwd=e.cwd);return e.env&&Object.keys(e.env).length>0&&(n.env=e.env),e.envVars&&e.envVars.length>0&&(n.env_vars=e.envVars),n}async function at(t,e,n){for(let[l,o]of Object.entries(e))zt(l,o);let r=V("codex",n),s=J("codex",n);await t.files.makeDir(r);let a=await mr(t,s);a.experimental_use_rmcp_client===void 0&&(a.experimental_use_rmcp_client=true);let c=gr(a,"mcp_servers",s);a.mcp_servers=c;for(let[l,o]of Object.entries(e))c[l]===void 0&&(c[l]=Xi(l,o));await tn(t,s,a);}async function lt(t,e,n,r={},s){let a=V("codex",s),c=J("codex",s);await t.files.makeDir(a);let l=await mr(t,c),o={...n?{[U]:n.sessionTagEnv,[K]:n.runTagEnv}:{},...r},d={name:"Evolve Gateway",base_url:e,env_key:"OPENAI_API_KEY",wire_api:"responses",...Object.keys(o).length>0?{env_http_headers:o}:{}},i=gr(l,"model_providers",c);l.model_provider==="evolve-gateway"&&en(i["evolve-gateway"],d)||(l.model_provider="evolve-gateway",i["evolve-gateway"]=d,l.model_providers=i,await tn(t,c,l));}async function nn(t,e,n,r,s){let a=M(e.configPath,s),c=a.slice(0,a.lastIndexOf("/"));await t.files.makeDir(c);let l={default_model:e.modelName,default_thinking:r.defaultThinking,default_permission_mode:"auto",thinking:{mode:r.defaultThinking?"on":"off",...r.defaultThinking&&r.thinkingEffort?{effort:r.thinkingEffort}:{}},providers:{[e.providerName]:{type:"kimi",base_url:r.baseUrl,api_key:r.apiKey,custom_headers:n}},models:{[e.modelName]:{provider:e.providerName,model:r.model,max_context_size:e.maxContextSize,capabilities:["image_in","thinking"]}}};await tn(t,a,l);}async function rn(t,e,n,r,s){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await tt(e,n,r,s);break;case "codex":await at(e,r,s);break;case "gemini":await nt(e,r,s);break;case "qwen":await rt(e,r,s);break;case "kimi":await Xt(e,r,s);break;case "opencode":await Qt(e,n,r);break;case "droid":await it(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function ct(){let t={};return function(d){let i;try{i=JSON.parse(d);}catch{return null}if(i._meta||i._prompt)return null;let u=i.session_id;switch(i.type){case "system":return null;case "assistant":return e(i.message?.content,"assistant",u);case "user":{let p=i.message?.content;return typeof p=="string"||Array.isArray(p)&&p.length===1&&p[0].type==="text"?null:e(p,"user",u)}case "result":return null;default:return null}};function e(o,d,i){if(typeof o=="string")return d==="user"?null:[{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}}}];if(!o||!Array.isArray(o))return null;let u=[];for(let p of o){let g=null;switch(p.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}};break;case "image":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:p.source?.type==="base64"?p.source.data:"",mimeType:p.source?.type==="base64"?p.source.media_type:"",uri:p.source?.type==="url"?p.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[p.id]=p,p.name==="TodoWrite")Array.isArray(p.input?.todos)&&(g={sessionUpdate:"plan",entries:c(p.input)});else {let m=n(p);g={sessionUpdate:"tool_call",toolCallId:p.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[p.tool_use_id];if(!m||(delete t[p.tool_use_id],m.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:p.tool_use_id,status:"is_error"in p&&p.is_error?"failed":"completed",...r(p,m)};break}}g&&u.push({sessionId:i,update:g});}return u.length>0?u:null}function n(o){let d=o.name,i=o.input||{};switch(d){case "Task":return {title:i.description||"Task",kind:"think",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "NotebookRead":return {title:i.notebook_path?`Read Notebook ${i.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "NotebookEdit":return {title:i.notebook_path?`Edit Notebook ${i.notebook_path}`:"Edit Notebook",kind:"edit",content:i.new_source?[{type:"content",content:{type:"text",text:i.new_source}}]:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "Bash":return {title:i.command?"`"+i.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:i.description?[{type:"content",content:{type:"text",text:i.description}}]:[],rawInput:i};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:i};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:i};case "Read":{let u="";return i.limit?u=" ("+((i.offset??0)+1)+" - "+((i.offset??0)+i.limit)+")":i.offset&&(u=" (from line "+(i.offset+1)+")"),{title:"Read "+(i.file_path??"File")+u,kind:"read",content:[],locations:i.file_path?[{path:i.file_path,line:i.offset??0}]:[],rawInput:i}}case "LS":return {title:i.path?`List \`${i.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:i};case "Edit":{let u=i.file_path;return {title:u?`Edit \`${u}\``:"Edit",kind:"edit",content:u?[{type:"diff",path:u,oldText:i.old_string??null,newText:i.new_string??""}]:[],locations:u?[{path:u}]:[],rawInput:i}}case "Write":return {title:i.file_path?`Write ${i.file_path}`:"Write",kind:"edit",content:i.file_path?[{type:"diff",path:i.file_path,oldText:null,newText:i.content??""}]:[],locations:i.file_path?[{path:i.file_path}]:[],rawInput:i};case "Glob":{let u="Find";return i.path&&(u+=` \`${i.path}\``),i.pattern&&(u+=` \`${i.pattern}\``),{title:u,kind:"search",content:[],locations:i.path?[{path:i.path}]:[],rawInput:i}}case "Grep":{let u="grep";return i["-i"]&&(u+=" -i"),i["-n"]&&(u+=" -n"),i["-A"]!==void 0&&(u+=` -A ${i["-A"]}`),i["-B"]!==void 0&&(u+=` -B ${i["-B"]}`),i["-C"]!==void 0&&(u+=` -C ${i["-C"]}`),i.output_mode==="files_with_matches"?u+=" -l":i.output_mode==="count"&&(u+=" -c"),i.head_limit!==void 0&&(u+=` | head -${i.head_limit}`),i.glob&&(u+=` --include="${i.glob}"`),i.type&&(u+=` --type=${i.type}`),i.multiline&&(u+=" -P"),u+=` "${i.pattern??""}"`,i.path&&(u+=` ${i.path}`),{title:u,kind:"search",content:[],rawInput:i}}case "WebFetch":return {title:i.url?`Fetch ${i.url}`:"Fetch",kind:"fetch",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "WebSearch":{let u=`"${i.query??""}"`;return i.allowed_domains?.length>0&&(u+=` (allowed: ${i.allowed_domains.join(", ")})`),i.blocked_domains?.length>0&&(u+=` (blocked: ${i.blocked_domains.join(", ")})`),{title:u,kind:"fetch",content:[],rawInput:i}}case "TodoWrite":return {title:Array.isArray(i.todos)?`Update TODOs: ${i.todos.map(u=>u.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:i};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:i.plan?[{type:"content",content:{type:"text",text:i.plan}}]:[],rawInput:i};default:if(d?.startsWith("mcp__")){let u=d.split("__"),p=u[1]||"mcp",g=u.slice(2).join("__")||d;return {title:`${p}: ${g}`,kind:"other",content:[],rawInput:i}}return {title:d||"Unknown Tool",kind:"other",content:[],rawInput:i}}}function r(o,d){let i=o.content;switch(d?.name){case "Read":return Array.isArray(i)&&i.length>0?{content:i.map(u=>({type:"content",content:u.type==="text"?{type:"text",text:l(u.text)}:a(u,false)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:l(i)}}]}:{};case "Edit":case "Write":case "Bash":return s(i,o.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return s(i,"is_error"in o?o.is_error:false)}}function s(o,d=false){return Array.isArray(o)&&o.length>0?{content:o.map(i=>({type:"content",content:a(i,d)}))}:typeof o=="string"&&o.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+o+"\n```":o}}]}:{}}function a(o,d){if(o.type==="text")return d?{type:"text",text:"```\n"+o.text+"\n```"}:{type:"text",text:o.text};if(o.type==="image"){if(o.data&&o.mimeType)return {type:"image",data:o.data,mimeType:o.mimeType};if(o.source?.type==="base64")return {type:"image",data:o.source.data||"",mimeType:o.source.media_type||""};if(o.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:o.source.url}}return o}function c(o){return o.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function l(o){let d="```",i=Array.from(o.matchAll(/^```+/gm));for(let[u]of i)for(;u.length>=d.length;)d+="`";return d+`
6
+ `+o+(o.endsWith(`
26
7
  `)?"":`
27
- `)+d}}function De(){return function(l){let d;try{d=JSON.parse(l);}catch{return null}if(d._meta||d._prompt)return null;let i=[];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&&i.push({update:u});break}case "item.updated":{let p=d.item;if(!p)return null;let u=n(p);u&&i.push({update:u});break}case "item.completed":{let p=d.item;if(!p)return null;let u=r(p);u&&i.push({update:u});break}default:return null}return i.length>0?i:null};function e(c){let l=c.id;switch(c.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${c.server}:${c.tool}`},{sessionUpdate:"tool_call",toolCallId:l,title:`${c.server}: ${c.tool}`,kind:"other",status:"in_progress",rawInput:c.arguments,content:[]};case "command_execution":return {type:"command_execution",name:c.command},{sessionUpdate:"tool_call",toolCallId:l,title:c.command?`\`${c.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:c.command},content:[]};case "web_search":return {type:"web_search",name:c.query},{sessionUpdate:"tool_call",toolCallId:l,title:`Search: ${c.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:o(c.items)};default:return null}}function n(c){return c.type==="todo_list"?{sessionUpdate:"plan",entries:o(c.items)}:null}function r(c){let l=c.id;switch(c.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c.text??c.summary?.join(`
28
- `)??c.content?.join(`
29
- `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:c.text??""}};case "mcp_tool_call":{let i=s(c.result),p=c.status==="failed"||c.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:l,status:p,content:i}}case "command_execution":{let i=c.aggregated_output?[{type:"content",content:{type:"text",text:c.aggregated_output}}]:[],p=c.status==="completed"||c.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:l,status:p,content:i}}case "file_change":{let i=c.changes??[],p=i.map(g=>({path:g.path})),u=i.length===1?`${i[0].kind==="add"?"Create":"Edit"} ${i[0].path}`:`Edit ${i.length} files`;return {sessionUpdate:"tool_call",toolCallId:l,title:u,kind:"edit",status:c.status==="completed"?"completed":"failed",content:i.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:p}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:l,title:`Search: ${c.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:o(c.items)};default:return null}}function s(c){return c?.content?Array.isArray(c.content)?c.content.map(l=>({type:"content",content:a(l)})):typeof c.content=="string"?[{type:"content",content:{type:"text",text:c.content}}]:[]:[]}function a(c){return c.type==="text"?{type:"text",text:c.text??""}:c.type==="image"?{type:"image",data:c.data??"",mimeType:c.mime_type??c.mimeType??"",uri:c.uri}:c}function o(c){if(!Array.isArray(c))return [];let l=false;return c.map(d=>{let i;return d.completed?i="completed":l?i="pending":(i="in_progress",l=true),{content:d.text??"",status:i,priority:"medium"}})}}var Kr={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"},jr=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 Ue(){let t=new Map,e,n=false,r="",s;return function(o){let c;try{c=JSON.parse(o);}catch{return null}if(!nn(c))return null;let l=Vr(c);if(l.sessionId&&(e=l.sessionId),l.errorText)return [j(e,l.errorText)];if(l.resultText)return r=l.resultText,n=true,[j(e,l.resultText)];if(l.handled)return null;let i=Gr(c)??c,p=tn(i);p&&(e=p);let u=[],g=x(i,"type");switch(g){case "system":return null;case "message":{let f=x(i,"role"),m=x(i,"text")||pt(i.content);if(!m)break;f==="assistant"&&(n=true,r=m,u.push(j(e,m)));break}case "completion":{let f=x(i,"finalText")||x(i,"result");f&&(!n||f!==r)&&(n=true,r=f,u.push(j(e,f)));break}case "assistant_text_delta":{let f=x(i,"textDelta")||x(i,"text");f&&(n=true,r+=f,u.push(j(e,f)));break}case "thinking_text_delta":{let f=x(i,"textDelta")||x(i,"text");if(f){let m=Xt(i,f,s);m&&(s=m.signature,u.push({sessionId:e,update:m.event}));}break}case "reasoning":{let f=x(i,"text");if(f){let m=Xt(i,f,s);m&&(s=m.signature,u.push({sessionId:e,update:m.event}));}break}case "assistant":{let f=x(i,"text")||pt(P(i.message)?.content);f&&(n=true,r=f,u.push(j(e,f)));break}case "tool_call":case "tool_call_delta":{let f=P(i.toolUse)??P(i.tool_use)??i,m=en(f,t);m&&u.push({sessionId:e,update:m});break}case "tool_result":{let f=zr(i,t);f&&u.push({sessionId:e,update:f});break}case "tool_progress_update":case "tool_progress":{let f=Jr(i);f&&u.push({sessionId:e,update:f});break}case "create_message":{for(let f of Wr(i,t)){if(f.sessionUpdate==="agent_message_chunk"){let m=f.content.type==="text"?f.content.text:"";if(n&&m===r)continue;n=true,r=m;}u.push({sessionId:e,update:f});}break}case "result":{let f=oe(i.result??i.text??i.error);f&&(n=true,r=f,u.push(j(e,f)));break}case "error":{let f=oe(i.message??i.error??i);f&&u.push(j(e,f));break}default:if(g&&!jr.has(g))return null}return u.length>0&&g!=="reasoning"&&g!=="thinking_text_delta"&&(s=void 0),u.length>0?u:null}}function Xt(t,e,n){let r=dt(t,"id")||dt(t,"messageId"),s=dt(t,"blockIndex"),a=`${x(t,"type")}:${r}:${s}:${e}`;return a===n?null:{signature:a,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function Vr(t){if(t.type!=="response")return {handled:false};let e=P(t.result),n=P(t.error),r=tn(e??t);if(n)return {handled:true,sessionId:r,errorText:oe(n.message??n)};let s=e?x(e,"finalText")||x(e,"result"):"";return {handled:true,sessionId:r,resultText:s}}function Gr(t){return t.method!=="droid.session_notification"?null:P(P(t.params)?.notification)}function Wr(t,e){let n=P(t.message);if(!n)return [];let r=[],s=n.content;if(Array.isArray(s))for(let a of s){let o=P(a);if(o&&o.type==="tool_use"){let c=en(o,e);c&&r.push(c);}}if(n.role==="assistant"){let a=pt(s);a&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}});}return r}function en(t,e){let n=x(t,"id")||x(t,"toolUseId")||x(t,"tool_use_id"),r=x(t,"name")||x(t,"toolName")||x(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let s=P(t.input)??P(t.toolInput)??P(t.arguments)??{};if(rn(r)==="todowrite"){let d=Hr(s);if(d)return d}let{title:a,kind:o,content:c,locations:l}=qr(r,s);return {sessionUpdate:"tool_call",toolCallId:n,title:a,kind:o,status:"pending",rawInput:s,content:c,locations:l}}function zr(t,e){let n=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id");if(!n)return null;let r=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:r,content:ut(t.content??t.result??t.error)}}function Jr(t){let e=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id");if(!e)return null;let n=P(t.update),r=oe(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?ut(r):void 0}}function Hr(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let s=P(r);if(!s)return [];let a=x(s,"content"),o=Yr(x(s,"status")),c=Qr(x(s,"priority"));return a?[{content:a,status:o,priority:c}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function qr(t,e){let n=Kr[rn(t)]||"other",r=x(e,"path")||x(e,"filePath")||x(e,"file_path")||x(e,"absolute_path"),s=x(e,"command"),a=x(e,"url"),o=r||s||a;return {title:o?`${t} ${o}`:t,kind:n,content:Object.keys(e).length>0?ut(e):[],locations:r?[{path:r}]:[]}}function tn(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 pt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=P(e);return n?x(n,"text")||x(n,"content"):""}).filter(Boolean).join(""):""}function ut(t){let e=oe(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function oe(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function nn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function P(t){return nn(t)?t:null}function x(t,e){let n=t[e];return typeof n=="string"?n:""}function dt(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function rn(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Yr(t){return t==="in_progress"||t==="completed"?t:"pending"}function Qr(t){return t==="high"||t==="low"?t:"medium"}var Zr={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 Be(){return function(o){let c;try{c=JSON.parse(o);}catch{return null}if(c._meta||c._prompt)return null;let l=c.session_id,d=[];switch(c.type){case "init":case "result":return null;case "message":{let i=t(c);i&&d.push({sessionId:l,update:i});break}case "tool_use":{let i=e(c);i&&d.push({sessionId:l,update:i});break}case "tool_result":{let i=n(c);i&&d.push({sessionId:l,update:i});break}case "error":{let i=r(c);i&&d.push({sessionId:l,update:i});break}default:return null}return d.length>0?d:null};function t(a){let o=a.role,c=a.content;return c?o==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}:o==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:c}}:null:null}function e(a){let o=a.tool_id,c=a.tool_name,l=a.parameters||{},{title:d,kind:i,content:p,locations:u}=s(c,l);return {sessionUpdate:"tool_call",toolCallId:o,title:d,kind:i,status:"pending",rawInput:l,content:p,locations:u}}function n(a){let o=a.tool_id,c=a.status,l=a.output,d=a.error,i=[];return l&&typeof l=="string"&&l.length>0&&i.push({type:"content",content:{type:"text",text:c==="error"?`\`\`\`
30
- ${l}
31
- \`\`\``:l}}),d?.message&&!l&&i.push({type:"content",content:{type:"text",text:`\`\`\`
8
+ `)+d}}function dt(){return function(o){let d;try{d=JSON.parse(o);}catch{return null}if(d._meta||d._prompt)return null;let i=[];switch(d.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "error":{let u=typeof d.message=="string"?d.message:JSON.stringify(d);i.push({update:{sessionUpdate:"error",message:u,fatal:false}});break}case "turn.failed":{let u=typeof d.error?.message=="string"?d.error.message:JSON.stringify(d.error??d);i.push({update:{sessionUpdate:"error",message:u,fatal:true}});break}case "item.started":{let u=d.item;if(!u)return null;let p=e(u);p&&i.push({update:p});break}case "item.updated":{let u=d.item;if(!u)return null;let p=n(u);p&&i.push({update:p});break}case "item.completed":{let u=d.item;if(!u)return null;let p=r(u);p&&i.push({update:p});break}default:return null}return i.length>0?i:null};function e(l){let o=l.id;switch(l.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${l.server}:${l.tool}`},{sessionUpdate:"tool_call",toolCallId:o,title:`${l.server}: ${l.tool}`,kind:"other",status:"in_progress",rawInput:l.arguments,content:[]};case "command_execution":return {type:"command_execution",name:l.command},{sessionUpdate:"tool_call",toolCallId:o,title:l.command?`\`${l.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:l.command},content:[]};case "web_search":return {type:"web_search",name:l.query},{sessionUpdate:"tool_call",toolCallId:o,title:`Search: ${l.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:c(l.items)};default:return null}}function n(l){return l.type==="todo_list"?{sessionUpdate:"plan",entries:c(l.items)}:null}function r(l){let o=l.id;switch(l.type){case "error":return {sessionUpdate:"error",message:typeof l.message=="string"?l.message:JSON.stringify(l),fatal:false};case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.text??l.summary?.join(`
9
+ `)??l.content?.join(`
10
+ `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text??""}};case "mcp_tool_call":{let i=s(l.result),u=l.status==="failed"||l.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:o,status:u,content:i}}case "command_execution":{let i=l.aggregated_output?[{type:"content",content:{type:"text",text:l.aggregated_output}}]:[],u=l.status==="completed"||l.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:o,status:u,content:i}}case "file_change":{let i=l.changes??[],u=i.map(g=>({path:g.path})),p=i.length===1?`${i[0].kind==="add"?"Create":"Edit"} ${i[0].path}`:`Edit ${i.length} files`;return {sessionUpdate:"tool_call",toolCallId:o,title:p,kind:"edit",status:l.status==="completed"?"completed":"failed",content:i.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:u}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:o,title:`Search: ${l.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:c(l.items)};default:return null}}function s(l){return l?.content?Array.isArray(l.content)?l.content.map(o=>({type:"content",content:a(o)})):typeof l.content=="string"?[{type:"content",content:{type:"text",text:l.content}}]:[]:[]}function a(l){return l.type==="text"?{type:"text",text:l.text??""}:l.type==="image"?{type:"image",data:l.data??"",mimeType:l.mime_type??l.mimeType??"",uri:l.uri}:l}function c(l){if(!Array.isArray(l))return [];let o=false;return l.map(d=>{let i;return d.completed?i="completed":o?i="pending":(i="in_progress",o=true),{content:d.text??"",status:i,priority:"medium"}})}}var Qi={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"},Zi=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 ut(){let t=new Map,e,n=false,r="",s;return function(c){let l;try{l=JSON.parse(c);}catch{return null}if(!wr(l))return null;let o=eo(l);if(o.sessionId&&(e=o.sessionId),o.errorText)return [z(e,o.errorText)];if(o.resultText)return r=o.resultText,n=true,[z(e,o.resultText)];if(o.handled)return null;let i=to(l)??l,u=yr(i);u&&(e=u);let p=[],g=x(i,"type");switch(g){case "system":return null;case "message":{let m=x(i,"role"),f=x(i,"text")||on(i.content);if(!f)break;m==="assistant"&&(n=true,r=f,p.push(z(e,f)));break}case "completion":{let m=x(i,"finalText")||x(i,"result");m&&(!n||m!==r)&&(n=true,r=m,p.push(z(e,m)));break}case "assistant_text_delta":{let m=x(i,"textDelta")||x(i,"text");m&&(n=true,r+=m,p.push(z(e,m)));break}case "thinking_text_delta":{let m=x(i,"textDelta")||x(i,"text");if(m){let f=fr(i,m,s);f&&(s=f.signature,p.push({sessionId:e,update:f.event}));}break}case "reasoning":{let m=x(i,"text");if(m){let f=fr(i,m,s);f&&(s=f.signature,p.push({sessionId:e,update:f.event}));}break}case "assistant":{let m=x(i,"text")||on(I(i.message)?.content);m&&(n=true,r=m,p.push(z(e,m)));break}case "tool_call":case "tool_call_delta":{let m=I(i.toolUse)??I(i.tool_use)??i,f=hr(m,t);f&&p.push({sessionId:e,update:f});break}case "tool_result":{let m=ro(i,t);m&&p.push({sessionId:e,update:m});break}case "tool_progress_update":case "tool_progress":{let m=so(i);m&&p.push({sessionId:e,update:m});break}case "create_message":{for(let m of no(i,t)){if(m.sessionUpdate==="agent_message_chunk"){let f=m.content.type==="text"?m.content.text:"";if(n&&f===r)continue;n=true,r=f;}p.push({sessionId:e,update:m});}break}case "result":{let m=ke(i.result??i.text??i.error);m&&(n=true,r=m,p.push(z(e,m)));break}case "error":{let m=ke(i.message??i.error??i);m&&p.push(z(e,m));break}default:if(g&&!Zi.has(g))return null}return p.length>0&&g!=="reasoning"&&g!=="thinking_text_delta"&&(s=void 0),p.length>0?p:null}}function fr(t,e,n){let r=sn(t,"id")||sn(t,"messageId"),s=sn(t,"blockIndex"),a=`${x(t,"type")}:${r}:${s}:${e}`;return a===n?null:{signature:a,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function eo(t){if(t.type!=="response")return {handled:false};let e=I(t.result),n=I(t.error),r=yr(e??t);if(n)return {handled:true,sessionId:r,errorText:ke(n.message??n)};let s=e?x(e,"finalText")||x(e,"result"):"";return {handled:true,sessionId:r,resultText:s}}function to(t){return t.method!=="droid.session_notification"?null:I(I(t.params)?.notification)}function no(t,e){let n=I(t.message);if(!n)return [];let r=[],s=n.content;if(Array.isArray(s))for(let a of s){let c=I(a);if(c&&c.type==="tool_use"){let l=hr(c,e);l&&r.push(l);}}if(n.role==="assistant"){let a=on(s);a&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}});}return r}function hr(t,e){let n=x(t,"id")||x(t,"toolUseId")||x(t,"tool_use_id"),r=x(t,"name")||x(t,"toolName")||x(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let s=I(t.input)??I(t.toolInput)??I(t.arguments)??I(t.parameters)??{};if(br(r)==="todowrite"){let d=io(s);if(d)return d}let{title:a,kind:c,content:l,locations:o}=oo(r,s);return {sessionUpdate:"tool_call",toolCallId:n,title:a,kind:c,status:"pending",rawInput:s,content:l,locations:o}}function ro(t,e){let n=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id")||x(t,"id")||x(t,"toolId");if(!n)return null;let r=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:r,content:an(t.content??t.result??t.value??t.error)}}function so(t){let e=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id")||x(t,"id")||x(t,"toolId");if(!e)return null;let n=I(t.update),r=ke(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?an(r):void 0}}function io(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let s=I(r);if(!s)return [];let a=x(s,"content"),c=ao(x(s,"status")),l=lo(x(s,"priority"));return a?[{content:a,status:c,priority:l}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function oo(t,e){let n=Qi[br(t)]||"other",r=x(e,"path")||x(e,"filePath")||x(e,"file_path")||x(e,"absolute_path"),s=x(e,"command"),a=x(e,"url"),c=r||s||a;return {title:c?`${t} ${c}`:t,kind:n,content:Object.keys(e).length>0?an(e):[],locations:r?[{path:r}]:[]}}function yr(t){if(t)return x(t,"session_id")||x(t,"sessionId")}function z(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function on(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=I(e);return n?x(n,"text")||x(n,"content"):""}).filter(Boolean).join(""):""}function an(t){let e=ke(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function ke(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function wr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function I(t){return wr(t)?t:null}function x(t,e){let n=t[e];return typeof n=="string"?n:""}function sn(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function br(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function ao(t){return t==="in_progress"||t==="completed"?t:"pending"}function lo(t){return t==="high"||t==="low"?t:"medium"}var co={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 pt(){return function(c){let l;try{l=JSON.parse(c);}catch{return null}if(l._meta||l._prompt)return null;let o=l.session_id,d=[];switch(l.type){case "init":case "result":return null;case "message":{let i=t(l);i&&d.push({sessionId:o,update:i});break}case "tool_use":{let i=e(l);i&&d.push({sessionId:o,update:i});break}case "tool_result":{let i=n(l);i&&d.push({sessionId:o,update:i});break}case "error":{let i=r(l);i&&d.push({sessionId:o,update:i});break}default:return null}return d.length>0?d:null};function t(a){let c=a.role,l=a.content;return l?c==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}:c==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:l}}:null:null}function e(a){let c=a.tool_id,l=a.tool_name,o=a.parameters||{},{title:d,kind:i,content:u,locations:p}=s(l,o);return {sessionUpdate:"tool_call",toolCallId:c,title:d,kind:i,status:"pending",rawInput:o,content:u,locations:p}}function n(a){let c=a.tool_id,l=a.status,o=a.output,d=a.error,i=[];return o&&typeof o=="string"&&o.length>0&&i.push({type:"content",content:{type:"text",text:l==="error"?`\`\`\`
11
+ ${o}
12
+ \`\`\``:o}}),d?.message&&!o&&i.push({type:"content",content:{type:"text",text:`\`\`\`
32
13
  ${d.message}
33
- \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:o,status:c==="success"?"completed":"failed",content:i}}function r(a){let o=a.severity,c=a.message;return c?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${o==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${c}`}}:null}function s(a,o){let c=Zr[a]||"other",l=[],d=[],i=a;switch(a){case "read_file":i=`Read ${o.absolute_path||o.file_path||"file"}`,(o.absolute_path||o.file_path)&&d.push({path:o.absolute_path||o.file_path});break;case "write_file":i=`Write ${o.file_path||"file"}`,o.file_path&&(d.push({path:o.file_path}),l.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "edit_file":i=`Edit ${o.file_path||"file"}`,o.file_path&&d.push({path:o.file_path});break;case "replace":i=`Edit ${o.file_path||"file"}`,o.file_path&&(d.push({path:o.file_path}),(o.old_string!==void 0||o.new_string!==void 0)&&l.push({type:"diff",path:o.file_path,oldText:o.old_string||"",newText:o.new_string||""}));break;case "run_shell_command":case "shell":i=o.command?`\`${o.command}\``:"Run command",o.description&&l.push({type:"content",content:{type:"text",text:o.description}});break;case "brave_web_search":case "web_search":case "google_web_search":i=o.query?`"${o.query}"`:"Web search";break;case "web_fetch":i=o.prompt?`Fetch: ${o.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${o.pattern||"files"}`,o.dir_path&&d.push({path:o.dir_path});break;case "grep":case "search_file_content":i=`grep "${o.pattern||o.query||""}"`;break;case "list_directory":i=`List ${o.dir_path||o.path||"directory"}`,(o.dir_path||o.path)&&d.push({path:o.dir_path||o.path});break;case "read_many_files":i=`Read ${o.include?.length||"multiple"} files`,Array.isArray(o.include)&&o.include.forEach(p=>d.push({path:p}));break;case "delegate_to_agent":i=o.agent_name?`Agent: ${o.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=o.fact?`Remember: "${o.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=o.name?`Activate skill: ${o.name}`:"Activate skill";break;default:i=a;}return {title:i,kind:c,content:l,locations:d}}}var Xr={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function sn(t){return t==="TodoList"||t==="SetTodoList"}function ft(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function an(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function mt(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=an(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 gt(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 r=mt(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=mt(t);n&&e.push(n);}return e}function ei(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&ft(e.content.text))}function ti(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=an(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 ni(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function on(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 r=n.title;if(typeof r!="string"||r.length===0)return null;let s=n.status;return {content:r,status:ni(s),priority:"medium"}}).filter(n=>n!==null):[]}function ht(){let t=new Set,e=0;function n(c,l){return typeof c=="string"&&c.length>0?c:(e+=1,`kimi_${l.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(l){let d;try{d=JSON.parse(l);}catch{return null}if(!d||typeof d!="object")return null;let i=d.role;return "_meta"in d||"_prompt"in d||i==="meta"?null:i==="assistant"?r(d):i==="tool"?s(d):typeof d.type=="string"&&"payload"in d?a(d):null};function r(c){let l=[],d=c.content,i=c.tool_calls;if(typeof d=="string"&&d.length>0)l.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let p of d){let u=ti(p);u&&l.push(u);}if(Array.isArray(i))for(let p of i){if(!p||typeof p!="object")continue;let u=p.function;if(!u)continue;let g=u.name??"",f=n(p.id,g),m;try{m=u.arguments?JSON.parse(u.arguments):{};}catch{m=u.arguments;}if(sn(g)){let k=on(m);k.length>0&&l.push({update:{sessionUpdate:"plan",entries:k}}),t.add(f);continue}let{title:h,kind:y,toolContent:w,locations:S}=o(g,typeof m=="object"&&m!==null?m:{});l.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:m,content:w,locations:S}});}return l.length>0?l:null}function s(c){let l=c.tool_call_id;if(typeof l!="string"||l.length===0)return null;if(t.has(l))return t.delete(l),null;let d=c.content,i=[],p=false;if(typeof d=="string")p=ft(d),d.length>0&&i.push({type:"content",content:{type:"text",text:d}});else if(Array.isArray(d))for(let u of d){let g=mt(u);g&&(g.type==="content"&&g.content.type==="text"&&ft(g.content.text)&&(p=true),i.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:l,status:p?"failed":"completed",content:i}}]}function a(c){let l=c.type,d=c.payload??{},i=[];switch(l){case "TextPart":{let p=d.text;typeof p=="string"&&p.length>0&&i.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});break}case "ThinkPart":{let p=d.think;typeof p=="string"&&p.length>0&&i.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 f;try{f=g.arguments?JSON.parse(g.arguments):{};}catch{f=g.arguments;}if(sn(p)){let S=on(f);S.length>0&&i.push({update:{sessionUpdate:"plan",entries:S}}),t.add(u);break}let{title:m,kind:h,toolContent:y,locations:w}=o(p,typeof f=="object"&&f!==null?f:{});i.push({update:{sessionUpdate:"tool_call",toolCallId:u,title:m,kind:h,status:"pending",rawInput:f,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=[],f=d.is_error===true;if(u&&typeof u=="object"&&!Array.isArray(u)){let m=u;f=f||m.type==="ToolError"||m.is_error===true,g.push(...gt(m.output)),g.length===0&&typeof m.message=="string"&&m.message.length>0&&g.push({type:"content",content:{type:"text",text:m.message}}),g.length===0&&g.push(...gt(u));}else g.push(...gt(u));f=f||ei(g),i.push({update:{sessionUpdate:"tool_call_update",toolCallId:p,status:f?"failed":"completed",content:g}});break}default:return null}return i.length>0?i:null}function o(c,l){let d=Xr[c]||"other",i=[],p=[],u=c;switch(c){case "Read":case "ReadFile":{let g=l.path??l.file_path;u=`Read ${g||"file"}`,g&&p.push({path:g});break}case "ReadMediaFile":{let g=l.path??l.file_path;u=`Read media ${g||"file"}`,g&&p.push({path:g});break}case "Write":case "WriteFile":{let g=l.path??l.file_path;u=`Write ${g||"file"}`,g&&(p.push({path:g}),typeof l.content=="string"&&i.push({type:"diff",path:g,oldText:null,newText:l.content}));break}case "Edit":case "StrReplaceFile":{let g=l.path??l.file_path;u=`Edit ${g||"file"}`,g&&p.push({path:g});break}case "Bash":case "Shell":u=l.command?`\`${l.command}\``:"Run command";break;case "Glob":u=`Find ${l.pattern||"files"}`,l.path&&p.push({path:l.path});break;case "Grep":u=`grep "${l.pattern||""}"`,l.path&&p.push({path:l.path});break;case "WebSearch":case "SearchWeb":u=l.query?`"${l.query}"`:"Web search";break;case "FetchURL":u=l.url?`Fetch ${l.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":u=l.description||"Subagent task";break;case "Think":u=l.thought||"Thinking";break;case "CreateSubagent":u=l.name?`Subagent: ${l.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":u="Update todos";break;default:u=c;}return {title:u,kind:d,toolContent:i,locations:p}}}var ri={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 ii(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function si(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 oi(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function cn(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:si(e.status),priority:oi(e.priority)}}).filter(e=>e!==null):[]}function ai(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let c=ii(r);return c?{type:"content",content:{type:"image",data:c.data,mimeType:c.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function ci(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 li(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function yt(){return function(o){let c;try{c=JSON.parse(o);}catch{return null}if(!c||typeof c!="object")return null;let l=c.sessionID,d=[];switch(c.type){case "step_start":case "step_finish":return null;case "text":{let i=t(c);i&&d.push({sessionId:l,update:i});break}case "reasoning":{let i=e(c);i&&d.push({sessionId:l,update:i});break}case "tool_use":{let i=n(c);for(let p of i)d.push({sessionId:l,update:p});break}case "error":{let i=r(c);i&&d.push({sessionId:l,update:i});break}default:return null}return d.length>0?d:null};function t(a){let o=a.part?.text;return typeof o!="string"||o.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}}}function e(a){let o=a.part?.text;return typeof o!="string"||o.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:o}}}function n(a){let o=a.part;if(!o)return [];let c=typeof o.callID=="string"?o.callID:"";if(c.length===0)return [];let l=typeof o.tool=="string"?o.tool.toLowerCase():"",d=typeof o.state=="object"&&o.state?o.state:{},i=typeof d.input=="object"&&d.input?d.input:{},p=d.status,u=d.title??d.metadata?.description??l,g=d.metadata?.exit,{kind:f,content:m,locations:h}=s(l,i),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:c,title:u,kind:f,status:"pending",rawInput:i,content:m,locations:h}),l==="todowrite"){let v=cn(i.todos);if(v.length===0&&typeof d.output=="string")try{v=cn(JSON.parse(d.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=li(p,g);if(w==="pending")return y;let S=ci(p,d),k=[];if(typeof S=="string"&&S.length>0&&k.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=ai(v);b&&k.push(b);}return y.push({sessionUpdate:"tool_call_update",toolCallId:c,status:w,content:k}),y}function r(a){let o=a.error?.name??"Error",c=a.error?.data?.message??a.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${o}: ${c}`}}}function s(a,o){let c=ri[a]||"other",l=[],d=[];switch(a){case "read":{let i=o.filePath??o.path;if(i){let p=o.offset;d.push({path:i,line:typeof p=="number"&&Number.isFinite(p)?Math.max(0,p-1):void 0});}break}case "write":{let i=o.filePath??o.path;i&&(d.push({path:i}),typeof o.content=="string"&&l.push({type:"diff",path:i,oldText:null,newText:o.content}));break}case "edit":case "multiedit":{let i=o.filePath??o.path;i&&(d.push({path:i}),a==="edit"&&(o.oldString!==void 0||o.newString!==void 0)&&l.push({type:"diff",path:i,oldText:o.oldString??"",newText:o.newString??""}));break}case "apply_patch":break;case "bash":{let i=o.command;i&&o.description?l.push({type:"content",content:{type:"text",text:o.description}}):i&&l.push({type:"content",content:{type:"text",text:i}});break}case "glob":case "list":{let i=o.path;i&&d.push({path:i});break}case "grep":{let i=o.path;i&&d.push({path:i});break}case "codesearch":case "websearch":{let i=o.query;i&&l.push({type:"content",content:{type:"text",text:i}});break}case "webfetch":{let i=o.url;i&&l.push({type:"content",content:{type:"text",text:i}});break}case "task":{let i=o.description;i&&l.push({type:"content",content:{type:"text",text:i}});break}}return {kind:c,content:l,locations:d}}}var di={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 Le(){let t=new Map,e=new Map;return function(i){let p;try{p=JSON.parse(i);}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,f=[];switch(u.type){case "assistant":{let m=n(u);for(let h of m)f.push({sessionId:g,update:h});break}case "stream_event":{let m=r(u);for(let h of m)f.push({sessionId:g,update:h});break}case "user":{let m=s(u);for(let h of m)f.push({sessionId:g,update:h});break}case "system":case "result":return null;default:return null}return f.length>0?f:null};function n(d){let i=[],p=d.message?.content;if(!Array.isArray(p))return i;for(let u of p){let g=a(u);i.push(...g);}return i}function r(d){let i=[],p=d.event;if(!p)return i;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,f=t.get(u);if(g?.type==="text_delta"&&g.text)i.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:g.text}});else if(g?.type==="thinking_delta"&&g.thinking)i.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g.thinking}});else if(g?.type==="input_json_delta"&&g.partial_json&&f?.type==="tool_use"){let m=e.get(u)||"";e.set(u,m+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 f=g,m=e.get(u)||"";e.delete(u);let h=f.input;if(m)try{h=JSON.parse(m);}catch{}let y={...f,input:h},w=o(y);w&&i.push(w);}else if(g.type==="tool_result"){let f=c(g);f&&i.push(f);}}}t.delete(u);break}}return i}function s(d){let i=d.message?.content,p=[];if(typeof i=="string")return p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:i}}),p;if(Array.isArray(i)){for(let u of i)if(u.type==="text")p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:u.text}});else if(u.type==="tool_result"){let g=c(u);g&&p.push(g);}}return p}function a(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 i=o(d);return i?[i]:[]}case "tool_result":{let i=c(d);return i?[i]:[]}}}function o(d){let i=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:f,content:m,locations:h}=l(p,u||{});return {sessionUpdate:"tool_call",toolCallId:i,title:g,kind:f,status:"pending",rawInput:u,content:m,locations:h}}function c(d){let i=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
- ${u}
37
- \`\`\``:u}});else if(Array.isArray(u)){for(let f of u)if(f.type==="text"){let m=f.text;g.push({type:"content",content:{type:"text",text:p?`\`\`\`
38
- ${m}
39
- \`\`\``:m}});}}return {sessionUpdate:"tool_call_update",toolCallId:i,status:p?"failed":"completed",content:g}}function l(d,i){let p=di[d]||"other",u=[],g=[],f=d;switch(d){case "Read":case "read_file":f=`Read ${i.file_path||i.absolute_path||"file"}`,(i.file_path||i.absolute_path)&&g.push({path:i.file_path||i.absolute_path});break;case "Write":case "write_file":f=`Write ${i.file_path||"file"}`,i.file_path&&(g.push({path:i.file_path}),u.push({type:"diff",path:i.file_path,oldText:null,newText:i.content||""}));break;case "Edit":case "edit_file":f=`Edit ${i.file_path||"file"}`,i.file_path&&g.push({path:i.file_path});break;case "Bash":case "shell":case "run_shell_command":f=i.command?`\`${i.command}\``:"Run command",i.description&&u.push({type:"content",content:{type:"text",text:i.description}});break;case "WebFetch":f=i.url?`Fetch ${i.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=i.query?`"${i.query}"`:"Web search";break;case "Glob":f=`Find ${i.pattern||"files"}`,i.path&&g.push({path:i.path});break;case "Grep":f=`grep "${i.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${i.path||"directory"}`,i.path&&g.push({path:i.path});break;case "Task":f=i.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=d;}return {title:f,kind:p,content:u,locations:g}}}function ln(t){return Le()(t)}function z(t){switch(t){case "claude":return $e();case "codex":return De();case "gemini":return Be();case "qwen":return Le();case "kimi":return ht();case "opencode":return yt();case "droid":return Ue();default:return ()=>null}}function pi(t,e){let n=e.trim();return n?z(t)(n):null}function ui(t,e){let n=[],r=e.split(`
40
- `),s=z(t);for(let a of r){let o=a.trim();if(!o)continue;let c=s(o);c&&n.push(...c);}return n}function M(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function q(t){return JSON.stringify(gi__default.default(t,{target:"jsonSchema7"}),null,2)}function Y(t){return JSON.stringify(t,null,2)}function dn(t,e=false){let n={};function r(s,a){for(let o of $__namespace.readdirSync(s)){let c=ae__namespace.join(s,o),l=a?`${a}/${o}`:o;$__namespace.statSync(c).isDirectory()?e&&r(c,l):n[l]=$__namespace.readFileSync(c);}}return r(t,""),n}function pn(t,e){for(let[n,r]of Object.entries(e)){let s=ae__namespace.join(t,n),a=ae__namespace.dirname(s);$__namespace.mkdirSync(a,{recursive:true});let o;r instanceof ArrayBuffer||r instanceof Uint8Array?o=Buffer.from(r):o=r,$__namespace.writeFileSync(s,o);}}function fi(t){let e=t.replace(/^~/,process.env.HOME||"");if(!$__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return $__namespace.readFileSync(e,"utf-8")}function Ne(t){let e=t?.type??Jt,n=D(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 o=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,c=t.providerBaseUrl??o??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:c,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 r=process.env[T];if(r)return {type:e,apiKey:r,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let c=(t?.model??n.defaultModel)?.split("/")[0],l=c?n.providerEnvMap[c]:void 0,d=l?process.env[l.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 s=process.env[n.apiKeyEnv];if(s){let c=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:s,baseUrl:c,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let o=process.env[n.oauthEnv];if(o){if(n.oauthFileName){let c=fi(o);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:c,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:o,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let a=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)${a}, or ${T} / ${n.apiKeyEnv} env var.`)}function mi(t){return `e2b_${Buffer.from(t,"utf8").toString("hex")}`}async function wt(){let t=process.env[Pe];if(t)try{let{createE2BProvider:a}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===rt()&&delete process.env.E2B_API_URL,a({apiKey:t})}catch(a){let o=a;throw o.message?.includes("Cannot find module")||o.message?.includes("MODULE_NOT_FOUND")?new Error(`${Pe} is set but @evolvingmachines/e2b failed to load.
41
- Try reinstalling: npm install @evolvingmachines/sdk`):o}let e=process.env[Ie];if(e)try{let{createDaytonaProvider:a}=await import('@evolvingmachines/daytona');return a({apiKey:e})}catch(a){let o=a;throw o.message?.includes("Cannot find module")||o.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ie} is set but @evolvingmachines/daytona failed to load.
42
- Try installing: npm install @evolvingmachines/daytona`):o}let n=process.env[Oe],r=process.env[it];if(n&&r)try{let{createModalProvider:a}=await import('@evolvingmachines/modal');return a({tokenId:n,tokenSecret:r})}catch(a){let o=a;throw o.message?.includes("Cannot find module")||o.message?.includes("MODULE_NOT_FOUND")?new Error(`${Oe} is set but @evolvingmachines/modal failed to load.
43
- Try installing: npm install @evolvingmachines/modal`):o}let s=process.env[T];if(s)try{let{createE2BProvider:a}=await import('@evolvingmachines/e2b');return a({apiKey:mi(s),apiUrl:rt()})}catch(a){let o=a;throw o.message?.includes("Cannot find module")||o.message?.includes("MODULE_NOT_FOUND")?new Error(`${T} is set but @evolvingmachines/e2b failed to load.
44
- Try reinstalling: npm install @evolvingmachines/sdk`):o}throw new Error(`No sandbox provider configured. Either:
45
- 1. Set ${T} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
46
- 2. Set ${Pe} environment variable (direct E2B access, get key at https://e2b.dev)
47
- 3. Set ${Ie} environment variable (direct Daytona access, get key at https://app.daytona.io)
48
- 4. Set ${Oe} and ${it} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
49
- 5. Pass sandbox explicitly: .withSandbox(provider)`)}function hi(t){return new Promise(e=>setTimeout(e,t))}async function I(t,e,n=0){let r=yi(e),s=e?.onItemRetry,a=null,o=0,c=r.backoffMs;for(;o<r.maxAttempts;){if(o++,a=await t(o),!r.retryOn(a))return a;if(o>=r.maxAttempts)break;if(s){let l=a.error??"Unknown error";s(n,o,l);}await hi(c),c*=r.backoffMultiplier;}return a}function yi(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var un=`## FILESYSTEM INSTRUCTIONS:
14
+ \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:c,status:l==="success"?"completed":"failed",content:i}}function r(a){let c=a.severity,l=a.message;return l?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${c==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${l}`}}:null}function s(a,c){let l=co[a]||"other",o=[],d=[],i=a;switch(a){case "read_file":i=`Read ${c.absolute_path||c.file_path||"file"}`,(c.absolute_path||c.file_path)&&d.push({path:c.absolute_path||c.file_path});break;case "write_file":i=`Write ${c.file_path||"file"}`,c.file_path&&(d.push({path:c.file_path}),o.push({type:"diff",path:c.file_path,oldText:null,newText:c.content||""}));break;case "edit_file":i=`Edit ${c.file_path||"file"}`,c.file_path&&d.push({path:c.file_path});break;case "replace":i=`Edit ${c.file_path||"file"}`,c.file_path&&(d.push({path:c.file_path}),(c.old_string!==void 0||c.new_string!==void 0)&&o.push({type:"diff",path:c.file_path,oldText:c.old_string||"",newText:c.new_string||""}));break;case "run_shell_command":case "shell":i=c.command?`\`${c.command}\``:"Run command",c.description&&o.push({type:"content",content:{type:"text",text:c.description}});break;case "brave_web_search":case "web_search":case "google_web_search":i=c.query?`"${c.query}"`:"Web search";break;case "web_fetch":i=c.prompt?`Fetch: ${c.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${c.pattern||"files"}`,c.dir_path&&d.push({path:c.dir_path});break;case "grep":case "search_file_content":i=`grep "${c.pattern||c.query||""}"`;break;case "list_directory":i=`List ${c.dir_path||c.path||"directory"}`,(c.dir_path||c.path)&&d.push({path:c.dir_path||c.path});break;case "read_many_files":i=`Read ${c.include?.length||"multiple"} files`,Array.isArray(c.include)&&c.include.forEach(u=>d.push({path:u}));break;case "delegate_to_agent":i=c.agent_name?`Agent: ${c.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=c.fact?`Remember: "${c.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=c.name?`Activate skill: ${c.name}`:"Activate skill";break;default:i=a;}return {title:i,kind:l,content:o,locations:d}}}var uo={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function vr(t){return t==="TodoList"||t==="SetTodoList"}function cn(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function _r(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function dn(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=_r(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 ln(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 r=dn(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=dn(t);n&&e.push(n);}return e}function po(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&cn(e.content.text))}function go(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=_r(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 mo(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function Sr(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 r=n.title;if(typeof r!="string"||r.length===0)return null;let s=n.status;return {content:r,status:mo(s),priority:"medium"}}).filter(n=>n!==null):[]}function un(){let t=new Set,e=0;function n(l,o){return typeof l=="string"&&l.length>0?l:(e+=1,`kimi_${o.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(o){let d;try{d=JSON.parse(o);}catch{return null}if(!d||typeof d!="object")return null;let i=d.role;return "_meta"in d||"_prompt"in d||i==="meta"?null:i==="assistant"?r(d):i==="tool"?s(d):typeof d.type=="string"&&"payload"in d?a(d):null};function r(l){let o=[],d=l.content,i=l.tool_calls;if(typeof d=="string"&&d.length>0)o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let u of d){let p=go(u);p&&o.push(p);}if(Array.isArray(i))for(let u of i){if(!u||typeof u!="object")continue;let p=u.function;if(!p)continue;let g=p.name??"",m=n(u.id,g),f;try{f=p.arguments?JSON.parse(p.arguments):{};}catch{f=p.arguments;}if(vr(g)){let S=Sr(f);S.length>0&&o.push({update:{sessionUpdate:"plan",entries:S}}),t.add(m);continue}let{title:h,kind:y,toolContent:w,locations:_}=c(g,typeof f=="object"&&f!==null?f:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:m,title:h,kind:y,status:"pending",rawInput:f,content:w,locations:_}});}return o.length>0?o:null}function s(l){let o=l.tool_call_id;if(typeof o!="string"||o.length===0)return null;if(t.has(o))return t.delete(o),null;let d=l.content,i=[],u=false;if(typeof d=="string")u=cn(d),d.length>0&&i.push({type:"content",content:{type:"text",text:d}});else if(Array.isArray(d))for(let p of d){let g=dn(p);g&&(g.type==="content"&&g.content.type==="text"&&cn(g.content.text)&&(u=true),i.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:i}}]}function a(l){let o=l.type,d=l.payload??{},i=[];switch(o){case "TextPart":{let u=d.text;typeof u=="string"&&u.length>0&&i.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u}}});break}case "ThinkPart":{let u=d.think;typeof u=="string"&&u.length>0&&i.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u}}});break}case "ToolCall":{let u=d.function?.name??"",p=n(d.id,u),g=d.function;if(!g)break;let m;try{m=g.arguments?JSON.parse(g.arguments):{};}catch{m=g.arguments;}if(vr(u)){let _=Sr(m);_.length>0&&i.push({update:{sessionUpdate:"plan",entries:_}}),t.add(p);break}let{title:f,kind:h,toolContent:y,locations:w}=c(u,typeof m=="object"&&m!==null?m:{});i.push({update:{sessionUpdate:"tool_call",toolCallId:p,title:f,kind:h,status:"pending",rawInput:m,content:y,locations:w}});break}case "ToolResult":{let u=d.tool_call_id;if(typeof u!="string"||u.length===0)break;if(t.has(u)){t.delete(u);break}let p=d.return_value??d.content,g=[],m=d.is_error===true;if(p&&typeof p=="object"&&!Array.isArray(p)){let f=p;m=m||f.type==="ToolError"||f.is_error===true,g.push(...ln(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(...ln(p));}else g.push(...ln(p));m=m||po(g),i.push({update:{sessionUpdate:"tool_call_update",toolCallId:u,status:m?"failed":"completed",content:g}});break}default:return null}return i.length>0?i:null}function c(l,o){let d=uo[l]||"other",i=[],u=[],p=l;switch(l){case "Read":case "ReadFile":{let g=o.path??o.file_path;p=`Read ${g||"file"}`,g&&u.push({path:g});break}case "ReadMediaFile":{let g=o.path??o.file_path;p=`Read media ${g||"file"}`,g&&u.push({path:g});break}case "Write":case "WriteFile":{let g=o.path??o.file_path;p=`Write ${g||"file"}`,g&&(u.push({path:g}),typeof o.content=="string"&&i.push({type:"diff",path:g,oldText:null,newText:o.content}));break}case "Edit":case "StrReplaceFile":{let g=o.path??o.file_path;p=`Edit ${g||"file"}`,g&&u.push({path:g});break}case "Bash":case "Shell":p=o.command?`\`${o.command}\``:"Run command";break;case "Glob":p=`Find ${o.pattern||"files"}`,o.path&&u.push({path:o.path});break;case "Grep":p=`grep "${o.pattern||""}"`,o.path&&u.push({path:o.path});break;case "WebSearch":case "SearchWeb":p=o.query?`"${o.query}"`:"Web search";break;case "FetchURL":p=o.url?`Fetch ${o.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":p=o.description||"Subagent task";break;case "Think":p=o.thought||"Thinking";break;case "CreateSubagent":p=o.name?`Subagent: ${o.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":p="Update todos";break;default:p=l;}return {title:p,kind:d,toolContent:i,locations:u}}}var fo={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 ho(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function yo(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 wo(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function xr(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:yo(e.status),priority:wo(e.priority)}}).filter(e=>e!==null):[]}function bo(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let l=ho(r);return l?{type:"content",content:{type:"image",data:l.data,mimeType:l.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function vo(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 So(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function pn(){return function(c){let l;try{l=JSON.parse(c);}catch{return null}if(!l||typeof l!="object")return null;let o=l.sessionID,d=[];switch(l.type){case "step_start":case "step_finish":return null;case "text":{let i=t(l);i&&d.push({sessionId:o,update:i});break}case "reasoning":{let i=e(l);i&&d.push({sessionId:o,update:i});break}case "tool_use":{let i=n(l);for(let u of i)d.push({sessionId:o,update:u});break}case "error":{let i=r(l);i&&d.push({sessionId:o,update:i});break}default:return null}return d.length>0?d:null};function t(a){let c=a.part?.text;return typeof c!="string"||c.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}function e(a){let c=a.part?.text;return typeof c!="string"||c.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c}}}function n(a){let c=a.part;if(!c)return [];let l=typeof c.callID=="string"?c.callID:"";if(l.length===0)return [];let o=typeof c.tool=="string"?c.tool.toLowerCase():"",d=typeof c.state=="object"&&c.state?c.state:{},i=typeof d.input=="object"&&d.input?d.input:{},u=d.status,p=d.title??d.metadata?.description??o,g=d.metadata?.exit,{kind:m,content:f,locations:h}=s(o,i),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:l,title:p,kind:m,status:"pending",rawInput:i,content:f,locations:h}),o==="todowrite"){let b=xr(i.todos);if(b.length===0&&typeof d.output=="string")try{b=xr(JSON.parse(d.output));}catch{}b.length>0&&y.push({sessionUpdate:"plan",entries:b});}let w=So(u,g);if(w==="pending")return y;let _=vo(u,d),S=[];if(typeof _=="string"&&_.length>0&&S.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
15
+ ${_}
16
+ \`\`\``:_}}),Array.isArray(d.attachments))for(let b of d.attachments){let v=bo(b);v&&S.push(v);}return y.push({sessionUpdate:"tool_call_update",toolCallId:l,status:w,content:S}),y}function r(a){let c=a.error?.name??"Error",l=a.error?.data?.message??a.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${c}: ${l}`}}}function s(a,c){let l=fo[a]||"other",o=[],d=[];switch(a){case "read":{let i=c.filePath??c.path;if(i){let u=c.offset;d.push({path:i,line:typeof u=="number"&&Number.isFinite(u)?Math.max(0,u-1):void 0});}break}case "write":{let i=c.filePath??c.path;i&&(d.push({path:i}),typeof c.content=="string"&&o.push({type:"diff",path:i,oldText:null,newText:c.content}));break}case "edit":case "multiedit":{let i=c.filePath??c.path;i&&(d.push({path:i}),a==="edit"&&(c.oldString!==void 0||c.newString!==void 0)&&o.push({type:"diff",path:i,oldText:c.oldString??"",newText:c.newString??""}));break}case "apply_patch":break;case "bash":{let i=c.command;i&&c.description?o.push({type:"content",content:{type:"text",text:c.description}}):i&&o.push({type:"content",content:{type:"text",text:i}});break}case "glob":case "list":{let i=c.path;i&&d.push({path:i});break}case "grep":{let i=c.path;i&&d.push({path:i});break}case "codesearch":case "websearch":{let i=c.query;i&&o.push({type:"content",content:{type:"text",text:i}});break}case "webfetch":{let i=c.url;i&&o.push({type:"content",content:{type:"text",text:i}});break}case "task":{let i=c.description;i&&o.push({type:"content",content:{type:"text",text:i}});break}}return {kind:l,content:o,locations:d}}}var _o={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 gt(){let t=new Map,e=new Map;return function(i){let u;try{u=JSON.parse(i);}catch{return null}if(!u||typeof u!="object")return null;let p=u;if("_meta"in p||"_prompt"in p)return null;let g=p.session_id||void 0,m=[];switch(p.type){case "assistant":{let f=n(p);for(let h of f)m.push({sessionId:g,update:h});break}case "stream_event":{let f=r(p);for(let h of f)m.push({sessionId:g,update:h});break}case "user":{let f=s(p);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 i=[],u=d.message?.content;if(!Array.isArray(u))return i;for(let p of u){let g=a(p);i.push(...g);}return i}function r(d){let i=[],u=d.event;if(!u)return i;switch(u.type){case "content_block_start":{let p=u.index??0,g=u.content_block;g&&(t.set(p,g),g.type==="tool_use"&&e.set(p,""));break}case "content_block_delta":{let p=u.index??0,g=u.delta,m=t.get(p);if(g?.type==="text_delta"&&g.text)i.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:g.text}});else if(g?.type==="thinking_delta"&&g.thinking)i.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(p)||"";e.set(p,f+g.partial_json);}break}case "content_block_stop":{let p=u.index??0,g=t.get(p);if(g&&!(g.type==="text"&&g.text)){if(!(g.type==="thinking"&&g.thinking)){if(g.type==="tool_use"){let m=g,f=e.get(p)||"";e.delete(p);let h=m.input;if(f)try{h=JSON.parse(f);}catch{}let y={...m,input:h},w=c(y);w&&i.push(w);}else if(g.type==="tool_result"){let m=l(g);m&&i.push(m);}}}t.delete(p);break}}return i}function s(d){let i=d.message?.content,u=[];if(typeof i=="string")return u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:i}}),u;if(Array.isArray(i)){for(let p of i)if(p.type==="text")u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:p.text}});else if(p.type==="tool_result"){let g=l(p);g&&u.push(g);}}return u}function a(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 i=c(d);return i?[i]:[]}case "tool_result":{let i=l(d);return i?[i]:[]}}}function c(d){let i=d.id,u=d.name,p=d.input;if(u==="TodoWrite"&&Array.isArray(p?.todos))return {sessionUpdate:"plan",entries:p.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:g,kind:m,content:f,locations:h}=o(u,p||{});return {sessionUpdate:"tool_call",toolCallId:i,title:g,kind:m,status:"pending",rawInput:p,content:f,locations:h}}function l(d){let i=d.tool_use_id,u=d.is_error??false,p=d.content,g=[];if(typeof p=="string"&&p.length>0)g.push({type:"content",content:{type:"text",text:u?`\`\`\`
17
+ ${p}
18
+ \`\`\``:p}});else if(Array.isArray(p)){for(let m of p)if(m.type==="text"){let f=m.text;g.push({type:"content",content:{type:"text",text:u?`\`\`\`
19
+ ${f}
20
+ \`\`\``:f}});}}return {sessionUpdate:"tool_call_update",toolCallId:i,status:u?"failed":"completed",content:g}}function o(d,i){let u=_o[d]||"other",p=[],g=[],m=d;switch(d){case "Read":case "read_file":m=`Read ${i.file_path||i.absolute_path||"file"}`,(i.file_path||i.absolute_path)&&g.push({path:i.file_path||i.absolute_path});break;case "Write":case "write_file":m=`Write ${i.file_path||"file"}`,i.file_path&&(g.push({path:i.file_path}),p.push({type:"diff",path:i.file_path,oldText:null,newText:i.content||""}));break;case "Edit":case "edit_file":m=`Edit ${i.file_path||"file"}`,i.file_path&&g.push({path:i.file_path});break;case "Bash":case "shell":case "run_shell_command":m=i.command?`\`${i.command}\``:"Run command",i.description&&p.push({type:"content",content:{type:"text",text:i.description}});break;case "WebFetch":m=i.url?`Fetch ${i.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":m=i.query?`"${i.query}"`:"Web search";break;case "Glob":m=`Find ${i.pattern||"files"}`,i.path&&g.push({path:i.path});break;case "Grep":m=`grep "${i.pattern||""}"`;break;case "LS":case "list_directory":m=`List ${i.path||"directory"}`,i.path&&g.push({path:i.path});break;case "Task":m=i.description||"Subagent task";break;case "TodoWrite":m="Update todos";break;case "ExitPlanMode":m="Exit plan mode";break;default:m=d;}return {title:m,kind:u,content:p,locations:g}}}function kr(t){return gt()(t)}function Cr(t){return !!t&&t.sessionUpdate!=="error"}function Q(t){switch(t){case "claude":return ct();case "codex":return dt();case "gemini":return pt();case "qwen":return gt();case "kimi":return un();case "opencode":return pn();case "droid":return ut();default:return ()=>null}}function xo(t,e){let n=e.trim();return n?Q(t)(n):null}function ko(t,e){let n=[],r=e.split(`
21
+ `),s=Q(t);for(let a of r){let c=a.trim();if(!c)continue;let l=s(c);l&&n.push(...l);}return n}function N(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function oe(t){return JSON.stringify(Co__default.default(t,{target:"jsonSchema7"}),null,2)}function ae(t){return JSON.stringify(t,null,2)}function Er(t,e=false){let n={};function r(s,a){for(let c of j__namespace.readdirSync(s)){let l=F__namespace.join(s,c),o=a?`${a}/${c}`:c;j__namespace.statSync(l).isDirectory()?e&&r(l,o):n[o]=j__namespace.readFileSync(l);}}return r(t,""),n}function Rr(t,e){let n=F__namespace.resolve(t),r=n.endsWith(F__namespace.sep)?n:n+F__namespace.sep;for(let[s,a]of Object.entries(e)){let c=F__namespace.resolve(n,s);if(!c.startsWith(r))throw new Error(`Unsafe file path escapes target directory: ${s}`);let l=F__namespace.dirname(c);j__namespace.mkdirSync(l,{recursive:true});let o;a instanceof ArrayBuffer||a instanceof Uint8Array?o=Buffer.from(a):o=a,j__namespace.writeFileSync(c,o);}}var W=class extends Error{field;constructor(e,n){super(n),this.name="EvolveConfigError",this.field=e;}};function Tr(t){return typeof t=="string"&&t.trim()!==""}function gn(t){return t==null?String(t):JSON.stringify(t)}function Ce(t){if(!t)return;if(t.type!==void 0&&!Ht(t.type))throw new W("type",`Evolve agent config: unknown agent type ${gn(t.type)}. Valid types: ${Object.keys(ie).join(", ")}.`);let e=t.type??Jt;if(t.model!==void 0&&!Tr(t.model))throw new W("model",`Evolve agent config: "model" is empty (${gn(t.model)}). Pass a model id such as "${O(e).defaultModel}", or omit model entirely to use ${e}'s default.`)}function mn(t){if(!t||!Tr(t.prompt))throw new W("prompt",`run() requires a non-empty "prompt" string, received ${gn(t?.prompt)}.`)}function fn(t){if(t){for(let e of be)if(e in t)throw new W(`observability.${e}`,`Evolve observability metadata: "${e}" is reserved for session identity and would split this run across two dashboard sessions. Reserved keys: ${be.join(", ")}. Use a different key, or set the session tag with .withSessionTagPrefix().`)}}function ft(t){if(t.externalGateway){if(t.providerApiKey||t.providerBaseUrl||t.oauthToken)throw new Error("externalGateway cannot be combined with providerApiKey/providerBaseUrl/oauthToken (direct mode)");if(t.apiKey)throw new Error("externalGateway cannot be combined with apiKey (Evolve gateway mode)")}}function Eo(t){let e=t.replace(/^~/,process.env.HOME||"");if(!j__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return j__namespace.readFileSync(e,"utf-8")}function ht(t){let e=t?.type??Jt,n=O(e);if(t?.externalGateway){ft(t);let{apiKey:c,baseUrl:l,revoke:o}=t.externalGateway;if(!c||!l||typeof o!="function")throw new Error("externalGateway requires apiKey, baseUrl, and a revoke() function");return {type:e,apiKey:c,baseUrl:l,isDirectMode:true,externalGateway:{revoke:o},model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize}}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,maxContextSize:t.maxContextSize}}if(t?.providerApiKey){let c=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,l=t.providerBaseUrl??c??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:l,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize};let r=process.env[P];if(r)return {type:e,apiKey:r,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize};if(n.providerEnvMap){let l=(t?.model??n.defaultModel)?.split("/")[0],o=l?n.providerEnvMap[l]:void 0,d=o?process.env[o.keyEnv]:void 0;if(d){let u=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:u,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}}let s=process.env[n.apiKeyEnv];if(s){let l=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:s,baseUrl:l,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}if(n.oauthEnv){let c=process.env[n.oauthEnv];if(c){if(n.oauthFileName){let l=Eo(c);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:l,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}return {type:e,apiKey:c,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}}let a=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)${a}, or ${P} / ${n.apiKeyEnv} env var.`)}function Po(t){return `e2b_${Buffer.from(t,"utf8").toString("hex")}`}var Dr=new WeakSet;function bn(t){return Dr.add(t),t}function Re(t){return Dr.has(t)}function Or(t,e){return new Error(`${P} is set but ${t} failed to load.
22
+ Try installing: ${e}`)}function Mr(t){return t.message?.includes("Cannot find module")||t.message?.includes("MODULE_NOT_FOUND")}function vn(t,e){if(!e||e.timeoutMs===void 0&&e.resources===void 0)return t;let n=t.create.bind(t);return t.create=(r={})=>n({...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.resources!==void 0?{resources:e.resources}:{},...r}),t}async function Te(t,e="e2b",n){let r=t||process.env[P];if(!r)throw new Error(`${P} is required for Evolve-managed sandbox features`);if(!Ye.includes(e))throw new Error(`Unknown managed sandbox provider "${e}". Supported: ${Ye.join(", ")}`);if(e==="daytona")try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return vn(bn(s({apiKey:r,apiUrl:ye("daytona"),managedToolboxUrl:nr()})),n)}catch(s){let a=s;throw Mr(a)?Or("@evolvingmachines/daytona","npm install @evolvingmachines/daytona"):a}if(e==="modal"){let{ManagedModalProvider:s}=await Promise.resolve().then(()=>(Ar(),Ir));return vn(bn(new s({apiKey:r,baseUrl:ye("modal")})),n)}try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return vn(bn(s({apiKey:Po(r),apiUrl:jt()})),n)}catch(s){let a=s;throw Mr(a)?Or("@evolvingmachines/e2b","npm install @evolvingmachines/sdk"):a}}function Io(t="e2b",e){let n=typeof e=="string"?{apiKey:e}:e??{},{apiKey:r,...s}=n;return Te(r,t,s)}async function Sn(){let t=process.env[Xe];if(t)try{let{createE2BProvider:a}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===jt()&&delete process.env.E2B_API_URL,a({apiKey:t})}catch(a){let c=a;throw c.message?.includes("Cannot find module")||c.message?.includes("MODULE_NOT_FOUND")?new Error(`${Xe} is set but @evolvingmachines/e2b failed to load.
23
+ Try reinstalling: npm install @evolvingmachines/sdk`):c}let e=process.env[Qe];if(e)try{let{createDaytonaProvider:a}=await import('@evolvingmachines/daytona');return a({apiKey:e})}catch(a){let c=a;throw c.message?.includes("Cannot find module")||c.message?.includes("MODULE_NOT_FOUND")?new Error(`${Qe} is set but @evolvingmachines/daytona failed to load.
24
+ Try installing: npm install @evolvingmachines/daytona`):c}let n=process.env[Ze],r=process.env[Kt];if(n&&r)try{let{createModalProvider:a}=await import('@evolvingmachines/modal');return a({tokenId:n,tokenSecret:r})}catch(a){let c=a;throw c.message?.includes("Cannot find module")||c.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ze} is set but @evolvingmachines/modal failed to load.
25
+ Try installing: npm install @evolvingmachines/modal`):c}let s=process.env[P];if(s)return Te(s);throw new Error(`No sandbox provider configured. Either:
26
+ 1. Set ${P} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
27
+ 2. Set ${Xe} environment variable (direct E2B access, get key at https://e2b.dev)
28
+ 3. Set ${Qe} environment variable (direct Daytona access, get key at https://app.daytona.io)
29
+ 4. Set ${Ze} and ${Kt} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
30
+ 5. Pass sandbox explicitly: .withSandbox(provider)`)}function Ao(t){return new Promise(e=>setTimeout(e,t))}async function D(t,e,n=0){let r=Oo(e),s=e?.onItemRetry,a=null,c=0,l=r.backoffMs;for(;c<r.maxAttempts;){if(c++,a=await t(c),!r.retryOn(a))return a;if(c>=r.maxAttempts)break;if(s){let o=a.error??"Unknown error";s(n,c,o);}await Ao(l),l*=r.backoffMultiplier;}return a}function Oo(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var Ur=`## FILESYSTEM INSTRUCTIONS:
50
31
 
51
32
  You are running in a sandbox environment.
52
33
 
@@ -79,7 +60,7 @@ Examples:
79
60
  - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
80
61
  - "Write a Python script" \u2192 \`output/parser.py\`
81
62
  - "Convert this to JSON" \u2192 \`output/data.json\`
82
- `;var gn=`## FILESYSTEM INSTRUCTIONS:
63
+ `;var $r=`## FILESYSTEM INSTRUCTIONS:
83
64
 
84
65
  You are running in a sandbox environment.
85
66
 
@@ -113,9 +94,9 @@ Examples:
113
94
  - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
114
95
  - "Write a Python script" \u2192 \`output/parser.py\`
115
96
  - "Convert this to JSON" \u2192 \`output/data.json\`
116
- `;var fn=`## SYSTEM PROMPT
97
+ `;var Lr=`## SYSTEM PROMPT
117
98
 
118
- {{systemPrompt}}`;var mn=`## STRUCTURED OUTPUT
99
+ {{systemPrompt}}`;var Br=`## STRUCTURED OUTPUT
119
100
 
120
101
  Your final result MUST be saved to \`output/result.json\` following this schema:
121
102
 
@@ -133,13 +114,13 @@ You are free to:
133
114
  But your final \`output/result.json\` MUST conform to the schema above.
134
115
 
135
116
  ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
136
- ### Never just state results as text.`;var hn=`## BROWSER AUTOMATION
117
+ ### Never just state results as text.`;var Nr=`## BROWSER AUTOMATION
137
118
 
138
119
  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 yn=`## Browser Automation
120
+ `;var Fr=`## Browser Automation
140
121
 
141
122
  The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
142
- `;var wn=`### 1. YOUR ROLE: BEST OF N JUDGE
123
+ `;var jr=`### 1. YOUR ROLE: BEST OF N JUDGE
143
124
 
144
125
  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
126
 
@@ -169,7 +150,7 @@ You must judge their work based on:
169
150
  5. Pick the best candidate (0-indexed)
170
151
 
171
152
  **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 vn=`### 1. YOUR ROLE: OUTPUT VERIFIER
153
+ `;var Kr=`### 1. YOUR ROLE: OUTPUT VERIFIER
173
154
 
174
155
  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
156
 
@@ -202,14 +183,14 @@ The output must satisfy:
202
183
  **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
184
 
204
185
  If failing, provide specific, actionable feedback explaining what needs to be fixed.
205
- `;var bn=`### CONTEXT STRUCTURE
186
+ `;var Jr=`### CONTEXT STRUCTURE
206
187
 
207
188
  \`\`\`
208
189
  {{fileTree}}
209
190
  \`\`\`
210
191
 
211
192
  Examine all files within each item folder before producing your output.
212
- `;var kn="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var Sn="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var xn=`{{originalPrompt}}
193
+ `;var Vr="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var Gr="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var qr=`{{originalPrompt}}
213
194
 
214
195
  ## IMPORTANT: Previous Attempt Failed Verification
215
196
 
@@ -218,38 +199,415 @@ Your previous attempt did not pass quality verification. Please address this fee
218
199
  {{feedback}}
219
200
 
220
201
  Make sure your output addresses all the feedback points above.
221
- `;var Cn=un,_n=gn,En=fn,Rn=mn,vt=hn,Tn=yn,bt=wn,Pn=kn,kt=vn,In=Sn,On=bn,St=xn;function F(t,e){let n=t;for(let[r,s]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${r}\\}\\}`,"g"),s);return n}function xt(t){let e=t.mode==="swe"?_n:Cn,n=F(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
202
+ `;var Hr=Ur,zr=$r,Wr=Lr,Yr=Br,_n=Nr,Xr=Fr,xn=jr,Qr=Vr,kn=Kr,Zr=Gr,es=Jr,Cn=qr;function q(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:n)}function En(t){let e=t.mode==="swe"?zr:Hr,n=q(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
222
203
 
223
204
 
224
205
  ${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
225
206
 
226
207
 
227
- ${F(En,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=M(t.schema)?q(t.schema):Y(t.schema);n+=`
208
+ ${q(Wr,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=N(t.schema)?oe(t.schema):ae(t.schema);n+=`
228
209
 
229
210
 
230
- ${F(Rn,{schema:r}).trim()}`;}return n}function Ke(t){let e=[...new Set(Object.keys(t).map(l=>l.split("/")[0]))].sort((l,d)=>l==="worker_task"?-1:d==="worker_task"?1:l.localeCompare(d));if(!e.length)return `context/
231
- (empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,s=Object.keys(t).some(l=>l.startsWith("worker_task/input/")),a=[];e.forEach((l,d)=>{let i=d===e.length-1,p=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=i?" ":"\u2502 ";if(l==="worker_task"){a.push({line:`${p}${l}/`,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"}),r&&g.push({name:"schema.json",comment:"expected output schema"}),s&&g.push({name:"input/",comment:"worker input files"}),g.forEach((f,m)=>{let y=m===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";a.push({line:`${u}${y}${f.name}`,comment:f.comment});});}else if(l.startsWith("candidate_")){let g=l.replace("candidate_","");a.push({line:`${p}${l}/`,comment:`worker ${g} solution`});}else if(l==="worker_output")a.push({line:`${p}${l}/`,comment:"output to verify"});else if(l.startsWith("item_")){let g=l.replace("item_","");a.push({line:`${p}${l}/`,comment:`input ${g}`});}else a.push({line:`${p}${l}/`,comment:""});});let o=Math.max(...a.map(l=>l.line.length)),c=["context/"];for(let l of a)if(l.comment){let d=" ".repeat(o-l.line.length+3);c.push(`${l.line}${d}# ${l.comment}`);}else c.push(l.line);return c.join(`
232
- `)}var An=ae.join(os$1.homedir(),Yt),ce=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(An,{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=Te(),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,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=ae.join(An,r),this.parser=z(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 r of n)this.bufferForDashboard(r);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let r of n)this.bufferForDashboard(r);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),this.isClosed=true,await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
211
+ ${q(Yr,{schema:r}).trim()}`;}return n}function bt(t){let e=[...new Set(Object.keys(t).map(o=>o.split("/")[0]))].sort((o,d)=>o==="worker_task"?-1:d==="worker_task"?1:o.localeCompare(d));if(!e.length)return `context/
212
+ (empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,s=Object.keys(t).some(o=>o.startsWith("worker_task/input/")),a=[];e.forEach((o,d)=>{let i=d===e.length-1,u=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",p=i?" ":"\u2502 ";if(o==="worker_task"){a.push({line:`${u}${o}/`,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"}),r&&g.push({name:"schema.json",comment:"expected output schema"}),s&&g.push({name:"input/",comment:"worker input files"}),g.forEach((m,f)=>{let y=f===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";a.push({line:`${p}${y}${m.name}`,comment:m.comment});});}else if(o.startsWith("candidate_")){let g=o.replace("candidate_","");a.push({line:`${u}${o}/`,comment:`worker ${g} solution`});}else if(o==="worker_output")a.push({line:`${u}${o}/`,comment:"output to verify"});else if(o.startsWith("item_")){let g=o.replace("item_","");a.push({line:`${u}${o}/`,comment:`input ${g}`});}else a.push({line:`${u}${o}/`,comment:""});});let c=Math.max(...a.map(o=>o.line.length)),l=["context/"];for(let o of a)if(o.comment){let d=" ".repeat(c-o.line.length+3);l.push(`${o.line}${d}# ${o.comment}`);}else l.push(o.line);return l.join(`
213
+ `)}var ts=F.join(os.homedir(),or),Pe=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;warnedKeys=new Set;localQueue=Promise.resolve();dirReady=promises.mkdir(ts,{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=We(),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,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=F.join(ts,r),this.parser=Q(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 r of n)this.bufferForDashboard(r);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let r of n)this.bufferForDashboard(r);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),this.isClosed=true,await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
233
214
  `)?e:e+`
234
215
  `;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
- `;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>=Qt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Zt));}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 r=1;r<=Ae;r++)try{let s=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(s.ok)return;if(s.status===429||s.status===401||s.status>=500){if(r===Ae){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(ot*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===Ae?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(ot*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Te();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)):{}}};function le(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}function de(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed integrations");return e}async function pe(t){return await t.text().catch(()=>"")}function Ct(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function $i(t){let e=Array.from(new Set((t??[]).map(n=>n.trim()).filter(Boolean)));if(e.length===0)throw new Error("withIntegrations() requires at least one app");return e}async function $n(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Ct(t.userId),apps:$i(t.apps),tools:t.tools,accounts:t.accounts,keys:t.keys,authConfigs:t.authConfigs,sessionTag:t.sessionTag}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integrations session create failed (${e.status}): ${await pe(e)}`);let n=await e.json();if(!n.mcp?.url)throw new Error("Managed integrations response missing mcp.url");return {url:n.mcp.url,headers:n.mcp.headers??{}}}async function Di(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Ct(t.userId),app:t.app,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration connect failed (${e.status}): ${await pe(e)}`);return await e.json()}async function Ui(t){let e=Array.from(new Set((t.userIds??[]).map(o=>Ct(o))));if(e.length===0)throw new Error("Integration accounts.list() requires at least one userId");let n=new URLSearchParams({userIds:e.join(",")});t.app&&n.set("app",t.app),t.statuses?.length&&n.set("statuses",t.statuses.join(","));let r={Authorization:`Bearer ${de(t.apiKey)}`,accept:"application/json"},s=await fetch(`${le(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Managed integration status failed (${s.status}): ${await pe(s)}`);return ((await s.json()).accounts??[]).map(o=>({userId:String(o.userId??""),app:String(o.app??""),appName:typeof o.appName=="string"?o.appName:void 0,appIcon:typeof o.appIcon=="string"?o.appIcon:void 0,accountLabel:typeof o.accountLabel=="string"?o.accountLabel:void 0,status:String(o.status??""),accountId:typeof o.accountId=="string"?o.accountId:void 0,updatedAt:typeof o.updatedAt=="string"?o.updatedAt:void 0}))}async function Bi(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account update failed (${e.status}): ${await pe(e)}`);return await e.json()}async function Li(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account delete failed (${e.status}): ${await pe(e)}`);return await e.json()}var Dn={auth:Di,accounts:{list:Ui,update:Bi,delete:Li}};util.promisify(child_process.exec);var Pt=util.promisify(child_process.execFile),Ln=Symbol.for("evolve:awsSdkCache"),Fn=Symbol.for("evolve:s3ClientCache");var qi=3600,Yi=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Qi(t){if(t.startsWith("s3://")){let s=t.slice(5),a=s.indexOf("/");return a===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,a),prefix:s.slice(a+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,r=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:r.join("/")};if(r.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:r[0],prefix:r.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function Ve(t,e,n,r){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:r}}let s=t?.bucket||"",a=t?.prefix||"",o=t?.endpoint;if(t?.url){let c=Qi(t.url);s=s||c.bucket,a=a||c.prefix,o=o||c.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:a,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:o,credentials:t?.credentials,mode:"byok"}}function _t(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 Zi(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 Xi(t,e){let n=D(t),r=Zi(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(c=>_t(c)):[_t(n.mcpConfig.settingsDir)],a=[...Yi.map(c=>`--exclude=${ue(c)}`),`--exclude=${ue(r+"/temp")}`,...(n.checkpointExcludes??[]).map(c=>`--exclude=${ue(_t(c))}`)].join(" "),o=[ue(r+"/"),...s.map(c=>ue(c+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${a} ${o}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Z(){let t=globalThis[Ln];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,s]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[Ln]={s3:r,presigner:s},{s3:r,presigner:s}}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 fe(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[Fn];if(r?.key===n)return r.client;let{s3:s}=await Z(),a=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Fn]={client:a,key:n},a}async function Hn(t,e,n){let{s3:r,presigner:s}=await Z(),a=await fe(t),o=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(a,o,{expiresIn:qi})}async function Nn(t,e){let{s3:n}=await Z(),r=await fe(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let a=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||a==="NotFound"||a==="NoSuchKey")return false;throw s}}async function qn(t,e){let{s3:n}=await Z(),a=await(await(await fe(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!a)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(a)}async function es(t,e,n){let{s3:r}=await Z();await(await fe(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Yn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function Qn(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function ts(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Zn(t,e,n,r){let s=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:r})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${a}`)}return s.json()}async function ns(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${r}`)}return n.json()}async function rs(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${r}`)}return n.json()}async function It(t,e,n,r,s){let a=new Date().toISOString(),o=Xi(n,r),c=await t.commands.run(o,{timeoutMs:12e4});if(c.exitCode!==0)throw new Error(`Checkpoint tar failed: ${c.stderr}`);let l=c.stdout.trim().split(`
237
- `).pop()?.trim();if(!l||l.length!==64)throw new Error(`Invalid checkpoint hash: ${l}`);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}),i=parseInt(d.stdout.trim(),10),p=Number.isNaN(i)?void 0:i,u;try{if(e.mode==="byok"){let g=Yn(e,l);if(!await Nn(e,g)){let h=await Hn(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 Nn(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=ts();let m={id:u,hash:l,tag:s.tag,timestamp:a,sizeBytes:p,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment,sandboxId:t.sandboxId};await es(e,Qn(e,u),m);}else {let g=await Zn(e,s.tag,l,"put");if(!g.alreadyExists){let m=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(m.exitCode!==0)throw new Error(`Checkpoint upload failed: ${m.stderr}`)}u=(await ns(e,{tag:s.tag,hash:l,sizeBytes:p??0,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:u,hash:l,tag:s.tag,timestamp:a,sizeBytes:p,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment}}async function Xn(t,e,n){let r=await At(e,n),s=r.hash,a={agentType:r.agentType,workspaceMode:r.workspaceMode},o=await rr(e,r),c=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${o}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(c.exitCode!==0)throw new Error(`Checkpoint download failed: ${c.stderr}`);let l=c.stdout.trim().split(`
238
- `).pop()?.trim();if(l!==s)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${l})`);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 a}function er(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||_,s=!t.url&&!t.bucket&&!!n;return Ve(t,s,r,n)}async function tr(t,e){let{s3:n}=await Z(),r=await fe(t),a=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,o=[],c;do{let u={Bucket:t.bucket,Prefix:a,...c&&{ContinuationToken:c}},g=await r.send(new n.ListObjectsV2Command(u));if(g.Contents)for(let f of g.Contents)f.Key?.endsWith(".json")&&f.LastModified&&o.push({key:f.Key,lastModified:f.LastModified});c=g.IsTruncated?g.NextContinuationToken:void 0;}while(c);if(o.length===0)return [];o.sort((u,g)=>{let f=g.lastModified.getTime()-u.lastModified.getTime();return f!==0?f:g.key<u.key?-1:g.key>u.key?1:0});let d=!!e?.tag?o:e?.limit?o.slice(0,e.limit):o,p=(await Promise.all(d.map(async u=>{try{return await qn(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 nr(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let r=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${s.status}): ${a}`)}return s.json()}function is(t){return t&&t>0?Math.min(t,500):100}async function Ot(t,e){return t.mode==="byok"?(await tr(t,{limit:1,tag:e?.tag}))[0]??null:(await nr(t,{limit:1,tag:e?.tag}))[0]??null}async function At(t,e){if(t.mode==="byok"){let n=Qn(t,e);try{return await qn(t,n)}catch(r){throw ss(r)?new Error(`Checkpoint ${e} not found`):r}}else return await rs(t,e)}async function Kn(t,e,n){if(e==="latest"){let r=await Ot(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function rr(t,e){if(t.mode==="byok")return Hn(t,Yn(t,e.hash),"get");{let n=await Zn(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function ir(t){return !(!t||ae.isAbsolute(t)||t.startsWith("-")||ae.normalize(t).startsWith("..")||t.includes("\0"))}function jn(t,e){let n=ae.resolve(t,e),r=ae.resolve(t),s=ae.relative(r,n);if(s.startsWith("..")||ae.isAbsolute(s))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function ss(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Et(t){let e=t.filter(n=>!ir(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var sr=10*1024*1024,Vn=false;async function or(){if(!Vn)try{await Pt("tar",["--version"]),Vn=!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 Gn(t,e){let n=await At(t,e),r=await rr(t,n),s=e.replace(/[^a-zA-Z0-9_-]/g,"_"),a=ae.join(os$1.tmpdir(),`evolve-dl-${s}-${Date.now()}.tar.gz`),o=await fetch(r);if(!o.ok)throw new Error(`Checkpoint download failed (${o.status})`);if(!o.body)throw new Error("Checkpoint download returned empty body");let c=crypto.createHash("sha256"),l=$.createWriteStream(a);try{let i=o.body.getReader();await new Promise((p,u)=>{l.on("error",u),l.on("finish",p);async function g(){for(;;){let{done:f,value:m}=await i.read();if(f){l.end();break}c.update(m),l.write(m)||await new Promise(h=>l.once("drain",h));}}g().catch(u);});}catch(i){throw l.destroy(),await promises.unlink(a).catch(()=>{}),i}let d=c.digest("hex");if(d!==n.hash)throw await promises.unlink(a).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:a,metadata:n}}async function Wn(t){await or();let{stdout:e}=await Pt("tar",["-tvzf",t],{maxBuffer:sr}),n=new Set,r=[],s=[];for(let a of e.trim().split(`
239
- `)){if(!a||a.startsWith("total "))continue;let o=a[0];if(o!=="-"&&o!=="d"&&o!=="l")throw new Error(`Archive contains unsupported entry type: "${o}"`);let c=a.match(/\d{2}:\d{2}\s+(.+)/)??a.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!c)continue;let l=c[1];if(o==="l"){let d=l.indexOf(" -> ");d!==-1&&(l=l.slice(0,d)),n.add(l);}else o==="d"?r.push(l.replace(/\/$/,"")):s.push(l);}return Et(r),Et([...n]),Et(s)}async function Rt(t,e,n){await or(),await promises.mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await Pt("tar",r,{maxBuffer:sr});}function os(t){let e="^",n=0;for(;n<t.length;){let r=t[n];r==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):r==="*"?(e+="[^/]*",n++):r==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(r)?(e+="\\"+r,n++):(e+=r,n++);}return e+="$",new RegExp(e)}function Mt(t,e){let n=er(t,e);return ar(n)}function as(t){let e=er(t||{});return ar(e)}function ar(t){return {async listCheckpoints(e){let n=is(e?.limit);return t.mode==="byok"?tr(t,{limit:n,tag:e?.tag}):nr(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return At(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,s=n?.to||process.cwd(),a=await Kn(t,e),{tmpPath:o,metadata:c}=await Gn(t,a);try{if(r)return await promises.mkdir(s,{recursive:!0}),await Wn(o),await Rt(o,s),s;{await promises.mkdir(s,{recursive:!0});let l=ae.join(s,`checkpoint-${c.id}.tar.gz`);return await promises.copyFile(o,l),l}}finally{await promises.unlink(o).catch(()=>{});}},async downloadFiles(e,n){let r=await Kn(t,e),{tmpPath:s}=await Gn(t,r),a;try{let o=await Wn(s),c;if(n?.files){let d=n.files.filter(p=>!ir(p));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let i=new Set(n.files);c=o.filter(p=>i.has(p));}else if(n?.glob){let d=n.glob.map(os);c=o.filter(i=>d.some(p=>p.test(i)));}else c=o;if(c.length===0)return {};a=ae.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`);try{await Rt(s,a,c);}catch(d){let i=d?.message??"";if(!i.includes("E2BIG")&&!i.includes("Argument list too long")&&!i.includes("ENAMETOOLONG"))throw d;await promises.rm(a,{recursive:!0,force:!0}).catch(()=>{}),a=ae.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`),await Rt(s,a);}let l={};return await Promise.all(c.map(async d=>{jn(a,d),l[d]=await promises.readFile(ae.join(a,d));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(l).map(async([d,i])=>{jn(n.to,d);let p=ae.join(n.to,d);await promises.mkdir(ae.dirname(p),{recursive:!0}),await promises.writeFile(p,i);}))),l}finally{a&&await promises.rm(a,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(s).catch(()=>{});}}}}function N(t){return `'${t.replace(/'/g,"'\\''")}'`}function Ge(t){return typeof t=="string"&&t.length>0}function X(t,e,n){let r=t[e];if(!Ge(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function cs(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
240
- ${n}`)}function ls(t,e){switch(t){case "droid":{let n=X(e,"marketplace",t),r=X(e,"plugin",t);return [`droid plugin marketplace add ${N(n)}`,`droid plugin install ${N(r)} --scope user`]}case "claude":{let n=X(e,"marketplace",t),r=X(e,"plugin",t);return [`claude plugin marketplace add ${N(n)} --scope user`,`claude plugin install ${N(r)} --scope user`]}case "gemini":{let n=X(e,"source",t),r=e,s=[`gemini extensions install ${N(n)}`];return Ge(r.ref)&&s.push(`--ref ${N(r.ref)}`),r.autoUpdate===true&&s.push("--auto-update"),r.preRelease===true&&s.push("--pre-release"),s.push("--consent"),r.skipSettings===true&&s.push("--skip-settings"),[s.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),r=e,s=[`codex plugin marketplace add ${N(n)}`];if(Ge(r.ref)&&s.push(`--ref ${N(r.ref)}`),Array.isArray(r.sparse))for(let a of r.sparse){if(!Ge(a))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");s.push(`--sparse ${N(a)}`);}return [s.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function cr(t,e,n){if(n?.length)for(let r of n){let s=ls(t,r);for(let a of s){let o=await e.commands.run(a,{timeoutMs:12e4});if(o.exitCode!==0)throw cs(a,o)}}}var ds=["actionbook","active-research","extract"],ps=["agent-browser"],us={actionbook:ds,"agent-browser":ps},ur="/home/user/.agent-browser",lr=`${ur}/config.json`,gr="/home/user/.actionbook",gs=`${gr}/config.toml`;function dr(t){return t==="actionbook"||t==="agent-browser"}function fs(t){return t.remote===true}function pr(t){if(t==null)return;if(typeof t!="string")throw new Error("browser profile must be a string");let e=t.trim();if(!e)throw new Error("browser profile cannot be empty");return e}function fr(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(dr(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(t.provider===void 0)return {provider:"agent-browser",managed:t.remote!==false,profile:pr(t.profile)};if(dr(t.provider))return {provider:t.provider,managed:fs(t),profile:pr(t.profile)};throw new Error("Unsupported browser configuration")}function mr(t,e){return Array.from(new Set([...e??[],...us[t]]))}function $t(t,e){return t==="actionbook"?{envs:{},files:[{path:gs,data:`version = 1
241
-
242
- [browser]
243
- mode = "cloud"
244
- cdp_endpoint = ${JSON.stringify(e.cdpUrl)}
245
- `}],directories:[gr]}:{envs:{AGENT_BROWSER_CONFIG:lr},files:[{path:lr,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
246
- `}],directories:[ur]}}function hr(t){return (t?.dashboardUrl||_).replace(/\/$/,"")}async function yr(t){return await t.text().catch(()=>"")}async function wr(t,e,n={}){let r=await fetch(`${hr(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,...t.profile?{profile:t.profile}:{}}),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`Managed browser session create failed (${r.status}): ${await yr(r)}`);let s=await r.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,browserAuthGrantToken:s.browserAuthGrantToken}}async function vr(t,e){let n=await fetch(`${hr(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 yr(n)}`)}var ys="RSA-OAEP-256",Dt="browser-login";function ws(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}function vs(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 bs(t){return await t.text().catch(()=>"")}async function me(t,e,n={}){let r=await fetch(`${ws(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${vs(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser credentials request failed (${r.status}): ${await bs(r)}`);return await r.json()}async function ks(t,e){let n=await me(t,"/api/browser-credentials/public-key"),r=crypto.publicEncrypt({key:n.publicKey,padding:crypto.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"utf8"));return {algorithm:ys,keyId:n.id,ciphertext:r.toString("base64url")}}var We=class{constructor(e={}){this.config=e;}toMetadata(e){let{account_label:n,...r}=e;return {...r,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 r=n.toString()?`?${n.toString()}`:"",s=await me(this.config,`/api/browser-credentials${r}`);return {credentials:s.credentials.map(a=>this.toMetadata(a)),total:s.total,count:s.count,offset:s.offset,hasMore:s.has_more??s.offset+s.count<s.total}}async create(e){let n=await ks(this.config,e.password),r=await me(this.config,"/api/browser-credentials",{method:"POST",body:JSON.stringify({website:e.website,account_label:e.accountLabel,email:e.email,encryptedPassword:n})});return {status:r.status,credential:this.toMetadata(r.credential)}}async delete(e){let n="id"in e?e:{website:e.website,account_label:e.accountLabel};return await me(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function Ut(t={}){return new We(t)}async function br(t){return (await me({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:Ss(t.config)})})).server}function Ss(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var Bt="x-evolve-provider-runtime-binding";function xs(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}async function Cs(t){return await t.text().catch(()=>"")}var he=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ProviderRuntimeTokenRequestError";}};function kr(t){return t instanceof he&&t.status===404}async function Lt(t,e,n={}){let r=await fetch(`${xs(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new he(r.status,`Provider runtime token request failed (${r.status}): ${await Cs(r)}`);return await r.json()}function _s(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.enabled===true&&(e.provider==="anthropic"||e.provider==="openai")&&(e.credentialMode==="provider_key"||e.credentialMode==="evolve_key")&&typeof e.token=="string"&&e.token.length>0&&typeof e.bindingSecret=="string"&&e.bindingSecret.length>0&&typeof e.baseUrl=="string"&&e.baseUrl.length>0&&typeof e.expiresAt=="string"&&e.expiresAt.length>0}async function Sr(t,e){let n=await Lt(t,"/api/provider-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!_s(n))throw new he(502,"Provider runtime token response was invalid");return n}async function xr(t,e){return (await Lt(t,"/api/provider-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function Cr(t,e){return (await Lt(t,"/api/provider-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}var _r="/home/user/.factory/evolve-session.json",Ft="EVOLVE_PROVIDER_RUNTIME_BINDING";function Nt(t){switch(t){case "claude":return "anthropic";case "codex":return "openai";default:return null}}function Ps(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function Er(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function Kt(t,e,n="newline"){let r=new Map;if(t){let s=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let a of s){let o=a.trim();if(!o)continue;let c=o.indexOf(":");if(c<=0)continue;let l=o.slice(0,c).trim(),d=o.slice(c+1).trim();r.set(l.toLowerCase(),`${l}: ${d}`);}}for(let[s,a]of Object.entries(e)){let o=s.toLowerCase();if(o===L&&r.has(o)&&n==="newline"){let c=r.get(o),l=c.slice(c.indexOf(":")+1).trim();r.set(o,`${s}: ${l},${a}`);}else r.set(o,`${s}: ${a}`);}return Array.from(r.values()).join(n==="comma"?", ":`
247
- `)}var Is=262144,Os=new Set(["low","medium","high","xhigh","max"]);function Rr(t){if(t)return Os.has(t)?t:void 0}function As(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var ye=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;providerRuntimeToken;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||qt,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 r=this.createAjvValidator();this.compiledValidator=r.compile(this.jsonSchema);}catch(r){throw new Error(`Invalid JSON Schema: ${r.message}`)}}this.registry=D(e.type),this.sessionTag=Er(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 r=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...r?{browser:r}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,r,s){let a=++this.nextOperationId;return this.activeOperationId=a,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),a}finalizeOperation(e,n,r,s="idle",a="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=a,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,a){let o=n==="run"?"run_background_complete":"command_background_complete",c=n==="run"?"run_background_failed":"command_background_failed",l=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,s,l,"interrupted");return}n==="run"&&a&&await this.writeDroidSessionState(a);let p=d.exitCode===0?o:c,u=d.exitCode===0?"idle":"error";this.finalizeOperation(e,s,p,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,c,"error");});}createAjvValidator(){let n={...qe[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 Es__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");let r=false;try{if(this.options.sandboxId)(this.options.mcpServers||this.options.integrations||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, integrations, 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),await this.ensureProviderRuntimeToken();let s=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:s,workingDirectory:this.workingDir}),r=!0,await this.bindProviderRuntimeToken(this.sandbox.sandboxId),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 r&&this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}return this.sandbox}buildEnvironmentVariables(){let e={},n=this.validatedUserSecretsForEnvironment();if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode){let r=ne(this.agentConfig.reasoningEffort),s=Rr(this.agentConfig.reasoningEffort);e.KIMI_MODEL_NAME=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),e.KIMI_MODEL_API_KEY=this.agentConfig.apiKey,e.KIMI_MODEL_PROVIDER_TYPE="kimi",e.KIMI_MODEL_MAX_CONTEXT_SIZE=String(this.registry.spendTrackingTomlProvider?.maxContextSize??Is),e.KIMI_MODEL_DEFAULT_THINKING=r?"true":"false",e.KIMI_MODEL_THINKING_MODE=r?"on":"off",s&&(e.KIMI_MODEL_THINKING_EFFORT=s),this.agentConfig.baseUrl&&(e.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl);}else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let r of Object.values(this.registry.providerEnvMap))e[r.keyEnv]=this.agentConfig.apiKey;else {let r=this.agentConfig.model?.split("/")[0],s=r?this.registry.providerEnvMap?.[r]:void 0,a=s?s.keyEnv:this.registry.apiKeyEnv,o=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:a;e[o]=this.agentConfig.apiKey;}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let r=G(this.registry.gatewayPath),s=this.activeProviderRuntimeToken();if(this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[O]:this.sessionTag}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=s?.baseUrl??r),s&&(e[this.registry.apiKeyEnv]=s.token,this.registry.spendTrackingEnvs&&(e[Ft]=s.bindingSecret)),!s){if(Nt(this.agentConfig.type))throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);e[T]=this.agentConfig.apiKey;}}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,$t(this.options.managedBrowser.provider,this.managedBrowserSession).envs),n&&Object.assign(e,n),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";e[r]=Kt(e[r],{[O]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},s);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}validatedUserSecretsForEnvironment(){if(!this.options.secrets)return;let e=new Set([T]),n=s=>{s&&e.add(s);};n(this.registry.apiKeyEnv),n(this.registry.baseUrlEnv);for(let s of Object.values(this.registry.providerEnvMap??{}))n(s.keyEnv);let r={};for(let[s,a]of Object.entries(this.options.secrets)){if(e.has(s))throw new Error(`${s} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);s!==this.registry.gatewayConfigEnv&&(r[s]=a);}return r}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await wr(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async ensureProviderRuntimeToken(){let e=Nt(this.agentConfig.type);if(this.agentConfig.isDirectMode||!e||!this.options.providerRouting||this.providerRuntimeToken)return;let n;try{n=await Sr(this.options.providerRouting,{provider:e,sessionTag:this.sessionTag});}catch(r){throw kr(r)?new Error(`${e} runtime token endpoint is required in gateway mode: ${r.message}`):r}this.providerRuntimeToken=n,this.providerRuntimeToken&&this.sandbox?.sandboxId&&await this.bindProviderRuntimeToken(this.sandbox.sandboxId);}async bindProviderRuntimeToken(e){if(!this.providerRuntimeToken||!this.options.providerRouting)return;if(!await xr(this.options.providerRouting,{token:this.providerRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind provider runtime token to sandbox")}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=$t(this.options.managedBrowser.provider,this.managedBrowserSession);for(let r of n.directories)await e.files.makeDir(r);for(let r of n.files)await e.files.write(r.path,r.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await vr(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}async closeProviderRuntimeToken(){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let e=this.providerRuntimeToken,n;try{for(let r=0;r<3;r++)try{if(!await Cr(this.options.providerRouting,{token:e.token}))throw new Error("Dashboard returned ok=false");return}catch(s){n=s,r<2&&await new Promise(a=>setTimeout(a,100*(r+1)));}console.warn(`[Evolve] Provider runtime token cleanup failed: ${n.message}`);}finally{this.providerRuntimeToken=void 0;}}buildGatewayConfigJson(e){let n=G(this.registry.gatewayPath),r=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),s={},a=this.options.secrets?.[this.registry.gatewayConfigEnv];if(a)try{s=JSON.parse(a);}catch{}let o=s.provider??{},c=o.litellm??{},l=c.options??{},d=c.models??{},i=d[r]??{},p=i.headers??{},u=this.agentConfig.type==="opencode"?Ye(this.agentConfig.reasoningEffort):void 0,g=i.variants??{},f=u?g[u]??{}:void 0;return s.provider={...o,litellm:{...c,npm:"@ai-sdk/openai-compatible",options:{...l,baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{...d,[r]:{...i,name:r,headers:{...p,...e},...u?{variants:{...g,[u]:{...f,reasoningEffort:u}}}:{}}}}},JSON.stringify(s)}activeProviderRuntimeToken(){let e=Nt(this.agentConfig.type);return e&&this.providerRuntimeToken?.provider===e?this.providerRuntimeToken:void 0}ensureSessionLogger(e){if(this.sessionLogger)return;let n=this.options.sandboxProvider;this.sessionLogger=new ce({provider:n?.name||n?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:e.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}:{}}});}async flushSessionLoggerWithTimeout(e=2e3){this.sessionLogger&&await Promise.race([this.sessionLogger.flush(),new Promise(n=>setTimeout(n,e))]);}providerRuntimeHeaderUpdates(){let e=this.activeProviderRuntimeToken();return e?{[Bt]:e.bindingSecret}:{}}buildProviderRuntimeProcessEnvs(){let e=this.activeProviderRuntimeToken();if(!e)return {};let n={[this.registry.apiKeyEnv]:e.token};if(this.registry.baseUrlEnv&&(n[this.registry.baseUrlEnv]=e.baseUrl),this.registry.spendTrackingEnvs&&(n[Ft]=e.bindingSecret),this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";n[r]=Kt(this.options.secrets?.[r],this.providerRuntimeHeaderUpdates(),s);}return n}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.buildProviderRuntimeProcessEnvs(),r=this.registry.customHeadersEnv;if(r){let a=this.options.secrets?.[r],o=this.registry.customHeadersFormat||"newline";return n[r]=Kt(a,{[O]:this.sessionTag,[L]:`${W}${e}`,...this.providerRuntimeHeaderUpdates()},o),n}let s=this.registry.spendTrackingEnvs;return s?{...n,[s.sessionTagEnv]:this.sessionTag,[s.runTagEnv]:`${W}${e}`}:this.registry.gatewayConfigEnv?{...n,[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[O]:this.sessionTag,[L]:`${W}${e}`})}:Object.keys(n).length>0?n:void 0}async writeCodexGatewayProviderConfig(e){this.agentConfig.isDirectMode||!this.registry.spendTrackingEnvs||this.agentConfig.type!=="codex"||await at(e,this.activeProviderRuntimeToken()?.baseUrl||this.agentConfig.baseUrl||G(),this.registry.spendTrackingEnvs,this.activeProviderRuntimeToken()?{[Bt]:Ft}:void 0);}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(a=>typeof a.sessionId=="string"&&a.sessionId.length>0)?.sessionId;if(r){this.droidSessionId=r;return}let s=this.extractDroidSessionId(e);s&&(this.droidSessionId=s);}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,r=n.sessionId??n.session_id;return typeof r=="string"&&r.length>0?r: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(_r);if(typeof n!="string")return;let r=JSON.parse(n);typeof r.sessionId=="string"&&r.sessionId.length>0&&(this.droidSessionId=r.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir("/home/user/.factory"),await e.files.write(_r,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 cr(this.agentConfig.type,e,this.options.plugins);}assertProviderRuntimeDoesNotExposeGatewayKey(e){if(!this.activeProviderRuntimeToken())return;let n=this.agentConfig.apiKey;for(let[r,s]of Object.entries(e))for(let a of Object.values(s.headers||{}))if(a.includes(n))throw new Error(`MCP server "${r}" would expose the Evolve API key inside the sandbox. Use managed agent-browser or remove this gateway-authenticated MCP server.`)}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge",s=r==="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 ${s}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let o=xt({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),c=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(c,o);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let a={...this.options.mcpServers};if(this.options.integrations){let o=await $n({...this.options.integrations,sessionTag:this.sessionTag});a={...a,integrations:{type:"http",url:o.url,headers:o.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 o=await br({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});a={...a,[Dt]:o};}Object.keys(a).length>0&&(this.assertProviderRuntimeDoesNotExposeGatewayKey(a),await lt(this.agentConfig.type,e,this.workingDir,a)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await this.writeCodexGatewayProviderConfig(e),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await _e(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[O]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:r,targetDir:s}=n;await e.files.makeDir(s);for(let a of this.skills){let o=`cp -r ${r}/${a} ${s}/ 2>/dev/null || true`;await e.commands.run(o,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([a,o])=>({path:`${this.workingDir}/context/${a}`,data:o}));if(r.length===0)return;let s=new Set(r.map(a=>a.path.substring(0,a.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([a,o])=>({path:a.startsWith("/")?a:`${this.workingDir}/${a}`,data:o}));if(r.length===0)return;let s=new Set(r.map(a=>a.path.substring(0,a.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:Ps(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:r,timeoutMs:s=se,background:a=false,checkpointComment:o}=e,{from:c}=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(c&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(c==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await Ot(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');c=v.id;}if(c){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),await this.ensureProviderRuntimeToken();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}),await this.bindProviderRuntimeToken(this.sandbox.sandboxId);let b=await Xn(this.sandbox,this.storage,c);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 C=this.options.workspaceMode||"knowledge";if(b.workspaceMode&&b.workspaceMode!==C)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${b.workspaceMode}, current: ${C})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let R=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!R}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=c,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(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),b}}let l=await this.getSandbox(n);await this.ensureProviderRuntimeToken(),await this.loadDroidSessionState(l),this.lastRunTimestamp=Date.now(),this.ensureSessionLogger(l),this.sessionLogger?.writePrompt(r),this.activeProviderRuntimeToken()&&await this.flushSessionLoggerWithTimeout();let d=this.buildCommand(r),i=crypto.randomUUID(),p=this.buildRunEnvs(i);await this.writeCodexGatewayProviderConfig(l),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await _e(l,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[O]:this.sessionTag,[L]:`${W}${i}`}),this.agentConfig.type==="qwen"&&await et(l,ne(this.agentConfig.reasoningEffort)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await ct(l,this.registry.spendTrackingTomlProvider,{[O]:this.sessionTag,[L]:`${W}${i}`},{baseUrl:As(G(this.registry.gatewayPath)),apiKey:this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:ne(this.agentConfig.reasoningEffort),thinkingEffort:Rr(this.agentConfig.reasoningEffort)}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await Re(l,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${G()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[O]:this.sessionTag,[L]:`${W}${i}`});let u="",g=z(this.agentConfig.type),f=v=>{u+=v;let b=u.split(`
248
- `);u=b.pop()??"";for(let C of b){if(!C.trim())continue;let R=g(C);if(this.captureDroidSession(C,R),this.sessionLogger?.writeEventParsed(C,R),n?.onStdout?.(C+`
249
- `),R&&n?.onContent)for(let K of R)n.onContent(K);}},m=v=>{n?.onStderr?.(v);},h=await l.commands.spawn(d,{cwd:this.workingDir,timeoutMs:s,envs:p,onStdout:f,onStderr:m}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,a)return this.watchBackgroundOperation(y,"run",h,n,l),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:i,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(l),this.sessionLogger&&!a&&await this.flushSessionLoggerWithTimeout();let k;if(this.storage&&!a&&w.exitCode===0)try{k=await It(l,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:o,parentId:this.lastCheckpointId}),this.lastCheckpointId=k.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:i,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:k}}async executeCommand(e,n={},r){let{timeoutMs:s=se,background:a=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 o=await this.getSandbox(r);await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.activeProviderRuntimeToken()&&(this.ensureSessionLogger(o),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let c="",l="",d=h=>{c+=h,r?.onStdout?.(h);},i=h=>{l+=h,r?.onStderr?.(h);},p=this.buildProviderRuntimeProcessEnvs(),u=await o.commands.spawn(e,{cwd:this.workingDir,timeoutMs:s,envs:Object.keys(p).length>0?p:void 0,onStdout:d,onStderr:i}),g=this.beginOperation("command",u,r,"command_start");if(a)return this.watchBackgroundOperation(g,"command",u,r),{sandboxId:o.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${u.processId}`,stderr:""};let f;try{f=await u.wait();}catch(h){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,r,"command_failed","error"),h}return this.interruptedOperations.delete(g)||f.exitCode===130?this.finalizeOperation(g,r,"command_interrupted","interrupted"):f.exitCode===0?this.finalizeOperation(g,r,"command_complete","idle"):this.finalizeOperation(g,r,"command_failed","error"),{sandboxId:o.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:f.exitCode,stdout:c||f.stdout||"",stderr:l||f.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(),r=`${this.workingDir}/output`,s=e?"":"-maxdepth 1",o=(await n.commands.run(`find ${r} ${s} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
251
- `).filter(Boolean),c=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,l=[],d=`${r}/`;for(let f of o){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);c>0&&y<c||l.push(m);}let i={},p=await Promise.all(l.map(async f=>{try{let m=await n.files.read(f);return {relativePath:f.startsWith(d)?f.slice(d.length):f.split("/").pop()||f,content:m}}catch{return null}}));for(let f of p)f&&(i[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:i,data:null};let u=i["result.json"];if(!u)return {files:i,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 f=JSON.parse(g);if(this.zodSchema){let m=this.zodSchema.safeParse(f);return m.success?{files:i,data:m.data}:{files:i,data:null,error:`Schema validation failed: ${m.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:i,data:f};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:i,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:i,data:null}}catch(f){return {files:i,data:null,error:`Failed to parse result.json: ${f.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 It(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.closeProviderRuntimeToken(),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,r=this.activeOperationKind,s=false;try{this.activeCommand?s=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(s=await this.sandbox.commands.kill(this.activeProcessId));}catch{s=false;}if(!s)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let a=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,a),s}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(r){n=r;}finally{await this.closeProviderRuntimeToken(),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=Er(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 r=process.env.EVOLVE_DASHBOARD_URL||_,s=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${a}`)}return s}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(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),s=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(s)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let o=new URLSearchParams({tag:n,runId:e.runId}),l=await(await this.fetchSpend(o)).json();return this.normalizeRunCost(l,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,a=r.runs[s];if(!a)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return a}};function Ms(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}function $s(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return e}async function Ds(t){return await t.text().catch(()=>"")}async function Tr(t,e,n={}){let r=await fetch(`${Ms(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${$s(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await Ds(r)}`);return r.status===204?{}:await r.json()}var ze=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await Tr(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await Tr(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function jt(t={}){return new ze(t)}var we=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){if(Object.prototype.hasOwnProperty.call(e,T))throw new Error(`${T} is reserved for Evolve-managed sandbox services and cannot be set with withSecrets()`);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}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=Dn;static browserCredentials=Ut;static browserProfiles=jt;async initializeAgent(){let e=Ne(this.config.agent),n=this.config.sandbox??await wt();if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");let r={},s,a,o=this.config.skills,c;if(this.config.browser){let i=fr(this.config.browser);if(c=i,i.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.');r=zt(e.apiKey);}if((i.provider==="actionbook"||i.provider==="agent-browser")&&(o=mr(i.provider,o),i.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${i.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);s=i.provider==="actionbook"?vt:Tn,a={provider:i.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||_,...i.profile?{profile:i.profile}:{}};}if(i.profile&&!i.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}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(!c||c.provider!=="agent-browser"||!c.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 l=this.config.storage!==void 0?Ve(this.config.storage,!e.isDirectMode,_,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:{...r,...this.config.mcpServers},browserPrompt:s,managedBrowser:a,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||_,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||_}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||_},storage:l};this.agent=new ye(e,d);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,s=this.listenerCount("lifecycle")>0;return {onStdout:e?a=>this.emit("stdout",a):void 0,onStderr:n?a=>this.emit("stderr",a):void 0,onContent:r?a=>this.emit("content",a):void 0,onLifecycle:s?a=>this.emit("lifecycle",a):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:r,from:s,checkpointComment:a}){if(s&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let o=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:a},o)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.executeCommand(e,n,r)}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=Ne(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:_,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 Mt(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Mt(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 J=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 Vt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Ht;if(n>st)throw new Error(`concurrency=${n} exceeds max ${st}. 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??se,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:s,verify:a}=e,o=e.retry??this.config.retry,c=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs;if(s&&a)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((i,p)=>s?this.executeMapItemWithBestOf(i,r,p,c,e,l,o):a?this.executeMapItemWithVerify(i,r,p,c,e,l,o):o?I(u=>this.executeMapItem(i,r,p,c,e,l,u),o,p):this.executeMapItem(i,r,p,c,e,l)));return te.from(d)}async filter(e){let{items:n,prompt:r,condition:s,verify:a}=e,o=e.retry??this.config.retry,c=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>a?this.executeFilterItemWithVerify(p,r,u,c,e,l,o):o?I(g=>this.executeFilterItem(p,r,u,c,e,l,g),o,u):this.executeFilterItem(p,r,u,c,e,l))),i=[];for(let p of d)if(p.status==="error")i.push(p);else if(p.data!==null)try{s(p.data)?i.push(p):i.push({...p,status:"filtered"});}catch(u){i.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(i)}async reduce(e){let{items:n,prompt:r,verify:s}=e,a=e.retry??this.config.retry,o=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,l=[],d=[];n.forEach((k,v)=>{l.push(this.getFiles(k)),d.push(this.getIndex(k,v));});let i={};l.forEach((k,v)=>{Object.entries(k).forEach(([b,C])=>{i[`item_${d[v]}/${b}`]=C;});});let p=Ke(i),u=F(On,{fileTree:p}),g=e.systemPrompt?`${u}
252
-
253
- ${e.systemPrompt}`:u,f=(k,v,b)=>({operationId:o,operation:"reduce",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:v,verifyRetry:b,...this.pipelineContextToMeta(e._pipelineContext)}),m=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,w=async(k,v,b,C)=>{let R=await this.semaphore.use(()=>this.execute(i,k,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:v,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:e.name,operationId:o,operation:"reduce",role:"worker",errorRetry:b,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),K=f(R,b,C&&C>1?C-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:K,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:K}},S=`${this.config.tag}-reduce`;return s?this.runWithVerification((k,v,b)=>w(k,v,void 0,b),{originalPrompt:r,inputFiles:i,verifyConfig:s,timeoutMs:c,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:o,baseTag:S,retry:a,operation:"reduce",_pipelineContext:e._pipelineContext}):a?I(k=>{let v=k>1?k-1:void 0,b=v?`${S}-er${v}`:S;return w(r,b,v)},a):w(r,S)}async bestOf(e){let{item:n,prompt:r,config:s}=e,a=e.retry??this.config.retry,o=s.n??s.taskAgents?.length;if(o===void 0)throw new Error("bestOf requires n or taskAgents");if(o<2)throw new Error("bestOf requires n >= 2");let c=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),i=s.mcpServers??this.config.mcpServers,p=s.judgeMcpServers??s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,g=s.judgeSkills??s.skills??this.config.skills,f=s.integrations??this.config.integrations,m=s.judgeIntegrations??s.integrations??this.config.integrations,h=await Promise.all(Array.from({length:o},async(v,b)=>{let C=a?await I(R=>this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:b,operationId:c,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:l,attempt:R}),a,b):await this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:b,operationId:c,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:l});return s.onCandidateComplete?.(0,b,C.status==="success"?"success":"error"),C})),y=a?await I(v=>this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m,attempt:v}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m}),w=h.findIndex(v=>v.status==="success"),S=y.decision?.winner??(w>=0?w:0);s.onJudgeComplete?.(0,S,y.decision?.reasoning??"Judge failed to provide reasoning");let k={operationId:c,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:o};return {winner:h[S]??h[0],winnerIndex:S,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:k,candidates:h}}async execute(e,n,r){let s=null,a="",o=r.tagPrefix,c={},l=null,d,i,p={...this.config.agent,...r.agent};try{s=new we().withAgent(p).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&s.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&s.withSystemPrompt(r.systemPrompt),r.mcpServers&&s.withMcpServers(r.mcpServers),r.skills?.length&&s.withSkills(r.skills),r.integrations&&s.withIntegrations(r.integrations),r.observability&&s.withObservability(r.observability),Object.keys(e).length>0&&s.withContext(e);let u=await s.run({prompt:n,timeoutMs:r.timeoutMs});a=u.sandboxId,o=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),c=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:r.schema?g?(l=g.data,g.error&&(d=g.error),g.rawData&&(i=g.rawData)):d="Failed to read output files from sandbox":l=c;}catch(u){if(d=u.message,s){o=s.getSessionTag()??r.tagPrefix;try{c=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:c,data:l,tag:o,sandboxId:a,error:d,rawData:i}}async executeMapItem(e,n,r,s,a,o,c=1){let l=this.getFiles(e),d=c>1?`${this.config.tag}-map-${r}-er${c-1}`:`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,l,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,g=a.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(l,i,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:d,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),m={operationId:s,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,errorRetry:c>1?c-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,s,a,o,c){let l=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=a.verify,p=a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,g=a.integrations??this.config.integrations,f=this.evaluatePrompt(n,l,r);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let m=async(h,y,w)=>{let S=await this.semaphore.use(()=>this.execute(l,h,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:y,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),k={operationId:s,operation:"map",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(S,k)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:l,verifyConfig:i,timeoutMs:o,systemPrompt:a.systemPrompt,schema:a.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:c,itemIndex:r,operation:"map",_pipelineContext:a._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,a,o,c){let l=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,l,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=a.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:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let g=a.mcpServers??this.config.mcpServers,f=p.mcpServers??g,m=p.judgeMcpServers??p.mcpServers??g,h=a.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,S=a.integrations??this.config.integrations,k=p.integrations??S,v=p.judgeIntegrations??p.integrations??S,b=await Promise.all(Array.from({length:u},async(ve,be)=>{let Wt=c?await I(Or=>this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:be,operationId:s,config:p,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:f,skills:y,integrations:k,timeoutMs:o,parentIndex:r,attempt:Or,_pipelineContext:a._pipelineContext}),c,be):await this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:be,operationId:s,config:p,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:f,skills:y,integrations:k,timeoutMs:o,parentIndex:r,_pipelineContext:a._pipelineContext});return p.onCandidateComplete?.(r,be,Wt.status==="success"?"success":"error"),Wt})),C=c?await I(ve=>this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:b,config:p,timeoutMs:o,operationId:s,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:m,skills:w,integrations:v,parentIndex:r,attempt:ve,_pipelineContext:a._pipelineContext}),{...c,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:b,config:p,timeoutMs:o,operationId:s,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:m,skills:w,integrations:v,parentIndex:r,_pipelineContext:a._pipelineContext}),R=b.findIndex(ve=>ve.status==="success"),K=C.decision?.winner??(R>=0?R:0),Gt=b[K]??b[0];p.onJudgeComplete?.(r,K,C.decision?.reasoning??"Judge failed to provide reasoning");let Ir={operationId:s,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:a.name,candidateCount:u,...this.pipelineContextToMeta(a._pipelineContext)};return {...Gt,meta:{...Gt.meta,operation:"map",swarmName:this.config.tag,operationName:a.name,itemIndex:r,...this.pipelineContextToMeta(a._pipelineContext)},bestOf:{winnerIndex:K,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Ir,candidates:b}}}async executeFilterItem(e,n,r,s,a,o,c=1){let l=this.getFiles(e),d=c>1?`${this.config.tag}-filter-${r}-er${c-1}`:`${this.config.tag}-filter-${r}`,i=a.mcpServers??this.config.mcpServers,p=a.skills??this.config.skills,u=a.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(l,n,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:i,skills:p,integrations:u,tagPrefix:d,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),f={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,errorRetry:c>1?c-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(g,f,l)}async executeFilterItemWithVerify(e,n,r,s,a,o,c){let l=this.getFiles(e),d=`${this.config.tag}-filter-${r}`,i=a.verify,p=a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,g=a.integrations??this.config.integrations,f=async(m,h,y)=>{let w=await this.semaphore.use(()=>this.execute(l,m,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:h,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),S={operationId:s,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(w,S,l)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:l,verifyConfig:i,timeoutMs:o,systemPrompt:a.systemPrompt,schema:a.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:c,itemIndex:r,operation:"filter",_pipelineContext:a._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:a,config:o,timeoutMs:c,parentIndex:l,attempt:d=1,_pipelineContext:i}=e,p=l!==void 0?`${this.config.tag}-map-${l}-bestof-cand-${s}`:`${this.config.tag}-bestof-cand-${s}`,u=d>1?`${p}-er${d-1}`:p,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:o.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:u,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:a,operation:"map",itemIndex:l,role:"candidate",candidateIndex:s,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(i)}})),f={operationId:a,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:s,errorRetry:d>1?d-1:void 0,candidateIndex:s,...this.pipelineContextToMeta(i)};return this.buildResult(g,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((r,s)=>{r.status==="error"&&(n[`candidate_${s}/_failed.txt`]=`STATUS: FAILED
254
-
255
- Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([a,o])=>{n[`candidate_${s}/${a}`]=o;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:a,parentIndex:o,attempt:c=1,_pipelineContext:l}=e,d=o!==void 0?`${this.config.tag}-map-${o}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=c>1?`${d}-er${c-1}`:d,p=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=Ke(p),g=F(bt,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:u}),f=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),m=await this.semaphore.use(()=>this.execute(p,Pn,{systemPrompt:g,schema:f,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:i,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:a,operation:"map",itemIndex:o,role:"judge",errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(l)}})),h=null;if(m.data&&!m.error)h=m.data;else if(m.rawData)try{let y=JSON.parse(m.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: ${m.error}`);}return {status:h?"success":"error",decision:h,tag:m.tag,sandboxId:m.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(([r,s])=>{n[`worker_output/${r}`]=s;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:s,workerTag:a,retryAttempt:o=1,operation:c,itemIndex:l,attemptIndex:d,_pipelineContext:i}=e,p=o>1?`${a}-verifier-er${o-1}`:`${a}-verifier`,u=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,f=n.verifierIntegrations??e.integrations,m=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=Ke(m),y=F(kt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(m,In,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:u,skills:g,integrations:f,tagPrefix:p,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:c,itemIndex:l,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i)}})),S=null;if(w.data&&!w.error)S=w.data;else if(w.rawData)try{let k=JSON.parse(w.rawData);S={passed:!!k.passed,reasoning:k.reasoning??"Verification completed",feedback:k.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 F(St,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:s,verifyConfig:a,timeoutMs:o,operationId:c,baseTag:l,retry:d,itemIndex:i=0,operation:p,_pipelineContext:u}=n,g=a.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let w=h>1?`${l}-vr${h-1}`:l,S=d?await I(b=>e(f,b>1?`${w}-er${b-1}`:w,h),d,i):await e(f,w,h);if(a.onWorkerComplete?.(i,h,S.status==="error"?"error":"success"),S.status==="error")return S;m=S;let k=d?await I(b=>this.executeVerify({inputFiles:s,outputFiles:S.files,taskPrompt:f,config:a,timeoutMs:o,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:c,workerTag:w,retryAttempt:b,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:S.files,taskPrompt:f,config:a,timeoutMs:o,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:c,workerTag:w,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),v={operationId:c,operation:"verify",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(a.onVerifierComplete?.(i,h,k.decision?.passed??false,k.decision?.feedback),k.decision?.passed)return {...S,verify:{passed:true,reasoning:k.decision.reasoning,verifyMeta:v,attempts:h}};if(h<g){let b=k.decision?.feedback??k.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(r,b);}}let y=h>1?`${l}-vr${h-1}`:l;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:c,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,r){if(typeof e=="string")return e;try{return e(n,r)}catch(s){return s}}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)?q(e.schema):Y(e.schema)),Object.entries(e.inputFiles).forEach(([r,s])=>{n[`worker_task/input/${r}`]=s;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&J in e&&e[J]===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,r){let s=r??e.files;return e.error?{[J]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[J]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[J]:true,status:"error",data:null,files:{},meta:n,error:e}}};var Je=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}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 He(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),r=[],s=e,a=Date.now();for(let c=0;c<this.steps.length;c++){let l=this.steps[c],d=l.config.name,i=Date.now();this.events.onStepStart?.({type:l.type,index:c,name:d,itemCount:s.length});let p={pipelineRunId:n,pipelineStepIndex:c};try{let u=await this.executeStep(l,s,c,d,p),g=Date.now()-i;if(r.push({type:l.type,index:c,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:l.type,index:c,name:d,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),l.type==="reduce")return {pipelineRunId:n,steps:r,output:u.output,totalDurationMs:Date.now()-a};s=u.nextItems;}catch(u){throw this.events.onStepError?.({type:l.type,index:c,name:d,error:u instanceof Error?u:new Error(String(u))}),u}}let o=r[r.length-1];return {pipelineRunId:n,steps:r,output:o?.results??[],totalDurationMs:Date.now()-a}}async executeStep(e,n,r,s,a){if(e.type==="map"){let l=e.config,d=await this.swarm.map({items:n,...l,_pipelineContext:a,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s),bestOf:this.wrapBestOf(l.bestOf,r,s)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let l=e.config,d=await this.swarm.filter({items:n,...l,_pipelineContext:a,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s)}),i=l.emit??"success",p=i==="success"?d.success:i==="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 o=e.config,c=await this.swarm.reduce({items:n,...o,_pipelineContext:a,retry:this.wrapRetry(o.retry,r,s),verify:this.wrapVerify(o.verify,r,s)});return {output:c,nextItems:[],successCount:c.status==="success"?1:0,errorCount:c.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,a,o)=>{e.onItemRetry?.(s,a,o),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:a,error:o});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,a,o)=>{e.onWorkerComplete?.(s,a,o),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:a,status:o});},onVerifierComplete:(s,a,o,c)=>{e.onVerifierComplete?.(s,a,o,c),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:a,passed:o,feedback:c});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,a,o)=>{e.onCandidateComplete?.(s,a,o),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:a,status:o});},onJudgeComplete:(s,a,o)=>{e.onJudgeComplete?.(s,a,o),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:a,reasoning:o});}}}},He=class t extends Je{constructor(e,n,r){super(e,n,r);}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]: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 Gs=6e5,Ws=5e3;function Pr(t,e,n){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be a positive number`);return r}function zs(t){let e=t?.apiKey||process.env[T];if(!e)throw new Error(`sessions() requires an API key. Set ${T} or pass { apiKey } in config.`);let n=t?.dashboardUrl||_;async function r(c,l){let d=await fetch(`${n}${c}`,{...l,headers:{Authorization:`Bearer ${e}`,...l?.headers}});if(!d.ok){let i=await d.text().catch(()=>"");throw new Error(`Dashboard API error (${d.status}): ${i||d.statusText}`)}return d}function s(c){return {id:c.id,tag:c.tag,agent:c.agent,model:c.model||null,provider:c.provider,sandboxId:c.sandboxId||null,state:c.isEnded?"ended":"live",runtimeStatus:c.runtimeStatus||"unknown",cost:typeof c.cost=="number"?c.cost:null,createdAt:c.createdAt,endedAt:c.endedAt||null,stepCount:c.stepCount||0,toolStats:c.toolStats||null}}function a(c,l){if(c.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(c.status||"unknown")})`);if(typeof c.replayUrl!="string"||typeof c.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:c.sessionId||l,status:"ready",replayUrl:c.replayUrl,downloadUrl:c.downloadUrl,suggestedStartSeconds:typeof c.suggestedStartSeconds=="number"?c.suggestedStartSeconds:void 0,sizeBytes:typeof c.sizeBytes=="number"?c.sizeBytes:void 0,readyAt:typeof c.readyAt=="string"?c.readyAt:void 0}}let o=c=>new Promise(l=>setTimeout(l,c));return {async list(c){let l=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(c?.limit??20,200)),paginated:"true"});if(c?.cursor&&l.set("cursor",c.cursor),c?.state&&c.state!=="all"&&l.set("state",c.state),c?.agent&&l.set("agent",c.agent),c?.tagPrefix&&l.set("tagPrefix",c.tagPrefix),c?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};l.set("sortDirection",p[c.sort]),c.sort==="cost"?l.set("sortField","cost"):l.set("sortField","timestamp");}let i=await(await r(`/api/sessions?${l}`)).json();return {items:(i.items||[]).map(s),nextCursor:i.nextCursor||null,hasMore:!!i.hasMore}},async get(c){let d=await(await r(`/api/sessions/${encodeURIComponent(c)}`)).json();return s(d)},async events(c,l){let d=new URLSearchParams;l?.since!=null&&d.set("since",String(l.since));let i=d.toString();return (await(await r(`/api/sessions/${encodeURIComponent(c)}/events${i?`?${i}`:""}`)).json()).events||[]},async download(c,l){let p=(await(await r(`/api/sessions/${encodeURIComponent(c)}`)).json()).tag||c,u=await fetch(`${n}/api/sessions/${encodeURIComponent(c)}/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=l?.to||process.cwd();await promises.mkdir(g,{recursive:true});let f=ae.join(g,`${p}.jsonl`);if(!u.body)throw new Error("Download response has no body");let m=stream.Readable.fromWeb(u.body);return await promises$1.pipeline(m,$.createWriteStream(f)),f},async browserReplay(c,l){let d=Pr("timeoutMs",l?.timeoutMs,Gs),i=Pr("intervalMs",l?.intervalMs,Ws),p=Date.now()+d,u=`/api/sessions/${encodeURIComponent(c)}/browser-replay`;for(;;){let g=p-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let f;try{f=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 m={};if(f.ok)m=await f.json();else {let h=await f.text().catch(()=>"");throw new Error(`Dashboard API error (${f.status}): ${h||f.statusText}`)}if(m.status==="ready")return a(m,c);if(m.status==="failed"){let h=typeof m.error=="string"?m.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 o(Math.min(i,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=Qe;exports.AGENT_TYPES=Ar;exports.Agent=ye;exports.BROWSER_ACTIONBOOK_PROMPT=vt;exports.BROWSER_LOGIN_MCP_SERVER_NAME=Dt;exports.BrowserCredentialsClient=We;exports.BrowserProfilesClient=ze;exports.Evolve=we;exports.JUDGE_PROMPT=bt;exports.Pipeline=Je;exports.RETRY_FEEDBACK_PROMPT=St;exports.SCHEMA_PROMPT=Rn;exports.SWARM_RESULT_BRAND=J;exports.SYSTEM_PROMPT=En;exports.Semaphore=ee;exports.Swarm=Vt;exports.SwarmResultList=te;exports.TerminalPipeline=He;exports.VALIDATION_PRESETS=qe;exports.VERIFY_PROMPT=kt;exports.WORKSPACE_PROMPT=Cn;exports.WORKSPACE_SWE_PROMPT=_n;exports.applyTemplate=F;exports.browserCredentials=Ut;exports.browserProfiles=jt;exports.buildWorkerSystemPrompt=xt;exports.createAgentParser=z;exports.createClaudeParser=$e;exports.createCodexParser=De;exports.createDroidParser=Ue;exports.createGeminiParser=Be;exports.executeWithRetry=I;exports.expandPath=V;exports.getAgentConfig=D;exports.getMcpSettingsDir=B;exports.getMcpSettingsPath=U;exports.isValidAgentType=$r;exports.isZodSchema=M;exports.jsonSchemaToString=Y;exports.parseNdjsonLine=pi;exports.parseNdjsonOutput=ui;exports.parseQwenOutput=ln;exports.readLocalDir=dn;exports.resolveStorageConfig=Ve;exports.saveLocalDir=pn;exports.sessions=zs;exports.storage=as;exports.writeClaudeMcpConfig=Se;exports.writeCodexMcpConfig=Me;exports.writeDroidGatewaySettings=Re;exports.writeDroidMcpConfig=Ee;exports.writeGeminiMcpConfig=xe;exports.writeMcpConfig=lt;exports.writeQwenMcpConfig=Ce;exports.zodSchemaToJson=q;
216
+ `;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.annotations()}},n=JSON.stringify(e)+`
217
+ `;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>=ar){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},lr));}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.annotations(),events:e};for(let r=1;r<=et;r++)try{let s=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(s.ok)return;if(s.status===429||s.status===401||s.status>=500){if(r===et){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Gt*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===et?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(Gt*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=We();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))}annotations(){if(!this.observability)return {};let e={};for(let[n,r]of Object.entries(this.observability))if(r!==void 0){if(be.includes(n)){this.warnedKeys.has(n)||(this.warnedKeys.add(n),console.warn(`[SessionLogger] observability key "${n}" is reserved for session identity \u2014 ignoring it.`));continue}e[n]=r;}return e}};function Ie(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function Ae(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed integrations");return e}async function Oe(t){return await t.text().catch(()=>"")}function Rn(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function Wo(t){let e=Array.from(new Set((t??[]).map(n=>n.trim()).filter(Boolean)));if(e.length===0)throw new Error("withIntegrations() requires at least one app");return e}async function rs(t){let e=await fetch(`${Ie(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${Ae(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Rn(t.userId),apps:Wo(t.apps),tools:t.tools,accounts:t.accounts,keys:t.keys,authConfigs:t.authConfigs,sessionTag:t.sessionTag}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integrations session create failed (${e.status}): ${await Oe(e)}`);let n=await e.json();if(!n.mcp?.url)throw new Error("Managed integrations response missing mcp.url");return {url:n.mcp.url,headers:n.mcp.headers??{}}}async function Yo(t){let e=await fetch(`${Ie(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${Ae(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Rn(t.userId),app:t.app,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration connect failed (${e.status}): ${await Oe(e)}`);return await e.json()}async function Xo(t){let e=Array.from(new Set((t.userIds??[]).map(c=>Rn(c))));if(e.length===0)throw new Error("Integration accounts.list() requires at least one userId");let n=new URLSearchParams({userIds:e.join(",")});t.app&&n.set("app",t.app),t.statuses?.length&&n.set("statuses",t.statuses.join(","));let r={Authorization:`Bearer ${Ae(t.apiKey)}`,accept:"application/json"},s=await fetch(`${Ie(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Managed integration status failed (${s.status}): ${await Oe(s)}`);return ((await s.json()).accounts??[]).map(c=>({userId:String(c.userId??""),app:String(c.app??""),appName:typeof c.appName=="string"?c.appName:void 0,appIcon:typeof c.appIcon=="string"?c.appIcon:void 0,accountLabel:typeof c.accountLabel=="string"?c.accountLabel:void 0,status:String(c.status??""),accountId:typeof c.accountId=="string"?c.accountId:void 0,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:void 0}))}async function Qo(t){let e=await fetch(`${Ie(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${Ae(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account update failed (${e.status}): ${await Oe(e)}`);return await e.json()}async function Zo(t){let e=await fetch(`${Ie(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${Ae(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account delete failed (${e.status}): ${await Oe(e)}`);return await e.json()}var ss={auth:Yo,accounts:{list:Xo,update:Qo,delete:Zo}};util.promisify(child_process.exec);var On=util.promisify(child_process.execFile),as=Symbol.for("evolve:awsSdkCache"),ls=Symbol.for("evolve:s3ClientCache");var da=3600,ua=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function pa(t){if(t.startsWith("s3://")){let s=t.slice(5),a=s.indexOf("/");return a===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,a),prefix:s.slice(a+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,r=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:r.join("/")};if(r.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:r[0],prefix:r.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function St(t,e,n,r){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:r}}let s=t?.bucket||"",a=t?.prefix||"",c=t?.endpoint;if(t?.url){let l=pa(t.url);s=s||l.bucket,a=a||l.prefix,c=c||l.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:a,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:c,credentials:t?.credentials,mode:"byok"}}function Tn(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 ga(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 Me(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function ma(t,e){let n=O(t),r=ga(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(l=>Tn(l)):[Tn(n.mcpConfig.settingsDir)],a=[...ua.map(l=>`--exclude=${Me(l)}`),`--exclude=${Me(r+"/temp")}`,...(n.checkpointExcludes??[]).map(l=>`--exclude=${Me(Tn(l))}`)].join(" "),c=[Me(r+"/"),...s.map(l=>Me(l+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${a} ${c}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function ce(){let t=globalThis[as];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,s]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[as]={s3:r,presigner:s},{s3:r,presigner:s}}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 Ue(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[ls];if(r?.key===n)return r.client;let{s3:s}=await ce(),a=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[ls]={client:a,key:n},a}async function ys(t,e,n){let{s3:r,presigner:s}=await ce(),a=await Ue(t),c=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(a,c,{expiresIn:da})}async function cs(t,e){let{s3:n}=await ce(),r=await Ue(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let a=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||a==="NotFound"||a==="NoSuchKey")return false;throw s}}async function ws(t,e){let{s3:n}=await ce(),a=await(await(await Ue(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!a)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(a)}async function fa(t,e,n){let{s3:r}=await ce();await(await Ue(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function bs(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function vs(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function ha(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Ss(t,e,n,r){let s=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:r})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${a}`)}return s.json()}async function ya(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${r}`)}return n.json()}async function wa(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${r}`)}return n.json()}async function Mn(t,e,n,r,s){let a=new Date().toISOString(),c=ma(n,r),l=await t.commands.run(c,{timeoutMs:12e4});if(l.exitCode!==0)throw new Error(`Checkpoint tar failed: ${l.stderr}`);let o=l.stdout.trim().split(`
218
+ `).pop()?.trim();if(!o||o.length!==64)throw new Error(`Invalid checkpoint hash: ${o}`);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}),i=parseInt(d.stdout.trim(),10),u=Number.isNaN(i)?void 0:i,p;try{if(e.mode==="byok"){let g=bs(e,o);if(!await cs(e,g)){let h=await ys(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 cs(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}p=ha();let f={id:p,hash:o,tag:s.tag,timestamp:a,sizeBytes:u,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment,sandboxId:t.sandboxId};await fa(e,vs(e,p),f);}else {let g=await Ss(e,s.tag,o,"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}`)}p=(await ya(e,{tag:s.tag,hash:o,sizeBytes:u??0,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:p,hash:o,tag:s.tag,timestamp:a,sizeBytes:u,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment}}async function _s(t,e,n){let r=await Un(e,n),s=r.hash,a={agentType:r.agentType,workspaceMode:r.workspaceMode},c=await Es(e,r),l=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${c}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(l.exitCode!==0)throw new Error(`Checkpoint download failed: ${l.stderr}`);let o=l.stdout.trim().split(`
219
+ `).pop()?.trim();if(o!==s)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${o})`);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 a}function xs(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||E,s=!t.url&&!t.bucket&&!!n;return St(t,s,r,n)}async function ks(t,e){let{s3:n}=await ce(),r=await Ue(t),a=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,c=[],l;do{let p={Bucket:t.bucket,Prefix:a,...l&&{ContinuationToken:l}},g=await r.send(new n.ListObjectsV2Command(p));if(g.Contents)for(let m of g.Contents)m.Key?.endsWith(".json")&&m.LastModified&&c.push({key:m.Key,lastModified:m.LastModified});l=g.IsTruncated?g.NextContinuationToken:void 0;}while(l);if(c.length===0)return [];c.sort((p,g)=>{let m=g.lastModified.getTime()-p.lastModified.getTime();return m!==0?m:g.key<p.key?-1:g.key>p.key?1:0});let d=!!e?.tag?c:e?.limit?c.slice(0,e.limit):c,u=(await Promise.all(d.map(async p=>{try{return await ws(t,p.key)}catch{return null}}))).filter(p=>p!==null);return e?.tag&&(u=u.filter(p=>p.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function Cs(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let r=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${s.status}): ${a}`)}return s.json()}function ba(t){return t&&t>0?Math.min(t,500):100}async function Dn(t,e){return t.mode==="byok"?(await ks(t,{limit:1,tag:e?.tag}))[0]??null:(await Cs(t,{limit:1,tag:e?.tag}))[0]??null}async function Un(t,e){if(t.mode==="byok"){let n=vs(t,e);try{return await ws(t,n)}catch(r){throw va(r)?new Error(`Checkpoint ${e} not found`):r}}else return await wa(t,e)}async function ds(t,e,n){if(e==="latest"){let r=await Dn(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function Es(t,e){if(t.mode==="byok")return ys(t,bs(t,e.hash),"get");{let n=await Ss(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function Rs(t){return !(!t||F.isAbsolute(t)||t.startsWith("-")||F.normalize(t).startsWith("..")||t.includes("\0"))}function us(t,e){let n=F.resolve(t,e),r=F.resolve(t),s=F.relative(r,n);if(s.startsWith("..")||F.isAbsolute(s))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function va(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Pn(t){let e=t.filter(n=>!Rs(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var Ts=10*1024*1024,ps=false;async function Ps(){if(!ps)try{await On("tar",["--version"]),ps=!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 gs(t,e){let n=await Un(t,e),r=await Es(t,n),s=e.replace(/[^a-zA-Z0-9_-]/g,"_"),a=F.join(os.tmpdir(),`evolve-dl-${s}-${Date.now()}.tar.gz`),c=await fetch(r);if(!c.ok)throw new Error(`Checkpoint download failed (${c.status})`);if(!c.body)throw new Error("Checkpoint download returned empty body");let l=crypto.createHash("sha256"),o=j.createWriteStream(a);try{let i=c.body.getReader();await new Promise((u,p)=>{o.on("error",p),o.on("finish",u);async function g(){for(;;){let{done:m,value:f}=await i.read();if(m){o.end();break}l.update(f),o.write(f)||await new Promise(h=>o.once("drain",h));}}g().catch(p);});}catch(i){throw o.destroy(),await promises.unlink(a).catch(()=>{}),i}let d=l.digest("hex");if(d!==n.hash)throw await promises.unlink(a).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:a,metadata:n}}async function ms(t){await Ps();let{stdout:e}=await On("tar",["-tvzf",t],{maxBuffer:Ts}),n=new Set,r=[],s=[];for(let a of e.trim().split(`
220
+ `)){if(!a||a.startsWith("total "))continue;let c=a[0];if(c!=="-"&&c!=="d"&&c!=="l")throw new Error(`Archive contains unsupported entry type: "${c}"`);let l=a.match(/\d{2}:\d{2}\s+(.+)/)??a.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!l)continue;let o=l[1];if(c==="l"){let d=o.indexOf(" -> ");d!==-1&&(o=o.slice(0,d)),n.add(o);}else c==="d"?r.push(o.replace(/\/$/,"")):s.push(o);}return Pn(r),Pn([...n]),Pn(s)}async function In(t,e,n){await Ps(),await promises.mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await On("tar",r,{maxBuffer:Ts});}function Sa(t){let e="^",n=0;for(;n<t.length;){let r=t[n];r==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):r==="*"?(e+="[^/]*",n++):r==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(r)?(e+="\\"+r,n++):(e+=r,n++);}return e+="$",new RegExp(e)}function $n(t,e){let n=xs(t,e);return Is(n)}function _a(t){let e=xs(t||{});return Is(e)}function Is(t){return {async listCheckpoints(e){let n=ba(e?.limit);return t.mode==="byok"?ks(t,{limit:n,tag:e?.tag}):Cs(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return Un(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,s=n?.to||process.cwd(),a=await ds(t,e),{tmpPath:c,metadata:l}=await gs(t,a);try{if(r)return await promises.mkdir(s,{recursive:!0}),await ms(c),await In(c,s),s;{await promises.mkdir(s,{recursive:!0});let o=F.join(s,`checkpoint-${l.id}.tar.gz`);return await promises.copyFile(c,o),o}}finally{await promises.unlink(c).catch(()=>{});}},async downloadFiles(e,n){let r=await ds(t,e),{tmpPath:s}=await gs(t,r),a;try{let c=await ms(s),l;if(n?.files){let d=n.files.filter(u=>!Rs(u));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let i=new Set(n.files);l=c.filter(u=>i.has(u));}else if(n?.glob){let d=n.glob.map(Sa);l=c.filter(i=>d.some(u=>u.test(i)));}else l=c;if(l.length===0)return {};a=F.join(os.tmpdir(),`evolve-extract-${Date.now()}`);try{await In(s,a,l);}catch(d){let i=d?.message??"";if(!i.includes("E2BIG")&&!i.includes("Argument list too long")&&!i.includes("ENAMETOOLONG"))throw d;await promises.rm(a,{recursive:!0,force:!0}).catch(()=>{}),a=F.join(os.tmpdir(),`evolve-extract-${Date.now()}`),await In(s,a);}let o={};return await Promise.all(l.map(async d=>{us(a,d),o[d]=await promises.readFile(F.join(a,d));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(o).map(async([d,i])=>{us(n.to,d);let u=F.join(n.to,d);await promises.mkdir(F.dirname(u),{recursive:!0}),await promises.writeFile(u,i);}))),o}finally{a&&await promises.rm(a,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(s).catch(()=>{});}}}}function H(t){return `'${t.replace(/'/g,"'\\''")}'`}function _t(t){return typeof t=="string"&&t.length>0}function de(t,e,n){let r=t[e];if(!_t(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function xa(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
221
+ ${n}`)}function ka(t,e){switch(t){case "droid":{let n=de(e,"marketplace",t),r=de(e,"plugin",t);return [`droid plugin marketplace add ${H(n)}`,`droid plugin install ${H(r)} --scope user`]}case "claude":{let n=de(e,"marketplace",t),r=de(e,"plugin",t);return [`claude plugin marketplace add ${H(n)} --scope user`,`claude plugin install ${H(r)} --scope user`]}case "gemini":{let n=de(e,"source",t),r=e,s=[`gemini extensions install ${H(n)}`];return _t(r.ref)&&s.push(`--ref ${H(r.ref)}`),r.autoUpdate===true&&s.push("--auto-update"),r.preRelease===true&&s.push("--pre-release"),s.push("--consent"),r.skipSettings===true&&s.push("--skip-settings"),[s.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=de(e,"marketplace",t),r=e,s=[`codex plugin marketplace add ${H(n)}`];if(_t(r.ref)&&s.push(`--ref ${H(r.ref)}`),Array.isArray(r.sparse))for(let a of r.sparse){if(!_t(a))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");s.push(`--sparse ${H(a)}`);}return [s.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function As(t,e,n){if(n?.length)for(let r of n){let s=ka(t,r);for(let a of s){let c=await e.commands.run(a,{timeoutMs:12e4});if(c.exitCode!==0)throw xa(a,c)}}}var Ea=["actionbook","active-research","extract"],Ra=["agent-browser"],Ta={actionbook:Ea,"agent-browser":Ra},Us="/home/user/.agent-browser",Os=`${Us}/config.json`,$s="/home/user/.actionbook",Pa=`${$s}/config.toml`;function Ms(t){return t==="actionbook"||t==="agent-browser"}function Ia(t){return t.remote===true}function Ds(t){if(t==null)return;if(typeof t!="string")throw new Error("browser profile must be a string");let e=t.trim();if(!e)throw new Error("browser profile cannot be empty");return e}function Ls(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(Ms(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(t.provider===void 0)return {provider:"agent-browser",managed:t.remote!==false,profile:Ds(t.profile)};if(Ms(t.provider))return {provider:t.provider,managed:Ia(t),profile:Ds(t.profile)};throw new Error("Unsupported browser configuration")}function Bs(t,e){return Array.from(new Set([...e??[],...Ta[t]]))}function Ln(t,e){return t==="actionbook"?{envs:{},files:[{path:Pa,data:smolToml.stringify({version:1,browser:{mode:"cloud",cdp_endpoint:e.cdpUrl}}).trimEnd()+`
222
+ `}],directories:[$s]}:{envs:{AGENT_BROWSER_CONFIG:Os},files:[{path:Os,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
223
+ `}],directories:[Us]}}function Ns(t){return (t?.dashboardUrl||E).replace(/\/$/,"")}async function Fs(t){return await t.text().catch(()=>"")}async function js(t,e,n={}){let r=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},browserAuth:n.browserCredentials===true,...t.profile?{profile:t.profile}:{}}),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`Managed browser session create failed (${r.status}): ${await Fs(r)}`);let s=await r.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,browserAuthGrantToken:s.browserAuthGrantToken}}async function Ks(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 Fs(n)}`)}var Ma="RSA-OAEP-256",Bn="browser-login";function Da(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function Ua(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 $a(t){return await t.text().catch(()=>"")}async function $e(t,e,n={}){let r=await fetch(`${Da(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${Ua(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser credentials request failed (${r.status}): ${await $a(r)}`);return await r.json()}async function La(t,e){let n=await $e(t,"/api/browser-credentials/public-key"),r=crypto.publicEncrypt({key:n.publicKey,padding:crypto.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"utf8"));return {algorithm:Ma,keyId:n.id,ciphertext:r.toString("base64url")}}var xt=class{constructor(e={}){this.config=e;}toMetadata(e){let{account_label:n,...r}=e;return {...r,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 r=n.toString()?`?${n.toString()}`:"",s=await $e(this.config,`/api/browser-credentials${r}`);return {credentials:s.credentials.map(a=>this.toMetadata(a)),total:s.total,count:s.count,offset:s.offset,hasMore:s.has_more??s.offset+s.count<s.total}}async create(e){let n=await La(this.config,e.password),r=await $e(this.config,"/api/browser-credentials",{method:"POST",body:JSON.stringify({website:e.website,account_label:e.accountLabel,email:e.email,encryptedPassword:n})});return {status:r.status,credential:this.toMetadata(r.credential)}}async delete(e){let n="id"in e?e:{website:e.website,account_label:e.accountLabel};return await $e(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function Nn(t={}){return new xt(t)}async function Js(t){return (await $e({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:Ba(t.config)})})).server}function Ba(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var Fn="x-evolve-provider-runtime-binding";function Na(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}async function Fa(t){return await t.text().catch(()=>"")}var Le=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ProviderRuntimeTokenRequestError";}};function Vs(t){return t instanceof Le&&t.status===404}async function jn(t,e,n={}){let r=await fetch(`${Na(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Le(r.status,`Provider runtime token request failed (${r.status}): ${await Fa(r)}`);return await r.json()}function ja(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.enabled===true&&(e.provider==="anthropic"||e.provider==="openai"||e.provider==="gemini"||e.provider==="dashscope"||e.provider==="kimi"||e.provider==="openrouter"||e.provider==="droid")&&(e.credentialMode==="provider_key"||e.credentialMode==="evolve_key")&&typeof e.token=="string"&&e.token.length>0&&typeof e.bindingSecret=="string"&&e.bindingSecret.length>0&&typeof e.baseUrl=="string"&&e.baseUrl.length>0&&typeof e.expiresAt=="string"&&e.expiresAt.length>0}async function Gs(t,e){let n=await jn(t,"/api/provider-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!ja(n))throw new Le(502,"Provider runtime token response was invalid");return n}async function qs(t,e){return (await jn(t,"/api/provider-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function Hs(t,e){return (await jn(t,"/api/provider-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}var Ct=18181,A="/tmp/evolve-managed-secrets",Be=`${A}/proxy.py`,pe=`${A}/config.json`,Z=`${A}/ca.crt`,kt=`${A}/ca.key`,ue=`${A}/ca-bundle.crt`,Ys=["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","http_proxy","https_proxy","all_proxy","NO_PROXY","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"];function Xs(){return [...Ys]}var Qs=String.raw`#!/usr/bin/env python3
224
+ import base64
225
+ import json
226
+ import os
227
+ import select
228
+ import secrets
229
+ import socket
230
+ import ssl
231
+ import subprocess
232
+ import sys
233
+ import tempfile
234
+ import threading
235
+ import urllib.error
236
+ import urllib.request
237
+
238
+ for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]:
239
+ os.environ.pop(key, None)
240
+
241
+ CONFIG_PATH = sys.argv[1]
242
+ with open(CONFIG_PATH, "r", encoding="utf-8") as f:
243
+ CONFIG = json.load(f)
244
+ try:
245
+ os.unlink(CONFIG_PATH)
246
+ except FileNotFoundError:
247
+ pass
248
+
249
+ MAX_BODY_BYTES = int(CONFIG.get("max_body_bytes", 10 * 1024 * 1024))
250
+ CONNECT_TIMEOUT_SECONDS = 15
251
+ SOCKET_TIMEOUT_SECONDS = 130
252
+ MAX_WORKERS = 100
253
+ WORKERS = threading.BoundedSemaphore(MAX_WORKERS)
254
+ HOST_PATTERNS = [h.lower() for h in CONFIG["hosts"]]
255
+ PLACEHOLDERS = set(CONFIG["placeholders"])
256
+ PLACEHOLDER_BYTES = [p.encode("utf-8") for p in CONFIG["placeholders"]]
257
+ BASE_DIR = CONFIG["base_dir"]
258
+ CERT_DIR = os.path.join(BASE_DIR, "certs")
259
+ os.makedirs(CERT_DIR, exist_ok=True)
260
+ CHANNEL_SECRET = secrets.token_urlsafe(32)
261
+
262
+ def register_channel():
263
+ payload = json.dumps({}).encode("utf-8")
264
+ req = urllib.request.Request(
265
+ CONFIG["channel_url"],
266
+ data=payload,
267
+ method="POST",
268
+ headers={
269
+ "content-type": "application/json",
270
+ "accept": "application/json",
271
+ "x-evolve-managed-secret-token": CONFIG["token"],
272
+ "x-evolve-managed-secret-binding": CONFIG["binding"],
273
+ "x-evolve-managed-secret-channel": CHANNEL_SECRET,
274
+ },
275
+ )
276
+ with urllib.request.urlopen(req, timeout=30) as resp:
277
+ if resp.status < 200 or resp.status >= 300:
278
+ raise RuntimeError("managed secret channel registration failed")
279
+
280
+ def host_matches(pattern, host):
281
+ host = host.lower()
282
+ if pattern.startswith("*."):
283
+ base = pattern[2:]
284
+ return host != base and host.endswith("." + base)
285
+ return host == pattern
286
+
287
+ def is_managed_host(host):
288
+ clean = host.split(":", 1)[0].strip("[]").lower()
289
+ return any(host_matches(pattern, clean) for pattern in HOST_PATTERNS)
290
+
291
+ def safe_name(host):
292
+ return "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in host)[:180]
293
+
294
+ def ensure_cert(host):
295
+ name = safe_name(host)
296
+ cert = os.path.join(CERT_DIR, name + ".crt")
297
+ key = os.path.join(CERT_DIR, name + ".key")
298
+ if os.path.exists(cert) and os.path.exists(key):
299
+ return cert, key
300
+ csr = os.path.join(CERT_DIR, name + ".csr")
301
+ ext = os.path.join(CERT_DIR, name + ".ext")
302
+ san = "IP:" + host if host.replace(".", "").isdigit() else "DNS:" + host
303
+ with open(ext, "w", encoding="utf-8") as f:
304
+ f.write("basicConstraints=critical,CA:FALSE\n")
305
+ f.write("keyUsage=critical,digitalSignature,keyEncipherment\n")
306
+ f.write("subjectAltName=" + san + "\n")
307
+ f.write("extendedKeyUsage=serverAuth\n")
308
+ subprocess.run(
309
+ ["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-subj", "/CN=" + host, "-out", csr],
310
+ check=True,
311
+ stdout=subprocess.DEVNULL,
312
+ stderr=subprocess.DEVNULL,
313
+ )
314
+ subprocess.run(
315
+ [
316
+ "openssl", "x509", "-req", "-in", csr,
317
+ "-CA", CONFIG["ca_cert"], "-CAkey", CONFIG["ca_key"], "-CAcreateserial",
318
+ "-out", cert, "-days", "30", "-sha256", "-extfile", ext,
319
+ ],
320
+ check=True,
321
+ stdout=subprocess.DEVNULL,
322
+ stderr=subprocess.DEVNULL,
323
+ )
324
+ return cert, key
325
+
326
+ def pipe_raw(client, host, port):
327
+ upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS)
328
+ client.settimeout(SOCKET_TIMEOUT_SECONDS)
329
+ upstream.settimeout(SOCKET_TIMEOUT_SECONDS)
330
+ try:
331
+ client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
332
+ sockets = [client, upstream]
333
+ while True:
334
+ readable, _, _ = select.select(sockets, [], [], 120)
335
+ if not readable:
336
+ break
337
+ for sock in readable:
338
+ data = sock.recv(65536)
339
+ if not data:
340
+ return
341
+ (upstream if sock is client else client).sendall(data)
342
+ finally:
343
+ upstream.close()
344
+
345
+ def recv_until(sock, marker, limit=65536):
346
+ data = b""
347
+ while marker not in data:
348
+ chunk = sock.recv(4096)
349
+ if not chunk:
350
+ break
351
+ data += chunk
352
+ if len(data) > limit:
353
+ raise RuntimeError("request headers too large")
354
+ return data
355
+
356
+ def parse_headers(blob):
357
+ head, rest = blob.split(b"\r\n\r\n", 1)
358
+ lines = head.decode("iso-8859-1").split("\r\n")
359
+ request_line = lines[0]
360
+ headers = {}
361
+ for line in lines[1:]:
362
+ if not line or ":" not in line:
363
+ continue
364
+ name, value = line.split(":", 1)
365
+ headers[name.strip()] = value.strip()
366
+ return request_line, headers, rest
367
+
368
+ def header_value(headers, name):
369
+ wanted = name.lower()
370
+ for key, value in headers.items():
371
+ if key.lower() == wanted:
372
+ return value
373
+ return None
374
+
375
+ def read_chunked_body(sock, initial):
376
+ data = initial
377
+ body = b""
378
+ while True:
379
+ while b"\r\n" not in data:
380
+ chunk = sock.recv(4096)
381
+ if not chunk:
382
+ raise RuntimeError("incomplete chunked request")
383
+ data += chunk
384
+ line, data = data.split(b"\r\n", 1)
385
+ size = int((line.split(b";", 1)[0].strip() or b"0"), 16)
386
+ if size == 0:
387
+ return body
388
+ if len(body) + size > MAX_BODY_BYTES:
389
+ raise RuntimeError("request body too large")
390
+ while len(data) < size + 2:
391
+ chunk = sock.recv(65536)
392
+ if not chunk:
393
+ raise RuntimeError("incomplete chunked request")
394
+ data += chunk
395
+ body += data[:size]
396
+ data = data[size + 2:]
397
+
398
+ def read_request(tls_sock):
399
+ blob = recv_until(tls_sock, b"\r\n\r\n")
400
+ if not blob:
401
+ return None
402
+ request_line, headers, rest = parse_headers(blob)
403
+ transfer_encoding = (header_value(headers, "Transfer-Encoding") or "").lower()
404
+ if "chunked" in transfer_encoding:
405
+ return request_line, headers, read_chunked_body(tls_sock, rest)
406
+ length = int(header_value(headers, "Content-Length") or "0")
407
+ if length > MAX_BODY_BYTES:
408
+ raise RuntimeError("request body too large")
409
+ body = rest
410
+ while len(body) < length:
411
+ chunk = tls_sock.recv(min(65536, length - len(body)))
412
+ if not chunk:
413
+ break
414
+ body += chunk
415
+ return request_line, headers, body[:length]
416
+
417
+ def uses_placeholder(path, headers, body):
418
+ if any(ph in path for ph in PLACEHOLDERS):
419
+ return True
420
+ if any(ph in value for ph in PLACEHOLDERS for value in headers.values()):
421
+ return True
422
+ return any(ph_b in body for ph_b in PLACEHOLDER_BYTES)
423
+
424
+ def call_dashboard(method, url, headers, body):
425
+ payload = json.dumps({
426
+ "method": method,
427
+ "url": url,
428
+ "headers": headers,
429
+ "bodyBase64": base64.b64encode(body).decode("ascii") if body else "",
430
+ }).encode("utf-8")
431
+ req = urllib.request.Request(
432
+ CONFIG["egress_url"],
433
+ data=payload,
434
+ method="POST",
435
+ headers={
436
+ "content-type": "application/json",
437
+ "accept": "application/json",
438
+ "x-evolve-managed-secret-token": CONFIG["token"],
439
+ "x-evolve-managed-secret-binding": CONFIG["binding"],
440
+ "x-evolve-managed-secret-channel": CHANNEL_SECRET,
441
+ },
442
+ )
443
+ try:
444
+ with urllib.request.urlopen(req, timeout=130) as resp:
445
+ return resp.status, resp.reason, json.loads(resp.read().decode("utf-8"))
446
+ except urllib.error.HTTPError as err:
447
+ text = err.read().decode("utf-8", "replace")
448
+ return err.code, "Managed Secret Egress Error", {"headers": {"content-type": "application/json"}, "bodyBase64": base64.b64encode(text.encode()).decode("ascii")}
449
+
450
+ def read_limited_response(stream):
451
+ chunks = []
452
+ total = 0
453
+ while True:
454
+ chunk = stream.read(65536)
455
+ if not chunk:
456
+ break
457
+ total += len(chunk)
458
+ if total > MAX_BODY_BYTES:
459
+ raise RuntimeError("response body too large")
460
+ chunks.append(chunk)
461
+ return b"".join(chunks)
462
+
463
+ def call_direct(method, url, headers, body):
464
+ hop_by_hop = {"connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "host", "content-length"}
465
+ request_headers = {k: v for k, v in headers.items() if k.lower() not in hop_by_hop}
466
+ req = urllib.request.Request(
467
+ url,
468
+ data=body if body else None,
469
+ method=method,
470
+ headers=request_headers,
471
+ )
472
+ try:
473
+ with urllib.request.urlopen(req, timeout=130) as resp:
474
+ return resp.status, resp.reason, {
475
+ "headers": dict(resp.headers.items()),
476
+ "bodyBase64": base64.b64encode(read_limited_response(resp)).decode("ascii"),
477
+ }
478
+ except urllib.error.HTTPError as err:
479
+ return err.code, err.reason, {
480
+ "headers": dict(err.headers.items()),
481
+ "bodyBase64": base64.b64encode(read_limited_response(err)).decode("ascii"),
482
+ }
483
+
484
+ def send_response(tls_sock, status, reason, result):
485
+ body = base64.b64decode(result.get("bodyBase64") or "")
486
+ headers = {str(k): str(v) for k, v in (result.get("headers") or {}).items()}
487
+ headers["content-length"] = str(len(body))
488
+ headers["connection"] = "close"
489
+ status_line = ("HTTP/1.1 %d %s\r\n" % (status, reason or "")).encode("ascii", "replace")
490
+ header_blob = b"".join((name + ": " + value + "\r\n").encode("iso-8859-1", "replace") for name, value in headers.items())
491
+ tls_sock.sendall(status_line + header_blob + b"\r\n" + body)
492
+
493
+ def dispatch_managed_request(method, url, headers, body):
494
+ if uses_placeholder(url, headers, body):
495
+ return call_dashboard(method, url, headers, body)
496
+ return call_direct(method, url, headers, body)
497
+
498
+ def handle_managed_connect(client, host, port):
499
+ client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
500
+ cert, key = ensure_cert(host)
501
+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
502
+ ctx.load_cert_chain(cert, key)
503
+ client.settimeout(SOCKET_TIMEOUT_SECONDS)
504
+ tls_sock = ctx.wrap_socket(client, server_side=True)
505
+ tls_sock.settimeout(SOCKET_TIMEOUT_SECONDS)
506
+ try:
507
+ request = read_request(tls_sock)
508
+ if not request:
509
+ return
510
+ request_line, headers, body = request
511
+ parts = request_line.split()
512
+ if len(parts) < 2:
513
+ raise RuntimeError("bad request line")
514
+ method, path = parts[0].upper(), parts[1]
515
+ if path.startswith("http://") or path.startswith("https://"):
516
+ url = path
517
+ else:
518
+ url = "https://%s%s" % (host if port == 443 else host + ":" + str(port), path)
519
+ status, reason, result = dispatch_managed_request(method, url, headers, body)
520
+ send_response(tls_sock, status, reason, result)
521
+ finally:
522
+ try:
523
+ tls_sock.close()
524
+ except Exception:
525
+ pass
526
+
527
+ def handle_client(client):
528
+ try:
529
+ client.settimeout(SOCKET_TIMEOUT_SECONDS)
530
+ blob = recv_until(client, b"\r\n\r\n")
531
+ if not blob:
532
+ return
533
+ request_line, headers, rest = parse_headers(blob)
534
+ parts = request_line.split()
535
+ if len(parts) < 3:
536
+ return
537
+ if parts[0].upper() == "CONNECT":
538
+ target = parts[1]
539
+ if ":" in target:
540
+ host, port_s = target.rsplit(":", 1)
541
+ port = int(port_s)
542
+ else:
543
+ host, port = target, 443
544
+ host = host.strip("[]")
545
+ if is_managed_host(host):
546
+ handle_managed_connect(client, host, port)
547
+ else:
548
+ pipe_raw(client, host, port)
549
+ return
550
+ client.sendall(b"HTTP/1.1 501 Not Implemented\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
551
+ except Exception as exc:
552
+ try:
553
+ body = json.dumps({"error": str(exc)}).encode("utf-8")
554
+ client.sendall(b"HTTP/1.1 502 Bad Gateway\r\ncontent-type: application/json\r\ncontent-length: " + str(len(body)).encode() + b"\r\nconnection: close\r\n\r\n" + body)
555
+ except Exception:
556
+ pass
557
+ finally:
558
+ try:
559
+ client.close()
560
+ except Exception:
561
+ pass
562
+
563
+ def serve():
564
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
565
+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
566
+ server.bind(("127.0.0.1", int(CONFIG["port"])))
567
+ server.listen(100)
568
+ while True:
569
+ client, _ = server.accept()
570
+ if not WORKERS.acquire(blocking=False):
571
+ try:
572
+ client.sendall(b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
573
+ except Exception:
574
+ pass
575
+ client.close()
576
+ continue
577
+ def run_client():
578
+ try:
579
+ handle_client(client)
580
+ finally:
581
+ WORKERS.release()
582
+ thread = threading.Thread(target=run_client, daemon=True)
583
+ thread.start()
584
+
585
+ if __name__ == "__main__":
586
+ register_channel()
587
+ serve()
588
+ `;function Ka(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function Ja(t){let e=t.apiKey||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed secrets");return e}async function Va(t){return await t.text().catch(()=>"")}async function Et(t,e,n={}){let r=await fetch(`${Ka(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${Ja(t)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Managed secrets request failed (${r.status}): ${await Va(r)}`);return await r.json()}function Kn(t={}){return {async list(){return (await Et(t,"/api/managed-secrets")).secrets??[]}}}function Ga(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function zs(t){try{return new URL(t).protocol==="https:"}catch{return false}}function qa(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.token=="string"&&e.token.startsWith("evrt_")&&typeof e.bindingSecret=="string"&&e.bindingSecret.startsWith("evrb_")&&typeof e.egressUrl=="string"&&zs(e.egressUrl)&&typeof e.channelUrl=="string"&&zs(e.channelUrl)&&typeof e.expiresAt=="string"&&Array.isArray(e.env)&&e.env.every(n=>{if(!n||typeof n!="object"||Array.isArray(n))return false;let r=n;return typeof r.name=="string"&&typeof r.envName=="string"&&typeof r.placeholder=="string"&&r.placeholder.startsWith("evsec_")&&Ga(r.allowedHosts)})}async function Zs(t,e){let n=await Et(t,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!qa(n))throw new Error("Invalid managed secret runtime token response");return n}async function ei(t,e){return (await Et(t,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function ti(t,e){return (await Et(t,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}function Ha(t){if(!Array.isArray(t)||t.length===0)throw new Error("withManagedSecrets() requires at least one secret");return t.map((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`managedSecrets[${n}] must be an object with a name`);let r=Ws(e.name,`managedSecrets[${n}].name`),s=e.as===void 0?void 0:Ws(e.as,`managedSecrets[${n}].as`);return s?{name:r,as:s}:{name:r}})}function Ws(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} is required`);let n=t.trim().toUpperCase();if(!/^[A-Z_][A-Z0-9_]{0,127}$/.test(n))throw new Error(`${e} must be a valid environment variable name`);if(n.startsWith("EVOLVE_"))throw new Error(`${e} cannot use the reserved EVOLVE_ prefix`);return n}function za(t){let e=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...Ys]),n=r=>{r&&e.add(r);};n(t.apiKeyEnv),n(t.baseUrlEnv),n(t.customHeadersEnv),n(t.gatewayConfigEnv),t.spendTrackingEnvs&&(n(t.spendTrackingEnvs.sessionTagEnv),n(t.spendTrackingEnvs.runTagEnv));for(let r of Object.values(t.providerEnvMap??{}))n(r.keyEnv);return e}function ni(t,e){if(!t)return;let n=Ha(t),r=za(e),s=new Set;for(let a of n){let c=a.as||a.name;if(r.has(c))throw new Error(`${c} is reserved for Evolve-managed sandbox services and cannot be used as a managed secret env var`);if(s.has(c))throw new Error(`duplicate managed secret env var: ${c}`);s.add(c);}return n}function ri(t){let e={};for(let s of t.env)e[s.envName]=s.placeholder;let n=`http://127.0.0.1:${Ct}`;e.HTTPS_PROXY=n,e.https_proxy=n,e.NODE_EXTRA_CA_CERTS=Z,e.SSL_CERT_FILE=ue,e.REQUESTS_CA_BUNDLE=ue,e.CURL_CA_BUNDLE=ue,e.GIT_SSL_CAINFO=ue;let r=new URL(t.egressUrl).hostname;return e.NO_PROXY=`localhost,127.0.0.1,::1,${r}`,e.no_proxy=e.NO_PROXY,e}function si(t){let e=Array.from(new Set(t.env.flatMap(n=>n.allowedHosts)));return JSON.stringify({egress_url:t.egressUrl,channel_url:t.channelUrl,token:t.token,binding:t.bindingSecret,hosts:e,placeholders:t.env.map(n=>n.placeholder),base_dir:A,ca_cert:Z,ca_key:kt,port:Ct,max_body_bytes:10*1024*1024},null,2)}function ii(){return ["umask 077",`mkdir -p ${A}/certs`,`chmod 700 ${A} ${A}/certs`,`chmod 700 ${Be} 2>/dev/null || true`,`chmod 600 ${pe} 2>/dev/null || true`,`if [ ! -f ${kt} ]; then openssl genrsa -out ${kt} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${Z} ]; then openssl req -x509 -new -nodes -key ${kt} -sha256 -days 30 -subj "/CN=Evolve Managed Secrets" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ${Z} >/dev/null 2>&1; fi`,`SYSTEM_CA_BUNDLE=""; for p in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem; do if [ -f "$p" ]; then SYSTEM_CA_BUNDLE="$p"; break; fi; done; if [ -n "$SYSTEM_CA_BUNDLE" ]; then cat "$SYSTEM_CA_BUNDLE" ${Z} > ${ue}; else cp ${Z} ${ue}; fi`,`if command -v update-ca-certificates >/dev/null 2>&1; then cp ${Z} /usr/local/share/ca-certificates/evolve-managed-secrets.crt 2>/dev/null && update-ca-certificates >/dev/null 2>&1 || true; fi`].join(" && ")}function oi(){return `umask 077 && exec python3 ${Be} ${pe}`}function ai(){return `rm -f ${pe}`}var Rt=256,li=100*1024*1024,ci=500*1024*1024;function Ne(t){return `'${t.replaceAll("'",`'"'"'`)}'`}function Wa(t){let e=t.trim();if(e==="")return [];let n=Buffer.from(e,"base64"),r=[],s=0;for(let a=0;a<n.length;a++)n[a]===0&&(r.push(n.toString("utf8",s,a)),s=a+1);return s<n.length&&r.push(n.toString("utf8",s,n.length)),r}async function di(t,e,n){if(n.length===0||n.length>Rt)throw new Error(`collectArtifacts() requires between 1 and ${Rt} paths.`);let r=n.map(u=>{if(!u||u.includes("\0"))throw new Error(`Invalid artifact path: ${JSON.stringify(u)}`);let p=F.posix.normalize(u);if(!F.posix.isAbsolute(p)&&(p===".."||p.startsWith("../")))throw new Error(`Artifact path escapes the working directory: ${u}`);return F.posix.isAbsolute(p)?p:F.posix.join(e,p)}),a=(await t.commands.run(r.map(u=>`if [ ! -e ${Ne(u)} ]; then echo MISSING ${Ne(u)}; elif [ ! -r ${Ne(u)} ]; then echo UNREADABLE ${Ne(u)}; fi`).join("; "),{cwd:e,timeoutMs:15e3})).stdout.split(`
589
+ `).map(u=>u.trim()).filter(Boolean);if(a.length>0)throw new Error(`Artifact roots are not collectable: ${a.join("; ")}`);let c;try{c=await t.commands.run(`set -o pipefail 2>/dev/null; find -- ${r.map(Ne).join(" ")} -type f -printf '%p\\0%s\\0' | base64 -w0`,{cwd:e,timeoutMs:3e4});}catch(u){throw new Error(`Artifact listing failed: ${u.message}`)}if(c.exitCode!==0)throw new Error(`Artifact listing failed (exit ${c.exitCode}): ${(c.stderr||"").slice(0,500)}`);let l=Wa(c.stdout);if(l.length%2!==0)throw new Error("Sandbox returned malformed artifact metadata.");let o=new Map,d=0;for(let u=0;u<l.length;u+=2){let p=l[u],g=Number(l[u+1]);if(!Number.isSafeInteger(g)||g<0)throw new Error(`Sandbox returned an invalid artifact size: ${p}`);if(g>li)throw new Error(`Artifact exceeds ${li} bytes: ${p}`);o.has(p)||(o.set(p,g),d+=g);}if(o.size>Rt)throw new Error(`Artifact collection exceeds ${Rt} files.`);if(d>ci)throw new Error(`Artifact collection exceeds ${ci} bytes.`);let i={};for(let u of [...o.keys()].sort()){let p=r.some(f=>u===f||u.startsWith(`${f.replace(/\/$/,"")}/`));if(!F.posix.isAbsolute(u)||!p)throw new Error(`Sandbox returned an invalid artifact path: ${u}`);let g=F.posix.relative(e,u),m=g&&g!==".."&&!g.startsWith("../")?g:u;i[m]=await t.files.read(u);}return i}var Tt="EVOLVE_PROVIDER_RUNTIME_BINDING",Jn="gemini-api-key";function Fe(t){switch(t){case "claude":return "anthropic";case "codex":return "openai";case "gemini":return "gemini";case "qwen":return "dashscope";case "kimi":return "kimi";case "opencode":return "openrouter";case "droid":return "droid";default:return null}}function Za(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function ui(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function Vn(t,e,n="newline"){let r=new Map;if(t){let s=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let a of s){let c=a.trim();if(!c)continue;let l=c.indexOf(":");if(l<=0)continue;let o=c.slice(0,l).trim(),d=c.slice(l+1).trim();r.set(o.toLowerCase(),`${o}: ${d}`);}}for(let[s,a]of Object.entries(e)){let c=s.toLowerCase();if(c===K&&r.has(c)&&n==="newline"){let l=r.get(c),o=l.slice(l.indexOf(":")+1).trim();r.set(c,`${s}: ${o},${a}`);}else r.set(c,`${s}: ${a}`);}return Array.from(r.values()).join(n==="comma"?", ":`
590
+ `)}var el=262144,tl=128e3;function pi(t,e){if(t.models.some(s=>s.alias===e||s.modelId===e))return true;let n=t.gatewayModelAliases;if(n&&(e in n||Object.values(n).includes(e)))return true;let r=t.directModelAliases;return !!(r&&(e in r||Object.values(r).includes(e)))}var nl=new Set(["low","medium","high","xhigh","max"]);function gi(t){if(t)return nl.has(t)?t:void 0}function Pt(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var je=class{agentConfig;options;sandbox;hasRun=false;workingDir;homeDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;providerRuntimeToken;managedSecretRuntimeToken;managedSecretProxy;credentialsSealed=false;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(Ce(e),fn(n.observability),n.managedSecrets){if(e.isDirectMode)throw new Error("managed secrets are available only in gateway mode with EVOLVE_API_KEY");if(n.sandboxId)throw new Error("managed secrets cannot be used with an existing sandbox; grants are sandbox-scoped.");if(n.sandboxProvider&&!Re(n.sandboxProvider))throw new Error("managed secrets require an Evolve-managed sandbox provider")}if(this.agentConfig=e,this.options=n,n.sandboxId&&n.sandboxCreateOptions?.user)throw new Error("sandbox user cannot be enforced when attaching to an existing sandbox; create a fresh sandbox with the user instead");if(this.homeDir=ir(n.sandboxCreateOptions?.user,n.sandboxCreateOptions?.homeDir),this.homeDir!==B){if(n.storage)throw new Error("Checkpoint storage requires the default /home/user sandbox home directory; remove sandbox user/homeDir or storage");if(n.managedBrowser||n.browserCredentials)throw new Error("Managed browser features require the default /home/user sandbox home directory")}if(this.workingDir=n.workingDirectory||n.sandboxCreateOptions?.workingDirectory||`${this.homeDir}/workspace`,this.sandboxState=n.sandboxId?"ready":"stopped",n.workspaceMode==="task"&&[n.context,n.files,n.systemPrompt,n.browserPrompt,n.schema].some(Boolean))throw new Error('workspaceMode "task" cannot be combined with context, files, systemPrompt, browserPrompt, or schema; the task owns the working directory');if(this.skills=n.skills,this.storage=n.storage,n.schema)if(N(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 r=this.createAjvValidator();this.compiledValidator=r.compile(this.jsonSchema);}catch(r){throw new Error(`Invalid JSON Schema: ${r.message}`)}}this.registry=O(e.type),this.sessionTag=ui(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 r=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...r?{browser:r}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,r,s){let a=++this.nextOperationId;return this.activeOperationId=a,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),a}finalizeOperation(e,n,r,s="idle",a="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=a,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,a){let c=n==="run"?"run_background_complete":"command_background_complete",l=n==="run"?"run_background_failed":"command_background_failed",o=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,s,o,"interrupted");return}n==="run"&&a&&await this.writeDroidSessionState(a);let u=d.exitCode===0?c:l,p=d.exitCode===0?"idle":"error";this.finalizeOperation(e,s,u,p);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,l,"error");});}createAjvValidator(){let n={...Ft[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 Ya__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot create or attach another 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");let r=false;try{if(this.options.sandboxId)(this.options.mcpServers||this.options.integrations||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, integrations, 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),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let s=this.buildEnvironmentVariables();this.sandbox=await n.create(this.buildSandboxCreateOptions(s)),r=!0,await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox),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 r&&this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}return this.sandbox}resolveKimiMaxContextSize(){if(typeof this.agentConfig.maxContextSize=="number")return this.agentConfig.maxContextSize;let e=this.agentConfig.model||this.registry.defaultModel;return pi(this.registry,e)||pi(this.registry,this.resolveCommandModel(e))?this.registry.models.find(s=>s.alias===e||s.modelId===e)?.maxContextSize??this.registry.spendTrackingTomlProvider?.maxContextSize??el:tl}reasoningEffort(){return pr(this.agentConfig.type,this.agentConfig.reasoningEffort)}buildKimiDirectModelEnvs(){let e=Se(this.reasoningEffort()),n=gi(this.reasoningEffort()),r={KIMI_MODEL_NAME:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),KIMI_MODEL_API_KEY:this.agentConfig.apiKey,KIMI_MODEL_PROVIDER_TYPE:"kimi",KIMI_MODEL_MAX_CONTEXT_SIZE:String(this.resolveKimiMaxContextSize()),KIMI_MODEL_DEFAULT_THINKING:e?"true":"false",KIMI_MODEL_THINKING_MODE:e?"on":"off"};return n&&(r.KIMI_MODEL_THINKING_EFFORT=n),this.agentConfig.baseUrl&&(r.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl),r}buildEnvironmentVariables(){let e={},n=this.validatedUserSecretsForEnvironment();if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode)Object.assign(e,this.buildKimiDirectModelEnvs());else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){if(!(!this.agentConfig.isDirectMode&&Fe(this.agentConfig.type))){if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let r of Object.values(this.registry.providerEnvMap))e[r.keyEnv]=this.agentConfig.apiKey;else {let r=this.agentConfig.model?.split("/")[0],s=r?this.registry.providerEnvMap?.[r]:void 0,a=s?s.keyEnv:this.registry.apiKeyEnv,c=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:a;e[c]=this.agentConfig.apiKey;}}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let r=L(this.registry.gatewayPath),s=this.requireActiveProviderRuntimeToken();if(this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[U]:this.sessionTag,...this.providerRuntimeHeaderUpdates()}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=s?.baseUrl??r),s&&(this.shouldExposeProviderRuntimeTokenEnv()&&(e[this.registry.apiKeyEnv]=s.token),this.agentConfig.type==="gemini"&&(e.GEMINI_DEFAULT_AUTH_TYPE=Jn),this.registry.spendTrackingEnvs&&(e[Tt]=s.bindingSecret)),!s){if(Fe(this.agentConfig.type))throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);e[P]=this.agentConfig.apiKey;}}if(this.agentConfig.externalGateway&&this.registry.gatewayConfigEnv&&(e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.externalGateway&&this.agentConfig.type==="gemini"&&(e.GEMINI_CLI_TRUST_WORKSPACE="true"),this.agentConfig.type==="claude"&&(e.IS_SANDBOX="1"),this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Ln(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.managedSecretRuntimeToken&&Object.assign(e,ri(this.managedSecretRuntimeToken)),n&&Object.assign(e,n),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";e[r]=Vn(e[r],{[U]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},s);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildSandboxCreateOptions(e){return {...this.options.sandboxCreateOptions,envs:e,workingDirectory:this.workingDir}}validatedUserSecretsForEnvironment(){let e={...this.options.sandboxCreateOptions?.envs,...this.options.secrets};if(Object.keys(e).length===0)return;let n=new Set;this.agentConfig.isDirectMode||(n.add(P),n.add(Tt),this.agentConfig.type==="gemini"&&n.add("GEMINI_DEFAULT_AUTH_TYPE"));let r=a=>{a&&n.add(a);};r(this.registry.apiKeyEnv),r(this.registry.baseUrlEnv);for(let a of Object.values(this.registry.providerEnvMap??{}))r(a.keyEnv);if(this.managedSecretRuntimeToken)for(let a of Xs())n.add(a);for(let a of this.managedSecretRuntimeToken?.env??[])r(a.envName);let s={};for(let[a,c]of Object.entries(e)){if(n.has(a))throw new Error(`${a} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);a!==this.registry.gatewayConfigEnv&&(s[a]=c);}return s}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await js(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async ensureProviderRuntimeToken(){let e=Fe(this.agentConfig.type);if(this.agentConfig.isDirectMode||!e||!this.options.providerRouting||this.providerRuntimeToken)return;let n;try{n=await Gs(this.options.providerRouting,{provider:e,sessionTag:this.sessionTag});}catch(r){throw Vs(r)?new Error(`${e} runtime token endpoint is required in gateway mode: ${r.message}`):r}this.providerRuntimeToken=n,this.providerRuntimeToken&&this.sandbox?.sandboxId&&await this.bindProviderRuntimeToken(this.sandbox.sandboxId);}async bindProviderRuntimeToken(e){if(!this.providerRuntimeToken||!this.options.providerRouting)return;if(!await qs(this.options.providerRouting,{token:this.providerRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind provider runtime token to sandbox")}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Ln(this.options.managedBrowser.provider,this.managedBrowserSession);for(let r of n.directories)await e.files.makeDir(r);for(let r of n.files)await e.files.write(r.path,r.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await Ks(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}async closeProviderRuntimeToken(e=false){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let n=this.providerRuntimeToken,r;for(let a=0;a<3;a++)try{if(!await Hs(this.options.providerRouting,{token:n.token}))throw new Error("Dashboard returned ok=false");this.providerRuntimeToken=void 0;return}catch(c){r=c,a<2&&await new Promise(l=>setTimeout(l,100*(a+1)));}let s=`Provider runtime token cleanup failed: ${r.message}`;if(e)throw new Error(s);console.warn(`[Evolve] ${s}`),this.providerRuntimeToken=void 0;}async ensureManagedSecretRuntimeToken(){this.managedSecretRuntimeToken||!this.options.managedSecrets||(this.managedSecretRuntimeToken=await Zs({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{sessionTag:this.sessionTag,secrets:this.options.managedSecrets.secrets}));}async bindManagedSecretRuntimeToken(e){if(!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;if(!await ei({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:this.managedSecretRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind managed secret runtime token to sandbox")}async setupManagedSecretEgress(e){if(!this.managedSecretRuntimeToken)return;if(await e.files.makeDir(A),await e.commands.run(`umask 077 && mkdir -p ${A}/certs && chmod 700 ${A} ${A}/certs`,{timeoutMs:5e3}),await e.files.write(Be,Qs),await e.files.write(pe,si(this.managedSecretRuntimeToken)),await e.commands.run(`chmod 700 ${Be} && chmod 600 ${pe}`,{timeoutMs:5e3}),await e.commands.run(ii(),{timeoutMs:3e4}),this.managedSecretProxy=await e.commands.spawn(oi(),{timeoutMs:3e4}),(await e.commands.run(`python3 - <<'PY'
591
+ import socket, sys, time
592
+ for _ in range(50):
593
+ try:
594
+ s = socket.create_connection(("127.0.0.1", ${Ct}), timeout=0.2)
595
+ s.close()
596
+ sys.exit(0)
597
+ except OSError:
598
+ time.sleep(0.1)
599
+ sys.exit(1)
600
+ PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy failed to start");await e.commands.run(ai(),{timeoutMs:5e3});}async closeManagedSecretRuntimeToken(){let e=this.managedSecretProxy;if(this.managedSecretProxy=void 0,e&&await e.kill().catch(()=>false),!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;let n=this.managedSecretRuntimeToken,r;try{for(let s=0;s<3;s++)try{if(!await ti({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:n.token}))throw new Error("Dashboard returned ok=false");return}catch(a){r=a,s<2&&await new Promise(c=>setTimeout(c,100*(s+1)));}console.warn(`[Evolve] Managed secret runtime token cleanup failed: ${r.message}`);}finally{this.managedSecretRuntimeToken=void 0;}}buildGatewayConfigJson(e){let n=this.requireActiveProviderRuntimeToken(),r=this.agentConfig.externalGateway?this.agentConfig.baseUrl??Pt(L(this.registry.gatewayPath)):n?.baseUrl??Pt(L(this.registry.gatewayPath)),s=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),a={},c=this.options.secrets?.[this.registry.gatewayConfigEnv];if(c)try{a=JSON.parse(c);}catch{}let l=a.provider??{},o=l.litellm??{},d=o.options??{},i=o.models??{},u=i[s]??{},p=u.headers??{},g=this.agentConfig.type==="opencode"?qt(this.reasoningEffort()):void 0,m=u.variants??{},f=g?m[g]??{}:void 0;return a.provider={...l,litellm:{...o,npm:"@ai-sdk/openai-compatible",options:{...d,baseURL:r,apiKey:n?.token??this.agentConfig.apiKey},models:{...i,[s]:{...u,name:s,headers:{...p,...e},...g?{variants:{...m,[g]:{...f,reasoningEffort:g}}}:{}}}}},JSON.stringify(a)}activeProviderRuntimeToken(){let e=Fe(this.agentConfig.type);return e&&this.providerRuntimeToken?.provider===e?this.providerRuntimeToken:void 0}requireActiveProviderRuntimeToken(){let e=Fe(this.agentConfig.type),n=this.activeProviderRuntimeToken();if(!this.agentConfig.isDirectMode&&e&&!n)throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);return n}ensureSessionLogger(e){if(this.sessionLogger)return;let n=this.options.sandboxProvider;this.sessionLogger=new Pe({provider:n?.name||n?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:e.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}:{}}});}async flushSessionLoggerWithTimeout(e=2e3){this.sessionLogger&&await Promise.race([this.sessionLogger.flush(),new Promise(n=>setTimeout(n,e))]);}requiresPreRunDashboardIngest(){return !!(this.activeProviderRuntimeToken()||this.managedSecretRuntimeToken)}providerRuntimeHeaderUpdates(){let e=this.activeProviderRuntimeToken();return e?{[Fn]:e.bindingSecret}:{}}shouldExposeProviderRuntimeTokenEnv(){return this.agentConfig.type!=="kimi"&&!this.registry.gatewayConfigEnv}buildProviderRuntimeProcessEnvs(){if(this.agentConfig.externalGateway){if(this.agentConfig.type==="kimi")return this.buildKimiDirectModelEnvs();let r={[this.registry.apiKeyEnv]:this.agentConfig.apiKey};return this.registry.baseUrlEnv&&this.agentConfig.baseUrl&&(r[this.registry.baseUrlEnv]=this.agentConfig.baseUrl),this.registry.gatewayConfigEnv&&(r[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.type==="gemini"&&(r.GEMINI_CLI_TRUST_WORKSPACE="true"),r}let e=this.activeProviderRuntimeToken();if(!e)return {};let n={};if(this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.apiKeyEnv]=e.token),this.agentConfig.type==="gemini"&&(n.GEMINI_DEFAULT_AUTH_TYPE=Jn),this.registry.baseUrlEnv&&this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.baseUrlEnv]=e.baseUrl),this.registry.spendTrackingEnvs&&(n[Tt]=e.bindingSecret),this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";n[r]=Vn(this.options.secrets?.[r],this.providerRuntimeHeaderUpdates(),s);}return n}buildRunEnvs(e){if(this.agentConfig.externalGateway)return this.buildProviderRuntimeProcessEnvs();if(this.agentConfig.isDirectMode)return;let n=this.buildProviderRuntimeProcessEnvs(),r=this.registry.customHeadersEnv;if(r){let a=this.options.secrets?.[r],c=this.registry.customHeadersFormat||"newline";return n[r]=Vn(a,{[U]:this.sessionTag,[K]:`${X}${e}`,...this.providerRuntimeHeaderUpdates()},c),n}let s=this.registry.spendTrackingEnvs;return s?{...n,[s.sessionTagEnv]:this.sessionTag,[s.runTagEnv]:`${X}${e}`}:this.registry.gatewayConfigEnv?{...n,[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[U]:this.sessionTag,[K]:`${X}${e}`,...this.providerRuntimeHeaderUpdates()})}:Object.keys(n).length>0?n:void 0}async writeCodexGatewayProviderConfig(e){if(this.agentConfig.type==="codex"){if(this.agentConfig.externalGateway){await lt(e,this.agentConfig.baseUrl||L(),void 0,void 0,this.homeDir);return}this.agentConfig.isDirectMode||!this.registry.spendTrackingEnvs||await lt(e,this.activeProviderRuntimeToken()?.baseUrl||this.agentConfig.baseUrl||L(),this.registry.spendTrackingEnvs,this.activeProviderRuntimeToken()?{[Fn]:Tt}:void 0,this.homeDir);}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(a=>typeof a.sessionId=="string"&&a.sessionId.length>0)?.sessionId;if(r){this.droidSessionId=r;return}let s=this.extractDroidSessionId(e);s&&(this.droidSessionId=s);}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,r=n.sessionId??n.session_id;return typeof r=="string"&&r.length>0?r:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}droidSessionStatePath(){return `${this.homeDir}/.factory/evolve-session.json`}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(this.droidSessionStatePath());if(typeof n!="string")return;let r=JSON.parse(n);typeof r.sessionId=="string"&&r.sessionId.length>0&&(this.droidSessionId=r.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir(`${this.homeDir}/.factory`),await e.files.write(this.droidSessionStatePath(),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=M(this.registry.mcpConfig.settingsDir,this.homeDir);await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.agentConfig.type==="gemini"&&(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&await this.writeGeminiGatewayAuthSettings(e),this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async writeGeminiGatewayAuthSettings(e){let n=M(this.registry.mcpConfig.settingsDir,this.homeDir),r=`${n}/${this.registry.mcpConfig.filename}`;await e.files.makeDir(n);let s={};try{let l=await e.files.read(r);typeof l=="string"&&l.trim()&&(s=JSON.parse(l));}catch(l){let o=l.message||"";if(!/not found|no such file|does not exist/i.test(o))throw l}let a=typeof s.security=="object"&&s.security!==null?s.security:{},c=typeof a.auth=="object"&&a.auth!==null?a.auth:{};s.security={...a,auth:{...c,selectedType:Jn}},await e.files.write(r,JSON.stringify(s,null,2));}async setupAgentPlugins(e){await As(this.agentConfig.type,e,this.options.plugins);}assertProviderRuntimeDoesNotExposeGatewayKey(e){if(!this.activeProviderRuntimeToken())return;let n=this.agentConfig.apiKey;for(let[r,s]of Object.entries(e))for(let a of Object.values(s.headers||{}))if(a.includes(n))throw new Error(`MCP server "${r}" would expose the Evolve API key inside the sandbox. Use managed agent-browser or remove this gateway-authenticated MCP server.`)}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge";if(r!=="task"){let a=r==="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 c=En({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),l=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(l,c);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);}let s={...this.options.mcpServers};if(this.options.integrations){let a=await rs({...this.options.integrations,sessionTag:this.sessionTag});s={...s,integrations:{type:"http",url:a.url,headers:a.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 a=await Js({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});s={...s,[Bn]:a};}Object.keys(s).length>0&&(this.assertProviderRuntimeDoesNotExposeGatewayKey(s),await rn(this.agentConfig.type,e,this.workingDir,s,this.homeDir)),await this.writeCodexGatewayProviderConfig(e),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await st(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[U]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,r=M(n.sourceDir,this.homeDir),s=M(n.targetDir,this.homeDir);await e.files.makeDir(s);for(let a of this.skills){let c=`cp -r ${r}/${a} ${s}/ 2>/dev/null || true`;await e.commands.run(c,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([a,c])=>({path:`${this.workingDir}/context/${a}`,data:c}));if(r.length===0)return;let s=new Set(r.map(a=>a.path.substring(0,a.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([a,c])=>({path:a.startsWith("/")?a:`${this.workingDir}/${a}`,data:c}));if(r.length===0)return;let s=new Set(r.map(a=>a.path.substring(0,a.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:Za(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.reasoningEffort(),isDirectMode:this.agentConfig.isDirectMode,isExternalGateway:!!this.agentConfig.externalGateway,skills:this.skills,homeDir:this.homeDir})}async writeKimiPerRunConfig(e,n){if(this.agentConfig.isDirectMode||!this.registry.spendTrackingTomlProvider)return;let r=this.requireActiveProviderRuntimeToken();await nn(e,{...this.registry.spendTrackingTomlProvider,maxContextSize:this.resolveKimiMaxContextSize()},{[U]:this.sessionTag,[K]:`${X}${n}`,...this.providerRuntimeHeaderUpdates()},{baseUrl:Pt(r?.baseUrl??L(this.registry.gatewayPath)),apiKey:r?.token??this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:Se(this.reasoningEffort()),thinkingEffort:gi(this.reasoningEffort())},this.homeDir);}async run(e,n){if(this.credentialsSealed)throw new Error("Agent credentials are sealed; this Evolve instance cannot run the agent again");mn(e);let{prompt:r,timeoutMs:s=we,background:a=false,checkpointComment:c}=e,{from:l}=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(l&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(l==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let b=await Dn(this.storage);if(!b)throw new Error('No checkpoints found for from: "latest".');l=b.id;}if(l){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),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let b=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create(this.buildSandboxCreateOptions(b)),await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox);let v=await _s(this.sandbox,this.storage,l);if(await this.setupManagedBrowser(this.sandbox),v.agentType&&v.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${v.agentType}, current: ${this.agentConfig.type})`);let R=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==R)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${R})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let k=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!k}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=l,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(v){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),v}}let o=await this.getSandbox(n);await this.ensureProviderRuntimeToken(),await this.loadDroidSessionState(o),this.lastRunTimestamp=Date.now(),this.ensureSessionLogger(o),this.sessionLogger?.writePrompt(r),this.requiresPreRunDashboardIngest()&&await this.flushSessionLoggerWithTimeout();let d=this.buildCommand(r),i=crypto.randomUUID(),u=this.buildRunEnvs(i);if(await this.writeCodexGatewayProviderConfig(o),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await st(o,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[U]:this.sessionTag,[K]:`${X}${i}`,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.agentConfig.type==="qwen"&&await Yt(o,Se(this.reasoningEffort()),this.homeDir),await this.writeKimiPerRunConfig(o,i),(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&this.registry.droidGatewaySettings){let b=!!this.agentConfig.externalGateway,v=b?void 0:this.requireActiveProviderRuntimeToken();await ot(o,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:b?this.agentConfig.baseUrl??L():Pt(v?.baseUrl??L()),apiKeyEnv:this.registry.apiKeyEnv},b?{}:{[U]:this.sessionTag,[K]:`${X}${i}`,...this.providerRuntimeHeaderUpdates()},this.homeDir);}let p="",g=Q(this.agentConfig.type),m=b=>{p+=b;let v=p.split(`
601
+ `);p=v.pop()??"";for(let R of v){if(!R.trim())continue;let k=g(R);if(this.captureDroidSession(R,k),this.sessionLogger?.writeEventParsed(R,k),n?.onStdout?.(R+`
602
+ `),k&&n?.onContent)for(let T of k)n.onContent(T);}},f=b=>{n?.onStderr?.(b);},h=await o.commands.spawn(d,{cwd:this.workingDir,timeoutMs:s,envs:u,onStdout:m,onStderr:f}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,a)return this.watchBackgroundOperation(y,"run",h,n,o),{sandboxId:o.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:i,exitCode:0,stdout:`Background process started with ID ${h.processId}`,stderr:""};let w;try{w=await h.wait();}catch(b){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n,"run_failed","error"),b}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"),p.trim()){let b=g(p);if(this.captureDroidSession(p,b),this.sessionLogger?.writeEventParsed(p,b),n?.onStdout?.(p+`
603
+ `),b&&n?.onContent)for(let v of b)n.onContent(v);}await this.writeDroidSessionState(o),this.sessionLogger&&!a&&await this.flushSessionLoggerWithTimeout();let S;if(this.storage&&!a&&w.exitCode===0)try{S=await Mn(o,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:c,parentId:this.lastCheckpointId}),this.lastCheckpointId=S.id;}catch(b){console.warn(`[Evolve] Auto-checkpoint failed: ${b.message}`);}return {sandboxId:o.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:i,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:S}}async executeCommand(e,n={},r){let{timeoutMs:s=we,background:a=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 c=await this.getSandbox(r);this.credentialsSealed||await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.requiresPreRunDashboardIngest()&&(this.ensureSessionLogger(c),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let l="",o="",d=h=>{l+=h,r?.onStdout?.(h);},i=h=>{o+=h,r?.onStderr?.(h);},u=this.credentialsSealed?{}:this.buildProviderRuntimeProcessEnvs(),p=await c.commands.spawn(e,{cwd:this.workingDir,timeoutMs:s,envs:Object.keys(u).length>0?u:void 0,onStdout:d,onStderr:i}),g=this.beginOperation("command",p,r,"command_start");if(a)return this.watchBackgroundOperation(g,"command",p,r),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let m;try{m=await p.wait();}catch(h){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,r,"command_failed","error"),h}return this.interruptedOperations.delete(g)||m.exitCode===130?this.finalizeOperation(g,r,"command_interrupted","interrupted"):m.exitCode===0?this.finalizeOperation(g,r,"command_complete","idle"):this.finalizeOperation(g,r,"command_failed","error"),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:m.exitCode,stdout:l||m.stdout||"",stderr:o||m.stderr||""}}async sealCredentials(){if(this.credentialsSealed)return;if(!this.sandbox)throw new Error("No active sandbox. Call run() or executeCommand() first.");if(this.activeCommand)throw new Error("Cannot seal credentials while a process is running.");if(this.agentConfig.isDirectMode&&!this.agentConfig.externalGateway)throw new Error("Credential sealing requires gateway mode; direct provider credentials cannot be revoked by Evolve");if([this.options.secrets&&Object.keys(this.options.secrets).length>0,this.options.sandboxCreateOptions?.envs&&Object.keys(this.options.sandboxCreateOptions.envs).length>0,this.options.managedSecrets,this.options.integrations,this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0,this.options.managedBrowser,this.options.browserCredentials].some(Boolean))throw new Error("Credential sealing requires a credential-minimal sandbox: omit secrets, managed secrets, integrations, MCP servers, and browser credentials");if(this.agentConfig.externalGateway){await this.agentConfig.externalGateway.revoke(),this.credentialsSealed=true;return}if(!this.providerRuntimeToken||!this.options.providerRouting)throw new Error("Cannot seal credentials: no active provider runtime token to revoke. Without a gateway-issued runtime token the sandbox may hold credentials Evolve cannot revoke, so sealing would be a false guarantee.");await this.closeProviderRuntimeToken(true),this.credentialsSealed=true;}isSealed(){return this.credentialsSealed}async collectArtifacts(e){if(!this.credentialsSealed)throw new Error("Call sealCredentials() before collecting artifacts.");if(!this.sandbox)throw new Error("No active sandbox.");if(this.activeCommand)throw new Error("Cannot collect artifacts while a process is running.");return di(this.sandbox,this.workingDir,e)}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 uploadFileFromPath(e,n){let r=await this.getSandbox(),s=e.startsWith("/")?e:`${this.workingDir}/${e}`,a=s.substring(0,s.lastIndexOf("/"));if(a&&await r.commands.run(`mkdir -p ${a}`,{timeoutMs:3e4}),r.files.writeFromPath){await r.files.writeFromPath(s,n);return}let{readFile:c}=await import('fs/promises');await r.files.write(s,await c(n));}async getOutputFiles(e=false){let n=await this.getSandbox(),r=`${this.workingDir}/output`,s=e?"":"-maxdepth 1",c=(await n.commands.run(`find ${r} ${s} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
604
+ `).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,o=[],d=`${r}/`;for(let m of c){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);l>0&&y<l||o.push(f);}let i={},u=await Promise.all(o.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 u)m&&(i[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:i,data:null};let p=i["result.json"];if(!p)return {files:i,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof p=="string"?p:new TextDecoder().decode(p);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:i,data:f.data}:{files:i,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:i,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:i,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:i,data:null}}catch(m){return {files:i,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 Mn(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.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");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.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),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,r=this.activeOperationKind,s=false;try{this.activeCommand?s=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(s=await this.sandbox.commands.kill(this.activeProcessId));}catch{s=false;}if(!s)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let a=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,a),s}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(r){n=r;}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),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=ui(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 r=process.env.EVOLVE_DASHBOARD_URL||E,s=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${a}`)}return s}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(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),s=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(s)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let c=new URLSearchParams({tag:n,runId:e.runId}),o=await(await this.fetchSpend(c)).json();return this.normalizeRunCost(o,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,a=r.runs[s];if(!a)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return a}};function rl(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function sl(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return e}async function il(t){return await t.text().catch(()=>"")}async function mi(t,e,n={}){let r=await fetch(`${rl(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${sl(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await il(r)}`);return r.status===204?{}:await r.json()}var It=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await mi(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await mi(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function Gn(t={}){return new It(t)}var Ke=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&&(Ce(e),ft(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},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}withManagedSecrets(e){return this.config.managedSecrets=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&&(N(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}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=ss;static browserCredentials=Nn;static browserProfiles=Gn;static managedSecrets=Kn;async initializeAgent(){let e=ht(this.config.agent),n=O(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let r=ni(this.config.managedSecrets,n);if(r&&this.config.sandbox&&!Re(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let s=this.config.sandbox??(r?await Te(e.apiKey):await Sn()),a={},c,l,o=this.config.skills,d;if(this.config.browser){let p=Ls(this.config.browser);if(d=p,p.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.');a=rr(e.apiKey);}if((p.provider==="actionbook"||p.provider==="agent-browser")&&(o=Bs(p.provider,o),p.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${p.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);c=p.provider==="actionbook"?_n:Xr,l={provider:p.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,...p.profile?{profile:p.profile}:{}};}if(p.profile&&!p.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}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(!d||d.provider!=="agent-browser"||!d.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 i=this.config.storage!==void 0?St(this.config.storage,!e.isDirectMode,E,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:s,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:r?{secrets:r,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E}:void 0,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:{...a,...this.config.mcpServers},browserPrompt:c,managedBrowser:l,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:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E},storage:i};this.agent=new je(e,u);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,s=this.listenerCount("lifecycle")>0;return {onStdout:e?a=>this.emit("stdout",a):void 0,onStderr:n?a=>this.emit("stderr",a):void 0,onContent:r?a=>this.emit("content",a):void 0,onLifecycle:s?a=>this.emit("lifecycle",a):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:r,from:s,checkpointComment:a}){if(s&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let c=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:a},c)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.executeCommand(e,n,r)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return (await this.agent.getSandbox(e)).sandboxId}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials();}isSealed(){return this.agent?.isSealed()??false}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}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 uploadFileFromPath(e,n){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,n)}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=ht(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 $n(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return $n(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");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 me=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 ee=Symbol.for("evolve.SwarmResult"),fe=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 qn=class t{config;semaphore;constructor(e={}){let n=e.concurrency??sr;if(n>Vt)throw new Error(`concurrency=${n} exceeds max ${Vt}. 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??we,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations},this.semaphore=new me(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:s,verify:a}=e,c=e.retry??this.config.retry,l=this.generateOperationId(),o=e.timeoutMs??this.config.timeoutMs;if(s&&a)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((i,u)=>s?this.executeMapItemWithBestOf(i,r,u,l,e,o,c):a?this.executeMapItemWithVerify(i,r,u,l,e,o,c):c?D(p=>this.executeMapItem(i,r,u,l,e,o,p),c,u):this.executeMapItem(i,r,u,l,e,o)));return fe.from(d)}async filter(e){let{items:n,prompt:r,condition:s,verify:a}=e,c=e.retry??this.config.retry,l=this.generateOperationId(),o=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((u,p)=>a?this.executeFilterItemWithVerify(u,r,p,l,e,o,c):c?D(g=>this.executeFilterItem(u,r,p,l,e,o,g),c,p):this.executeFilterItem(u,r,p,l,e,o))),i=[];for(let u of d)if(u.status==="error")i.push(u);else if(u.data!==null)try{s(u.data)?i.push(u):i.push({...u,status:"filtered"});}catch(p){i.push({...u,status:"error",data:null,error:`Condition function threw: ${p.message}`});}return fe.from(i)}async reduce(e){let{items:n,prompt:r,verify:s}=e,a=e.retry??this.config.retry,c=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,o=[],d=[];n.forEach((S,b)=>{o.push(this.getFiles(S)),d.push(this.getIndex(S,b));});let i={};o.forEach((S,b)=>{Object.entries(S).forEach(([v,R])=>{i[`item_${d[b]}/${v}`]=R;});});let u=bt(i),p=q(es,{fileTree:u}),g=e.systemPrompt?`${p}
605
+
606
+ ${e.systemPrompt}`:p,m=(S,b,v)=>({operationId:c,operation:"reduce",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:b,verifyRetry:v,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,w=async(S,b,v,R)=>{let k=await this.semaphore.use(()=>this.execute(i,S,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,integrations:y,tagPrefix:b,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:e.name,operationId:c,operation:"reduce",role:"worker",errorRetry:v,verifyRetry:R&&R>1?R-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),T=m(k,v,R&&R>1?R-1:void 0);return k.error?{status:"error",data:null,files:k.files,meta:T,error:k.error,rawData:k.rawData}:{status:"success",data:k.data,files:k.files,meta:T}},_=`${this.config.tag}-reduce`;return s?this.runWithVerification((S,b,v)=>w(S,b,void 0,v),{originalPrompt:r,inputFiles:i,verifyConfig:s,timeoutMs:l,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,integrations:y,operationId:c,baseTag:_,retry:a,operation:"reduce",_pipelineContext:e._pipelineContext}):a?D(S=>{let b=S>1?S-1:void 0,v=b?`${_}-er${b}`:_;return w(r,v,b)},a):w(r,_)}async bestOf(e){let{item:n,prompt:r,config:s}=e,a=e.retry??this.config.retry,c=s.n??s.taskAgents?.length;if(c===void 0)throw new Error("bestOf requires n or taskAgents");if(c<2)throw new Error("bestOf requires n >= 2");let l=this.generateOperationId(),o=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),i=s.mcpServers??this.config.mcpServers,u=s.judgeMcpServers??s.mcpServers??this.config.mcpServers,p=s.skills??this.config.skills,g=s.judgeSkills??s.skills??this.config.skills,m=s.integrations??this.config.integrations,f=s.judgeIntegrations??s.integrations??this.config.integrations,h=await Promise.all(Array.from({length:c},async(b,v)=>{let R=a?await D(k=>this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:l,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:p,integrations:m,timeoutMs:o,attempt:k}),a,v):await this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:l,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:p,integrations:m,timeoutMs:o});return s.onCandidateComplete?.(0,v,R.status==="success"?"success":"error"),R})),y=a?await D(b=>this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:o,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:g,integrations:f,attempt:b}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:o,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:g,integrations:f}),w=h.findIndex(b=>b.status==="success"),_=y.decision?.winner??(w>=0?w:0);s.onJudgeComplete?.(0,_,y.decision?.reasoning??"Judge failed to provide reasoning");let S={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:c};return {winner:h[_]??h[0],winnerIndex:_,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:S,candidates:h}}async execute(e,n,r){let s=null,a="",c=r.tagPrefix,l={},o=null,d,i,u={...this.config.agent,...r.agent};try{s=new Ke().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&s.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&s.withSystemPrompt(r.systemPrompt),r.mcpServers&&s.withMcpServers(r.mcpServers),r.skills?.length&&s.withSkills(r.skills),r.integrations&&s.withIntegrations(r.integrations),r.observability&&s.withObservability(r.observability),Object.keys(e).length>0&&s.withContext(e);let p=await s.run({prompt:n,timeoutMs:r.timeoutMs});a=p.sandboxId,c=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),l=g.files;}catch{}p.exitCode!==0?d=`Agent exited with code ${p.exitCode}`:r.schema?g?(o=g.data,g.error&&(d=g.error),g.rawData&&(i=g.rawData)):d="Failed to read output files from sandbox":o=l;}catch(p){if(d=p.message,s){c=s.getSessionTag()??r.tagPrefix;try{l=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:l,data:o,tag:c,sandboxId:a,error:d,rawData:i}}async executeMapItem(e,n,r,s,a,c,l=1){let o=this.getFiles(e),d=l>1?`${this.config.tag}-map-${r}-er${l-1}`:`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,o,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let u=a.mcpServers??this.config.mcpServers,p=a.skills??this.config.skills,g=a.integrations??this.config.integrations,m=await this.semaphore.use(()=>this.execute(o,i,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:d,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),f={operationId:s,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,r,s,a,c,l){let o=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=a.verify,u=a.mcpServers??this.config.mcpServers,p=a.skills??this.config.skills,g=a.integrations??this.config.integrations,m=this.evaluatePrompt(n,o,r);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let f=async(h,y,w)=>{let _=await this.semaphore.use(()=>this.execute(o,h,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:y,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),S={operationId:s,operation:"map",tag:_.tag,sandboxId:_.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(_,S)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:o,verifyConfig:i,timeoutMs:c,systemPrompt:a.systemPrompt,schema:a.schema,mcpServers:u,skills:p,integrations:g,operationId:s,baseTag:d,retry:l,itemIndex:r,operation:"map",_pipelineContext:a._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,a,c,l){let o=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,o,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let u=a.bestOf,p=u.n??u.taskAgents?.length;if(p===void 0||p<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let g=a.mcpServers??this.config.mcpServers,m=u.mcpServers??g,f=u.judgeMcpServers??u.mcpServers??g,h=a.skills??this.config.skills,y=u.skills??h,w=u.judgeSkills??u.skills??h,_=a.integrations??this.config.integrations,S=u.integrations??_,b=u.judgeIntegrations??u.integrations??_,v=await Promise.all(Array.from({length:p},async(He,ze)=>{let Zn=l?await D(Bi=>this.executeBestOfCandidate({inputFiles:o,prompt:i,candidateIndex:ze,operationId:s,config:u,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:m,skills:y,integrations:S,timeoutMs:c,parentIndex:r,attempt:Bi,_pipelineContext:a._pipelineContext}),l,ze):await this.executeBestOfCandidate({inputFiles:o,prompt:i,candidateIndex:ze,operationId:s,config:u,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:m,skills:y,integrations:S,timeoutMs:c,parentIndex:r,_pipelineContext:a._pipelineContext});return u.onCandidateComplete?.(r,ze,Zn.status==="success"?"success":"error"),Zn})),R=l?await D(He=>this.executeBestOfJudge({inputFiles:o,taskPrompt:i,candidates:v,config:u,timeoutMs:c,operationId:s,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:f,skills:w,integrations:b,parentIndex:r,attempt:He,_pipelineContext:a._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:o,taskPrompt:i,candidates:v,config:u,timeoutMs:c,operationId:s,systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,mcpServers:f,skills:w,integrations:b,parentIndex:r,_pipelineContext:a._pipelineContext}),k=v.findIndex(He=>He.status==="success"),T=R.decision?.winner??(k>=0?k:0),$=v[T]??v[0];u.onJudgeComplete?.(r,T,R.decision?.reasoning??"Judge failed to provide reasoning");let Li={operationId:s,operation:"bestof-judge",tag:R.tag,sandboxId:R.sandboxId,swarmName:this.config.tag,operationName:a.name,candidateCount:p,...this.pipelineContextToMeta(a._pipelineContext)};return {...$,meta:{...$.meta,operation:"map",swarmName:this.config.tag,operationName:a.name,itemIndex:r,...this.pipelineContextToMeta(a._pipelineContext)},bestOf:{winnerIndex:T,judgeReasoning:R.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Li,candidates:v}}}async executeFilterItem(e,n,r,s,a,c,l=1){let o=this.getFiles(e),d=l>1?`${this.config.tag}-filter-${r}-er${l-1}`:`${this.config.tag}-filter-${r}`,i=a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,p=a.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(o,n,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:i,skills:u,integrations:p,tagPrefix:d,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),m={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(g,m,o)}async executeFilterItemWithVerify(e,n,r,s,a,c,l){let o=this.getFiles(e),d=`${this.config.tag}-filter-${r}`,i=a.verify,u=a.mcpServers??this.config.mcpServers,p=a.skills??this.config.skills,g=a.integrations??this.config.integrations,m=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(o,f,{systemPrompt:a.systemPrompt,schema:a.schema,schemaOptions:a.schemaOptions,agent:a.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:h,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:a.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(a._pipelineContext)}})),_={operationId:s,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:a.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(a._pipelineContext)};return this.buildResult(w,_,o)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:o,verifyConfig:i,timeoutMs:c,systemPrompt:a.systemPrompt,schema:a.schema,mcpServers:u,skills:p,integrations:g,operationId:s,baseTag:d,retry:l,itemIndex:r,operation:"filter",_pipelineContext:a._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:a,config:c,timeoutMs:l,parentIndex:o,attempt:d=1,_pipelineContext:i}=e,u=o!==void 0?`${this.config.tag}-map-${o}-bestof-cand-${s}`:`${this.config.tag}-bestof-cand-${s}`,p=d>1?`${u}-er${d-1}`:u,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:c.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:p,timeoutMs:l,observability:{swarmName:this.config.tag,operationId:a,operation:"map",itemIndex:o,role:"candidate",candidateIndex:s,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(i)}})),m={operationId:a,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:s,errorRetry:d>1?d-1:void 0,candidateIndex:s,...this.pipelineContextToMeta(i)};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((r,s)=>{r.status==="error"&&(n[`candidate_${s}/_failed.txt`]=`STATUS: FAILED
607
+
608
+ Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([a,c])=>{n[`candidate_${s}/${a}`]=c;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:a,parentIndex:c,attempt:l=1,_pipelineContext:o}=e,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=l>1?`${d}-er${l-1}`:d,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),p=bt(u),g=q(xn,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:p}),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(u,Qr,{systemPrompt:g,schema:m,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:i,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:a,operation:"map",itemIndex:c,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o)}})),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(([r,s])=>{n[`worker_output/${r}`]=s;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:s,workerTag:a,retryAttempt:c=1,operation:l,itemIndex:o,attemptIndex:d,_pipelineContext:i}=e,u=c>1?`${a}-verifier-er${c-1}`:`${a}-verifier`,p=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,m=n.verifierIntegrations??e.integrations,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=bt(f),y=q(kn,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(f,Zr,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:p,skills:g,integrations:m,tagPrefix:u,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:l,itemIndex:o,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(i)}})),_=null;if(w.data&&!w.error)_=w.data;else if(w.rawData)try{let S=JSON.parse(w.rawData);_={passed:!!S.passed,reasoning:S.reasoning??"Verification completed",feedback:S.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:_?"success":"error",decision:_,tag:w.tag,sandboxId:w.sandboxId,error:_?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return q(Cn,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:s,verifyConfig:a,timeoutMs:c,operationId:l,baseTag:o,retry:d,itemIndex:i=0,operation:u,_pipelineContext:p}=n,g=a.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,m=r,f=null,h=0;for(;h<g;){h++;let w=h>1?`${o}-vr${h-1}`:o,_=d?await D(v=>e(m,v>1?`${w}-er${v-1}`:w,h),d,i):await e(m,w,h);if(a.onWorkerComplete?.(i,h,_.status==="error"?"error":"success"),_.status==="error")return _;f=_;let S=d?await D(v=>this.executeVerify({inputFiles:s,outputFiles:_.files,taskPrompt:m,config:a,timeoutMs:c,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:l,workerTag:w,retryAttempt:v,operation:u,itemIndex:i,attemptIndex:h,_pipelineContext:p}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:_.files,taskPrompt:m,config:a,timeoutMs:c,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:l,workerTag:w,operation:u,itemIndex:i,attemptIndex:h,_pipelineContext:p}),b={operationId:l,operation:"verify",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)};if(a.onVerifierComplete?.(i,h,S.decision?.passed??false,S.decision?.feedback),S.decision?.passed)return {..._,verify:{passed:true,reasoning:S.decision.reasoning,verifyMeta:b,attempts:h}};if(h<g){let v=S.decision?.feedback??S.decision?.reasoning??"Output did not meet criteria";m=t.buildRetryPromptWithFeedback(r,v);}}let y=h>1?`${o}-vr${h-1}`:o;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:l,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)},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,r){if(typeof e=="string")return e;try{return e(n,r)}catch(s){return s}}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"]=N(e.schema)?oe(e.schema):ae(e.schema)),Object.entries(e.inputFiles).forEach(([r,s])=>{n[`worker_task/input/${r}`]=s;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&ee in e&&e[ee]===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,r){let s=r??e.files;return e.error?{[ee]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[ee]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[ee]:true,status:"error",data:null,files:{},meta:n,error:e}}};var At=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}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 Ot(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),r=[],s=e,a=Date.now();for(let l=0;l<this.steps.length;l++){let o=this.steps[l],d=o.config.name,i=Date.now();this.events.onStepStart?.({type:o.type,index:l,name:d,itemCount:s.length});let u={pipelineRunId:n,pipelineStepIndex:l};try{let p=await this.executeStep(o,s,l,d,u),g=Date.now()-i;if(r.push({type:o.type,index:l,durationMs:g,results:p.output}),this.events.onStepComplete?.({type:o.type,index:l,name:d,durationMs:g,successCount:p.successCount,errorCount:p.errorCount,filteredCount:p.filteredCount}),o.type==="reduce")return {pipelineRunId:n,steps:r,output:p.output,totalDurationMs:Date.now()-a};s=p.nextItems;}catch(p){throw this.events.onStepError?.({type:o.type,index:l,name:d,error:p instanceof Error?p:new Error(String(p))}),p}}let c=r[r.length-1];return {pipelineRunId:n,steps:r,output:c?.results??[],totalDurationMs:Date.now()-a}}async executeStep(e,n,r,s,a){if(e.type==="map"){let o=e.config,d=await this.swarm.map({items:n,...o,_pipelineContext:a,retry:this.wrapRetry(o.retry,r,s),verify:this.wrapVerify(o.verify,r,s),bestOf:this.wrapBestOf(o.bestOf,r,s)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let o=e.config,d=await this.swarm.filter({items:n,...o,_pipelineContext:a,retry:this.wrapRetry(o.retry,r,s),verify:this.wrapVerify(o.verify,r,s)}),i=o.emit??"success",u=i==="success"?d.success:i==="filtered"?d.filtered:[...d.success,...d.filtered];return {output:[...d],nextItems:u,successCount:d.success.length,errorCount:d.error.length,filteredCount:d.filtered.length}}let c=e.config,l=await this.swarm.reduce({items:n,...c,_pipelineContext:a,retry:this.wrapRetry(c.retry,r,s),verify:this.wrapVerify(c.verify,r,s)});return {output:l,nextItems:[],successCount:l.status==="success"?1:0,errorCount:l.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,a,c)=>{e.onItemRetry?.(s,a,c),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:a,error:c});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,a,c)=>{e.onWorkerComplete?.(s,a,c),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:a,status:c});},onVerifierComplete:(s,a,c,l)=>{e.onVerifierComplete?.(s,a,c,l),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:a,passed:c,feedback:l});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,a,c)=>{e.onCandidateComplete?.(s,a,c),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:a,status:c});},onJudgeComplete:(s,a,c)=>{e.onJudgeComplete?.(s,a,c),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:a,reasoning:c});}}}},Ot=class t extends At{constructor(e,n,r){super(e,n,r);}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]: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 ml=6e5,fl=5e3;function fi(t,e,n){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be a positive number`);return r}function hl(t){let e=t?.apiKey||process.env[P];if(!e)throw new Error(`sessions() requires an API key. Set ${P} or pass { apiKey } in config.`);let n=t?.dashboardUrl||E;async function r(l,o){let d=await fetch(`${n}${l}`,{...o,headers:{Authorization:`Bearer ${e}`,...o?.headers}});if(!d.ok){let i=await d.text().catch(()=>"");throw new Error(`Dashboard API error (${d.status}): ${i||d.statusText}`)}return d}function s(l){return {id:l.id,tag:l.tag,agent:l.agent,model:l.model||null,provider:l.provider,sandboxId:l.sandboxId||null,state:l.isEnded?"ended":"live",runtimeStatus:l.runtimeStatus||"unknown",cost:typeof l.cost=="number"?l.cost:null,createdAt:l.createdAt,endedAt:l.endedAt||null,stepCount:l.stepCount||0,toolStats:l.toolStats||null}}function a(l,o){if(l.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(l.status||"unknown")})`);if(typeof l.replayUrl!="string"||typeof l.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:l.sessionId||o,status:"ready",replayUrl:l.replayUrl,downloadUrl:l.downloadUrl,suggestedStartSeconds:typeof l.suggestedStartSeconds=="number"?l.suggestedStartSeconds:void 0,sizeBytes:typeof l.sizeBytes=="number"?l.sizeBytes:void 0,readyAt:typeof l.readyAt=="string"?l.readyAt:void 0}}let c=l=>new Promise(o=>setTimeout(o,l));return {async list(l){let o=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(l?.limit??20,200)),paginated:"true"});if(l?.cursor&&o.set("cursor",l.cursor),l?.state&&l.state!=="all"&&o.set("state",l.state),l?.agent&&o.set("agent",l.agent),l?.tagPrefix&&o.set("tagPrefix",l.tagPrefix),l?.sort){let u={newest:"desc",oldest:"asc",cost:"desc"};o.set("sortDirection",u[l.sort]),l.sort==="cost"?o.set("sortField","cost"):o.set("sortField","timestamp");}let i=await(await r(`/api/sessions?${o}`)).json();return {items:(i.items||[]).map(s),nextCursor:i.nextCursor||null,hasMore:!!i.hasMore}},async get(l){let d=await(await r(`/api/sessions/${encodeURIComponent(l)}`)).json();return s(d)},async events(l,o){let d=new URLSearchParams;o?.since!=null&&d.set("since",String(o.since));let i=d.toString();return (await(await r(`/api/sessions/${encodeURIComponent(l)}/events${i?`?${i}`:""}`)).json()).events||[]},async download(l,o){let u=(await(await r(`/api/sessions/${encodeURIComponent(l)}`)).json()).tag||l,p=await fetch(`${n}/api/sessions/${encodeURIComponent(l)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!p.ok){let h=await p.text().catch(()=>"");throw new Error(`Download failed (${p.status}): ${h||p.statusText}`)}let g=o?.to||process.cwd();await promises.mkdir(g,{recursive:true});let m=F.join(g,`${u}.jsonl`);if(!p.body)throw new Error("Download response has no body");let f=stream.Readable.fromWeb(p.body);return await promises$1.pipeline(f,j.createWriteStream(m)),m},async browserReplay(l,o){let d=fi("timeoutMs",o?.timeoutMs,ml),i=fi("intervalMs",o?.intervalMs,fl),u=Date.now()+d,p=`/api/sessions/${encodeURIComponent(l)}/browser-replay`;for(;;){let g=u-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let m;try{m=await fetch(`${n}${p}`,{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 a(f,l);if(f.status==="failed"){let h=typeof f.error=="string"?f.error:"unknown error";throw new Error(`Browser replay failed: ${h}`)}if(Date.now()>=u)throw new Error(`Browser replay timed out after ${d}ms`);await c(Math.min(i,Math.max(0,u-Date.now())));}}}}var hi=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","INDETERMINATE","CANCELLED"],yi=["e2b","daytona","modal"],wi=["trace-parsed","verifier","trace-stdout","trace-stderr","trajectory","agent-home"],Hn=["missing_authorization","invalid_api_key","credential_service_unavailable","rate_limited","insufficient_credits","invalid_json","invalid_input","invalid_limit","invalid_status","invalid_cursor","invalid_after","invalid_format","invalid_ids","invalid_multipart","idempotency_key_reused","dataset_not_found","dataset_version_not_found","dataset_name_taken","dataset_in_use","dataset_not_owned","upstream_not_watchable","no_active_version","version_not_ready","version_not_activatable","unknown_task_names","no_tasks","agent_not_found","agent_name_taken","agent_name_reserved","agent_invalid_name","agent_source_required","agent_source_conflict","agent_invalid_env","agent_too_large","agent_limit_reached","agent_version_not_found","job_too_large","provider_unsupported","job_not_found","job_not_terminal","no_failed_trials","trial_not_found","concurrent_update","regrade_source_ineligible","no_regradable_trials","import_not_found","import_too_large","invalid_archive","package_not_retained","package_corrupt","package_missing","internal_error"];function Mt(t){return typeof t=="string"&&Hn.includes(t)}var re=class extends Error{status;code;param;details;retryAfterSec;requestId;constructor(e,n,r,s){super(r),this.name="EvolveApiError",this.status=e,this.code=n,s?.param!==void 0&&(this.param=s.param),s?.details!==void 0&&(this.details=s.details),s?.retryAfterSec!==void 0&&(this.retryAfterSec=s.retryAfterSec),s?.requestId!==void 0&&(this.requestId=s.requestId);}isKnownCode(){return Mt(this.code)}};function ki(t,e){try{let a=JSON.parse(t)?.error?.retryAfterSec;if(typeof a=="number"&&Number.isFinite(a))return a}catch{}let n=e.headers?.get?.("retry-after");if(typeof n!="string"||n.trim()==="")return;let r=Number(n);return Number.isFinite(r)?r:void 0}async function Qn(t){let e=await t.text().catch(()=>""),n=t.headers?.get?.("x-request-id")??void 0,r=ki(e,t);try{let s=JSON.parse(e);if(s?.error&&typeof s.error=="object"){let a=typeof s.error.code=="string"?s.error.code:"unknown_error",c=typeof s.error.message=="string"?s.error.message:t.statusText;throw new re(t.status,a,c,{param:typeof s.error.param=="string"?s.error.param:void 0,details:s.error.details&&typeof s.error.details=="object"?s.error.details:void 0,retryAfterSec:r,requestId:typeof s.error.requestId=="string"?s.error.requestId:n})}}catch(s){if(s instanceof re)throw s}throw new re(t.status,"unknown_error",e||t.statusText,{retryAfterSec:r,requestId:n})}var Bt=class extends Error{dataset;constructor(e){super(`Dataset "${e}" has no active version`),this.name="NoActiveVersionError",this.dataset=e;}},Ml=1e3,Dl=3e4,Ul=new Set(["COMPLETED","CANCELLED","FAILED"]),$l=new Set(["job.completed","job.cancelled","job.failed"]),Ll=2e3,Bl=new Set(["COMPLETED","FAILED"]);function qe(t,e){let n=e?.apiKey||process.env[P];if(!n)throw new Error(`${t}() requires an API key. Set ${P} or pass { apiKey } in config.`);let r=(e?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"");return {apiKey:n,baseUrl:r}}async function C(t,e,n){let r=await fetch(`${t.baseUrl}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,...n?.headers}});return r.ok||await Qn(r),r}function Si(t){let e=t.indexOf("@");if(e===-1)return {name:t.trim()};let n=t.slice(0,e).trim(),r=t.slice(e+1).trim();if(!n||!r)throw new Error(`Invalid dataset ref "${t}": expected "name" or "name@version"`);return {name:n,version:r}}function Ci(t){return {name:t.name,version:t.version}}function Ei(t){return {name:t.name,model_name:t.model_name,version:t.version??null,reasoning_effort:t.reasoning_effort??null}}function Nl(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.status!="string")return null;let n=e.failure&&typeof e.failure=="object"&&!Array.isArray(e.failure)?e.failure:{},r=typeof e.code=="string"?e.code:n.code,s=typeof e.message=="string"?e.message:n.message;return {status:e.status,attempts:typeof e.attempts=="number"?e.attempts:0,code:typeof r=="string"?r:null,message:typeof s=="string"?s:null}}function Dt(t){return {version:t.version,state:t.state,created_at:t.created_at,task_count:t.task_count??0,gate:Nl(t.gate)}}function Fl(t){return {task_name:t.task_name,agent_timeout_sec:t.agent_timeout_sec,verifier_timeout_sec:t.verifier_timeout_sec,providers:t.providers}}function jl(t){return {action:t.action,type:t.type,job_id:t.job_id}}function ne(t){let e=t.trials??{};return {id:t.id,job_name:t.job_name,status:t.status,datasets:(t.datasets??[]).map(Ci),agents:(t.agents??[]).map(Ei),n_attempts:t.n_attempts,n_concurrent_trials:t.n_concurrent_trials,max_trial_spend_usd:t.max_trial_spend_usd,worst_case_spend_usd:t.worst_case_spend_usd,sandbox_provider:t.sandbox_provider,counts:t.counts,n_total_trials:t.n_total_trials??0,trials:{total:e.total??0,byStatus:e.byStatus??{}},stats:t.stats??{},failure:t.failure??null,source_jobs:(t.source_jobs??[]).map(jl),is_regrade:t.is_regrade===true,idempotent_replay:t.idempotent_replay===true,started_at:t.started_at,updated_at:t.updated_at,finished_at:t.finished_at??null}}function Y(t,e){let n=t??{};return {items:Array.isArray(n.items)?n.items.map(e):[],nextCursor:n.nextCursor??null,hasMore:n.hasMore===true}}function se(t,e){let n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);for(let[s,a]of Object.entries(e??{}))a!==void 0&&n.set(s,a);let r=n.toString();return r?`?${r}`:""}function Ut(t){if(!t||typeof t!="object")return null;let e=t;return {started_at:e.started_at??null,finished_at:e.finished_at??null}}function Kl(t){let e=t.model_info??{};return {name:t.name,version:t.version??null,model_info:{name:e.name,provider:e.provider??null},reasoning_effort:t.reasoning_effort??null}}function Yn(t){return {id:t.id,job_id:t.job_id,task_name:t.task_name,source:t.source,agent_info:Kl(t.agent_info||{}),attempt:t.attempt,status:t.status,reward:t.reward??null,verifier_result:t.verifier_result??null,exception_info:t.exception_info??null,agent_result:t.agent_result??null,environment_setup:Ut(t.environment_setup),agent_setup:Ut(t.agent_setup),agent_execution:Ut(t.agent_execution),verifier:Ut(t.verifier),step_results:t.step_results??null,spend_source:t.spend_source??null,live_spent_usd:t.live_spent_usd??null,live_spend_at:t.live_spend_at??null,max_trial_spend_usd:t.max_trial_spend_usd??null,sandbox_provider:t.sandbox_provider??null,sandbox_id:t.sandbox_id??null,verifier_sandbox_id:t.verifier_sandbox_id??null,verifier_environment_mode:t.verifier_environment_mode??null,attempt_phase:t.attempt_phase??null,session_ref:t.session_ref??null,started_at:t.started_at??null,finished_at:t.finished_at??null}}function $t(t){return {name:t.name,source:t.source,run_command:t.run_command,env:t.env??{},created_at:t.created_at,updated_at:t.updated_at}}function Lt(t){let e={id:t.id,status:t.status,name:t.name,version:t.version,failure:t.failure??null,warnings:t.warnings??[]};return typeof t.task_count=="number"&&(e.task_count=t.task_count),typeof t.created_at=="string"&&(e.created_at=t.created_at),typeof t.updated_at=="string"&&(e.updated_at=t.updated_at),e}function Ri(t){let e=t??{};return {scored:e.scored??0,total:e.total??0}}function Jl(t){return {id:t.id,datasets:(t.datasets??[]).map(Ci),status:t.status,mean_reward:t.mean_reward??null,coverage:Ri(t.coverage),cost_usd:t.cost_usd??0,agents:(t.agents||[]).map(Ei),started_at:t.started_at}}function Vl(t){return {job_id:t.job_id,status:t.status,mean_reward:t.mean_reward??null,coverage:Ri(t.coverage)}}function Gl(t){return {task_name:t.task_name,disagreement:t.disagreement===true,cells:(t.cells||[]).map(Vl)}}function ql(t){return {seq:t.seq,type:t.type,data:t.data??{}}}function Xn(t){if(t?.aborted)throw t.reason instanceof Error?t.reason:new Error("Watch aborted")}function _i(t,e){return e?.aborted?true:t?.name==="AbortError"}function Je(t,e){return new Promise((n,r)=>{let s=setTimeout(()=>{e?.removeEventListener("abort",a),n();},t),a=()=>{clearTimeout(s),r(e?.reason instanceof Error?e.reason:new Error("Watch aborted"));};e?.addEventListener("abort",a,{once:true});})}function Hl(t){let e="",n=false;return {push(r){n&&(r="\r"+r,n=false),r.endsWith("\r")&&(r=r.slice(0,-1),n=true),e+=r.replace(/\r\n|\r/g,`
609
+ `);let s;for(;(s=e.indexOf(`
610
+
611
+ `))!==-1;){let a=e.slice(0,s);e=e.slice(s+2);let c,l,o=[];for(let d of a.split(`
612
+ `)){if(!d||d.startsWith(":"))continue;let i=d.indexOf(":"),u=i===-1?d:d.slice(0,i),p=i===-1?"":d.slice(i+1);p.startsWith(" ")&&(p=p.slice(1)),u==="id"?c=p:u==="event"?l=p:u==="data"&&o.push(p);}(c!==void 0||l!==void 0||o.length>0)&&t({id:c,event:l,data:o.join(`
613
+ `)});}}}}function he(t,e){let n,r=()=>n??=t({limit:e?.limit,cursor:e?.cursor});return {then(s,a){return r().then(s,a)},catch(s){return r().catch(s)},finally(s){return r().finally(s)},async*[Symbol.asyncIterator](){let s=e?.cursor;for(;;){let a=await t({limit:e?.limit,cursor:s});for(let c of a.items)yield c;if(!a.nextCursor)return;s=a.nextCursor;}}}}function Nt(t,e){let n=new FormData;for(let[r,s]of Object.entries(t))s!==void 0&&n.set(r,s);return e&&n.set("archive",new Blob([e.bytes],{type:"application/gzip"}),e.filename),n}function zl(t){let e,n=()=>(e||(e=(async()=>{let r=await t.next();for(;!r.done;)r=await t.next();return r.value})()),e);return {then(r,s){return n().then(r,s)},catch(r){return n().catch(r)},finally(r){return n().finally(r)},[Symbol.asyncIterator](){return t}}}var Ti="x-package-sha256",Ve=class extends Error{constructor(n,r){super(`downloaded bytes do not match the digest the server stated (expected ${n}, got ${r})`);this.expected=n;this.actual=r;}name="EvolveDigestMismatchError"},Ge=class extends Error{constructor(n,r){super(`download ended early: the server declared ${n} bytes and ${r} arrived`);this.expectedBytes=n;this.receivedBytes=r;}name="EvolveIncompleteDownloadError"};function Pi(t,e){let n=t.headers.get("Content-Length");if(n===null)return;let r=Number(n);if(Number.isFinite(r)&&e!==r)throw new Ge(r,e)}async function Ii(t,e){let n=t.headers.get(Ti);if(!n)return;let{createHash:r}=await import('crypto'),s=r("sha256").update(e).digest("hex");if(s!==n)throw new Ve(n,s)}function Wl(t,e){let r=(t.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/);if(!r)return e;let s=F.basename(r[1]);return s===""||s==="."||s===".."||/[/\\]/.test(s)||/[\u0000-\u001f]/.test(s)?e:s}async function Ai(t,e,n){if(!t.body)throw new Error("Download response has no body");await promises.mkdir(e,{recursive:true});let r=F.join(e,Wl(t,n)),{createHash:s,randomBytes:a}=await import('crypto'),c=`${r}.${a(8).toString("hex")}.part`,l=s("sha256"),o=0,d=stream.Readable.fromWeb(t.body);d.on("data",i=>{l.update(i),o+=i.length;});try{await promises$1.pipeline(d,j.createWriteStream(c));let i=t.headers.get("Content-Length");if(i!==null&&o!==Number(i))throw new Ge(Number(i),o);let u=t.headers.get(Ti),p=l.digest("hex");if(u&&p!==u)throw new Ve(u,p);await promises.rename(c,r);}catch(i){throw await promises.rm(c,{force:true}).catch(()=>{}),i}return r}function Oi(t){let e=qe("datasets",t);async function n(o){let d=await C(e,`/api/datasets/imports/${encodeURIComponent(o)}`);return Lt(await d.json())}function r(o){if(!o||typeof o!="object")return null;let d=o;return {ref:d.ref,current_commit:d.current_commit,latest_commit:d.latest_commit??null,moved:d.moved===true,behind_by:typeof d.behind_by=="number"?d.behind_by:null,checked_at:d.checked_at??null,error:d.error??null,auto_import:d.auto_import===true}}function s(o){return {name:o.name,title:o.title??null,description:o.description??null,active_version:o.active_version?Dt(o.active_version):null,versions:(o.versions||[]).map(Dt),selected_version:o.selected_version?Dt(o.selected_version):null,tasks:Y(o.tasks,Fl),upstream:r(o.upstream),created_at:o.created_at,updated_at:o.updated_at}}async function a(o,d){let i=Si(o),u=se(d,{version:i.version}),p=await C(e,`/api/datasets/${encodeURIComponent(i.name)}${u}`);return s(await p.json())}function c(o){return {name:o.name,title:o.title??null,description:o.description??null,active_version:o.active_version?Dt(o.active_version):null,upstream:r(o.upstream)}}async function l(o){let d=await C(e,`/api/datasets${se(o,{search:o?.search})}`);return Y(await d.json(),c)}return {list(o){return he(d=>l({...d,search:o?.search}),o)},get:a,async getActive(o,d){let i=await a(o,d);if(i.active_version===null)throw new Bt(o);return {name:i.name,title:i.title,description:i.description,active_version:i.active_version,version:i.active_version.version,tasks:i.tasks??{items:[],nextCursor:null,hasMore:false},versions:i.versions??[],created_at:i.created_at,updated_at:i.updated_at}},async publish(o){let d=o.source;if(d?.directory){let{tarGzipDirectory:i}=await Promise.resolve().then(()=>(Wn(),zn)),u=await i(d.directory),p=await C(e,"/api/datasets/publish",{method:"POST",body:Nt({name:o.name,version:o.version},{bytes:u,filename:"corpus.tar.gz"})});return Lt(await p.json())}if(d&&"git_url"in d&&d.git_url){let i=await C(e,"/api/datasets/publish",{method:"POST",body:Nt({name:o.name,version:o.version,git_url:d.git_url,git_ref:d.git_ref})});return Lt(await i.json())}throw new Error("datasets().publish() requires either a git source ({ source: { git_url, git_ref } }) or a local corpus directory ({ source: { directory } }), plus name and version")},getImport:n,async watchImport(o,d){let i=d?.pollIntervalMs??Ll,u=null;for(;;){Xn(d?.signal);let p;try{p=await n(o);}catch(g){if(g instanceof re&&(g.status===429||g.status===503)){await Je(Math.max((g.retryAfterSec??0)*1e3,i),d?.signal);continue}throw g}if(p.status!==u&&(u=p.status,d?.onStatus?.(p)),Bl.has(p.status))return p;await Je(i,d?.signal);}},download:(async(o,d)=>{let i=Si(o),u=i.version?`?version=${encodeURIComponent(i.version)}`:"",p=await C(e,`/api/datasets/${encodeURIComponent(i.name)}/download${u}`);if(d?.stream){if(!p.body)throw new Error("Package response has no body");return p.body}if(d?.to)return Ai(p,d.to,`${i.name}-corpus.tar.gz`);let g=Buffer.from(await p.arrayBuffer());return Pi(p,g.length),await Ii(p,g),g}),listImports(o){return he(async d=>{let i=new URLSearchParams;d.limit!==void 0&&i.set("limit",String(d.limit)),d.cursor!==void 0&&i.set("cursor",d.cursor),o?.status!==void 0&&i.set("status",o.status),o?.dataset!==void 0&&i.set("dataset",o.dataset);let u=i.toString()?`?${i}`:"",p=await C(e,`/api/datasets/imports${u}`);return Y(await p.json(),Lt)},o)},async activate(o,d){let i=await C(e,`/api/datasets/${encodeURIComponent(o)}/versions/${encodeURIComponent(d)}/activate`,{method:"POST"});return s(await i.json())},async update(o,d){let i=await C(e,`/api/datasets/${encodeURIComponent(o)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});return c(await i.json())},async delete(o){await C(e,`/api/datasets/${encodeURIComponent(o)}`,{method:"DELETE"});}}}function Mi(t){let e=qe("agents",t);return {async create(n){let r=await xi("agents().create()",n),s=await C(e,"/api/agents",{method:"POST",body:r});return $t(await s.json())},list(n){return he(async r=>{let s=await C(e,`/api/agents${se(r)}`);return Y(await s.json(),$t)},n)},async get(n){let r=await C(e,`/api/agents/${encodeURIComponent(n)}`);return $t(await r.json())},async delete(n){await C(e,`/api/agents/${encodeURIComponent(n)}`,{method:"DELETE"});},async upsert(n,r){let s=await xi("agents().upsert()",{...r,name:n}),a=await C(e,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",body:s});return $t(await a.json())}}}async function xi(t,e){let n=typeof e.install_script=="string",r=typeof e.directory=="string";if(n&&r)throw new Error(`${t} takes EITHER an install script ({ install_script }) or a local directory ({ directory }), not both`);if(!n&&!r)throw new Error(`${t} requires either an install script ({ install_script }) or a local directory ({ directory }), plus run_command`);let s={name:e.name,run_command:e.run_command,...e.env!==void 0?{env:JSON.stringify(e.env)}:{},...n?{install_script:e.install_script}:{}};if(r){let{tarGzipDirectory:a}=await Promise.resolve().then(()=>(Wn(),zn)),c=await a(e.directory);return Nt(s,{bytes:c,filename:"source.tar.gz"})}return Nt(s)}function Di(t){let e=qe("jobs",t);async function n(l){let o=await C(e,`/api/jobs/${encodeURIComponent(l)}`);return ne(await o.json())}async function r(l){let o=await C(e,`/api/jobs${se(l,{search:l?.search})}`);return Y(await o.json(),ne)}function s(l){let o=l.trials??{};return {task_name:l.task_name,source:l.source,trials:{total:o.total??0,byStatus:o.byStatus??{}},mean_reward:l.mean_reward??null,cost_usd:l.cost_usd??null}}async function a(l,o){let d=se(o,{status:o?.status?.length?o.status.join(","):void 0,dataset:o?.dataset}),i=await C(e,`/api/jobs/${encodeURIComponent(l)}/trials${d}`);return Y(await i.json(),Yn)}async function*c(l,o){let{onEvent:d,signal:i}=o??{},u=o?.reconnectDelayMs??Ml,p=o?.maxReconnectDelayMs??Dl,g=null,m=false,f=false,h=u;for(;!m;){Xn(i);let y;try{y=await fetch(`${e.baseUrl}/api/jobs/${encodeURIComponent(l)}/events`,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"text/event-stream",...g!==null?{"Last-Event-ID":String(g)}:{}},signal:i});}catch(k){if(_i(k,i))throw k;await Je(h,i),h=Math.min(h*2,p);continue}if(!y.ok){if(y.status===429||y.status>=500){let k=await y.text().catch(()=>""),T=ki(k,y)??0,$=T>0?Math.max(T*1e3,h):h;await Je($,i),h=Math.min(h*2,p);continue}await Qn(y);}if(!y.body)throw new Error("Event stream response has no body");let w=false,_=[],S=Hl(k=>{let T=Number(k.id),$={seq:Number.isInteger(T)?T:-1,type:k.event||"message",data:k.data?Xl(k.data):{}};Number.isInteger(T)&&(g=T),w=true,$l.has($.type)&&(m=true),_.push($);}),b=y.body.getReader(),v=new TextDecoder;try{for(;!m;){let{done:k,value:T}=await b.read();if(k)break;S.push(v.decode(T,{stream:!0}));for(let $ of _)d?.($),yield $;_.length=0;}}catch(k){if(_i(k,i))throw k}finally{await b.cancel().catch(()=>{});}if(m)break;Xn(i);let R=await n(l);if(Ul.has(R.status)){if(f)return R;f=true;continue}w&&(h=u),await Je(h,i),h=Math.min(h*2,p);}return n(l)}return {async start(l,o){let d=await C(e,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...o?.idempotencyKey?{"Idempotency-Key":o.idempotencyKey}:{}},body:JSON.stringify(l)});return ne(await d.json())},get:n,list(l){return he(o=>r({...o,search:l?.search}),l)},trials(l,o){return he(d=>a(l,{...d,status:o?.status,dataset:o?.dataset}),o)},tasks(l,o){return he(async d=>{let i=await C(e,`/api/jobs/${encodeURIComponent(l)}/tasks${se(d)}`);return Y(await i.json(),s)},o)},watch(l,o){return zl(c(l,o))},async cancel(l){let o=await C(e,`/api/jobs/${encodeURIComponent(l)}/cancel`,{method:"POST"});return ne(await o.json())},async compare(l){let o=l.map(encodeURIComponent).join(","),i=await(await C(e,`/api/jobs/compare?ids=${o}`)).json();return {jobs:(i.jobs||[]).map(Jl),taskMatrix:(i.taskMatrix||[]).map(Gl)}},async resume(l,o,d){let i=await C(e,`/api/jobs/${encodeURIComponent(l)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...d?.idempotencyKey?{"Idempotency-Key":d.idempotencyKey}:{}},body:JSON.stringify(o??{})});return ne(await i.json())},async regrade(l,o){let d={};o?.statuses?.length&&(d.statuses=o.statuses),o?.task_name!==void 0&&(d.task_name=o.task_name);let i=await C(e,`/api/jobs/${encodeURIComponent(l)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});return ne(await i.json())},download:(async(l,o)=>{let d=await C(e,`/api/jobs/${encodeURIComponent(l)}/download`);if(o?.stream){if(!d.body)throw new Error("Download response has no body");return d.body}if(o?.to)return Ai(d,o.to,`job-${l}-results.tar.gz`);let i=Buffer.from(await d.arrayBuffer());return Pi(d,i.length),await Ii(d,i),i})}}function Ui(t){let e=qe("trials",t);async function n(s,a){let c=await C(e,`/api/trials/${encodeURIComponent(s)}/trace${se(a)}`);return Y(await c.json(),ql)}async function r(s,a){let l=await(await C(e,`/api/trials/${encodeURIComponent(s)}/trace?stream=${a}`)).json();return a==="agent-home"?l.files??null:l.log??null}return {async get(s){let a=await C(e,`/api/trials/${encodeURIComponent(s)}`);return Yn(await a.json())},trace:n,artifact:r,async*traceEvents(s,a){let c=a?.cursor;for(;;){let l=await n(s,{cursor:c,limit:a?.limit});for(let o of l.items)yield o;if(!l.nextCursor)return;c=l.nextCursor;}},async regrade(s){let a=await C(e,`/api/trials/${encodeURIComponent(s)}/regrade`,{method:"POST"});return ne(await a.json())},async stop(s){let c=await(await C(e,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:s})})).json();return {stopped:(c.stopped??[]).map(Yn),already_terminal:c.already_terminal??[],not_found:c.not_found??[]}}}}function Yl(t){let e=qe("auth",t);return {async status(){let r=await(await C(e,"/api/auth/status")).json(),s=r.key??{};return {user_id:r.user_id,email:r.email??null,key:{id:s.id,label:s.label??null,created_at:s.created_at,last_used_at:s.last_used_at??null}}}}}function Xl(t){try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{value:e}}catch{return {raw:t}}}function Ql(t){let e,n,r,s;return {get datasets(){return e??=Oi(t)},get agents(){return n??=Mi(t)},get jobs(){return r??=Di(t)},get trials(){return s??=Ui(t)},meta(){return $i(t)}}}async function $i(t){let e=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,""),n=await fetch(`${e}/api/meta`);return n.ok||await Qn(n),await n.json()}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=ie;exports.AGENT_TYPES=Fi;exports.Agent=je;exports.BINARY_EFFORT_VALUES=dr;exports.BROWSER_ACTIONBOOK_PROMPT=_n;exports.BROWSER_LOGIN_MCP_SERVER_NAME=Bn;exports.BrowserCredentialsClient=xt;exports.BrowserProfilesClient=It;exports.DEFAULT_REASONING_EFFORT=ur;exports.EVAL_SANDBOX_PROVIDERS=yi;exports.Evolve=Ke;exports.EvolveApiError=re;exports.EvolveConfigError=W;exports.EvolveDigestMismatchError=Ve;exports.EvolveIncompleteDownloadError=Ge;exports.HOSTED_ERROR_CODES=Hn;exports.JUDGE_PROMPT=xn;exports.MANAGED_SANDBOX_PROVIDERS=Ye;exports.NoActiveVersionError=Bt;exports.Pipeline=At;exports.REASONING_EFFORTS=cr;exports.RETRY_FEEDBACK_PROMPT=Cn;exports.SCHEMA_PROMPT=Yr;exports.SWARM_RESULT_BRAND=ee;exports.SYSTEM_PROMPT=Wr;exports.Semaphore=me;exports.Swarm=qn;exports.SwarmResultList=fe;exports.TRIAL_ARTIFACT_STREAMS=wi;exports.TRIAL_STATUSES=hi;exports.TerminalPipeline=Ot;exports.VALIDATION_PRESETS=Ft;exports.VERIFY_PROMPT=kn;exports.WORKSPACE_PROMPT=Hr;exports.WORKSPACE_SWE_PROMPT=zr;exports.agents=Mi;exports.applyTemplate=q;exports.auth=Yl;exports.browserCredentials=Nn;exports.browserProfiles=Gn;exports.buildWorkerSystemPrompt=En;exports.createAgentParser=Q;exports.createClaudeParser=ct;exports.createCodexParser=dt;exports.createDroidParser=ut;exports.createGeminiParser=pt;exports.datasets=Oi;exports.executeWithRetry=D;exports.expandPath=M;exports.getAgentConfig=O;exports.getMcpSettingsDir=V;exports.getMcpSettingsPath=J;exports.harnessEffortVocabulary=ji;exports.hosted=Ql;exports.isAgentWorkUpdate=Cr;exports.isHostedErrorCode=Mt;exports.isValidAgentType=Ht;exports.isZodSchema=N;exports.jobs=Di;exports.jsonSchemaToString=ae;exports.managedSandbox=Io;exports.managedSecrets=Kn;exports.meta=$i;exports.parseNdjsonLine=xo;exports.parseNdjsonOutput=ko;exports.parseQwenOutput=kr;exports.readLocalDir=Er;exports.resolveStorageConfig=St;exports.saveLocalDir=Rr;exports.sessions=hl;exports.storage=_a;exports.trials=Ui;exports.writeClaudeMcpConfig=tt;exports.writeCodexMcpConfig=at;exports.writeDroidGatewaySettings=ot;exports.writeDroidMcpConfig=it;exports.writeGeminiMcpConfig=nt;exports.writeMcpConfig=rn;exports.writeQwenMcpConfig=rt;exports.zodSchemaToJson=oe;