@evolvingmachines/sdk 0.0.46 → 0.0.48

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,9 +1,9 @@
1
- 'use strict';var events=require('events'),cs=require('ajv'),crypto=require('crypto'),Xr=require('zod-to-json-schema'),$=require('fs'),oe=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 cs__default=/*#__PURE__*/_interopDefault(cs);var Xr__default=/*#__PURE__*/_interopDefault(Xr);var $__namespace=/*#__PURE__*/_interopNamespace($);var oe__namespace=/*#__PURE__*/_interopNamespace(oe);var yr={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},We={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};function Je(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function He(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 wr(t){return Je(t)?"--thinking":"--no-thinking"}function vr(t){let e=He(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:"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 ":"",o=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${s}--model ${e}${o} --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 ":"",o=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${o} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k2.6",models:[{alias:"kimi-k2.6",modelId:"moonshot/kimi-k2.6",description:"Latest: long-horizon coding, swarm orchestration"},{alias:"kimi-k2.6-turbo",modelId:"kimi-k2.6-turbo",description:"Evolve-managed Kimi K2.6 turbo 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",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.6-turbo":"kimi-k2.6-turbo","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,reasoningEffort:s})=>{let o=n?"--continue ":"",l=r?"":"--config-file /home/user/.kimi/evolve-config.toml ";return `printf '%s' "${t}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${wr(s)} ${l}${o}`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-sonnet-4.6",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-sonnet-4.6",modelId:"openrouter/anthropic/claude-sonnet-4.6",description:"Anthropic Sonnet via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-4.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 o=n?"--continue ":"",l=e.startsWith("openrouter/")?e:`openrouter/${e}`,a=vr(s);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model ${l} --format json${a} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model litellm/${l} --format json${a} "${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:o})=>{let l=o?"":"--settings /home/user/.factory/evolve-settings.json ",a=o?e:"custom:Evolve-Gateway-0",c=s?` --reasoning-effort ${s}`:"",d=n&&r?`--session-id ${ze(r)} `:"";return `printf '%s' ${ze(t)} | droid ${l}exec ${d}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${ze(a)}${c}`}}};function D(t){let e=qe[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function br(t){return t in qe}function V(t){return t.replace(/^~/,"/home/user")}function ze(t){return `'${t.replace(/'/g,"'\\''")}'`}function B(t){let e=D(t);return `${V(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function U(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 Ye(t,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${t}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${t}" cannot specify both command and url`)}function ne(t){for(let[e,n]of Object.entries(t))Ye(e,n);}function re(t){return t.type?t.type:t.command?"stdio":"sse"}function Sr(t){let e=re(t);return {...t,type:e}}function xr(t){let{type:e,url:n,...r}=t;return re(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function kr(t){return {type:re(t),...t}}function Cr(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function _r(t){let e=re(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:o,envVars:l,...a}=t;if(e==="stdio"&&t.command)return {type:"stdio",...a};if(t.url){let c={...a,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??r;return d&&Object.keys(d).length>0&&(c.headers=d),c}return {type:e==="stdio"?"stdio":"http",...a}}async function Qe(t,e,n,r){ne(n);let s=U(e),o=B(e);await t.files.makeDir(s);let l={};try{let c=await t.files.read(o);typeof c=="string"&&(l=JSON.parse(c));}catch(c){if(!A(c))throw c}let a=Object.fromEntries(Object.entries(n).map(([c,d])=>[c,r(d)]));await t.files.write(o,JSON.stringify({...l,mcpServers:a},null,2));}async function we(t,e,n){ne(n);let r=U("claude"),s=B("claude"),o=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,kr(c)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:o},null,2)),await t.files.makeDir(r);let l={};try{let a=await t.files.read(s);typeof a=="string"&&(l=JSON.parse(a));}catch(a){if(!A(a))throw a}l.enableAllProjectMcpServers=true,await t.files.write(s,JSON.stringify(l,null,2));}async function ve(t,e){await Qe(t,"gemini",e,Sr);}async function be(t,e){await Qe(t,"qwen",e,xr);}async function Se(t,e,n,r){let s=U(e),o=B(e);await t.files.makeDir(s);let l={};try{let p=await t.files.read(o);typeof p=="string"&&(l=JSON.parse(p));}catch(p){if(!A(p))throw p}let a=n.split("."),c=l;for(let p=0;p<a.length-1;p++){let u=a[p];(typeof c[u]!="object"||c[u]===null)&&(c[u]={}),c=c[u];}let d=a[a.length-1],i=typeof c[d]=="object"&&c[d]!==null?c[d]:{};c[d]={...i,...r},await t.files.write(o,JSON.stringify(l,null,2));}async function Ze(t,e){let n=U("qwen"),r=B("qwen");await t.files.makeDir(n);let s={};try{let c=await t.files.read(r);typeof c=="string"&&(s=JSON.parse(c));}catch(c){if(!A(c))throw c}let o=s.model??{},l=o.generationConfig??{},a=l.extra_body??{};s.model={...o,generationConfig:{...l,extra_body:{...a,enable_thinking:e}}},await t.files.write(r,JSON.stringify(s,null,2));}async function Xe(t,e){await Qe(t,"kimi",e,Cr);}async function xe(t,e,n){ne(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let o={};try{let a=await t.files.read(s);typeof a=="string"&&(o=JSON.parse(a));}catch(a){if(!A(a))throw a}let l=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,_r(c)]));await t.files.write(s,JSON.stringify({...o,mcpServers:l},null,2));}async function ke(t,e,n){let r=V(e.settingsPath),s=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(s);let o={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(o,null,2));}async function et(t,e,n){ne(n);let r=`${e}/opencode.json`,s={};try{let l=await t.files.read(r);typeof l=="string"&&(s=JSON.parse(l));}catch(l){if(!A(l))throw l}let o=Object.fromEntries(Object.entries(n).map(([l,a])=>[l,Er(a)]));await t.files.write(r,JSON.stringify({...s,mcp:o},null,2));}function Er(t){let e=re(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 H(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Ce(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||E;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function tt(){return Ce("/api/managed/e2b")}function Ut(t){return {"browser-use":{type:"http",url:H("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var T="EVOLVE_API_KEY",_e="E2B_API_KEY",Ee="DAYTONA_API_KEY",Te="MODAL_TOKEN_ID",nt="MODAL_TOKEN_SECRET",Lt="claude",ie=36e5,Ft=4,rt=100,Nt="/home/user/workspace",E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",O="x-litellm-customer-id",L="x-litellm-tags",G="run:",Kt=".evolve-sdk/observability/sessions",jt=100,Vt=5e3,Re=3,it=1e3;function R(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>R(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,r])=>`${n} = ${R(r)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function Ie(t,e){for(let[c,d]of Object.entries(e))Ye(c,d);let n=U("codex"),r=B("codex");await t.files.makeDir(n);let s="";try{let c=await t.files.read(r);typeof c=="string"&&(s=c);}catch(c){if(!A(c))throw c}let o=[],l=[];s.includes("experimental_use_rmcp_client")||(o.push("# Enable improved RMCP client (recommended)"),o.push("experimental_use_rmcp_client = true")),s.includes("[mcp_servers]")||l.push("[mcp_servers]","");for(let[c,d]of Object.entries(e)){if(s.includes(`[mcp_servers.${c}]`))continue;l.push(`[mcp_servers.${c}]`);let i=d.type??(d.command?"stdio":"http");if(i==="http"||i==="sse"||!!d.url){if(!d.url)throw new Error(`MCP server "${c}" is missing url for ${i} transport`);l.push(`url = ${R(d.url)}`),d.bearerTokenEnvVar&&l.push(`bearer_token_env_var = ${R(d.bearerTokenEnvVar)}`);let u=d.httpHeaders??d.headers;u&&Object.keys(u).length>0&&l.push(`http_headers = ${R(u)}`),d.envHttpHeaders&&Object.keys(d.envHttpHeaders).length>0&&l.push(`env_http_headers = ${R(d.envHttpHeaders)}`);}else l.push(`command = ${R(d.command)}`),d.args&&d.args.length>0&&l.push(`args = ${R(d.args)}`),d.cwd&&l.push(`cwd = ${R(d.cwd)}`);d.env&&Object.keys(d.env).length>0&&l.push(`env = ${R(d.env)}`),d.envVars&&d.envVars.length>0&&l.push(`env_vars = ${R(d.envVars)}`),l.push("");}let a=[s.trim(),o.join(`
1
+ 'use strict';var events=require('events'),us=require('ajv'),crypto=require('crypto'),ri=require('zod-to-json-schema'),$=require('fs'),oe=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 us__default=/*#__PURE__*/_interopDefault(us);var ri__default=/*#__PURE__*/_interopDefault(ri);var $__namespace=/*#__PURE__*/_interopNamespace($);var oe__namespace=/*#__PURE__*/_interopNamespace(oe);var Sr={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},We={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};function He(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function qe(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 xr(t){return He(t)?"--thinking":"--no-thinking"}function kr(t){let e=qe(t);return e?` --variant ${e} --thinking`:""}var Ye={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 ":"",o=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${s}--model ${e}${o} --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 ":"",o=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${o} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k2.6",models:[{alias:"kimi-k2.6",modelId:"moonshot/kimi-k2.6",description:"Latest: long-horizon coding, swarm orchestration"},{alias:"kimi-k2.6-turbo",modelId:"kimi-k2.6-turbo",description:"Evolve-managed Kimi K2.6 turbo 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",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.6-turbo":"kimi-k2.6-turbo","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,reasoningEffort:s})=>{let o=n?"--continue ":"",l=r?"":"--config-file /home/user/.kimi/evolve-config.toml ";return `printf '%s' "${t}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${xr(s)} ${l}${o}`}},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 o=n?"--continue ":"",l=e.startsWith("openrouter/")?e:`openrouter/${e}`,a=kr(s);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model ${l} --format json${a} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model litellm/${l} --format json${a} "${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:o})=>{let l=o?"":"--settings /home/user/.factory/evolve-settings.json ",a=o?e:"custom:Evolve-Gateway-0",c=s?` --reasoning-effort ${s}`:"",d=n&&r?`--session-id ${Je(r)} `:"";return `printf '%s' ${Je(t)} | droid ${l}exec ${d}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${Je(a)}${c}`}}};function D(t){let e=Ye[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function Cr(t){return t in Ye}function V(t){return t.replace(/^~/,"/home/user")}function Je(t){return `'${t.replace(/'/g,"'\\''")}'`}function B(t){let e=D(t);return `${V(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function U(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 Qe(t,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${t}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${t}" cannot specify both command and url`)}function ne(t){for(let[e,n]of Object.entries(t))Qe(e,n);}function re(t){return t.type?t.type:t.command?"stdio":"sse"}function _r(t){let e=re(t);return {...t,type:e}}function Er(t){let{type:e,url:n,...r}=t;return re(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function Tr(t){return {type:re(t),...t}}function Rr(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function Ir(t){let e=re(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:o,envVars:l,...a}=t;if(e==="stdio"&&t.command)return {type:"stdio",...a};if(t.url){let c={...a,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??r;return d&&Object.keys(d).length>0&&(c.headers=d),c}return {type:e==="stdio"?"stdio":"http",...a}}async function Ze(t,e,n,r){ne(n);let s=U(e),o=B(e);await t.files.makeDir(s);let l={};try{let c=await t.files.read(o);typeof c=="string"&&(l=JSON.parse(c));}catch(c){if(!A(c))throw c}let a=Object.fromEntries(Object.entries(n).map(([c,d])=>[c,r(d)]));await t.files.write(o,JSON.stringify({...l,mcpServers:a},null,2));}async function we(t,e,n){ne(n);let r=U("claude"),s=B("claude"),o=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,Tr(c)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:o},null,2)),await t.files.makeDir(r);let l={};try{let a=await t.files.read(s);typeof a=="string"&&(l=JSON.parse(a));}catch(a){if(!A(a))throw a}l.enableAllProjectMcpServers=true,await t.files.write(s,JSON.stringify(l,null,2));}async function be(t,e){await Ze(t,"gemini",e,_r);}async function ve(t,e){await Ze(t,"qwen",e,Er);}async function Se(t,e,n,r){let s=U(e),o=B(e);await t.files.makeDir(s);let l={};try{let p=await t.files.read(o);typeof p=="string"&&(l=JSON.parse(p));}catch(p){if(!A(p))throw p}let a=n.split("."),c=l;for(let p=0;p<a.length-1;p++){let u=a[p];(typeof c[u]!="object"||c[u]===null)&&(c[u]={}),c=c[u];}let d=a[a.length-1],i=typeof c[d]=="object"&&c[d]!==null?c[d]:{};c[d]={...i,...r},await t.files.write(o,JSON.stringify(l,null,2));}async function Xe(t,e){let n=U("qwen"),r=B("qwen");await t.files.makeDir(n);let s={};try{let c=await t.files.read(r);typeof c=="string"&&(s=JSON.parse(c));}catch(c){if(!A(c))throw c}let o=s.model??{},l=o.generationConfig??{},a=l.extra_body??{};s.model={...o,generationConfig:{...l,extra_body:{...a,enable_thinking:e}}},await t.files.write(r,JSON.stringify(s,null,2));}async function et(t,e){await Ze(t,"kimi",e,Rr);}async function xe(t,e,n){ne(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let o={};try{let a=await t.files.read(s);typeof a=="string"&&(o=JSON.parse(a));}catch(a){if(!A(a))throw a}let l=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,Ir(c)]));await t.files.write(s,JSON.stringify({...o,mcpServers:l},null,2));}async function ke(t,e,n){let r=V(e.settingsPath),s=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(s);let o={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(o,null,2));}async function tt(t,e,n){ne(n);let r=`${e}/opencode.json`,s={};try{let l=await t.files.read(r);typeof l=="string"&&(s=JSON.parse(l));}catch(l){if(!A(l))throw l}let o=Object.fromEntries(Object.entries(n).map(([l,a])=>[l,Pr(a)]));await t.files.write(r,JSON.stringify({...s,mcp:o},null,2));}function Pr(t){let e=re(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 H(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Ce(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||_;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function nt(){return Ce("/api/managed/e2b")}function Ft(t){return {"browser-use":{type:"http",url:H("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var T="EVOLVE_API_KEY",_e="E2B_API_KEY",Ee="DAYTONA_API_KEY",Te="MODAL_TOKEN_ID",rt="MODAL_TOKEN_SECRET",Nt="claude",ie=36e5,Kt=4,it=100,jt="/home/user/workspace",_=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",O="x-litellm-customer-id",L="x-litellm-tags",G="run:",Vt=".evolve-sdk/observability/sessions",Gt=100,zt=5e3,Re=3,st=1e3;function R(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>R(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,r])=>`${n} = ${R(r)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function Ie(t,e){for(let[c,d]of Object.entries(e))Qe(c,d);let n=U("codex"),r=B("codex");await t.files.makeDir(n);let s="";try{let c=await t.files.read(r);typeof c=="string"&&(s=c);}catch(c){if(!A(c))throw c}let o=[],l=[];s.includes("experimental_use_rmcp_client")||(o.push("# Enable improved RMCP client (recommended)"),o.push("experimental_use_rmcp_client = true")),s.includes("[mcp_servers]")||l.push("[mcp_servers]","");for(let[c,d]of Object.entries(e)){if(s.includes(`[mcp_servers.${c}]`))continue;l.push(`[mcp_servers.${c}]`);let i=d.type??(d.command?"stdio":"http");if(i==="http"||i==="sse"||!!d.url){if(!d.url)throw new Error(`MCP server "${c}" is missing url for ${i} transport`);l.push(`url = ${R(d.url)}`),d.bearerTokenEnvVar&&l.push(`bearer_token_env_var = ${R(d.bearerTokenEnvVar)}`);let u=d.httpHeaders??d.headers;u&&Object.keys(u).length>0&&l.push(`http_headers = ${R(u)}`),d.envHttpHeaders&&Object.keys(d.envHttpHeaders).length>0&&l.push(`env_http_headers = ${R(d.envHttpHeaders)}`);}else l.push(`command = ${R(d.command)}`),d.args&&d.args.length>0&&l.push(`args = ${R(d.args)}`),d.cwd&&l.push(`cwd = ${R(d.cwd)}`);d.env&&Object.keys(d.env).length>0&&l.push(`env = ${R(d.env)}`),d.envVars&&d.envVars.length>0&&l.push(`env_vars = ${R(d.envVars)}`),l.push("");}let a=[s.trim(),o.join(`
2
2
  `),l.join(`
3
3
  `)].filter(c=>c.length>0);await t.files.write(r,a.join(`
4
4
 
5
5
  `)+`
6
- `);}async function st(t,e,n){let r=U("codex"),s=B("codex");await t.files.makeDir(r);let o="";try{let m=await t.files.read(s);typeof m=="string"&&(o=m);}catch(m){if(!A(m))throw m}let l=o.search(/^\[/m),a=l>=0?o.slice(0,l):o,c=l>=0?o.slice(l):"",d=o.includes("[model_providers.evolve-gateway]"),i=/^model_provider\s*=\s*"evolve-gateway"/m.test(a);if(d&&i)return;o=(a.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
6
+ `);}async function ot(t,e,n){let r=U("codex"),s=B("codex");await t.files.makeDir(r);let o="";try{let m=await t.files.read(s);typeof m=="string"&&(o=m);}catch(m){if(!A(m))throw m}let l=o.search(/^\[/m),a=l>=0?o.slice(0,l):o,c=l>=0?o.slice(l):"",d=o.includes("[model_providers.evolve-gateway]"),i=/^model_provider\s*=\s*"evolve-gateway"/m.test(a);if(d&&i)return;o=(a.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
7
7
 
8
8
  `)+c).replace(/^\n+/,"");let u='model_provider = "evolve-gateway"',g=d?"":["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${R(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${R({[O]:n.sessionTagEnv,[L]:n.runTagEnv})}`].join(`
9
9
  `),f;if(!o.trim())f=g?`${u}
@@ -19,34 +19,34 @@ ${g}
19
19
  `+u,g&&(f=f.trimEnd()+`
20
20
 
21
21
  `+g),f+=`
22
- `;}await t.files.write(s,f);}async function ot(t,e,n){let r=V(e.configPath),s=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(s);let o=[`default_model = ${R(e.modelName)}`,"",`[providers.${e.providerName}]`,'type = "kimi"','base_url = ""','api_key = ""',`custom_headers = ${R(n)}`,"",`[models.${e.modelName}]`,`provider = ${R(e.providerName)}`,'model = ""',`max_context_size = ${e.maxContextSize}`].join(`
22
+ `;}await t.files.write(s,f);}async function at(t,e,n){let r=V(e.configPath),s=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(s);let o=[`default_model = ${R(e.modelName)}`,"",`[providers.${e.providerName}]`,'type = "kimi"','base_url = ""','api_key = ""',`custom_headers = ${R(n)}`,"",`[models.${e.modelName}]`,`provider = ${R(e.providerName)}`,'model = ""',`max_context_size = ${e.maxContextSize}`].join(`
23
23
  `)+`
24
- `;await t.files.write(r,o);}async function at(t,e,n,r){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await we(e,n,r);break;case "codex":await Ie(e,r);break;case "gemini":await ve(e,r);break;case "qwen":await be(e,r);break;case "kimi":await Xe(e,r);break;case "opencode":await et(e,n,r);break;case "droid":await xe(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Pe(){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(c,d,i){if(typeof c=="string")return d==="user"?null:[{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let p=[];for(let u of c){let g=null;switch(u.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:u.source?.type==="base64"?u.source.data:"",mimeType:u.source?.type==="base64"?u.source.media_type:"",uri:u.source?.type==="url"?u.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[u.id]=u,u.name==="TodoWrite")Array.isArray(u.input?.todos)&&(g={sessionUpdate:"plan",entries:l(u.input)});else {let 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(c){let d=c.name,i=c.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(c,d){let i=c.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:a(p.text)}:o(p,false)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:a(i)}}]}:{};case "Edit":case "Write":case "Bash":return s(i,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return s(i,"is_error"in c?c.is_error:false)}}function s(c,d=false){return Array.isArray(c)&&c.length>0?{content:c.map(i=>({type:"content",content:o(i,d)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+c+"\n```":c}}]}:{}}function o(c,d){if(c.type==="text")return d?{type:"text",text:"```\n"+c.text+"\n```"}:{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return {type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return {type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function l(c){return c.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function a(c){let d="```",i=Array.from(c.matchAll(/^```+/gm));for(let[p]of i)for(;p.length>=d.length;)d+="`";return d+`
24
+ `;await t.files.write(r,o);}async function ct(t,e,n,r){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await we(e,n,r);break;case "codex":await Ie(e,r);break;case "gemini":await be(e,r);break;case "qwen":await ve(e,r);break;case "kimi":await et(e,r);break;case "opencode":await tt(e,n,r);break;case "droid":await xe(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Pe(){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(c,d,i){if(typeof c=="string")return d==="user"?null:[{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let p=[];for(let u of c){let g=null;switch(u.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:u.source?.type==="base64"?u.source.data:"",mimeType:u.source?.type==="base64"?u.source.media_type:"",uri:u.source?.type==="url"?u.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[u.id]=u,u.name==="TodoWrite")Array.isArray(u.input?.todos)&&(g={sessionUpdate:"plan",entries:l(u.input)});else {let 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(c){let d=c.name,i=c.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(c,d){let i=c.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:a(p.text)}:o(p,false)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:a(i)}}]}:{};case "Edit":case "Write":case "Bash":return s(i,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return s(i,"is_error"in c?c.is_error:false)}}function s(c,d=false){return Array.isArray(c)&&c.length>0?{content:c.map(i=>({type:"content",content:o(i,d)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+c+"\n```":c}}]}:{}}function o(c,d){if(c.type==="text")return d?{type:"text",text:"```\n"+c.text+"\n```"}:{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return {type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return {type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function l(c){return c.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function a(c){let d="```",i=Array.from(c.matchAll(/^```+/gm));for(let[p]of i)for(;p.length>=d.length;)d+="`";return d+`
25
25
  `+c+(c.endsWith(`
26
26
  `)?"":`
27
27
  `)+d}}function Oe(){return function(c){let d;try{d=JSON.parse(c);}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(a){let c=a.id;switch(a.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${a.server}:${a.tool}`},{sessionUpdate:"tool_call",toolCallId:c,title:`${a.server}: ${a.tool}`,kind:"other",status:"in_progress",rawInput:a.arguments,content:[]};case "command_execution":return {type:"command_execution",name:a.command},{sessionUpdate:"tool_call",toolCallId:c,title:a.command?`\`${a.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:a.command},content:[]};case "web_search":return {type:"web_search",name:a.query},{sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${a.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(a.items)};default:return null}}function n(a){return a.type==="todo_list"?{sessionUpdate:"plan",entries:l(a.items)}:null}function r(a){let c=a.id;switch(a.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a.text??a.summary?.join(`
28
28
  `)??a.content?.join(`
29
- `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:a.text??""}};case "mcp_tool_call":{let i=s(a.result),p=a.status==="failed"||a.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:i}}case "command_execution":{let i=a.aggregated_output?[{type:"content",content:{type:"text",text:a.aggregated_output}}]:[],p=a.status==="completed"||a.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:i}}case "file_change":{let i=a.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:c,title:u,kind:"edit",status:a.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:c,title:`Search: ${a.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(a.items)};default:return null}}function s(a){return a?.content?Array.isArray(a.content)?a.content.map(c=>({type:"content",content:o(c)})):typeof a.content=="string"?[{type:"content",content:{type:"text",text:a.content}}]:[]:[]}function o(a){return a.type==="text"?{type:"text",text:a.text??""}:a.type==="image"?{type:"image",data:a.data??"",mimeType:a.mime_type??a.mimeType??"",uri:a.uri}:a}function l(a){if(!Array.isArray(a))return [];let c=false;return a.map(d=>{let i;return d.completed?i="completed":c?i="pending":(i="in_progress",c=true),{content:d.text??"",status:i,priority:"medium"}})}}var Tr={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"},Rr=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 Ae(){let t=new Map,e,n=false,r="",s;return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(!Jt(a))return null;let c=Ir(a);if(c.sessionId&&(e=c.sessionId),c.errorText)return [j(e,c.errorText)];if(c.resultText)return r=c.resultText,n=true,[j(e,c.resultText)];if(c.handled)return null;let i=Pr(a)??a,p=zt(i);p&&(e=p);let u=[],g=k(i,"type");switch(g){case "system":return null;case "message":{let f=k(i,"role"),m=k(i,"text")||lt(i.content);if(!m)break;f==="assistant"&&(n=true,r=m,u.push(j(e,m)));break}case "completion":{let f=k(i,"finalText")||k(i,"result");f&&(!n||f!==r)&&(n=true,r=f,u.push(j(e,f)));break}case "assistant_text_delta":{let f=k(i,"textDelta")||k(i,"text");f&&(n=true,r+=f,u.push(j(e,f)));break}case "thinking_text_delta":{let f=k(i,"textDelta")||k(i,"text");if(f){let m=Gt(i,f,s);m&&(s=m.signature,u.push({sessionId:e,update:m.event}));}break}case "reasoning":{let f=k(i,"text");if(f){let m=Gt(i,f,s);m&&(s=m.signature,u.push({sessionId:e,update:m.event}));}break}case "assistant":{let f=k(i,"text")||lt(I(i.message)?.content);f&&(n=true,r=f,u.push(j(e,f)));break}case "tool_call":case "tool_call_delta":{let f=I(i.toolUse)??I(i.tool_use)??i,m=Wt(f,t);m&&u.push({sessionId:e,update:m});break}case "tool_result":{let f=Ar(i,t);f&&u.push({sessionId:e,update:f});break}case "tool_progress_update":case "tool_progress":{let f=Mr(i);f&&u.push({sessionId:e,update:f});break}case "create_message":{for(let f of Or(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=se(i.result??i.text??i.error);f&&(n=true,r=f,u.push(j(e,f)));break}case "error":{let f=se(i.message??i.error??i);f&&u.push(j(e,f));break}default:if(g&&!Rr.has(g))return null}return u.length>0&&g!=="reasoning"&&g!=="thinking_text_delta"&&(s=void 0),u.length>0?u:null}}function Gt(t,e,n){let r=ct(t,"id")||ct(t,"messageId"),s=ct(t,"blockIndex"),o=`${k(t,"type")}:${r}:${s}:${e}`;return o===n?null:{signature:o,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function Ir(t){if(t.type!=="response")return {handled:false};let e=I(t.result),n=I(t.error),r=zt(e??t);if(n)return {handled:true,sessionId:r,errorText:se(n.message??n)};let s=e?k(e,"finalText")||k(e,"result"):"";return {handled:true,sessionId:r,resultText:s}}function Pr(t){return t.method!=="droid.session_notification"?null:I(I(t.params)?.notification)}function Or(t,e){let n=I(t.message);if(!n)return [];let r=[],s=n.content;if(Array.isArray(s))for(let o of s){let l=I(o);if(l&&l.type==="tool_use"){let a=Wt(l,e);a&&r.push(a);}}if(n.role==="assistant"){let o=lt(s);o&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}});}return r}function Wt(t,e){let n=k(t,"id")||k(t,"toolUseId")||k(t,"tool_use_id"),r=k(t,"name")||k(t,"toolName")||k(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let s=I(t.input)??I(t.toolInput)??I(t.arguments)??{};if(Ht(r)==="todowrite"){let d=$r(s);if(d)return d}let{title:o,kind:l,content:a,locations:c}=Dr(r,s);return {sessionUpdate:"tool_call",toolCallId:n,title:o,kind:l,status:"pending",rawInput:s,content:a,locations:c}}function Ar(t,e){let n=k(t,"toolUseId")||k(t,"tool_use_id")||k(t,"tool_id");if(!n)return null;let r=k(t,"toolName")||k(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:dt(t.content??t.result??t.error)}}function Mr(t){let e=k(t,"toolUseId")||k(t,"tool_use_id")||k(t,"tool_id");if(!e)return null;let n=I(t.update),r=se(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?dt(r):void 0}}function $r(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let s=I(r);if(!s)return [];let o=k(s,"content"),l=Br(k(s,"status")),a=Ur(k(s,"priority"));return o?[{content:o,status:l,priority:a}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function Dr(t,e){let n=Tr[Ht(t)]||"other",r=k(e,"path")||k(e,"filePath")||k(e,"file_path")||k(e,"absolute_path"),s=k(e,"command"),o=k(e,"url"),l=r||s||o;return {title:l?`${t} ${l}`:t,kind:n,content:Object.keys(e).length>0?dt(e):[],locations:r?[{path:r}]:[]}}function zt(t){if(t)return k(t,"session_id")||k(t,"sessionId")}function j(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function lt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=I(e);return n?k(n,"text")||k(n,"content"):""}).filter(Boolean).join(""):""}function dt(t){let e=se(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function se(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function Jt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function I(t){return Jt(t)?t:null}function k(t,e){let n=t[e];return typeof n=="string"?n:""}function ct(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function Ht(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Br(t){return t==="in_progress"||t==="completed"?t:"pending"}function Ur(t){return t==="high"||t==="low"?t:"medium"}var Lr={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 Me(){return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(a._meta||a._prompt)return null;let c=a.session_id,d=[];switch(a.type){case "init":case "result":return null;case "message":{let i=t(a);i&&d.push({sessionId:c,update:i});break}case "tool_use":{let i=e(a);i&&d.push({sessionId:c,update:i});break}case "tool_result":{let i=n(a);i&&d.push({sessionId:c,update:i});break}case "error":{let i=r(a);i&&d.push({sessionId:c,update:i});break}default:return null}return d.length>0?d:null};function t(o){let l=o.role,a=o.content;return a?l==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}:l==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:a}}:null:null}function e(o){let l=o.tool_id,a=o.tool_name,c=o.parameters||{},{title:d,kind:i,content:p,locations:u}=s(a,c);return {sessionUpdate:"tool_call",toolCallId:l,title:d,kind:i,status:"pending",rawInput:c,content:p,locations:u}}function n(o){let l=o.tool_id,a=o.status,c=o.output,d=o.error,i=[];return c&&typeof c=="string"&&c.length>0&&i.push({type:"content",content:{type:"text",text:a==="error"?`\`\`\`
29
+ `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:a.text??""}};case "mcp_tool_call":{let i=s(a.result),p=a.status==="failed"||a.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:i}}case "command_execution":{let i=a.aggregated_output?[{type:"content",content:{type:"text",text:a.aggregated_output}}]:[],p=a.status==="completed"||a.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:p,content:i}}case "file_change":{let i=a.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:c,title:u,kind:"edit",status:a.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:c,title:`Search: ${a.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(a.items)};default:return null}}function s(a){return a?.content?Array.isArray(a.content)?a.content.map(c=>({type:"content",content:o(c)})):typeof a.content=="string"?[{type:"content",content:{type:"text",text:a.content}}]:[]:[]}function o(a){return a.type==="text"?{type:"text",text:a.text??""}:a.type==="image"?{type:"image",data:a.data??"",mimeType:a.mime_type??a.mimeType??"",uri:a.uri}:a}function l(a){if(!Array.isArray(a))return [];let c=false;return a.map(d=>{let i;return d.completed?i="completed":c?i="pending":(i="in_progress",c=true),{content:d.text??"",status:i,priority:"medium"}})}}var Or={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"},Ar=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 Ae(){let t=new Map,e,n=false,r="",s;return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(!qt(a))return null;let c=Mr(a);if(c.sessionId&&(e=c.sessionId),c.errorText)return [j(e,c.errorText)];if(c.resultText)return r=c.resultText,n=true,[j(e,c.resultText)];if(c.handled)return null;let i=$r(a)??a,p=Ht(i);p&&(e=p);let u=[],g=k(i,"type");switch(g){case "system":return null;case "message":{let f=k(i,"role"),m=k(i,"text")||dt(i.content);if(!m)break;f==="assistant"&&(n=true,r=m,u.push(j(e,m)));break}case "completion":{let f=k(i,"finalText")||k(i,"result");f&&(!n||f!==r)&&(n=true,r=f,u.push(j(e,f)));break}case "assistant_text_delta":{let f=k(i,"textDelta")||k(i,"text");f&&(n=true,r+=f,u.push(j(e,f)));break}case "thinking_text_delta":{let f=k(i,"textDelta")||k(i,"text");if(f){let m=Wt(i,f,s);m&&(s=m.signature,u.push({sessionId:e,update:m.event}));}break}case "reasoning":{let f=k(i,"text");if(f){let m=Wt(i,f,s);m&&(s=m.signature,u.push({sessionId:e,update:m.event}));}break}case "assistant":{let f=k(i,"text")||dt(I(i.message)?.content);f&&(n=true,r=f,u.push(j(e,f)));break}case "tool_call":case "tool_call_delta":{let f=I(i.toolUse)??I(i.tool_use)??i,m=Jt(f,t);m&&u.push({sessionId:e,update:m});break}case "tool_result":{let f=Br(i,t);f&&u.push({sessionId:e,update:f});break}case "tool_progress_update":case "tool_progress":{let f=Ur(i);f&&u.push({sessionId:e,update:f});break}case "create_message":{for(let f of Dr(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=se(i.result??i.text??i.error);f&&(n=true,r=f,u.push(j(e,f)));break}case "error":{let f=se(i.message??i.error??i);f&&u.push(j(e,f));break}default:if(g&&!Ar.has(g))return null}return u.length>0&&g!=="reasoning"&&g!=="thinking_text_delta"&&(s=void 0),u.length>0?u:null}}function Wt(t,e,n){let r=lt(t,"id")||lt(t,"messageId"),s=lt(t,"blockIndex"),o=`${k(t,"type")}:${r}:${s}:${e}`;return o===n?null:{signature:o,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function Mr(t){if(t.type!=="response")return {handled:false};let e=I(t.result),n=I(t.error),r=Ht(e??t);if(n)return {handled:true,sessionId:r,errorText:se(n.message??n)};let s=e?k(e,"finalText")||k(e,"result"):"";return {handled:true,sessionId:r,resultText:s}}function $r(t){return t.method!=="droid.session_notification"?null:I(I(t.params)?.notification)}function Dr(t,e){let n=I(t.message);if(!n)return [];let r=[],s=n.content;if(Array.isArray(s))for(let o of s){let l=I(o);if(l&&l.type==="tool_use"){let a=Jt(l,e);a&&r.push(a);}}if(n.role==="assistant"){let o=dt(s);o&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}});}return r}function Jt(t,e){let n=k(t,"id")||k(t,"toolUseId")||k(t,"tool_use_id"),r=k(t,"name")||k(t,"toolName")||k(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let s=I(t.input)??I(t.toolInput)??I(t.arguments)??{};if(Yt(r)==="todowrite"){let d=Lr(s);if(d)return d}let{title:o,kind:l,content:a,locations:c}=Fr(r,s);return {sessionUpdate:"tool_call",toolCallId:n,title:o,kind:l,status:"pending",rawInput:s,content:a,locations:c}}function Br(t,e){let n=k(t,"toolUseId")||k(t,"tool_use_id")||k(t,"tool_id");if(!n)return null;let r=k(t,"toolName")||k(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:pt(t.content??t.result??t.error)}}function Ur(t){let e=k(t,"toolUseId")||k(t,"tool_use_id")||k(t,"tool_id");if(!e)return null;let n=I(t.update),r=se(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?pt(r):void 0}}function Lr(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let s=I(r);if(!s)return [];let o=k(s,"content"),l=Nr(k(s,"status")),a=Kr(k(s,"priority"));return o?[{content:o,status:l,priority:a}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function Fr(t,e){let n=Or[Yt(t)]||"other",r=k(e,"path")||k(e,"filePath")||k(e,"file_path")||k(e,"absolute_path"),s=k(e,"command"),o=k(e,"url"),l=r||s||o;return {title:l?`${t} ${l}`:t,kind:n,content:Object.keys(e).length>0?pt(e):[],locations:r?[{path:r}]:[]}}function Ht(t){if(t)return k(t,"session_id")||k(t,"sessionId")}function j(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function dt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=I(e);return n?k(n,"text")||k(n,"content"):""}).filter(Boolean).join(""):""}function pt(t){let e=se(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function se(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function qt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function I(t){return qt(t)?t:null}function k(t,e){let n=t[e];return typeof n=="string"?n:""}function lt(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function Yt(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Nr(t){return t==="in_progress"||t==="completed"?t:"pending"}function Kr(t){return t==="high"||t==="low"?t:"medium"}var jr={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 Me(){return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(a._meta||a._prompt)return null;let c=a.session_id,d=[];switch(a.type){case "init":case "result":return null;case "message":{let i=t(a);i&&d.push({sessionId:c,update:i});break}case "tool_use":{let i=e(a);i&&d.push({sessionId:c,update:i});break}case "tool_result":{let i=n(a);i&&d.push({sessionId:c,update:i});break}case "error":{let i=r(a);i&&d.push({sessionId:c,update:i});break}default:return null}return d.length>0?d:null};function t(o){let l=o.role,a=o.content;return a?l==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}:l==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:a}}:null:null}function e(o){let l=o.tool_id,a=o.tool_name,c=o.parameters||{},{title:d,kind:i,content:p,locations:u}=s(a,c);return {sessionUpdate:"tool_call",toolCallId:l,title:d,kind:i,status:"pending",rawInput:c,content:p,locations:u}}function n(o){let l=o.tool_id,a=o.status,c=o.output,d=o.error,i=[];return c&&typeof c=="string"&&c.length>0&&i.push({type:"content",content:{type:"text",text:a==="error"?`\`\`\`
30
30
  ${c}
31
31
  \`\`\``:c}}),d?.message&&!c&&i.push({type:"content",content:{type:"text",text:`\`\`\`
32
32
  ${d.message}
33
- \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:l,status:a==="success"?"completed":"failed",content:i}}function r(o){let l=o.severity,a=o.message;return a?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${l==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${a}`}}:null}function s(o,l){let a=Lr[o]||"other",c=[],d=[],i=o;switch(o){case "read_file":i=`Read ${l.absolute_path||l.file_path||"file"}`,(l.absolute_path||l.file_path)&&d.push({path:l.absolute_path||l.file_path});break;case "write_file":i=`Write ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),c.push({type:"diff",path:l.file_path,oldText:null,newText:l.content||""}));break;case "edit_file":i=`Edit ${l.file_path||"file"}`,l.file_path&&d.push({path:l.file_path});break;case "replace":i=`Edit ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),(l.old_string!==void 0||l.new_string!==void 0)&&c.push({type:"diff",path:l.file_path,oldText:l.old_string||"",newText:l.new_string||""}));break;case "run_shell_command":case "shell":i=l.command?`\`${l.command}\``:"Run command",l.description&&c.push({type:"content",content:{type:"text",text:l.description}});break;case "brave_web_search":case "web_search":case "google_web_search":i=l.query?`"${l.query}"`:"Web search";break;case "web_fetch":i=l.prompt?`Fetch: ${l.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${l.pattern||"files"}`,l.dir_path&&d.push({path:l.dir_path});break;case "grep":case "search_file_content":i=`grep "${l.pattern||l.query||""}"`;break;case "list_directory":i=`List ${l.dir_path||l.path||"directory"}`,(l.dir_path||l.path)&&d.push({path:l.dir_path||l.path});break;case "read_many_files":i=`Read ${l.include?.length||"multiple"} files`,Array.isArray(l.include)&&l.include.forEach(p=>d.push({path:p}));break;case "delegate_to_agent":i=l.agent_name?`Agent: ${l.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=l.fact?`Remember: "${l.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=l.name?`Activate skill: ${l.name}`:"Activate skill";break;default:i=o;}return {title:i,kind:a,content:c,locations:d}}}var Fr={ReadFile:"read",ReadMediaFile:"read",WriteFile:"edit",StrReplaceFile:"edit",Shell:"execute",Glob:"search",Grep:"search",SearchWeb:"fetch",FetchURL:"fetch",Task:"think",Think:"think",CreateSubagent:"think",SetTodoList:"other"};function ut(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function Yt(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 gt(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=Yt(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 pt(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=gt(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=gt(t);n&&e.push(n);}return e}function Nr(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&ut(e.content.text))}function Kr(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=Yt(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 jr(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function qt(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:jr(s),priority:"medium"}}).filter(n=>n!==null):[]}function ft(){let t=new Set,e=0;function n(a,c){return typeof a=="string"&&a.length>0?a:(e+=1,`kimi_${c.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(c){let d;try{d=JSON.parse(c);}catch{return null}if(!d||typeof d!="object"||"_meta"in d||"_prompt"in d)return null;let i=d.role;return i==="assistant"?r(d):i==="tool"?s(d):typeof d.type=="string"&&"payload"in d?o(d):null};function r(a){let c=[],d=a.content,i=a.tool_calls;if(typeof d=="string"&&d.length>0)c.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let p of d){let u=Kr(p);u&&c.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(g==="SetTodoList"){let S=qt(m);S.length>0&&c.push({update:{sessionUpdate:"plan",entries:S}}),t.add(f);continue}let{title:h,kind:y,toolContent:w,locations:x}=l(g,typeof m=="object"&&m!==null?m:{});c.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:m,content:w,locations:x}});}return c.length>0?c:null}function s(a){let c=a.tool_call_id;if(typeof c!="string"||c.length===0)return null;if(t.has(c))return t.delete(c),null;let d=a.content,i=[],p=false;if(typeof d=="string")p=ut(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=gt(u);g&&(g.type==="content"&&g.content.type==="text"&&ut(g.content.text)&&(p=true),i.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:c,status:p?"failed":"completed",content:i}}]}function o(a){let c=a.type,d=a.payload??{},i=[];switch(c){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(p==="SetTodoList"){let x=qt(f);x.length>0&&i.push({update:{sessionUpdate:"plan",entries:x}}),t.add(u);break}let{title:m,kind:h,toolContent:y,locations:w}=l(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(...pt(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(...pt(u));}else g.push(...pt(u));f=f||Nr(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 l(a,c){let d=Fr[a]||"other",i=[],p=[],u=a;switch(a){case "ReadFile":{let g=c.path??c.file_path;u=`Read ${g||"file"}`,g&&p.push({path:g});break}case "ReadMediaFile":{let g=c.path??c.file_path;u=`Read media ${g||"file"}`,g&&p.push({path:g});break}case "WriteFile":{let g=c.path??c.file_path;u=`Write ${g||"file"}`,g&&(p.push({path:g}),typeof c.content=="string"&&i.push({type:"diff",path:g,oldText:null,newText:c.content}));break}case "StrReplaceFile":{let g=c.path??c.file_path;u=`Edit ${g||"file"}`,g&&p.push({path:g});break}case "Shell":u=c.command?`\`${c.command}\``:"Run command";break;case "Glob":u=`Find ${c.pattern||"files"}`,c.path&&p.push({path:c.path});break;case "Grep":u=`grep "${c.pattern||""}"`,c.path&&p.push({path:c.path});break;case "SearchWeb":u=c.query?`"${c.query}"`:"Web search";break;case "FetchURL":u=c.url?`Fetch ${c.url}`:"Web fetch";break;case "Task":u=c.description||"Subagent task";break;case "Think":u=c.thought||"Thinking";break;case "CreateSubagent":u=c.name?`Subagent: ${c.name}`:"Create subagent";break;case "SetTodoList":u="Update todos";break;default:u=a;}return {title:u,kind:d,toolContent:i,locations:p}}}var Vr={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 Gr(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 Wr(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 zr(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function Qt(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return null;let n=e.content;return typeof n!="string"||n.length===0?null:{content:n,status:Wr(e.status),priority:zr(e.priority)}}).filter(e=>e!==null):[]}function Jr(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 a=Gr(r);return a?{type:"content",content:{type:"image",data:a.data,mimeType:a.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 Hr(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 qr(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function mt(){return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(!a||typeof a!="object")return null;let c=a.sessionID,d=[];switch(a.type){case "step_start":case "step_finish":return null;case "text":{let i=t(a);i&&d.push({sessionId:c,update:i});break}case "reasoning":{let i=e(a);i&&d.push({sessionId:c,update:i});break}case "tool_use":{let i=n(a);for(let p of i)d.push({sessionId:c,update:p});break}case "error":{let i=r(a);i&&d.push({sessionId:c,update:i});break}default:return null}return d.length>0?d:null};function t(o){let l=o.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}function e(o){let l=o.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l}}}function n(o){let l=o.part;if(!l)return [];let a=typeof l.callID=="string"?l.callID:"";if(a.length===0)return [];let c=typeof l.tool=="string"?l.tool.toLowerCase():"",d=typeof l.state=="object"&&l.state?l.state:{},i=typeof d.input=="object"&&d.input?d.input:{},p=d.status,u=d.title??d.metadata?.description??c,g=d.metadata?.exit,{kind:f,content:m,locations:h}=s(c,i),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:a,title:u,kind:f,status:"pending",rawInput:i,content:m,locations:h}),c==="todowrite"){let v=Qt(i.todos);if(v.length===0&&typeof d.output=="string")try{v=Qt(JSON.parse(d.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=qr(p,g);if(w==="pending")return y;let x=Hr(p,d),S=[];if(typeof x=="string"&&x.length>0&&S.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
33
+ \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:l,status:a==="success"?"completed":"failed",content:i}}function r(o){let l=o.severity,a=o.message;return a?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${l==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${a}`}}:null}function s(o,l){let a=jr[o]||"other",c=[],d=[],i=o;switch(o){case "read_file":i=`Read ${l.absolute_path||l.file_path||"file"}`,(l.absolute_path||l.file_path)&&d.push({path:l.absolute_path||l.file_path});break;case "write_file":i=`Write ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),c.push({type:"diff",path:l.file_path,oldText:null,newText:l.content||""}));break;case "edit_file":i=`Edit ${l.file_path||"file"}`,l.file_path&&d.push({path:l.file_path});break;case "replace":i=`Edit ${l.file_path||"file"}`,l.file_path&&(d.push({path:l.file_path}),(l.old_string!==void 0||l.new_string!==void 0)&&c.push({type:"diff",path:l.file_path,oldText:l.old_string||"",newText:l.new_string||""}));break;case "run_shell_command":case "shell":i=l.command?`\`${l.command}\``:"Run command",l.description&&c.push({type:"content",content:{type:"text",text:l.description}});break;case "brave_web_search":case "web_search":case "google_web_search":i=l.query?`"${l.query}"`:"Web search";break;case "web_fetch":i=l.prompt?`Fetch: ${l.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${l.pattern||"files"}`,l.dir_path&&d.push({path:l.dir_path});break;case "grep":case "search_file_content":i=`grep "${l.pattern||l.query||""}"`;break;case "list_directory":i=`List ${l.dir_path||l.path||"directory"}`,(l.dir_path||l.path)&&d.push({path:l.dir_path||l.path});break;case "read_many_files":i=`Read ${l.include?.length||"multiple"} files`,Array.isArray(l.include)&&l.include.forEach(p=>d.push({path:p}));break;case "delegate_to_agent":i=l.agent_name?`Agent: ${l.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=l.fact?`Remember: "${l.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=l.name?`Activate skill: ${l.name}`:"Activate skill";break;default:i=o;}return {title:i,kind:a,content:c,locations:d}}}var Vr={ReadFile:"read",ReadMediaFile:"read",WriteFile:"edit",StrReplaceFile:"edit",Shell:"execute",Glob:"search",Grep:"search",SearchWeb:"fetch",FetchURL:"fetch",Task:"think",Think:"think",CreateSubagent:"think",SetTodoList:"other"};function gt(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function Zt(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 ft(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=Zt(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 ut(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=ft(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=ft(t);n&&e.push(n);}return e}function Gr(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&gt(e.content.text))}function zr(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=Zt(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 Wr(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function Qt(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:Wr(s),priority:"medium"}}).filter(n=>n!==null):[]}function mt(){let t=new Set,e=0;function n(a,c){return typeof a=="string"&&a.length>0?a:(e+=1,`kimi_${c.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(c){let d;try{d=JSON.parse(c);}catch{return null}if(!d||typeof d!="object"||"_meta"in d||"_prompt"in d)return null;let i=d.role;return i==="assistant"?r(d):i==="tool"?s(d):typeof d.type=="string"&&"payload"in d?o(d):null};function r(a){let c=[],d=a.content,i=a.tool_calls;if(typeof d=="string"&&d.length>0)c.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let p of d){let u=zr(p);u&&c.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(g==="SetTodoList"){let S=Qt(m);S.length>0&&c.push({update:{sessionUpdate:"plan",entries:S}}),t.add(f);continue}let{title:h,kind:y,toolContent:w,locations:x}=l(g,typeof m=="object"&&m!==null?m:{});c.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:m,content:w,locations:x}});}return c.length>0?c:null}function s(a){let c=a.tool_call_id;if(typeof c!="string"||c.length===0)return null;if(t.has(c))return t.delete(c),null;let d=a.content,i=[],p=false;if(typeof d=="string")p=gt(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=ft(u);g&&(g.type==="content"&&g.content.type==="text"&&gt(g.content.text)&&(p=true),i.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:c,status:p?"failed":"completed",content:i}}]}function o(a){let c=a.type,d=a.payload??{},i=[];switch(c){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(p==="SetTodoList"){let x=Qt(f);x.length>0&&i.push({update:{sessionUpdate:"plan",entries:x}}),t.add(u);break}let{title:m,kind:h,toolContent:y,locations:w}=l(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(...ut(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(...ut(u));}else g.push(...ut(u));f=f||Gr(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 l(a,c){let d=Vr[a]||"other",i=[],p=[],u=a;switch(a){case "ReadFile":{let g=c.path??c.file_path;u=`Read ${g||"file"}`,g&&p.push({path:g});break}case "ReadMediaFile":{let g=c.path??c.file_path;u=`Read media ${g||"file"}`,g&&p.push({path:g});break}case "WriteFile":{let g=c.path??c.file_path;u=`Write ${g||"file"}`,g&&(p.push({path:g}),typeof c.content=="string"&&i.push({type:"diff",path:g,oldText:null,newText:c.content}));break}case "StrReplaceFile":{let g=c.path??c.file_path;u=`Edit ${g||"file"}`,g&&p.push({path:g});break}case "Shell":u=c.command?`\`${c.command}\``:"Run command";break;case "Glob":u=`Find ${c.pattern||"files"}`,c.path&&p.push({path:c.path});break;case "Grep":u=`grep "${c.pattern||""}"`,c.path&&p.push({path:c.path});break;case "SearchWeb":u=c.query?`"${c.query}"`:"Web search";break;case "FetchURL":u=c.url?`Fetch ${c.url}`:"Web fetch";break;case "Task":u=c.description||"Subagent task";break;case "Think":u=c.thought||"Thinking";break;case "CreateSubagent":u=c.name?`Subagent: ${c.name}`:"Create subagent";break;case "SetTodoList":u="Update todos";break;default:u=a;}return {title:u,kind:d,toolContent:i,locations:p}}}var Jr={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 Hr(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 qr(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 Yr(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function Xt(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:qr(e.status),priority:Yr(e.priority)}}).filter(e=>e!==null):[]}function Qr(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 a=Hr(r);return a?{type:"content",content:{type:"image",data:a.data,mimeType:a.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 Zr(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 Xr(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function ht(){return function(l){let a;try{a=JSON.parse(l);}catch{return null}if(!a||typeof a!="object")return null;let c=a.sessionID,d=[];switch(a.type){case "step_start":case "step_finish":return null;case "text":{let i=t(a);i&&d.push({sessionId:c,update:i});break}case "reasoning":{let i=e(a);i&&d.push({sessionId:c,update:i});break}case "tool_use":{let i=n(a);for(let p of i)d.push({sessionId:c,update:p});break}case "error":{let i=r(a);i&&d.push({sessionId:c,update:i});break}default:return null}return d.length>0?d:null};function t(o){let l=o.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}function e(o){let l=o.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l}}}function n(o){let l=o.part;if(!l)return [];let a=typeof l.callID=="string"?l.callID:"";if(a.length===0)return [];let c=typeof l.tool=="string"?l.tool.toLowerCase():"",d=typeof l.state=="object"&&l.state?l.state:{},i=typeof d.input=="object"&&d.input?d.input:{},p=d.status,u=d.title??d.metadata?.description??c,g=d.metadata?.exit,{kind:f,content:m,locations:h}=s(c,i),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:a,title:u,kind:f,status:"pending",rawInput:i,content:m,locations:h}),c==="todowrite"){let b=Xt(i.todos);if(b.length===0&&typeof d.output=="string")try{b=Xt(JSON.parse(d.output));}catch{}b.length>0&&y.push({sessionUpdate:"plan",entries:b});}let w=Xr(p,g);if(w==="pending")return y;let x=Zr(p,d),S=[];if(typeof x=="string"&&x.length>0&&S.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
34
34
  ${x}
35
- \`\`\``:x}}),Array.isArray(d.attachments))for(let v of d.attachments){let b=Jr(v);b&&S.push(b);}return y.push({sessionUpdate:"tool_call_update",toolCallId:a,status:w,content:S}),y}function r(o){let l=o.error?.name??"Error",a=o.error?.data?.message??o.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${l}: ${a}`}}}function s(o,l){let a=Vr[o]||"other",c=[],d=[];switch(o){case "read":{let i=l.filePath??l.path;if(i){let p=l.offset;d.push({path:i,line:typeof p=="number"&&Number.isFinite(p)?Math.max(0,p-1):void 0});}break}case "write":{let i=l.filePath??l.path;i&&(d.push({path:i}),typeof l.content=="string"&&c.push({type:"diff",path:i,oldText:null,newText:l.content}));break}case "edit":case "multiedit":{let i=l.filePath??l.path;i&&(d.push({path:i}),o==="edit"&&(l.oldString!==void 0||l.newString!==void 0)&&c.push({type:"diff",path:i,oldText:l.oldString??"",newText:l.newString??""}));break}case "apply_patch":break;case "bash":{let i=l.command;i&&l.description?c.push({type:"content",content:{type:"text",text:l.description}}):i&&c.push({type:"content",content:{type:"text",text:i}});break}case "glob":case "list":{let i=l.path;i&&d.push({path:i});break}case "grep":{let i=l.path;i&&d.push({path:i});break}case "codesearch":case "websearch":{let i=l.query;i&&c.push({type:"content",content:{type:"text",text:i}});break}case "webfetch":{let i=l.url;i&&c.push({type:"content",content:{type:"text",text:i}});break}case "task":{let i=l.description;i&&c.push({type:"content",content:{type:"text",text:i}});break}}return {kind:a,content:c,locations:d}}}var Yr={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 $e(){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=o(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=l(y);w&&i.push(w);}else if(g.type==="tool_result"){let f=a(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=a(u);g&&p.push(g);}}return p}function o(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=l(d);return i?[i]:[]}case "tool_result":{let i=a(d);return i?[i]:[]}}}function l(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}=c(p,u||{});return {sessionUpdate:"tool_call",toolCallId:i,title:g,kind:f,status:"pending",rawInput:u,content:m,locations:h}}function a(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?`\`\`\`
35
+ \`\`\``:x}}),Array.isArray(d.attachments))for(let b of d.attachments){let v=Qr(b);v&&S.push(v);}return y.push({sessionUpdate:"tool_call_update",toolCallId:a,status:w,content:S}),y}function r(o){let l=o.error?.name??"Error",a=o.error?.data?.message??o.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${l}: ${a}`}}}function s(o,l){let a=Jr[o]||"other",c=[],d=[];switch(o){case "read":{let i=l.filePath??l.path;if(i){let p=l.offset;d.push({path:i,line:typeof p=="number"&&Number.isFinite(p)?Math.max(0,p-1):void 0});}break}case "write":{let i=l.filePath??l.path;i&&(d.push({path:i}),typeof l.content=="string"&&c.push({type:"diff",path:i,oldText:null,newText:l.content}));break}case "edit":case "multiedit":{let i=l.filePath??l.path;i&&(d.push({path:i}),o==="edit"&&(l.oldString!==void 0||l.newString!==void 0)&&c.push({type:"diff",path:i,oldText:l.oldString??"",newText:l.newString??""}));break}case "apply_patch":break;case "bash":{let i=l.command;i&&l.description?c.push({type:"content",content:{type:"text",text:l.description}}):i&&c.push({type:"content",content:{type:"text",text:i}});break}case "glob":case "list":{let i=l.path;i&&d.push({path:i});break}case "grep":{let i=l.path;i&&d.push({path:i});break}case "codesearch":case "websearch":{let i=l.query;i&&c.push({type:"content",content:{type:"text",text:i}});break}case "webfetch":{let i=l.url;i&&c.push({type:"content",content:{type:"text",text:i}});break}case "task":{let i=l.description;i&&c.push({type:"content",content:{type:"text",text:i}});break}}return {kind:a,content:c,locations:d}}}var ei={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 $e(){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=o(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=l(y);w&&i.push(w);}else if(g.type==="tool_result"){let f=a(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=a(u);g&&p.push(g);}}return p}function o(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=l(d);return i?[i]:[]}case "tool_result":{let i=a(d);return i?[i]:[]}}}function l(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}=c(p,u||{});return {sessionUpdate:"tool_call",toolCallId:i,title:g,kind:f,status:"pending",rawInput:u,content:m,locations:h}}function a(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
36
  ${u}
37
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
38
  ${m}
39
- \`\`\``:m}});}}return {sessionUpdate:"tool_call_update",toolCallId:i,status:p?"failed":"completed",content:g}}function c(d,i){let p=Yr[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 Zt(t){return $e()(t)}function W(t){switch(t){case "claude":return Pe();case "codex":return Oe();case "gemini":return Me();case "qwen":return $e();case "kimi":return ft();case "opencode":return mt();case "droid":return Ae();default:return ()=>null}}function Qr(t,e){let n=e.trim();return n?W(t)(n):null}function Zr(t,e){let n=[],r=e.split(`
40
- `),s=W(t);for(let o of r){let l=o.trim();if(!l)continue;let a=s(l);a&&n.push(...a);}return n}function M(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function q(t){return JSON.stringify(Xr__default.default(t,{target:"jsonSchema7"}),null,2)}function Y(t){return JSON.stringify(t,null,2)}function Xt(t,e=false){let n={};function r(s,o){for(let l of $__namespace.readdirSync(s)){let a=oe__namespace.join(s,l),c=o?`${o}/${l}`:l;$__namespace.statSync(a).isDirectory()?e&&r(a,c):n[c]=$__namespace.readFileSync(a);}}return r(t,""),n}function en(t,e){for(let[n,r]of Object.entries(e)){let s=oe__namespace.join(t,n),o=oe__namespace.dirname(s);$__namespace.mkdirSync(o,{recursive:true});let l;r instanceof ArrayBuffer||r instanceof Uint8Array?l=Buffer.from(r):l=r,$__namespace.writeFileSync(s,l);}}function ei(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 Be(t){let e=t?.type??Lt,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 l=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,a=t.providerBaseUrl??l??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:a,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort};let r=process.env[T];if(r)return {type:e,apiKey:r,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let a=(t?.model??n.defaultModel)?.split("/")[0],c=a?n.providerEnvMap[a]:void 0,d=c?process.env[c.keyEnv]:void 0;if(d){let p=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:p,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let s=process.env[n.apiKeyEnv];if(s){let a=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:s,baseUrl:a,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let l=process.env[n.oauthEnv];if(l){if(n.oauthFileName){let a=ei(l);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:a,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:l,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let o=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)${o}, or ${T} / ${n.apiKeyEnv} env var.`)}async function ht(){let t=process.env[_e];if(t)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===tt()&&delete process.env.E2B_API_URL,o({apiKey:t})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${_e} is set but @evolvingmachines/e2b failed to load.
39
+ \`\`\``:m}});}}return {sessionUpdate:"tool_call_update",toolCallId:i,status:p?"failed":"completed",content:g}}function c(d,i){let p=ei[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 en(t){return $e()(t)}function z(t){switch(t){case "claude":return Pe();case "codex":return Oe();case "gemini":return Me();case "qwen":return $e();case "kimi":return mt();case "opencode":return ht();case "droid":return Ae();default:return ()=>null}}function ti(t,e){let n=e.trim();return n?z(t)(n):null}function ni(t,e){let n=[],r=e.split(`
40
+ `),s=z(t);for(let o of r){let l=o.trim();if(!l)continue;let a=s(l);a&&n.push(...a);}return n}function M(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function q(t){return JSON.stringify(ri__default.default(t,{target:"jsonSchema7"}),null,2)}function Y(t){return JSON.stringify(t,null,2)}function tn(t,e=false){let n={};function r(s,o){for(let l of $__namespace.readdirSync(s)){let a=oe__namespace.join(s,l),c=o?`${o}/${l}`:l;$__namespace.statSync(a).isDirectory()?e&&r(a,c):n[c]=$__namespace.readFileSync(a);}}return r(t,""),n}function nn(t,e){for(let[n,r]of Object.entries(e)){let s=oe__namespace.join(t,n),o=oe__namespace.dirname(s);$__namespace.mkdirSync(o,{recursive:true});let l;r instanceof ArrayBuffer||r instanceof Uint8Array?l=Buffer.from(r):l=r,$__namespace.writeFileSync(s,l);}}function ii(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 Be(t){let e=t?.type??Nt,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 l=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,a=t.providerBaseUrl??l??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:a,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort};let r=process.env[T];if(r)return {type:e,apiKey:r,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let a=(t?.model??n.defaultModel)?.split("/")[0],c=a?n.providerEnvMap[a]:void 0,d=c?process.env[c.keyEnv]:void 0;if(d){let p=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:p,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let s=process.env[n.apiKeyEnv];if(s){let a=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:s,baseUrl:a,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let l=process.env[n.oauthEnv];if(l){if(n.oauthFileName){let a=ii(l);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:a,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:l,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let o=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)${o}, or ${T} / ${n.apiKeyEnv} env var.`)}async function yt(){let t=process.env[_e];if(t)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===nt()&&delete process.env.E2B_API_URL,o({apiKey:t})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${_e} is set but @evolvingmachines/e2b failed to load.
41
41
  Try reinstalling: npm install @evolvingmachines/sdk`):l}let e=process.env[Ee];if(e)try{let{createDaytonaProvider:o}=await import('@evolvingmachines/daytona');return o({apiKey:e})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ee} is set but @evolvingmachines/daytona failed to load.
42
- Try installing: npm install @evolvingmachines/daytona`):l}let n=process.env[Te],r=process.env[nt];if(n&&r)try{let{createModalProvider:o}=await import('@evolvingmachines/modal');return o({tokenId:n,tokenSecret:r})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${Te} is set but @evolvingmachines/modal failed to load.
43
- Try installing: npm install @evolvingmachines/modal`):l}let s=process.env[T];if(s)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return o({apiKey:s,apiUrl:tt()})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${T} is set but @evolvingmachines/e2b failed to load.
42
+ Try installing: npm install @evolvingmachines/daytona`):l}let n=process.env[Te],r=process.env[rt];if(n&&r)try{let{createModalProvider:o}=await import('@evolvingmachines/modal');return o({tokenId:n,tokenSecret:r})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${Te} is set but @evolvingmachines/modal failed to load.
43
+ Try installing: npm install @evolvingmachines/modal`):l}let s=process.env[T];if(s)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return o({apiKey:s,apiUrl:nt()})}catch(o){let l=o;throw l.message?.includes("Cannot find module")||l.message?.includes("MODULE_NOT_FOUND")?new Error(`${T} is set but @evolvingmachines/e2b failed to load.
44
44
  Try reinstalling: npm install @evolvingmachines/sdk`):l}throw new Error(`No sandbox provider configured. Either:
45
45
  1. Set ${T} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
46
46
  2. Set ${_e} environment variable (direct E2B access, get key at https://e2b.dev)
47
47
  3. Set ${Ee} environment variable (direct Daytona access, get key at https://app.daytona.io)
48
- 4. Set ${Te} and ${nt} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
49
- 5. Pass sandbox explicitly: .withSandbox(provider)`)}function ti(t){return new Promise(e=>setTimeout(e,t))}async function P(t,e,n=0){let r=ni(e),s=e?.onItemRetry,o=null,l=0,a=r.backoffMs;for(;l<r.maxAttempts;){if(l++,o=await t(l),!r.retryOn(o))return o;if(l>=r.maxAttempts)break;if(s){let c=o.error??"Unknown error";s(n,l,c);}await ti(a),a*=r.backoffMultiplier;}return o}function ni(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var tn=`## FILESYSTEM INSTRUCTIONS:
48
+ 4. Set ${Te} and ${rt} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
49
+ 5. Pass sandbox explicitly: .withSandbox(provider)`)}function si(t){return new Promise(e=>setTimeout(e,t))}async function P(t,e,n=0){let r=oi(e),s=e?.onItemRetry,o=null,l=0,a=r.backoffMs;for(;l<r.maxAttempts;){if(l++,o=await t(l),!r.retryOn(o))return o;if(l>=r.maxAttempts)break;if(s){let c=o.error??"Unknown error";s(n,l,c);}await si(a),a*=r.backoffMultiplier;}return o}function oi(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var rn=`## FILESYSTEM INSTRUCTIONS:
50
50
 
51
51
  You are running in a sandbox environment.
52
52
 
@@ -79,7 +79,7 @@ Examples:
79
79
  - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
80
80
  - "Write a Python script" \u2192 \`output/parser.py\`
81
81
  - "Convert this to JSON" \u2192 \`output/data.json\`
82
- `;var nn=`## FILESYSTEM INSTRUCTIONS:
82
+ `;var sn=`## FILESYSTEM INSTRUCTIONS:
83
83
 
84
84
  You are running in a sandbox environment.
85
85
 
@@ -113,9 +113,9 @@ Examples:
113
113
  - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
114
114
  - "Write a Python script" \u2192 \`output/parser.py\`
115
115
  - "Convert this to JSON" \u2192 \`output/data.json\`
116
- `;var rn=`## SYSTEM PROMPT
116
+ `;var on=`## SYSTEM PROMPT
117
117
 
118
- {{systemPrompt}}`;var sn=`## STRUCTURED OUTPUT
118
+ {{systemPrompt}}`;var an=`## STRUCTURED OUTPUT
119
119
 
120
120
  Your final result MUST be saved to \`output/result.json\` following this schema:
121
121
 
@@ -133,13 +133,13 @@ You are free to:
133
133
  But your final \`output/result.json\` MUST conform to the schema above.
134
134
 
135
135
  ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
136
- ### Never just state results as text.`;var on=`## BROWSER AUTOMATION
136
+ ### Never just state results as text.`;var cn=`## BROWSER AUTOMATION
137
137
 
138
138
  Actionbook is preconfigured for remote browser automation in this environment. When browser automation is needed, start sessions with \`actionbook browser start --session s1\`, then use normal Actionbook browser commands. Do not override the configured browser mode or browser endpoint unless the user explicitly asks.
139
- `;var an=`## Browser Automation
139
+ `;var ln=`## Browser Automation
140
140
 
141
141
  The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
142
- `;var cn=`### 1. YOUR ROLE: BEST OF N JUDGE
142
+ `;var dn=`### 1. YOUR ROLE: BEST OF N JUDGE
143
143
 
144
144
  You are a judge. {{candidateCount}} AI workers attempted the same task independently. Your job is to analyze their solution attempts and pick the best one based on the evaluation criteria below.
145
145
 
@@ -169,7 +169,7 @@ You must judge their work based on:
169
169
  5. Pick the best candidate (0-indexed)
170
170
 
171
171
  **IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
172
- `;var ln=`### 1. YOUR ROLE: OUTPUT VERIFIER
172
+ `;var pn=`### 1. YOUR ROLE: OUTPUT VERIFIER
173
173
 
174
174
  You are a quality verifier. An AI worker produced output for a task. Your job is to verify whether the output meets the specified quality criteria.
175
175
 
@@ -202,14 +202,14 @@ The output must satisfy:
202
202
  **IMPORTANT:** Be thorough and fair. Cite specific evidence. If the output generally achieves the goal with minor issues, consider passing. Only fail if there are significant problems that violate the criteria.
203
203
 
204
204
  If failing, provide specific, actionable feedback explaining what needs to be fixed.
205
- `;var dn=`### CONTEXT STRUCTURE
205
+ `;var un=`### CONTEXT STRUCTURE
206
206
 
207
207
  \`\`\`
208
208
  {{fileTree}}
209
209
  \`\`\`
210
210
 
211
211
  Examine all files within each item folder before producing your output.
212
- `;var pn="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var un="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var gn=`{{originalPrompt}}
212
+ `;var gn="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var fn="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var mn=`{{originalPrompt}}
213
213
 
214
214
  ## IMPORTANT: Previous Attempt Failed Verification
215
215
 
@@ -218,38 +218,38 @@ Your previous attempt did not pass quality verification. Please address this fee
218
218
  {{feedback}}
219
219
 
220
220
  Make sure your output addresses all the feedback points above.
221
- `;var fn=tn,mn=nn,hn=rn,yn=sn,yt=on,wn=an,wt=cn,vn=pn,vt=ln,bn=un,Sn=dn,bt=gn;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 St(t){let e=t.mode==="swe"?mn:fn,n=F(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
221
+ `;var hn=rn,yn=sn,wn=on,bn=an,wt=cn,vn=ln,bt=dn,Sn=gn,vt=pn,xn=fn,kn=un,St=mn;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"?yn:hn,n=F(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
222
222
 
223
223
 
224
224
  ${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
225
225
 
226
226
 
227
- ${F(hn,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=M(t.schema)?q(t.schema):Y(t.schema);n+=`
227
+ ${F(wn,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=M(t.schema)?q(t.schema):Y(t.schema);n+=`
228
228
 
229
229
 
230
- ${F(yn,{schema:r}).trim()}`;}return n}function Ue(t){let e=[...new Set(Object.keys(t).map(c=>c.split("/")[0]))].sort((c,d)=>c==="worker_task"?-1:d==="worker_task"?1:c.localeCompare(d));if(!e.length)return `context/
230
+ ${F(bn,{schema:r}).trim()}`;}return n}function Ue(t){let e=[...new Set(Object.keys(t).map(c=>c.split("/")[0]))].sort((c,d)=>c==="worker_task"?-1:d==="worker_task"?1:c.localeCompare(d));if(!e.length)return `context/
231
231
  (empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,s=Object.keys(t).some(c=>c.startsWith("worker_task/input/")),o=[];e.forEach((c,d)=>{let i=d===e.length-1,p=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=i?" ":"\u2502 ";if(c==="worker_task"){o.push({line:`${p}${c}/`,comment:"task given to worker"});let g=[];n&&g.push({name:"system_prompt.txt",comment:"worker system prompt"}),g.push({name:"user_prompt.txt",comment:"worker task prompt"}),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 ";o.push({line:`${u}${y}${f.name}`,comment:f.comment});});}else if(c.startsWith("candidate_")){let g=c.replace("candidate_","");o.push({line:`${p}${c}/`,comment:`worker ${g} solution`});}else if(c==="worker_output")o.push({line:`${p}${c}/`,comment:"output to verify"});else if(c.startsWith("item_")){let g=c.replace("item_","");o.push({line:`${p}${c}/`,comment:`input ${g}`});}else o.push({line:`${p}${c}/`,comment:""});});let l=Math.max(...o.map(c=>c.line.length)),a=["context/"];for(let c of o)if(c.comment){let d=" ".repeat(l-c.line.length+3);a.push(`${c.line}${d}# ${c.comment}`);}else a.push(c.line);return a.join(`
232
- `)}var xn=oe.join(os$1.homedir(),Kt),ae=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(xn,{recursive:true}).catch(()=>{});eventBuffer=[];dashboardQueue=Promise.resolve();flushTimer;constructor(e){this.validateConfig(e),this.provider=e.provider,this.agent=e.agent,this.model=e.model,this.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=Ce(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=oe.join(xn,r),this.parser=W(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let 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.isClosed=true,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
232
+ `)}var Cn=oe.join(os$1.homedir(),Vt),ae=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(Cn,{recursive:true}).catch(()=>{});eventBuffer=[];dashboardQueue=Promise.resolve();flushTimer;constructor(e){this.validateConfig(e),this.provider=e.provider,this.agent=e.agent,this.model=e.model,this.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=Ce(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=oe.join(Cn,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.isClosed=true,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
233
233
  `)?e:e+`
234
234
  `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let n=JSON.stringify(e)+`
235
235
  `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&(this.eventBuffer.push(e),this.scheduleFlush());}writeMeta(){let e={_meta:{tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandbox_id:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability)}},n=JSON.stringify(e)+`
236
- `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=jt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Vt));}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<=Re;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===Re){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(it*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===Re?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(it*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Ce();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};function ce(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function le(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 de(t){return await t.text().catch(()=>"")}function xt(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function vi(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 Cn(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${le(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:xt(t.userId),apps:vi(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 de(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 bi(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${le(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:xt(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 de(e)}`);return await e.json()}async function Si(t){let e=Array.from(new Set((t.userIds??[]).map(l=>xt(l))));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 ${le(t.apiKey)}`,accept:"application/json"},s=await fetch(`${ce(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 de(s)}`);return ((await s.json()).accounts??[]).map(l=>({userId:String(l.userId??""),app:String(l.app??""),appName:typeof l.appName=="string"?l.appName:void 0,appIcon:typeof l.appIcon=="string"?l.appIcon:void 0,accountLabel:typeof l.accountLabel=="string"?l.accountLabel:void 0,status:String(l.status??""),accountId:typeof l.accountId=="string"?l.accountId:void 0,updatedAt:typeof l.updatedAt=="string"?l.updatedAt:void 0}))}async function xi(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${le(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 de(e)}`);return await e.json()}async function ki(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${le(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 de(e)}`);return await e.json()}var _n={auth:bi,accounts:{list:Si,update:xi,delete:ki}};util.promisify(child_process.exec);var Et=util.promisify(child_process.execFile),Rn=Symbol.for("evolve:awsSdkCache"),In=Symbol.for("evolve:s3ClientCache");var $i=3600,Di=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Bi(t){if(t.startsWith("s3://")){let s=t.slice(5),o=s.indexOf("/");return o===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,o),prefix:s.slice(o+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 Ne(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||"",o=t?.prefix||"",l=t?.endpoint;if(t?.url){let a=Bi(t.url);s=s||a.bucket,o=o||a.prefix,l=l||a.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:o,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:l,credentials:t?.credentials,mode:"byok"}}function Pn(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 Ui(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 Le(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Li(t,e){let n=D(t),r=Ui(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(a=>Pn(a)):[Pn(n.mcpConfig.settingsDir)],o=[...Di.map(a=>`--exclude=${Le(a)}`),`--exclude=${Le(r+"/temp")}`].join(" "),l=[Le(r+"/"),...s.map(a=>Le(a+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${o} ${l}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Z(){let t=globalThis[Rn];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[Rn]={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[In];if(r?.key===n)return r.client;let{s3:s}=await Z(),o=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[In]={client:o,key:n},o}async function Fn(t,e,n){let{s3:r,presigner:s}=await Z(),o=await ue(t),l=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(o,l,{expiresIn:$i})}async function On(t,e){let{s3:n}=await Z(),r=await ue(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let o=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||o==="NotFound"||o==="NoSuchKey")return false;throw s}}async function Nn(t,e){let{s3:n}=await Z(),o=await(await(await ue(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!o)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(o)}async function Fi(t,e,n){let{s3:r}=await Z();await(await ue(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Kn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function jn(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Ni(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Vn(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 o=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${o}`)}return s.json()}async function Ki(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 ji(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 Tt(t,e,n,r,s){let o=new Date().toISOString(),l=Li(n,r),a=await t.commands.run(l,{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint tar failed: ${a.stderr}`);let c=a.stdout.trim().split(`
237
- `).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);let d=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),i=parseInt(d.stdout.trim(),10),p=Number.isNaN(i)?void 0:i,u;try{if(e.mode==="byok"){let g=Kn(e,c);if(!await On(e,g)){let h=await Fn(e,g,"put"),y=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(y.exitCode!==0)throw new Error(`Checkpoint upload failed: ${y.stderr}`);if(!await On(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=Ni();let m={id:u,hash:c,tag:s.tag,timestamp:o,sizeBytes:p,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment,sandboxId:t.sandboxId};await Fi(e,jn(e,u),m);}else {let g=await Vn(e,s.tag,c,"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 Ki(e,{tag:s.tag,hash:c,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:c,tag:s.tag,timestamp:o,sizeBytes:p,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment}}async function Gn(t,e,n){let r=await It(e,n),s=r.hash,o={agentType:r.agentType,workspaceMode:r.workspaceMode},l=await Hn(e,r),a=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${l}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(a.exitCode!==0)throw new Error(`Checkpoint download failed: ${a.stderr}`);let c=a.stdout.trim().split(`
238
- `).pop()?.trim();if(c!==s)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${c})`);let d=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(d.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${d.stderr}`);return o}function Wn(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||E,s=!t.url&&!t.bucket&&!!n;return Ne(t,s,r,n)}async function zn(t,e){let{s3:n}=await Z(),r=await ue(t),o=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,l=[],a;do{let u={Bucket:t.bucket,Prefix:o,...a&&{ContinuationToken:a}},g=await r.send(new n.ListObjectsV2Command(u));if(g.Contents)for(let f of g.Contents)f.Key?.endsWith(".json")&&f.LastModified&&l.push({key:f.Key,lastModified:f.LastModified});a=g.IsTruncated?g.NextContinuationToken:void 0;}while(a);if(l.length===0)return [];l.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?l:e?.limit?l.slice(0,e.limit):l,p=(await Promise.all(d.map(async u=>{try{return await Nn(t,u.key)}catch{return null}}))).filter(u=>u!==null);return e?.tag&&(p=p.filter(u=>u.tag===e.tag)),e?.limit&&p.length>e.limit&&(p=p.slice(0,e.limit)),p}async function Jn(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let r=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${s.status}): ${o}`)}return s.json()}function Vi(t){return t&&t>0?Math.min(t,500):100}async function Rt(t,e){return t.mode==="byok"?(await zn(t,{limit:1,tag:e?.tag}))[0]??null:(await Jn(t,{limit:1,tag:e?.tag}))[0]??null}async function It(t,e){if(t.mode==="byok"){let n=jn(t,e);try{return await Nn(t,n)}catch(r){throw Gi(r)?new Error(`Checkpoint ${e} not found`):r}}else return await ji(t,e)}async function An(t,e,n){if(e==="latest"){let r=await Rt(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function Hn(t,e){if(t.mode==="byok")return Fn(t,Kn(t,e.hash),"get");{let n=await Vn(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function qn(t){return !(!t||oe.isAbsolute(t)||t.startsWith("-")||oe.normalize(t).startsWith("..")||t.includes("\0"))}function Mn(t,e){let n=oe.resolve(t,e),r=oe.resolve(t),s=oe.relative(r,n);if(s.startsWith("..")||oe.isAbsolute(s))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Gi(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function kt(t){let e=t.filter(n=>!qn(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var Yn=10*1024*1024,$n=false;async function Qn(){if(!$n)try{await Et("tar",["--version"]),$n=!0;}catch{throw new Error("The 'tar' command is not available on this system. Storage download/extract requires tar (available on macOS, Linux, and Windows with Git Bash or WSL).")}}async function Dn(t,e){let n=await It(t,e),r=await Hn(t,n),s=e.replace(/[^a-zA-Z0-9_-]/g,"_"),o=oe.join(os$1.tmpdir(),`evolve-dl-${s}-${Date.now()}.tar.gz`),l=await fetch(r);if(!l.ok)throw new Error(`Checkpoint download failed (${l.status})`);if(!l.body)throw new Error("Checkpoint download returned empty body");let a=crypto.createHash("sha256"),c=$.createWriteStream(o);try{let i=l.body.getReader();await new Promise((p,u)=>{c.on("error",u),c.on("finish",p);async function g(){for(;;){let{done:f,value:m}=await i.read();if(f){c.end();break}a.update(m),c.write(m)||await new Promise(h=>c.once("drain",h));}}g().catch(u);});}catch(i){throw c.destroy(),await promises.unlink(o).catch(()=>{}),i}let d=a.digest("hex");if(d!==n.hash)throw await promises.unlink(o).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:o,metadata:n}}async function Bn(t){await Qn();let{stdout:e}=await Et("tar",["-tvzf",t],{maxBuffer:Yn}),n=new Set,r=[],s=[];for(let o of e.trim().split(`
239
- `)){if(!o||o.startsWith("total "))continue;let l=o[0];if(l!=="-"&&l!=="d"&&l!=="l")throw new Error(`Archive contains unsupported entry type: "${l}"`);let a=o.match(/\d{2}:\d{2}\s+(.+)/)??o.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!a)continue;let c=a[1];if(l==="l"){let d=c.indexOf(" -> ");d!==-1&&(c=c.slice(0,d)),n.add(c);}else l==="d"?r.push(c.replace(/\/$/,"")):s.push(c);}return kt(r),kt([...n]),kt(s)}async function Ct(t,e,n){await Qn(),await promises.mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await Et("tar",r,{maxBuffer:Yn});}function Wi(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 Pt(t,e){let n=Wn(t,e);return Zn(n)}function zi(t){let e=Wn(t||{});return Zn(e)}function Zn(t){return {async listCheckpoints(e){let n=Vi(e?.limit);return t.mode==="byok"?zn(t,{limit:n,tag:e?.tag}):Jn(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return It(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,s=n?.to||process.cwd(),o=await An(t,e),{tmpPath:l,metadata:a}=await Dn(t,o);try{if(r)return await promises.mkdir(s,{recursive:!0}),await Bn(l),await Ct(l,s),s;{await promises.mkdir(s,{recursive:!0});let c=oe.join(s,`checkpoint-${a.id}.tar.gz`);return await promises.copyFile(l,c),c}}finally{await promises.unlink(l).catch(()=>{});}},async downloadFiles(e,n){let r=await An(t,e),{tmpPath:s}=await Dn(t,r),o;try{let l=await Bn(s),a;if(n?.files){let d=n.files.filter(p=>!qn(p));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let i=new Set(n.files);a=l.filter(p=>i.has(p));}else if(n?.glob){let d=n.glob.map(Wi);a=l.filter(i=>d.some(p=>p.test(i)));}else a=l;if(a.length===0)return {};o=oe.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`);try{await Ct(s,o,a);}catch(d){let i=d?.message??"";if(!i.includes("E2BIG")&&!i.includes("Argument list too long")&&!i.includes("ENAMETOOLONG"))throw d;await promises.rm(o,{recursive:!0,force:!0}).catch(()=>{}),o=oe.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`),await Ct(s,o);}let c={};return await Promise.all(a.map(async d=>{Mn(o,d),c[d]=await promises.readFile(oe.join(o,d));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(c).map(async([d,i])=>{Mn(n.to,d);let p=oe.join(n.to,d);await promises.mkdir(oe.dirname(p),{recursive:!0}),await promises.writeFile(p,i);}))),c}finally{o&&await promises.rm(o,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(s).catch(()=>{});}}}}function N(t){return `'${t.replace(/'/g,"'\\''")}'`}function Ke(t){return typeof t=="string"&&t.length>0}function X(t,e,n){let r=t[e];if(!Ke(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function Ji(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
240
- ${n}`)}function Hi(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 Ke(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(Ke(r.ref)&&s.push(`--ref ${N(r.ref)}`),Array.isArray(r.sparse))for(let o of r.sparse){if(!Ke(o))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");s.push(`--sparse ${N(o)}`);}return [s.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function Xn(t,e,n){if(n?.length)for(let r of n){let s=Hi(t,r);for(let o of s){let l=await e.commands.run(o,{timeoutMs:12e4});if(l.exitCode!==0)throw Ji(o,l)}}}var qi=["actionbook","active-research","extract"],Yi=["agent-browser"],Qi={actionbook:qi,"agent-browser":Yi},nr="/home/user/.agent-browser",er=`${nr}/config.json`,rr="/home/user/.actionbook",Zi=`${rr}/config.toml`;function tr(t){return t==="actionbook"||t==="agent-browser"}function Xi(t){return t.remote===true}function ir(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(tr(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(tr(t.provider))return {provider:t.provider,managed:Xi(t)};throw new Error("Unsupported browser configuration")}function sr(t,e){return Array.from(new Set([...e??[],...Qi[t]]))}function Ot(t,e){return t==="actionbook"?{envs:{},files:[{path:Zi,data:`version = 1
236
+ `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=Gt){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<=Re;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===Re){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(st*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===Re?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(st*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Ce();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};function ce(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}function le(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 de(t){return await t.text().catch(()=>"")}function kt(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function ki(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 En(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${le(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:kt(t.userId),apps:ki(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 de(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 Ci(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${le(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:kt(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 de(e)}`);return await e.json()}async function _i(t){let e=Array.from(new Set((t.userIds??[]).map(l=>kt(l))));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 ${le(t.apiKey)}`,accept:"application/json"},s=await fetch(`${ce(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 de(s)}`);return ((await s.json()).accounts??[]).map(l=>({userId:String(l.userId??""),app:String(l.app??""),appName:typeof l.appName=="string"?l.appName:void 0,appIcon:typeof l.appIcon=="string"?l.appIcon:void 0,accountLabel:typeof l.accountLabel=="string"?l.accountLabel:void 0,status:String(l.status??""),accountId:typeof l.accountId=="string"?l.accountId:void 0,updatedAt:typeof l.updatedAt=="string"?l.updatedAt:void 0}))}async function Ei(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${le(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 de(e)}`);return await e.json()}async function Ti(t){let e=await fetch(`${ce(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${le(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 de(e)}`);return await e.json()}var Tn={auth:Ci,accounts:{list:_i,update:Ei,delete:Ti}};util.promisify(child_process.exec);var Tt=util.promisify(child_process.execFile),Pn=Symbol.for("evolve:awsSdkCache"),On=Symbol.for("evolve:s3ClientCache");var Li=3600,Fi=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Ni(t){if(t.startsWith("s3://")){let s=t.slice(5),o=s.indexOf("/");return o===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,o),prefix:s.slice(o+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 Ne(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||"",o=t?.prefix||"",l=t?.endpoint;if(t?.url){let a=Ni(t.url);s=s||a.bucket,o=o||a.prefix,l=l||a.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:o,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:l,credentials:t?.credentials,mode:"byok"}}function An(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 Ki(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 Le(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function ji(t,e){let n=D(t),r=Ki(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(a=>An(a)):[An(n.mcpConfig.settingsDir)],o=[...Fi.map(a=>`--exclude=${Le(a)}`),`--exclude=${Le(r+"/temp")}`].join(" "),l=[Le(r+"/"),...s.map(a=>Le(a+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${o} ${l}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Z(){let t=globalThis[Pn];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[Pn]={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[On];if(r?.key===n)return r.client;let{s3:s}=await Z(),o=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[On]={client:o,key:n},o}async function Kn(t,e,n){let{s3:r,presigner:s}=await Z(),o=await ue(t),l=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(o,l,{expiresIn:Li})}async function Mn(t,e){let{s3:n}=await Z(),r=await ue(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let o=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||o==="NotFound"||o==="NoSuchKey")return false;throw s}}async function jn(t,e){let{s3:n}=await Z(),o=await(await(await ue(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!o)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(o)}async function Vi(t,e,n){let{s3:r}=await Z();await(await ue(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Vn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function Gn(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Gi(){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 o=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${o}`)}return s.json()}async function zi(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 Wi(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 Rt(t,e,n,r,s){let o=new Date().toISOString(),l=ji(n,r),a=await t.commands.run(l,{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint tar failed: ${a.stderr}`);let c=a.stdout.trim().split(`
237
+ `).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);let d=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),i=parseInt(d.stdout.trim(),10),p=Number.isNaN(i)?void 0:i,u;try{if(e.mode==="byok"){let g=Vn(e,c);if(!await Mn(e,g)){let h=await Kn(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 Mn(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=Gi();let m={id:u,hash:c,tag:s.tag,timestamp:o,sizeBytes:p,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment,sandboxId:t.sandboxId};await Vi(e,Gn(e,u),m);}else {let g=await zn(e,s.tag,c,"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 zi(e,{tag:s.tag,hash:c,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:c,tag:s.tag,timestamp:o,sizeBytes:p,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment}}async function Wn(t,e,n){let r=await Pt(e,n),s=r.hash,o={agentType:r.agentType,workspaceMode:r.workspaceMode},l=await Yn(e,r),a=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${l}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(a.exitCode!==0)throw new Error(`Checkpoint download failed: ${a.stderr}`);let c=a.stdout.trim().split(`
238
+ `).pop()?.trim();if(c!==s)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${c})`);let d=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(d.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${d.stderr}`);return o}function Jn(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||_,s=!t.url&&!t.bucket&&!!n;return Ne(t,s,r,n)}async function Hn(t,e){let{s3:n}=await Z(),r=await ue(t),o=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,l=[],a;do{let u={Bucket:t.bucket,Prefix:o,...a&&{ContinuationToken:a}},g=await r.send(new n.ListObjectsV2Command(u));if(g.Contents)for(let f of g.Contents)f.Key?.endsWith(".json")&&f.LastModified&&l.push({key:f.Key,lastModified:f.LastModified});a=g.IsTruncated?g.NextContinuationToken:void 0;}while(a);if(l.length===0)return [];l.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?l:e?.limit?l.slice(0,e.limit):l,p=(await Promise.all(d.map(async u=>{try{return await jn(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 qn(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 o=await s.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${s.status}): ${o}`)}return s.json()}function Ji(t){return t&&t>0?Math.min(t,500):100}async function It(t,e){return t.mode==="byok"?(await Hn(t,{limit:1,tag:e?.tag}))[0]??null:(await qn(t,{limit:1,tag:e?.tag}))[0]??null}async function Pt(t,e){if(t.mode==="byok"){let n=Gn(t,e);try{return await jn(t,n)}catch(r){throw Hi(r)?new Error(`Checkpoint ${e} not found`):r}}else return await Wi(t,e)}async function $n(t,e,n){if(e==="latest"){let r=await It(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function Yn(t,e){if(t.mode==="byok")return Kn(t,Vn(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 Qn(t){return !(!t||oe.isAbsolute(t)||t.startsWith("-")||oe.normalize(t).startsWith("..")||t.includes("\0"))}function Dn(t,e){let n=oe.resolve(t,e),r=oe.resolve(t),s=oe.relative(r,n);if(s.startsWith("..")||oe.isAbsolute(s))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Hi(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Ct(t){let e=t.filter(n=>!Qn(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var Zn=10*1024*1024,Bn=false;async function Xn(){if(!Bn)try{await Tt("tar",["--version"]),Bn=!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 Un(t,e){let n=await Pt(t,e),r=await Yn(t,n),s=e.replace(/[^a-zA-Z0-9_-]/g,"_"),o=oe.join(os$1.tmpdir(),`evolve-dl-${s}-${Date.now()}.tar.gz`),l=await fetch(r);if(!l.ok)throw new Error(`Checkpoint download failed (${l.status})`);if(!l.body)throw new Error("Checkpoint download returned empty body");let a=crypto.createHash("sha256"),c=$.createWriteStream(o);try{let i=l.body.getReader();await new Promise((p,u)=>{c.on("error",u),c.on("finish",p);async function g(){for(;;){let{done:f,value:m}=await i.read();if(f){c.end();break}a.update(m),c.write(m)||await new Promise(h=>c.once("drain",h));}}g().catch(u);});}catch(i){throw c.destroy(),await promises.unlink(o).catch(()=>{}),i}let d=a.digest("hex");if(d!==n.hash)throw await promises.unlink(o).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:o,metadata:n}}async function Ln(t){await Xn();let{stdout:e}=await Tt("tar",["-tvzf",t],{maxBuffer:Zn}),n=new Set,r=[],s=[];for(let o of e.trim().split(`
239
+ `)){if(!o||o.startsWith("total "))continue;let l=o[0];if(l!=="-"&&l!=="d"&&l!=="l")throw new Error(`Archive contains unsupported entry type: "${l}"`);let a=o.match(/\d{2}:\d{2}\s+(.+)/)??o.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!a)continue;let c=a[1];if(l==="l"){let d=c.indexOf(" -> ");d!==-1&&(c=c.slice(0,d)),n.add(c);}else l==="d"?r.push(c.replace(/\/$/,"")):s.push(c);}return Ct(r),Ct([...n]),Ct(s)}async function _t(t,e,n){await Xn(),await promises.mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await Tt("tar",r,{maxBuffer:Zn});}function qi(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 Ot(t,e){let n=Jn(t,e);return er(n)}function Yi(t){let e=Jn(t||{});return er(e)}function er(t){return {async listCheckpoints(e){let n=Ji(e?.limit);return t.mode==="byok"?Hn(t,{limit:n,tag:e?.tag}):qn(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return Pt(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,s=n?.to||process.cwd(),o=await $n(t,e),{tmpPath:l,metadata:a}=await Un(t,o);try{if(r)return await promises.mkdir(s,{recursive:!0}),await Ln(l),await _t(l,s),s;{await promises.mkdir(s,{recursive:!0});let c=oe.join(s,`checkpoint-${a.id}.tar.gz`);return await promises.copyFile(l,c),c}}finally{await promises.unlink(l).catch(()=>{});}},async downloadFiles(e,n){let r=await $n(t,e),{tmpPath:s}=await Un(t,r),o;try{let l=await Ln(s),a;if(n?.files){let d=n.files.filter(p=>!Qn(p));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let i=new Set(n.files);a=l.filter(p=>i.has(p));}else if(n?.glob){let d=n.glob.map(qi);a=l.filter(i=>d.some(p=>p.test(i)));}else a=l;if(a.length===0)return {};o=oe.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`);try{await _t(s,o,a);}catch(d){let i=d?.message??"";if(!i.includes("E2BIG")&&!i.includes("Argument list too long")&&!i.includes("ENAMETOOLONG"))throw d;await promises.rm(o,{recursive:!0,force:!0}).catch(()=>{}),o=oe.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`),await _t(s,o);}let c={};return await Promise.all(a.map(async d=>{Dn(o,d),c[d]=await promises.readFile(oe.join(o,d));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(c).map(async([d,i])=>{Dn(n.to,d);let p=oe.join(n.to,d);await promises.mkdir(oe.dirname(p),{recursive:!0}),await promises.writeFile(p,i);}))),c}finally{o&&await promises.rm(o,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(s).catch(()=>{});}}}}function N(t){return `'${t.replace(/'/g,"'\\''")}'`}function Ke(t){return typeof t=="string"&&t.length>0}function X(t,e,n){let r=t[e];if(!Ke(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function Qi(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
240
+ ${n}`)}function Zi(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 Ke(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(Ke(r.ref)&&s.push(`--ref ${N(r.ref)}`),Array.isArray(r.sparse))for(let o of r.sparse){if(!Ke(o))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");s.push(`--sparse ${N(o)}`);}return [s.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function tr(t,e,n){if(n?.length)for(let r of n){let s=Zi(t,r);for(let o of s){let l=await e.commands.run(o,{timeoutMs:12e4});if(l.exitCode!==0)throw Qi(o,l)}}}var Xi=["actionbook","active-research","extract"],es=["agent-browser"],ts={actionbook:Xi,"agent-browser":es},sr="/home/user/.agent-browser",nr=`${sr}/config.json`,or="/home/user/.actionbook",ns=`${or}/config.toml`;function rr(t){return t==="actionbook"||t==="agent-browser"}function rs(t){return t.remote===true}function ir(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 ar(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(rr(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:ir(t.profile)};if(rr(t.provider))return {provider:t.provider,managed:rs(t),profile:ir(t.profile)};throw new Error("Unsupported browser configuration")}function cr(t,e){return Array.from(new Set([...e??[],...ts[t]]))}function At(t,e){return t==="actionbook"?{envs:{},files:[{path:ns,data:`version = 1
241
241
 
242
242
  [browser]
243
243
  mode = "cloud"
244
244
  cdp_endpoint = ${JSON.stringify(e.cdpUrl)}
245
- `}],directories:[rr]}:{envs:{AGENT_BROWSER_CONFIG:er},files:[{path:er,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
246
- `}],directories:[nr]}}function or(t){return (t?.dashboardUrl||E).replace(/\/$/,"")}async function ar(t){return await t.text().catch(()=>"")}async function cr(t,e,n={}){let r=await fetch(`${or(t)}/api/browser-sessions`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({sessionTag:e,options:{remote:true},browserAuth:n.browserCredentials===true}),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`Managed browser session create failed (${r.status}): ${await ar(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 lr(t,e){let n=await fetch(`${or(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 ar(n)}`)}var ns="RSA-OAEP-256",At="browser-login";function rs(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function is(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 ss(t){return await t.text().catch(()=>"")}async function ge(t,e,n={}){let r=await fetch(`${rs(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${is(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 ss(r)}`);return await r.json()}async function os(t,e){let n=await ge(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:ns,keyId:n.id,ciphertext:r.toString("base64url")}}var je=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 ge(this.config,`/api/browser-credentials${r}`);return {credentials:s.credentials.map(o=>this.toMetadata(o)),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 os(this.config,e.password),r=await ge(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 ge(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function Mt(t={}){return new je(t)}async function dr(t){return (await ge({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:as(t.config)})})).server}function as(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var pr="/home/user/.factory/evolve-session.json";function ps(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function ur(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function gr(t,e,n="newline"){let r=new Map;if(t){let s=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let o of s){let l=o.trim();if(!l)continue;let a=l.indexOf(":");if(a<=0)continue;let c=l.slice(0,a).trim(),d=l.slice(a+1).trim();r.set(c.toLowerCase(),`${c}: ${d}`);}}for(let[s,o]of Object.entries(e)){let l=s.toLowerCase();if(l===L&&r.has(l)&&n==="newline"){let a=r.get(l),c=a.slice(a.indexOf(":")+1).trim();r.set(l,`${s}: ${c},${o}`);}else r.set(l,`${s}: ${o}`);}return Array.from(r.values()).join(n==="comma"?", ":`
247
- `)}var fe=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||Nt,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=ur(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 o=++this.nextOperationId;return this.activeOperationId=o,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),o}finalizeOperation(e,n,r,s="idle",o="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=o,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,o){let l=n==="run"?"run_background_complete":"command_background_complete",a=n==="run"?"run_background_failed":"command_background_failed",c=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,s,c,"interrupted");return}n==="run"&&o&&await this.writeDroidSessionState(o);let p=d.exitCode===0?l:a,u=d.exitCode===0?"idle":"error";this.finalizeOperation(e,s,p,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,a,"error");});}createAjvValidator(){let n={...We[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 cs__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.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);let r=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:r,workingDirectory:this.workingDir}),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(r){throw await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),r}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let n of Object.values(this.registry.providerEnvMap))e[n.keyEnv]=this.agentConfig.apiKey;else {let n=this.agentConfig.model?.split("/")[0],r=n?this.registry.providerEnvMap?.[n]:void 0,s=r?r.keyEnv:this.registry.apiKeyEnv,o=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:s;e[o]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=H(this.registry.gatewayPath);this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[O]:this.sessionTag}):this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=n),e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Ot(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.options.secrets){if(Object.prototype.hasOwnProperty.call(this.options.secrets,T))throw new Error(`${T} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);Object.assign(e,this.options.secrets);}if(!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let n=this.registry.customHeadersEnv,r=this.registry.customHeadersFormat||"newline";e[n]=gr(e[n],{[O]:this.sessionTag},r);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await cr(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Ot(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 lr(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}buildGatewayConfigJson(e){let n=H(this.registry.gatewayPath),r=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),s={},o=this.options.secrets?.[this.registry.gatewayConfigEnv];if(o)try{s=JSON.parse(o);}catch{}let l=s.provider??{},a=l.litellm??{},c=a.options??{},d=a.models??{},i=d[r]??{},p=i.headers??{},u=this.agentConfig.type==="opencode"?He(this.agentConfig.reasoningEffort):void 0,g=i.variants??{},f=u?g[u]??{}:void 0;return s.provider={...l,litellm:{...a,npm:"@ai-sdk/openai-compatible",options:{...c,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)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.registry.customHeadersEnv;if(n){let s=this.options.secrets?.[n],o=this.registry.customHeadersFormat||"newline";return {[n]:gr(s,{[O]:this.sessionTag,[L]:`${G}${e}`},o)}}let r=this.registry.spendTrackingEnvs;if(r)return {[r.sessionTagEnv]:this.sessionTag,[r.runTagEnv]:`${G}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[O]:this.sessionTag,[L]:`${G}${e}`})}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(o=>typeof o.sessionId=="string"&&o.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(pr);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(pr,JSON.stringify({sessionId:this.droidSessionId},null,2)));}resolveGatewayModel(e){return this.agentConfig.isDirectMode?e:this.registry.gatewayModelAliases?.[e]??e}resolveCommandModel(e){return (this.agentConfig.isDirectMode?this.registry.directModelAliases:this.registry.gatewayModelAliases)?.[e]??e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupAgentPlugins(e){await Xn(this.agentConfig.type,e,this.options.plugins);}async setupWorkspace(e,n){let 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 l=St({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),a=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(a,l);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let o={...this.options.mcpServers};if(this.options.integrations){let l=await Cn({...this.options.integrations,sessionTag:this.sessionTag});o={...o,integrations:{type:"http",url:l.url,headers:l.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let l=await dr({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});o={...o,[At]:l};}Object.keys(o).length>0&&await at(this.agentConfig.type,e,this.workingDir,o),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await st(e,this.agentConfig.baseUrl||H(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Se(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 o of this.skills){let l=`cp -r ${r}/${o} ${s}/ 2>/dev/null || true`;await e.commands.run(l,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([o,l])=>({path:`${this.workingDir}/context/${o}`,data:l}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.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(([o,l])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:l}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.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=ie,background:o=false,checkpointComment:l}=e,{from:a}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(a&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(a==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await Rt(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');a=v.id;}if(a){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");await this.ensureManagedBrowserSession(n);let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir});let b=await Gn(this.sandbox,this.storage,a);if(await this.setupManagedBrowser(this.sandbox),b.agentType&&b.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${b.agentType}, current: ${this.agentConfig.type})`);let 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 _=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!_}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=a,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(b){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),b}}let c=await this.getSandbox(n);if(await this.loadDroidSessionState(c),this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new ae({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:c.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}this.sessionLogger.writePrompt(r);let d=this.buildCommand(r),i=crypto.randomUUID(),p=this.buildRunEnvs(i);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Se(c,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[O]:this.sessionTag,[L]:`${G}${i}`}),this.agentConfig.type==="qwen"&&await Ze(c,Je(this.agentConfig.reasoningEffort)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await ot(c,this.registry.spendTrackingTomlProvider,{[O]:this.sessionTag,[L]:`${G}${i}`}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await ke(c,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${H()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[O]:this.sessionTag,[L]:`${G}${i}`});let u="",g=W(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 _=g(C);if(this.captureDroidSession(C,_),this.sessionLogger?.writeEventParsed(C,_),n?.onStdout?.(C+`
249
- `),_&&n?.onContent)for(let K of _)n.onContent(K);}},m=v=>{n?.onStderr?.(v);},h=await c.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,o)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.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(c),this.sessionLogger&&!o&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let S;if(this.storage&&!o&&w.exitCode===0)try{S=await Tt(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:l,parentId:this.lastCheckpointId}),this.lastCheckpointId=S.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.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=ie,background:o=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let l=await this.getSandbox(r);this.lastRunTimestamp=Date.now();let a="",c="",d=m=>{a+=m,r?.onStdout?.(m);},i=m=>{c+=m,r?.onStderr?.(m);},p=await l.commands.spawn(e,{cwd:this.workingDir,timeoutMs:s,onStdout:d,onStderr:i}),u=this.beginOperation("command",p,r,"command_start");if(o)return this.watchBackgroundOperation(u,"command",p,r),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let g;try{g=await p.wait();}catch(m){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,r,"command_failed","error"),m}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,r,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,r,"command_complete","idle"):this.finalizeOperation(u,r,"command_failed","error"),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:g.exitCode,stdout:a||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),r=`${this.workingDir}/output`,s=e?"":"-maxdepth 1",l=(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),a=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${r}/`;for(let f of l){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);a>0&&y<a||c.push(m);}let i={},p=await Promise.all(c.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 Tt(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=n.id,n}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,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 o=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,o),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.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=ur(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 o=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${o}`)}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 l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,o=r.runs[s];if(!o)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return o}};var me=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=_n;static browserCredentials=Mt;async initializeAgent(){let e=Be(this.config.agent),n=this.config.sandbox??await ht();if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");let r={},s,o,l=this.config.skills,a;if(this.config.browser){let i=ir(this.config.browser);if(a=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=Ut(e.apiKey);}if((i.provider==="actionbook"||i.provider==="agent-browser")&&(l=sr(i.provider,l),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"?yt:wn,o={provider:i.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E};}}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!a||a.provider!=="agent-browser"||!a.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let c=this.config.storage!==void 0?Ne(this.config.storage,!e.isDirectMode,E,e.isDirectMode?void 0:e.apiKey):void 0,d={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...r,...this.config.mcpServers},browserPrompt:s,managedBrowser:o,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E}:void 0,storage:c};this.agent=new fe(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?o=>this.emit("stdout",o):void 0,onStderr:n?o=>this.emit("stderr",o):void 0,onContent:r?o=>this.emit("content",o):void 0,onLifecycle:s?o=>this.emit("lifecycle",o):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:o}){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 l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o},l)}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=Be(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 Pt(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Pt(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var ee=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e;}async use(e){await this.acquire();try{return await e()}finally{this.release();}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++;}};var z=Symbol.for("evolve.SwarmResult"),te=class t extends Array{get success(){return this.filter(e=>e.status==="success")}get filtered(){return this.filter(e=>e.status==="filtered")}get error(){return this.filter(e=>e.status==="error")}static from(e){let n=new t;return n.push(...e),n}};var $t=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Ft;if(n>rt)throw new Error(`concurrency=${n} exceeds max ${rt}. 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??ie,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:o}=e,l=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(s&&o)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,a,e,c,l):o?this.executeMapItemWithVerify(i,r,p,a,e,c,l):l?P(u=>this.executeMapItem(i,r,p,a,e,c,u),l,p):this.executeMapItem(i,r,p,a,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:r,condition:s,verify:o}=e,l=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>o?this.executeFilterItemWithVerify(p,r,u,a,e,c,l):l?P(g=>this.executeFilterItem(p,r,u,a,e,c,g),l,u):this.executeFilterItem(p,r,u,a,e,c))),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,o=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((S,v)=>{c.push(this.getFiles(S)),d.push(this.getIndex(S,v));});let i={};c.forEach((S,v)=>{Object.entries(S).forEach(([b,C])=>{i[`item_${d[v]}/${b}`]=C;});});let p=Ue(i),u=F(Sn,{fileTree:p}),g=e.systemPrompt?`${u}
245
+ `}],directories:[or]}:{envs:{AGENT_BROWSER_CONFIG:nr},files:[{path:nr,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
246
+ `}],directories:[sr]}}function lr(t){return (t?.dashboardUrl||_).replace(/\/$/,"")}async function dr(t){return await t.text().catch(()=>"")}async function pr(t,e,n={}){let r=await fetch(`${lr(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 dr(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 ur(t,e){let n=await fetch(`${lr(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 dr(n)}`)}var os="RSA-OAEP-256",Mt="browser-login";function as(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}function cs(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 ls(t){return await t.text().catch(()=>"")}async function ge(t,e,n={}){let r=await fetch(`${as(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${cs(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 ls(r)}`);return await r.json()}async function ds(t,e){let n=await ge(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:os,keyId:n.id,ciphertext:r.toString("base64url")}}var je=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 ge(this.config,`/api/browser-credentials${r}`);return {credentials:s.credentials.map(o=>this.toMetadata(o)),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 ds(this.config,e.password),r=await ge(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 ge(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function $t(t={}){return new je(t)}async function gr(t){return (await ge({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:ps(t.config)})})).server}function ps(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var fr="/home/user/.factory/evolve-session.json";function ms(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function mr(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function hr(t,e,n="newline"){let r=new Map;if(t){let s=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let o of s){let l=o.trim();if(!l)continue;let a=l.indexOf(":");if(a<=0)continue;let c=l.slice(0,a).trim(),d=l.slice(a+1).trim();r.set(c.toLowerCase(),`${c}: ${d}`);}}for(let[s,o]of Object.entries(e)){let l=s.toLowerCase();if(l===L&&r.has(l)&&n==="newline"){let a=r.get(l),c=a.slice(a.indexOf(":")+1).trim();r.set(l,`${s}: ${c},${o}`);}else r.set(l,`${s}: ${o}`);}return Array.from(r.values()).join(n==="comma"?", ":`
247
+ `)}var fe=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||jt,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=mr(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 o=++this.nextOperationId;return this.activeOperationId=o,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),o}finalizeOperation(e,n,r,s="idle",o="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=o,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,o){let l=n==="run"?"run_background_complete":"command_background_complete",a=n==="run"?"run_background_failed":"command_background_failed",c=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,s,c,"interrupted");return}n==="run"&&o&&await this.writeDroidSessionState(o);let p=d.exitCode===0?l:a,u=d.exitCode===0?"idle":"error";this.finalizeOperation(e,s,p,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,a,"error");});}createAjvValidator(){let n={...We[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 us__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.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);let r=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:r,workingDirectory:this.workingDir}),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(r){throw await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),r}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let n of Object.values(this.registry.providerEnvMap))e[n.keyEnv]=this.agentConfig.apiKey;else {let n=this.agentConfig.model?.split("/")[0],r=n?this.registry.providerEnvMap?.[n]:void 0,s=r?r.keyEnv:this.registry.apiKeyEnv,o=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:s;e[o]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=H(this.registry.gatewayPath);this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[O]:this.sessionTag}):this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=n),e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,At(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.options.secrets){if(Object.prototype.hasOwnProperty.call(this.options.secrets,T))throw new Error(`${T} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);Object.assign(e,this.options.secrets);}if(!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let n=this.registry.customHeadersEnv,r=this.registry.customHeadersFormat||"newline";e[n]=hr(e[n],{[O]:this.sessionTag},r);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await pr(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=At(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 ur(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}buildGatewayConfigJson(e){let n=H(this.registry.gatewayPath),r=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),s={},o=this.options.secrets?.[this.registry.gatewayConfigEnv];if(o)try{s=JSON.parse(o);}catch{}let l=s.provider??{},a=l.litellm??{},c=a.options??{},d=a.models??{},i=d[r]??{},p=i.headers??{},u=this.agentConfig.type==="opencode"?qe(this.agentConfig.reasoningEffort):void 0,g=i.variants??{},f=u?g[u]??{}:void 0;return s.provider={...l,litellm:{...a,npm:"@ai-sdk/openai-compatible",options:{...c,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)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.registry.customHeadersEnv;if(n){let s=this.options.secrets?.[n],o=this.registry.customHeadersFormat||"newline";return {[n]:hr(s,{[O]:this.sessionTag,[L]:`${G}${e}`},o)}}let r=this.registry.spendTrackingEnvs;if(r)return {[r.sessionTagEnv]:this.sessionTag,[r.runTagEnv]:`${G}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[O]:this.sessionTag,[L]:`${G}${e}`})}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(o=>typeof o.sessionId=="string"&&o.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(fr);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(fr,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 tr(this.agentConfig.type,e,this.options.plugins);}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 l=xt({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),a=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(a,l);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let o={...this.options.mcpServers};if(this.options.integrations){let l=await En({...this.options.integrations,sessionTag:this.sessionTag});o={...o,integrations:{type:"http",url:l.url,headers:l.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let l=await gr({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});o={...o,[Mt]:l};}Object.keys(o).length>0&&await ct(this.agentConfig.type,e,this.workingDir,o),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await ot(e,this.agentConfig.baseUrl||H(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Se(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 o of this.skills){let l=`cp -r ${r}/${o} ${s}/ 2>/dev/null || true`;await e.commands.run(l,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([o,l])=>({path:`${this.workingDir}/context/${o}`,data:l}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.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(([o,l])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:l}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.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:ms(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=ie,background:o=false,checkpointComment:l}=e,{from:a}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(a&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(a==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let b=await It(this.storage);if(!b)throw new Error('No checkpoints found for from: "latest".');a=b.id;}if(a){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");await this.ensureManagedBrowserSession(n);let b=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:b,workingDirectory:this.workingDir});let v=await Wn(this.sandbox,this.storage,a);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 C=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==C)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${C})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let E=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!E}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=a,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(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),v}}let c=await this.getSandbox(n);if(await this.loadDroidSessionState(c),this.lastRunTimestamp=Date.now(),!this.sessionLogger){let b=this.options.sandboxProvider;this.sessionLogger=new ae({provider:b?.name||b?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:c.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}this.sessionLogger.writePrompt(r);let d=this.buildCommand(r),i=crypto.randomUUID(),p=this.buildRunEnvs(i);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Se(c,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[O]:this.sessionTag,[L]:`${G}${i}`}),this.agentConfig.type==="qwen"&&await Xe(c,He(this.agentConfig.reasoningEffort)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await at(c,this.registry.spendTrackingTomlProvider,{[O]:this.sessionTag,[L]:`${G}${i}`}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await ke(c,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${H()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[O]:this.sessionTag,[L]:`${G}${i}`});let u="",g=z(this.agentConfig.type),f=b=>{u+=b;let v=u.split(`
248
+ `);u=v.pop()??"";for(let C of v){if(!C.trim())continue;let E=g(C);if(this.captureDroidSession(C,E),this.sessionLogger?.writeEventParsed(C,E),n?.onStdout?.(C+`
249
+ `),E&&n?.onContent)for(let K of E)n.onContent(K);}},m=b=>{n?.onStderr?.(b);},h=await c.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,o)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.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"),u.trim()){let b=g(u);if(this.captureDroidSession(u,b),this.sessionLogger?.writeEventParsed(u,b),n?.onStdout?.(u+`
250
+ `),b&&n?.onContent)for(let v of b)n.onContent(v);}await this.writeDroidSessionState(c),this.sessionLogger&&!o&&await Promise.race([this.sessionLogger.flush(),new Promise(b=>setTimeout(b,2e3))]);let S;if(this.storage&&!o&&w.exitCode===0)try{S=await Rt(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:l,parentId:this.lastCheckpointId}),this.lastCheckpointId=S.id;}catch(b){console.warn(`[Evolve] Auto-checkpoint failed: ${b.message}`);}return {sandboxId:c.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=ie,background:o=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let l=await this.getSandbox(r);this.lastRunTimestamp=Date.now();let a="",c="",d=m=>{a+=m,r?.onStdout?.(m);},i=m=>{c+=m,r?.onStderr?.(m);},p=await l.commands.spawn(e,{cwd:this.workingDir,timeoutMs:s,onStdout:d,onStderr:i}),u=this.beginOperation("command",p,r,"command_start");if(o)return this.watchBackgroundOperation(u,"command",p,r),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let g;try{g=await p.wait();}catch(m){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,r,"command_failed","error"),m}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,r,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,r,"command_complete","idle"):this.finalizeOperation(u,r,"command_failed","error"),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:g.exitCode,stdout:a||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),r=`${this.workingDir}/output`,s=e?"":"-maxdepth 1",l=(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),a=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${r}/`;for(let f of l){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);a>0&&y<a||c.push(m);}let i={},p=await Promise.all(c.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 Rt(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=n.id,n}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,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 o=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,o),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.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=mr(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 o=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${o}`)}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 l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,o=r.runs[s];if(!o)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return o}};function hs(t){return (t||process.env.EVOLVE_DASHBOARD_URL||_).replace(/\/$/,"")}function ys(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 ws(t){return await t.text().catch(()=>"")}async function yr(t,e,n={}){let r=await fetch(`${hs(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${ys(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 ws(r)}`);return r.status===204?{}:await r.json()}var Ve=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 yr(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await yr(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function Dt(t={}){return new Ve(t)}var me=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=Tn;static browserCredentials=$t;static browserProfiles=Dt;async initializeAgent(){let e=Be(this.config.agent),n=this.config.sandbox??await yt();if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");let r={},s,o,l=this.config.skills,a;if(this.config.browser){let i=ar(this.config.browser);if(a=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=Ft(e.apiKey);}if((i.provider==="actionbook"||i.provider==="agent-browser")&&(l=cr(i.provider,l),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"?wt:vn,o={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(!a||a.provider!=="agent-browser"||!a.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let c=this.config.storage!==void 0?Ne(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:o,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:l,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,storage:c};this.agent=new fe(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?o=>this.emit("stdout",o):void 0,onStderr:n?o=>this.emit("stderr",o):void 0,onContent:r?o=>this.emit("content",o):void 0,onLifecycle:s?o=>this.emit("lifecycle",o):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:o}){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 l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o},l)}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=Be(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 Ot(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Ot(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 W=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 Bt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Kt;if(n>it)throw new Error(`concurrency=${n} exceeds max ${it}. 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??ie,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:o}=e,l=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(s&&o)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,a,e,c,l):o?this.executeMapItemWithVerify(i,r,p,a,e,c,l):l?P(u=>this.executeMapItem(i,r,p,a,e,c,u),l,p):this.executeMapItem(i,r,p,a,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:r,condition:s,verify:o}=e,l=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>o?this.executeFilterItemWithVerify(p,r,u,a,e,c,l):l?P(g=>this.executeFilterItem(p,r,u,a,e,c,g),l,u):this.executeFilterItem(p,r,u,a,e,c))),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,o=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((S,b)=>{c.push(this.getFiles(S)),d.push(this.getIndex(S,b));});let i={};c.forEach((S,b)=>{Object.entries(S).forEach(([v,C])=>{i[`item_${d[b]}/${v}`]=C;});});let p=Ue(i),u=F(kn,{fileTree:p}),g=e.systemPrompt?`${u}
252
252
 
253
- ${e.systemPrompt}`:u,f=(S,v,b)=>({operationId:l,operation:"reduce",tag:S.tag,sandboxId:S.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(S,v,b,C)=>{let _=await this.semaphore.use(()=>this.execute(i,S,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:v,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:e.name,operationId:l,operation:"reduce",role:"worker",errorRetry:b,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),K=f(_,b,C&&C>1?C-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:K,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:K}},x=`${this.config.tag}-reduce`;return s?this.runWithVerification((S,v,b)=>w(S,v,void 0,b),{originalPrompt:r,inputFiles:i,verifyConfig:s,timeoutMs:a,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:l,baseTag:x,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?P(S=>{let v=S>1?S-1:void 0,b=v?`${x}-er${v}`:x;return w(r,b,v)},o):w(r,x)}async bestOf(e){let{item:n,prompt:r,config:s}=e,o=e.retry??this.config.retry,l=s.n??s.taskAgents?.length;if(l===void 0)throw new Error("bestOf requires n or taskAgents");if(l<2)throw new Error("bestOf requires n >= 2");let a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),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:l},async(v,b)=>{let C=o?await P(_=>this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:b,operationId:a,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:c,attempt:_}),o,b):await this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:b,operationId:a,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:c});return s.onCandidateComplete?.(0,b,C.status==="success"?"success":"error"),C})),y=o?await P(v=>this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:c,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m,attempt:v}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:c,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m}),w=h.findIndex(v=>v.status==="success"),x=y.decision?.winner??(w>=0?w:0);s.onJudgeComplete?.(0,x,y.decision?.reasoning??"Judge failed to provide reasoning");let S={operationId:a,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:l};return {winner:h[x]??h[0],winnerIndex:x,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:S,candidates:h}}async execute(e,n,r){let s=null,o="",l=r.tagPrefix,a={},c=null,d,i,p={...this.config.agent,...r.agent};try{s=new me().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});o=u.sandboxId,l=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),a=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:r.schema?g?(c=g.data,g.error&&(d=g.error),g.rawData&&(i=g.rawData)):d="Failed to read output files from sandbox":c=a;}catch(u){if(d=u.message,s){l=s.getSessionTag()??r.tagPrefix;try{a=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:a,data:c,tag:l,sandboxId:o,error:d,rawData:i}}async executeMapItem(e,n,r,s,o,l,a=1){let c=this.getFiles(e),d=a>1?`${this.config.tag}-map-${r}-er${a-1}`:`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,c,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(c,i,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),m={operationId:s,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,s,o,l,a){let c=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=o.verify,p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=this.evaluatePrompt(n,c,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 x=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:y,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),S={operationId:s,operation:"map",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(x,S)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:c,verifyConfig:i,timeoutMs:l,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:a,itemIndex:r,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,o,l,a){let c=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,c,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=o.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=o.mcpServers??this.config.mcpServers,f=p.mcpServers??g,m=p.judgeMcpServers??p.mcpServers??g,h=o.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,x=o.integrations??this.config.integrations,S=p.integrations??x,v=p.judgeIntegrations??p.integrations??x,b=await Promise.all(Array.from({length:u},async(he,ye)=>{let Bt=a?await P(hr=>this.executeBestOfCandidate({inputFiles:c,prompt:i,candidateIndex:ye,operationId:s,config:p,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:l,parentIndex:r,attempt:hr,_pipelineContext:o._pipelineContext}),a,ye):await this.executeBestOfCandidate({inputFiles:c,prompt:i,candidateIndex:ye,operationId:s,config:p,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:l,parentIndex:r,_pipelineContext:o._pipelineContext});return p.onCandidateComplete?.(r,ye,Bt.status==="success"?"success":"error"),Bt})),C=a?await P(he=>this.executeBestOfJudge({inputFiles:c,taskPrompt:i,candidates:b,config:p,timeoutMs:l,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:v,parentIndex:r,attempt:he,_pipelineContext:o._pipelineContext}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:i,candidates:b,config:p,timeoutMs:l,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:v,parentIndex:r,_pipelineContext:o._pipelineContext}),_=b.findIndex(he=>he.status==="success"),K=C.decision?.winner??(_>=0?_:0),Dt=b[K]??b[0];p.onJudgeComplete?.(r,K,C.decision?.reasoning??"Judge failed to provide reasoning");let mr={operationId:s,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:u,...this.pipelineContextToMeta(o._pipelineContext)};return {...Dt,meta:{...Dt.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:r,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:K,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:mr,candidates:b}}}async executeFilterItem(e,n,r,s,o,l,a=1){let c=this.getFiles(e),d=a>1?`${this.config.tag}-filter-${r}-er${a-1}`:`${this.config.tag}-filter-${r}`,i=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,u=o.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:i,skills:p,integrations:u,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(g,f,c)}async executeFilterItemWithVerify(e,n,r,s,o,l,a){let c=this.getFiles(e),d=`${this.config.tag}-filter-${r}`,i=o.verify,p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=async(m,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,m,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:h,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),x={operationId:s,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(w,x,c)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:c,verifyConfig:i,timeoutMs:l,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:a,itemIndex:r,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:o,config:l,timeoutMs:a,parentIndex:c,attempt:d=1,_pipelineContext:i}=e,p=c!==void 0?`${this.config.tag}-map-${c}-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:l.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:u,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:c,role:"candidate",candidateIndex:s,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(i)}})),f={operationId:o,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
253
+ ${e.systemPrompt}`:u,f=(S,b,v)=>({operationId:l,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)}),m=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,w=async(S,b,v,C)=>{let E=await this.semaphore.use(()=>this.execute(i,S,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:b,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:e.name,operationId:l,operation:"reduce",role:"worker",errorRetry:v,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),K=f(E,v,C&&C>1?C-1:void 0);return E.error?{status:"error",data:null,files:E.files,meta:K,error:E.error,rawData:E.rawData}:{status:"success",data:E.data,files:E.files,meta:K}},x=`${this.config.tag}-reduce`;return s?this.runWithVerification((S,b,v)=>w(S,b,void 0,v),{originalPrompt:r,inputFiles:i,verifyConfig:s,timeoutMs:a,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:l,baseTag:x,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?P(S=>{let b=S>1?S-1:void 0,v=b?`${x}-er${b}`:x;return w(r,v,b)},o):w(r,x)}async bestOf(e){let{item:n,prompt:r,config:s}=e,o=e.retry??this.config.retry,l=s.n??s.taskAgents?.length;if(l===void 0)throw new Error("bestOf requires n or taskAgents");if(l<2)throw new Error("bestOf requires n >= 2");let a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),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:l},async(b,v)=>{let C=o?await P(E=>this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:a,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:c,attempt:E}),o,v):await this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:a,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:c});return s.onCandidateComplete?.(0,v,C.status==="success"?"success":"error"),C})),y=o?await P(b=>this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:c,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m,attempt:b}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:c,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m}),w=h.findIndex(b=>b.status==="success"),x=y.decision?.winner??(w>=0?w:0);s.onJudgeComplete?.(0,x,y.decision?.reasoning??"Judge failed to provide reasoning");let S={operationId:a,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:l};return {winner:h[x]??h[0],winnerIndex:x,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:S,candidates:h}}async execute(e,n,r){let s=null,o="",l=r.tagPrefix,a={},c=null,d,i,p={...this.config.agent,...r.agent};try{s=new me().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});o=u.sandboxId,l=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),a=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:r.schema?g?(c=g.data,g.error&&(d=g.error),g.rawData&&(i=g.rawData)):d="Failed to read output files from sandbox":c=a;}catch(u){if(d=u.message,s){l=s.getSessionTag()??r.tagPrefix;try{a=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:a,data:c,tag:l,sandboxId:o,error:d,rawData:i}}async executeMapItem(e,n,r,s,o,l,a=1){let c=this.getFiles(e),d=a>1?`${this.config.tag}-map-${r}-er${a-1}`:`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,c,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(c,i,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),m={operationId:s,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,s,o,l,a){let c=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=o.verify,p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=this.evaluatePrompt(n,c,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 x=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:y,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),S={operationId:s,operation:"map",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(x,S)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:c,verifyConfig:i,timeoutMs:l,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:a,itemIndex:r,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,o,l,a){let c=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,c,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=o.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=o.mcpServers??this.config.mcpServers,f=p.mcpServers??g,m=p.judgeMcpServers??p.mcpServers??g,h=o.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,x=o.integrations??this.config.integrations,S=p.integrations??x,b=p.judgeIntegrations??p.integrations??x,v=await Promise.all(Array.from({length:u},async(he,ye)=>{let Lt=a?await P(vr=>this.executeBestOfCandidate({inputFiles:c,prompt:i,candidateIndex:ye,operationId:s,config:p,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:l,parentIndex:r,attempt:vr,_pipelineContext:o._pipelineContext}),a,ye):await this.executeBestOfCandidate({inputFiles:c,prompt:i,candidateIndex:ye,operationId:s,config:p,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:l,parentIndex:r,_pipelineContext:o._pipelineContext});return p.onCandidateComplete?.(r,ye,Lt.status==="success"?"success":"error"),Lt})),C=a?await P(he=>this.executeBestOfJudge({inputFiles:c,taskPrompt:i,candidates:v,config:p,timeoutMs:l,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:b,parentIndex:r,attempt:he,_pipelineContext:o._pipelineContext}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:i,candidates:v,config:p,timeoutMs:l,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:b,parentIndex:r,_pipelineContext:o._pipelineContext}),E=v.findIndex(he=>he.status==="success"),K=C.decision?.winner??(E>=0?E:0),Ut=v[K]??v[0];p.onJudgeComplete?.(r,K,C.decision?.reasoning??"Judge failed to provide reasoning");let br={operationId:s,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:u,...this.pipelineContextToMeta(o._pipelineContext)};return {...Ut,meta:{...Ut.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:r,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:K,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:br,candidates:v}}}async executeFilterItem(e,n,r,s,o,l,a=1){let c=this.getFiles(e),d=a>1?`${this.config.tag}-filter-${r}-er${a-1}`:`${this.config.tag}-filter-${r}`,i=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,u=o.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:i,skills:p,integrations:u,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(g,f,c)}async executeFilterItemWithVerify(e,n,r,s,o,l,a){let c=this.getFiles(e),d=`${this.config.tag}-filter-${r}`,i=o.verify,p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=async(m,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,m,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:h,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),x={operationId:s,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(w,x,c)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:c,verifyConfig:i,timeoutMs:l,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:a,itemIndex:r,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:o,config:l,timeoutMs:a,parentIndex:c,attempt:d=1,_pipelineContext:i}=e,p=c!==void 0?`${this.config.tag}-map-${c}-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:l.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:u,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:c,role:"candidate",candidateIndex:s,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(i)}})),f={operationId:o,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
254
 
255
- Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([o,l])=>{n[`candidate_${s}/${o}`]=l;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:o,parentIndex:l,attempt:a=1,_pipelineContext:c}=e,d=l!==void 0?`${this.config.tag}-map-${l}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=a>1?`${d}-er${a-1}`:d,p=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=Ue(p),g=F(wt,{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,vn,{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:o,operation:"map",itemIndex:l,role:"judge",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(c)}})),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:o,retryAttempt:l=1,operation:a,itemIndex:c,attemptIndex:d,_pipelineContext:i}=e,p=l>1?`${o}-verifier-er${l-1}`:`${o}-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=Ue(m),y=F(vt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(m,bn,{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:a,itemIndex:c,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(i)}})),x=null;if(w.data&&!w.error)x=w.data;else if(w.rawData)try{let S=JSON.parse(w.rawData);x={passed:!!S.passed,reasoning:S.reasoning??"Verification completed",feedback:S.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:x?"success":"error",decision:x,tag:w.tag,sandboxId:w.sandboxId,error:x?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return F(bt,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:s,verifyConfig:o,timeoutMs:l,operationId:a,baseTag:c,retry:d,itemIndex:i=0,operation:p,_pipelineContext:u}=n,g=o.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let w=h>1?`${c}-vr${h-1}`:c,x=d?await P(b=>e(f,b>1?`${w}-er${b-1}`:w,h),d,i):await e(f,w,h);if(o.onWorkerComplete?.(i,h,x.status==="error"?"error":"success"),x.status==="error")return x;m=x;let S=d?await P(b=>this.executeVerify({inputFiles:s,outputFiles:x.files,taskPrompt:f,config:o,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,retryAttempt:b,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:x.files,taskPrompt:f,config:o,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),v={operationId:a,operation:"verify",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(o.onVerifierComplete?.(i,h,S.decision?.passed??false,S.decision?.feedback),S.decision?.passed)return {...x,verify:{passed:true,reasoning:S.decision.reasoning,verifyMeta:v,attempts:h}};if(h<g){let b=S.decision?.feedback??S.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(r,b);}}let y=h>1?`${c}-vr${h-1}`:c;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:a,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,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&&z in e&&e[z]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,r){let s=r??e.files;return e.error?{[z]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[z]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[z]:true,status:"error",data:null,files:{},meta:n,error:e}}};var Ve=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 Ge(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,o=Date.now();for(let a=0;a<this.steps.length;a++){let c=this.steps[a],d=c.config.name,i=Date.now();this.events.onStepStart?.({type:c.type,index:a,name:d,itemCount:s.length});let p={pipelineRunId:n,pipelineStepIndex:a};try{let u=await this.executeStep(c,s,a,d,p),g=Date.now()-i;if(r.push({type:c.type,index:a,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:c.type,index:a,name:d,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),c.type==="reduce")return {pipelineRunId:n,steps:r,output:u.output,totalDurationMs:Date.now()-o};s=u.nextItems;}catch(u){throw this.events.onStepError?.({type:c.type,index:a,name:d,error:u instanceof Error?u:new Error(String(u))}),u}}let l=r[r.length-1];return {pipelineRunId:n,steps:r,output:l?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,r,s,o){if(e.type==="map"){let c=e.config,d=await this.swarm.map({items:n,...c,_pipelineContext:o,retry:this.wrapRetry(c.retry,r,s),verify:this.wrapVerify(c.verify,r,s),bestOf:this.wrapBestOf(c.bestOf,r,s)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,d=await this.swarm.filter({items:n,...c,_pipelineContext:o,retry:this.wrapRetry(c.retry,r,s),verify:this.wrapVerify(c.verify,r,s)}),i=c.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 l=e.config,a=await this.swarm.reduce({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s)});return {output:a,nextItems:[],successCount:a.status==="success"?1:0,errorCount:a.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,o,l)=>{e.onItemRetry?.(s,o,l),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,error:l});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,o,l)=>{e.onWorkerComplete?.(s,o,l),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,status:l});},onVerifierComplete:(s,o,l,a)=>{e.onVerifierComplete?.(s,o,l,a),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,passed:l,feedback:a});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,o,l)=>{e.onCandidateComplete?.(s,o,l),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:o,status:l});},onJudgeComplete:(s,o,l)=>{e.onJudgeComplete?.(s,o,l),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:o,reasoning:l});}}}},Ge=class t extends Ve{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 bs=6e5,Ss=5e3;function fr(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 xs(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||E;async function r(a,c){let d=await fetch(`${n}${a}`,{...c,headers:{Authorization:`Bearer ${e}`,...c?.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(a){return {id:a.id,tag:a.tag,agent:a.agent,model:a.model||null,provider:a.provider,sandboxId:a.sandboxId||null,state:a.isEnded?"ended":"live",runtimeStatus:a.runtimeStatus||"unknown",cost:typeof a.cost=="number"?a.cost:null,createdAt:a.createdAt,endedAt:a.endedAt||null,stepCount:a.stepCount||0,toolStats:a.toolStats||null}}function o(a,c){if(a.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(a.status||"unknown")})`);if(typeof a.replayUrl!="string"||typeof a.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:a.sessionId||c,status:"ready",replayUrl:a.replayUrl,downloadUrl:a.downloadUrl,suggestedStartSeconds:typeof a.suggestedStartSeconds=="number"?a.suggestedStartSeconds:void 0,sizeBytes:typeof a.sizeBytes=="number"?a.sizeBytes:void 0,readyAt:typeof a.readyAt=="string"?a.readyAt:void 0}}let l=a=>new Promise(c=>setTimeout(c,a));return {async list(a){let c=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(a?.limit??20,200)),paginated:"true"});if(a?.cursor&&c.set("cursor",a.cursor),a?.state&&a.state!=="all"&&c.set("state",a.state),a?.agent&&c.set("agent",a.agent),a?.tagPrefix&&c.set("tagPrefix",a.tagPrefix),a?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};c.set("sortDirection",p[a.sort]),a.sort==="cost"?c.set("sortField","cost"):c.set("sortField","timestamp");}let i=await(await r(`/api/sessions?${c}`)).json();return {items:(i.items||[]).map(s),nextCursor:i.nextCursor||null,hasMore:!!i.hasMore}},async get(a){let d=await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json();return s(d)},async events(a,c){let d=new URLSearchParams;c?.since!=null&&d.set("since",String(c.since));let i=d.toString();return (await(await r(`/api/sessions/${encodeURIComponent(a)}/events${i?`?${i}`:""}`)).json()).events||[]},async download(a,c){let p=(await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json()).tag||a,u=await fetch(`${n}/api/sessions/${encodeURIComponent(a)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!u.ok){let h=await u.text().catch(()=>"");throw new Error(`Download failed (${u.status}): ${h||u.statusText}`)}let g=c?.to||process.cwd();await promises.mkdir(g,{recursive:true});let f=oe.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(a,c){let d=fr("timeoutMs",c?.timeoutMs,bs),i=fr("intervalMs",c?.intervalMs,Ss),p=Date.now()+d,u=`/api/sessions/${encodeURIComponent(a)}/browser-replay`;for(;;){let g=p-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let 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 o(m,a);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 l(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=yr;exports.Agent=fe;exports.BROWSER_ACTIONBOOK_PROMPT=yt;exports.BROWSER_LOGIN_MCP_SERVER_NAME=At;exports.BrowserCredentialsClient=je;exports.Evolve=me;exports.JUDGE_PROMPT=wt;exports.Pipeline=Ve;exports.RETRY_FEEDBACK_PROMPT=bt;exports.SCHEMA_PROMPT=yn;exports.SWARM_RESULT_BRAND=z;exports.SYSTEM_PROMPT=hn;exports.Semaphore=ee;exports.Swarm=$t;exports.SwarmResultList=te;exports.TerminalPipeline=Ge;exports.VALIDATION_PRESETS=We;exports.VERIFY_PROMPT=vt;exports.WORKSPACE_PROMPT=fn;exports.WORKSPACE_SWE_PROMPT=mn;exports.applyTemplate=F;exports.browserCredentials=Mt;exports.buildWorkerSystemPrompt=St;exports.createAgentParser=W;exports.createClaudeParser=Pe;exports.createCodexParser=Oe;exports.createDroidParser=Ae;exports.createGeminiParser=Me;exports.executeWithRetry=P;exports.expandPath=V;exports.getAgentConfig=D;exports.getMcpSettingsDir=U;exports.getMcpSettingsPath=B;exports.isValidAgentType=br;exports.isZodSchema=M;exports.jsonSchemaToString=Y;exports.parseNdjsonLine=Qr;exports.parseNdjsonOutput=Zr;exports.parseQwenOutput=Zt;exports.readLocalDir=Xt;exports.resolveStorageConfig=Ne;exports.saveLocalDir=en;exports.sessions=xs;exports.storage=zi;exports.writeClaudeMcpConfig=we;exports.writeCodexMcpConfig=Ie;exports.writeDroidGatewaySettings=ke;exports.writeDroidMcpConfig=xe;exports.writeGeminiMcpConfig=ve;exports.writeMcpConfig=at;exports.writeQwenMcpConfig=be;exports.zodSchemaToJson=q;
255
+ Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([o,l])=>{n[`candidate_${s}/${o}`]=l;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:o,parentIndex:l,attempt:a=1,_pipelineContext:c}=e,d=l!==void 0?`${this.config.tag}-map-${l}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=a>1?`${d}-er${a-1}`:d,p=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=Ue(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,Sn,{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:o,operation:"map",itemIndex:l,role:"judge",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(c)}})),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:o,retryAttempt:l=1,operation:a,itemIndex:c,attemptIndex:d,_pipelineContext:i}=e,p=l>1?`${o}-verifier-er${l-1}`:`${o}-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=Ue(m),y=F(vt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(m,xn,{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:a,itemIndex:c,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(i)}})),x=null;if(w.data&&!w.error)x=w.data;else if(w.rawData)try{let S=JSON.parse(w.rawData);x={passed:!!S.passed,reasoning:S.reasoning??"Verification completed",feedback:S.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:x?"success":"error",decision:x,tag:w.tag,sandboxId:w.sandboxId,error:x?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:o,timeoutMs:l,operationId:a,baseTag:c,retry:d,itemIndex:i=0,operation:p,_pipelineContext:u}=n,g=o.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let w=h>1?`${c}-vr${h-1}`:c,x=d?await P(v=>e(f,v>1?`${w}-er${v-1}`:w,h),d,i):await e(f,w,h);if(o.onWorkerComplete?.(i,h,x.status==="error"?"error":"success"),x.status==="error")return x;m=x;let S=d?await P(v=>this.executeVerify({inputFiles:s,outputFiles:x.files,taskPrompt:f,config:o,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,retryAttempt:v,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:x.files,taskPrompt:f,config:o,timeoutMs:l,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),b={operationId:a,operation:"verify",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(o.onVerifierComplete?.(i,h,S.decision?.passed??false,S.decision?.feedback),S.decision?.passed)return {...x,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";f=t.buildRetryPromptWithFeedback(r,v);}}let y=h>1?`${c}-vr${h-1}`:c;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:a,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,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&&W in e&&e[W]===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?{[W]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[W]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[W]:true,status:"error",data:null,files:{},meta:n,error:e}}};var Ge=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 ze(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,o=Date.now();for(let a=0;a<this.steps.length;a++){let c=this.steps[a],d=c.config.name,i=Date.now();this.events.onStepStart?.({type:c.type,index:a,name:d,itemCount:s.length});let p={pipelineRunId:n,pipelineStepIndex:a};try{let u=await this.executeStep(c,s,a,d,p),g=Date.now()-i;if(r.push({type:c.type,index:a,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:c.type,index:a,name:d,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),c.type==="reduce")return {pipelineRunId:n,steps:r,output:u.output,totalDurationMs:Date.now()-o};s=u.nextItems;}catch(u){throw this.events.onStepError?.({type:c.type,index:a,name:d,error:u instanceof Error?u:new Error(String(u))}),u}}let l=r[r.length-1];return {pipelineRunId:n,steps:r,output:l?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,r,s,o){if(e.type==="map"){let c=e.config,d=await this.swarm.map({items:n,...c,_pipelineContext:o,retry:this.wrapRetry(c.retry,r,s),verify:this.wrapVerify(c.verify,r,s),bestOf:this.wrapBestOf(c.bestOf,r,s)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,d=await this.swarm.filter({items:n,...c,_pipelineContext:o,retry:this.wrapRetry(c.retry,r,s),verify:this.wrapVerify(c.verify,r,s)}),i=c.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 l=e.config,a=await this.swarm.reduce({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s)});return {output:a,nextItems:[],successCount:a.status==="success"?1:0,errorCount:a.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,o,l)=>{e.onItemRetry?.(s,o,l),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,error:l});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,o,l)=>{e.onWorkerComplete?.(s,o,l),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,status:l});},onVerifierComplete:(s,o,l,a)=>{e.onVerifierComplete?.(s,o,l,a),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,passed:l,feedback:a});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,o,l)=>{e.onCandidateComplete?.(s,o,l),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:o,status:l});},onJudgeComplete:(s,o,l)=>{e.onJudgeComplete?.(s,o,l),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:o,reasoning:l});}}}},ze=class t extends Ge{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 Ts=6e5,Rs=5e3;function wr(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 Is(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(a,c){let d=await fetch(`${n}${a}`,{...c,headers:{Authorization:`Bearer ${e}`,...c?.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(a){return {id:a.id,tag:a.tag,agent:a.agent,model:a.model||null,provider:a.provider,sandboxId:a.sandboxId||null,state:a.isEnded?"ended":"live",runtimeStatus:a.runtimeStatus||"unknown",cost:typeof a.cost=="number"?a.cost:null,createdAt:a.createdAt,endedAt:a.endedAt||null,stepCount:a.stepCount||0,toolStats:a.toolStats||null}}function o(a,c){if(a.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(a.status||"unknown")})`);if(typeof a.replayUrl!="string"||typeof a.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:a.sessionId||c,status:"ready",replayUrl:a.replayUrl,downloadUrl:a.downloadUrl,suggestedStartSeconds:typeof a.suggestedStartSeconds=="number"?a.suggestedStartSeconds:void 0,sizeBytes:typeof a.sizeBytes=="number"?a.sizeBytes:void 0,readyAt:typeof a.readyAt=="string"?a.readyAt:void 0}}let l=a=>new Promise(c=>setTimeout(c,a));return {async list(a){let c=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(a?.limit??20,200)),paginated:"true"});if(a?.cursor&&c.set("cursor",a.cursor),a?.state&&a.state!=="all"&&c.set("state",a.state),a?.agent&&c.set("agent",a.agent),a?.tagPrefix&&c.set("tagPrefix",a.tagPrefix),a?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};c.set("sortDirection",p[a.sort]),a.sort==="cost"?c.set("sortField","cost"):c.set("sortField","timestamp");}let i=await(await r(`/api/sessions?${c}`)).json();return {items:(i.items||[]).map(s),nextCursor:i.nextCursor||null,hasMore:!!i.hasMore}},async get(a){let d=await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json();return s(d)},async events(a,c){let d=new URLSearchParams;c?.since!=null&&d.set("since",String(c.since));let i=d.toString();return (await(await r(`/api/sessions/${encodeURIComponent(a)}/events${i?`?${i}`:""}`)).json()).events||[]},async download(a,c){let p=(await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json()).tag||a,u=await fetch(`${n}/api/sessions/${encodeURIComponent(a)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!u.ok){let h=await u.text().catch(()=>"");throw new Error(`Download failed (${u.status}): ${h||u.statusText}`)}let g=c?.to||process.cwd();await promises.mkdir(g,{recursive:true});let f=oe.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(a,c){let d=wr("timeoutMs",c?.timeoutMs,Ts),i=wr("intervalMs",c?.intervalMs,Rs),p=Date.now()+d,u=`/api/sessions/${encodeURIComponent(a)}/browser-replay`;for(;;){let g=p-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let 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 o(m,a);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 l(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=Ye;exports.AGENT_TYPES=Sr;exports.Agent=fe;exports.BROWSER_ACTIONBOOK_PROMPT=wt;exports.BROWSER_LOGIN_MCP_SERVER_NAME=Mt;exports.BrowserCredentialsClient=je;exports.BrowserProfilesClient=Ve;exports.Evolve=me;exports.JUDGE_PROMPT=bt;exports.Pipeline=Ge;exports.RETRY_FEEDBACK_PROMPT=St;exports.SCHEMA_PROMPT=bn;exports.SWARM_RESULT_BRAND=W;exports.SYSTEM_PROMPT=wn;exports.Semaphore=ee;exports.Swarm=Bt;exports.SwarmResultList=te;exports.TerminalPipeline=ze;exports.VALIDATION_PRESETS=We;exports.VERIFY_PROMPT=vt;exports.WORKSPACE_PROMPT=hn;exports.WORKSPACE_SWE_PROMPT=yn;exports.applyTemplate=F;exports.browserCredentials=$t;exports.browserProfiles=Dt;exports.buildWorkerSystemPrompt=xt;exports.createAgentParser=z;exports.createClaudeParser=Pe;exports.createCodexParser=Oe;exports.createDroidParser=Ae;exports.createGeminiParser=Me;exports.executeWithRetry=P;exports.expandPath=V;exports.getAgentConfig=D;exports.getMcpSettingsDir=U;exports.getMcpSettingsPath=B;exports.isValidAgentType=Cr;exports.isZodSchema=M;exports.jsonSchemaToString=Y;exports.parseNdjsonLine=ti;exports.parseNdjsonOutput=ni;exports.parseQwenOutput=en;exports.readLocalDir=tn;exports.resolveStorageConfig=Ne;exports.saveLocalDir=nn;exports.sessions=Is;exports.storage=Yi;exports.writeClaudeMcpConfig=we;exports.writeCodexMcpConfig=Ie;exports.writeDroidGatewaySettings=ke;exports.writeDroidMcpConfig=xe;exports.writeGeminiMcpConfig=be;exports.writeMcpConfig=ct;exports.writeQwenMcpConfig=ve;exports.zodSchemaToJson=q;