@evolvingmachines/sdk 0.0.55 → 0.0.57

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.js DELETED
@@ -1,630 +0,0 @@
1
- import {EventEmitter}from'events';import co from'ajv';import {randomBytes,randomUUID,publicEncrypt,constants,createHash}from'crypto';import Ki from'zod-to-json-schema';import*as U from'fs';import {createWriteStream}from'fs';import*as pe from'path';import {join,dirname,isAbsolute,normalize,resolve,relative}from'path';import {mkdir,appendFile,rm,readFile,writeFile,unlink,copyFile}from'fs/promises';import {homedir,tmpdir}from'os';import {exec,execFile}from'child_process';import {promisify}from'util';import {z as z$1}from'zod';export{E2BProvider,createE2BProvider}from'@evolvingmachines/e2b';export{DaytonaProvider,createDaytonaProvider}from'@evolvingmachines/daytona';export{ModalProvider,createModalProvider}from'@evolvingmachines/modal';import {Readable}from'stream';import {pipeline}from'stream/promises';var oi={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},at={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};function ae(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function ct(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 ai(t){let e=ct(t);return e?` --variant ${e} --thinking`:""}var dt={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 i=n?"--continue ":"",o=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${i}--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 i=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${i} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.1-pro-preview",models:[{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"},{alias:"gemini-3.1-flash-lite-preview",modelId:"gemini-3.1-flash-lite-preview",description:"Cost-efficient, low latency"},{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest Flash model"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Frontier flash performance"},{alias:"gemini-2.5-pro",modelId:"gemini-2.5-pro",description:"Complex tasks, deep reasoning"},{alias:"gemini-2.5-flash",modelId:"gemini-2.5-flash",description:"Balance speed/reasoning"},{alias:"gemini-2.5-flash-lite",modelId:"gemini-2.5-flash-lite",description:"Simple tasks, fastest"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${oe(t)} --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 i=n?"--continue ":"",o=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${i}--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-k2p6-raptor",modelId:"kimi-k2p6-raptor",description:"Evolve-managed Kimi K2.6 Raptor route for latency-sensitive agent runs"},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"},{alias:"kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Previous multimodal flagship"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2p6-raptor":"kimi-k2p6-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n})=>{let r=e?"--continue ":"",i=oe(t),o="--config-file /home/user/.kimi-code/config.toml",a="$(if [ -f /home/user/.kimi-code/mcp.json ]; then printf ' --mcp-config-file /home/user/.kimi-code/mcp.json'; fi)",c=ae(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${r}${o}${a}${c} -p ${i} --output-format stream-json; else kimi ${r}-p ${i} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-sonnet-4.6",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-4.6",modelId:"openrouter/anthropic/claude-sonnet-4.6",description:"Anthropic Sonnet via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-4.8",modelId:"openrouter/anthropic/claude-opus-4.8",description:"Anthropic Opus via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-5.5",modelId:"openrouter/openai/gpt-5.5",description:"OpenAI GPT-5.5 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4",modelId:"openrouter/openai/gpt-5.4",description:"OpenAI GPT-5.4 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4-mini",modelId:"openrouter/openai/gpt-5.4-mini",description:"OpenAI GPT-5.4 Mini via OpenRouter"},{alias:"openrouter/openai/gpt-5.3-codex",modelId:"openrouter/openai/gpt-5.3-codex",description:"OpenAI Codex via OpenRouter"},{alias:"openrouter/openai/gpt-5.2",modelId:"openrouter/openai/gpt-5.2",description:"OpenAI GPT-5.2 via OpenRouter"},{alias:"openrouter/google/gemini-3.1-pro-preview",modelId:"openrouter/google/gemini-3.1-pro-preview",description:"Gemini 3.1 Pro via OpenRouter"},{alias:"openrouter/google/gemini-3.5-flash",modelId:"openrouter/google/gemini-3.5-flash",description:"Gemini 3.5 Flash via OpenRouter"},{alias:"openrouter/google/gemini-3-flash-preview",modelId:"openrouter/google/gemini-3-flash-preview",description:"Gemini 3 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-next",modelId:"openrouter/qwen/qwen3-coder-next",description:"Qwen Coder Next via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-plus",modelId:"openrouter/qwen/qwen3-coder-plus",description:"Qwen Coder via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.6",modelId:"openrouter/moonshotai/kimi-k2.6",description:"Kimi K2.6 via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.5",modelId:"openrouter/moonshotai/kimi-k2.5",description:"Kimi K2.5 via OpenRouter"},{alias:"openrouter/z-ai/glm-5",modelId:"openrouter/z-ai/glm-5",description:"Zhipu GLM-5 via OpenRouter"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,reasoningEffort:i})=>{let o=n?"--continue ":"",a=e.startsWith("openrouter/")?e:`openrouter/${e}`,c=ai(i);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model ${a} --format json${c} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model litellm/${a} --format json${c} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",defaultModel:"gpt-5.5",models:[{alias:"claude-opus-4-8",modelId:"claude-opus-4-8",description:"Factory-managed Claude Opus 4.8"},{alias:"claude-opus-4-8-fast",modelId:"claude-opus-4-8-fast",description:"Factory-managed Claude Opus 4.8 Fast Mode"},{alias:"claude-sonnet-4-6",modelId:"claude-sonnet-4-6",description:"Factory-managed Claude Sonnet 4.6"},{alias:"claude-opus-4-6",modelId:"claude-opus-4-6",description:"Factory-managed Claude Opus 4.6"},{alias:"claude-opus-4-6-fast",modelId:"claude-opus-4-6-fast",description:"Factory-managed Claude Opus 4.6 Fast Mode"},{alias:"claude-opus-4-5",modelId:"claude-opus-4-5-20251101",description:"Factory-managed Claude Opus 4.5"},{alias:"claude-sonnet-4-5",modelId:"claude-sonnet-4-5-20250929",description:"Factory-managed Claude Sonnet 4.5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Factory-managed GPT-5.5"},{alias:"gpt-5.5-fast",modelId:"gpt-5.5-fast",description:"Factory-managed GPT-5.5 Fast Mode"},{alias:"gpt-5.5-pro",modelId:"gpt-5.5-pro",description:"Factory-managed GPT-5.5 Pro"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Factory-managed GPT-5.4"},{alias:"gpt-5.4-fast",modelId:"gpt-5.4-fast",description:"Factory-managed GPT-5.4 Fast Mode"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Factory-managed GPT-5.4 Mini"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Factory-managed GPT-5.3-Codex"},{alias:"gpt-5.3-codex-fast",modelId:"gpt-5.3-codex-fast",description:"Factory-managed GPT-5.3-Codex Fast"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Factory-managed GPT-5.2"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Factory-managed GPT-5.2-Codex"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Factory-managed Gemini 3.1 Pro"},{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Factory-managed Gemini 3 Pro"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Factory-managed Gemini 3 Flash"},{alias:"kimi-k2.6",modelId:"kimi-k2.6",description:"Factory-managed Droid Core Kimi K2.6"},{alias:"kimi-k2.5",modelId:"kimi-k2.5",description:"Factory-managed Droid Core Kimi K2.5"},{alias:"deepseek-v4-pro",modelId:"deepseek-v4-pro",description:"Factory-managed Droid Core DeepSeek V4 Pro"},{alias:"minimax-m2.7",modelId:"minimax-m2.7",description:"Factory-managed Droid Core MiniMax M2.7"},{alias:"minimax-m2.5",modelId:"minimax-m2.5",description:"Factory-managed Droid Core MiniMax M2.5"},{alias:"glm-5.1",modelId:"glm-5.1",description:"Factory-managed Droid Core GLM-5.1"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5","deepseek-v4-pro":"deepseek/deepseek-v4-pro","minimax-m2.7":"minimax/minimax-m2.7","minimax-m2.5":"minimax/minimax-m2.5","glm-5.1":"openrouter/z-ai/glm-5.1"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:t,model:e,isResume:n,sessionId:r,reasoningEffort:i,isDirectMode:o})=>{let a=o?"":"--settings /home/user/.factory/evolve-settings.json ",c=o?e:"custom:Evolve-Gateway-0",d=i?` --reasoning-effort ${i}`:"",l=n&&r?`--session-id ${oe(r)} `:"";return `printf '%s' ${oe(t)} | droid ${a}exec ${l}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${oe(c)}${d}`}}};function A(t){let e=dt[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function ci(t){return t in dt}function G(t){return t.replace(/^~/,"/home/user")}function oe(t){return `'${t.replace(/'/g,"'\\''")}'`}function B(t){let e=A(t);return `${G(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function L(t){let e=A(t);return G(e.mcpConfig.settingsDir)}function D(t){if(t instanceof Error){let e=t.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function lt(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 ce(t){for(let[e,n]of Object.entries(t))lt(e,n);}function de(t){return t.type?t.type:t.command?"stdio":"sse"}function di(t){let e=de(t);return {...t,type:e}}function li(t){let{type:e,url:n,...r}=t;return de(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function ui(t){return {type:de(t),...t}}function pi(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function gi(t){let e=de(t),{type:n,httpHeaders:r,envHttpHeaders:i,bearerTokenEnvVar:o,envVars:a,...c}=t;if(e==="stdio"&&t.command)return {type:"stdio",...c};if(t.url){let d={...c,type:e==="sse"?"sse":"http",url:t.url},l=t.headers??r;return l&&Object.keys(l).length>0&&(d.headers=l),d}return {type:e==="stdio"?"stdio":"http",...c}}async function ut(t,e,n,r){ce(n);let i=L(e),o=B(e);await t.files.makeDir(i);let a={};try{let d=await t.files.read(o);typeof d=="string"&&(a=JSON.parse(d));}catch(d){if(!D(d))throw d}let c=Object.fromEntries(Object.entries(n).map(([d,l])=>[d,r(l)]));await t.files.write(o,JSON.stringify({...a,mcpServers:c},null,2));}async function Pe(t,e,n){ce(n);let r=L("claude"),i=B("claude"),o=Object.fromEntries(Object.entries(n).map(([c,d])=>[c,ui(d)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:o},null,2)),await t.files.makeDir(r);let a={};try{let c=await t.files.read(i);typeof c=="string"&&(a=JSON.parse(c));}catch(c){if(!D(c))throw c}a.enableAllProjectMcpServers=true,await t.files.write(i,JSON.stringify(a,null,2));}async function Ie(t,e){await ut(t,"gemini",e,di);}async function Oe(t,e){await ut(t,"qwen",e,li);}async function Ae(t,e,n,r){let i=L(e),o=B(e);await t.files.makeDir(i);let a={};try{let u=await t.files.read(o);typeof u=="string"&&(a=JSON.parse(u));}catch(u){if(!D(u))throw u}let c=n.split("."),d=a;for(let u=0;u<c.length-1;u++){let p=c[u];(typeof d[p]!="object"||d[p]===null)&&(d[p]={}),d=d[p];}let l=c[c.length-1],s=typeof d[l]=="object"&&d[l]!==null?d[l]:{};d[l]={...s,...r},await t.files.write(o,JSON.stringify(a,null,2));}async function pt(t,e){let n=L("qwen"),r=B("qwen");await t.files.makeDir(n);let i={};try{let d=await t.files.read(r);typeof d=="string"&&(i=JSON.parse(d));}catch(d){if(!D(d))throw d}let o=i.model??{},a=o.generationConfig??{},c=a.extra_body??{};i.model={...o,generationConfig:{...a,extra_body:{...c,enable_thinking:e}}},await t.files.write(r,JSON.stringify(i,null,2));}async function gt(t,e){await ut(t,"kimi",e,pi);}async function Me(t,e,n){ce(n);let r=`${e}/.factory`,i=`${r}/mcp.json`;await t.files.makeDir(r);let o={};try{let c=await t.files.read(i);typeof c=="string"&&(o=JSON.parse(c));}catch(c){if(!D(c))throw c}let a=Object.fromEntries(Object.entries(n).map(([c,d])=>[c,gi(d)]));await t.files.write(i,JSON.stringify({...o,mcpServers:a},null,2));}async function De(t,e,n){let r=G(e.settingsPath),i=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(i);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 ft(t,e,n){ce(n);let r=`${e}/opencode.json`,i={};try{let a=await t.files.read(r);typeof a=="string"&&(i=JSON.parse(a));}catch(a){if(!D(a))throw a}let o=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,fi(c)]));await t.files.write(r,JSON.stringify({...i,mcp:o},null,2));}function fi(t){let e=de(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 $e(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||C;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function mt(){return $e("/api/managed/e2b")}function on(t){return {"browser-use":{type:"http",url:H("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var R="EVOLVE_API_KEY",Ue="E2B_API_KEY",Be="DAYTONA_API_KEY",Le="MODAL_TOKEN_ID",ht="MODAL_TOKEN_SECRET",an="claude",le=36e5,cn=4,yt=100,dn="/home/user/workspace",C=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",M="x-litellm-customer-id",N="x-litellm-tags",W="run:",ln=".evolve-sdk/observability/sessions",un=100,pn=5e3,Ne=3,wt=1e3;function E(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>E(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,r])=>`${n} = ${E(r)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function Fe(t,e){for(let[d,l]of Object.entries(e))lt(d,l);let n=L("codex"),r=B("codex");await t.files.makeDir(n);let i="";try{let d=await t.files.read(r);typeof d=="string"&&(i=d);}catch(d){if(!D(d))throw d}let o=[],a=[];i.includes("experimental_use_rmcp_client")||(o.push("# Enable improved RMCP client (recommended)"),o.push("experimental_use_rmcp_client = true")),i.includes("[mcp_servers]")||a.push("[mcp_servers]","");for(let[d,l]of Object.entries(e)){if(i.includes(`[mcp_servers.${d}]`))continue;a.push(`[mcp_servers.${d}]`);let s=l.type??(l.command?"stdio":"http");if(s==="http"||s==="sse"||!!l.url){if(!l.url)throw new Error(`MCP server "${d}" is missing url for ${s} transport`);a.push(`url = ${E(l.url)}`),l.bearerTokenEnvVar&&a.push(`bearer_token_env_var = ${E(l.bearerTokenEnvVar)}`);let p=l.httpHeaders??l.headers;p&&Object.keys(p).length>0&&a.push(`http_headers = ${E(p)}`),l.envHttpHeaders&&Object.keys(l.envHttpHeaders).length>0&&a.push(`env_http_headers = ${E(l.envHttpHeaders)}`);}else a.push(`command = ${E(l.command)}`),l.args&&l.args.length>0&&a.push(`args = ${E(l.args)}`),l.cwd&&a.push(`cwd = ${E(l.cwd)}`);l.env&&Object.keys(l.env).length>0&&a.push(`env = ${E(l.env)}`),l.envVars&&l.envVars.length>0&&a.push(`env_vars = ${E(l.envVars)}`),a.push("");}let c=[i.trim(),o.join(`
2
- `),a.join(`
3
- `)].filter(d=>d.length>0);await t.files.write(r,c.join(`
4
-
5
- `)+`
6
- `);}async function vt(t,e,n,r={}){let i=L("codex"),o=B("codex");await t.files.makeDir(i);let a="";try{let w=await t.files.read(o);typeof w=="string"&&(a=w);}catch(w){if(!D(w))throw w}let c=a.search(/^\[/m),d=c>=0?a.slice(0,c):a,l=c>=0?a.slice(c):"",s=a.includes("[model_providers.evolve-gateway]"),u=/^model_provider\s*=\s*"evolve-gateway"/m.test(d),p={[M]:n.sessionTagEnv,[N]:n.runTagEnv,...r},g=["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${E(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${E(p)}`].join(`
7
- `);if(s&&u&&a.includes(g))return;a=(d.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
8
-
9
- `)+l).replace(/\n?\[model_providers\.evolve-gateway\][\s\S]*?(?=\n\[|\s*$)/,"").replace(/^\n+/,"");let m='model_provider = "evolve-gateway"',h=g,y;if(!a.trim())y=h?`${m}
10
-
11
- ${h}
12
- `:`${m}
13
- `;else {let w=a.search(/^\[/m);w>0?y=a.slice(0,w)+m+`
14
-
15
- `+a.slice(w).trimEnd():w===0?y=m+`
16
-
17
- `+a.trimEnd():y=a.trimEnd()+`
18
-
19
- `+m,h&&(y=y.trimEnd()+`
20
-
21
- `+h),y+=`
22
- `;}await t.files.write(o,y);}async function bt(t,e,n,r){let i=G(e.configPath),o=i.slice(0,i.lastIndexOf("/"));await t.files.makeDir(o);let a=[`default_model = ${E(e.modelName)}`,`default_thinking = ${E(r.defaultThinking)}`,'default_permission_mode = "auto"',"","[thinking]",`mode = ${E(r.defaultThinking?"on":"off")}`];r.defaultThinking&&r.thinkingEffort&&a.push(`effort = ${E(r.thinkingEffort)}`),a.push("",`[providers.${e.providerName}]`,'type = "kimi"',`base_url = ${E(r.baseUrl)}`,`api_key = ${E(r.apiKey)}`,`custom_headers = ${E(n)}`,"",`[models.${e.modelName}]`,`provider = ${E(e.providerName)}`,`model = ${E(r.model)}`,`max_context_size = ${e.maxContextSize}`,`capabilities = ${E(["image_in","thinking"])}`);let c=a.join(`
23
- `)+`
24
- `;await t.files.write(i,c);}async function St(t,e,n,r){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await Pe(e,n,r);break;case "codex":await Fe(e,r);break;case "gemini":await Ie(e,r);break;case "qwen":await Oe(e,r);break;case "kimi":await gt(e,r);break;case "opencode":await ft(e,n,r);break;case "droid":await Me(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Ke(){let t={};return function(l){let s;try{s=JSON.parse(l);}catch{return null}if(s._meta||s._prompt)return null;let u=s.session_id;switch(s.type){case "system":return null;case "assistant":return e(s.message?.content,"assistant",u);case "user":{let p=s.message?.content;return typeof p=="string"||Array.isArray(p)&&p.length===1&&p[0].type==="text"?null:e(p,"user",u)}case "result":return null;default:return null}};function e(d,l,s){if(typeof d=="string")return l==="user"?null:[{sessionId:s,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}}];if(!d||!Array.isArray(d))return null;let u=[];for(let p of d){let g=null;switch(p.type){case "text":case "text_delta":if(l==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}};break;case "image":if(l==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:p.source?.type==="base64"?p.source.data:"",mimeType:p.source?.type==="base64"?p.source.media_type:"",uri:p.source?.type==="url"?p.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[p.id]=p,p.name==="TodoWrite")Array.isArray(p.input?.todos)&&(g={sessionUpdate:"plan",entries:a(p.input)});else {let f=n(p);g={sessionUpdate:"tool_call",toolCallId:p.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[p.tool_use_id];if(!f||(delete t[p.tool_use_id],f.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:p.tool_use_id,status:"is_error"in p&&p.is_error?"failed":"completed",...r(p,f)};break}}g&&u.push({sessionId:s,update:g});}return u.length>0?u:null}function n(d){let l=d.name,s=d.input||{};switch(l){case "Task":return {title:s.description||"Task",kind:"think",content:s.prompt?[{type:"content",content:{type:"text",text:s.prompt}}]:[],rawInput:s};case "NotebookRead":return {title:s.notebook_path?`Read Notebook ${s.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:s.notebook_path?[{path:s.notebook_path}]:[],rawInput:s};case "NotebookEdit":return {title:s.notebook_path?`Edit Notebook ${s.notebook_path}`:"Edit Notebook",kind:"edit",content:s.new_source?[{type:"content",content:{type:"text",text:s.new_source}}]:[],locations:s.notebook_path?[{path:s.notebook_path}]:[],rawInput:s};case "Bash":return {title:s.command?"`"+s.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:s.description?[{type:"content",content:{type:"text",text:s.description}}]:[],rawInput:s};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:s};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:s};case "Read":{let u="";return s.limit?u=" ("+((s.offset??0)+1)+" - "+((s.offset??0)+s.limit)+")":s.offset&&(u=" (from line "+(s.offset+1)+")"),{title:"Read "+(s.file_path??"File")+u,kind:"read",content:[],locations:s.file_path?[{path:s.file_path,line:s.offset??0}]:[],rawInput:s}}case "LS":return {title:s.path?`List \`${s.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:s};case "Edit":{let u=s.file_path;return {title:u?`Edit \`${u}\``:"Edit",kind:"edit",content:u?[{type:"diff",path:u,oldText:s.old_string??null,newText:s.new_string??""}]:[],locations:u?[{path:u}]:[],rawInput:s}}case "Write":return {title:s.file_path?`Write ${s.file_path}`:"Write",kind:"edit",content:s.file_path?[{type:"diff",path:s.file_path,oldText:null,newText:s.content??""}]:[],locations:s.file_path?[{path:s.file_path}]:[],rawInput:s};case "Glob":{let u="Find";return s.path&&(u+=` \`${s.path}\``),s.pattern&&(u+=` \`${s.pattern}\``),{title:u,kind:"search",content:[],locations:s.path?[{path:s.path}]:[],rawInput:s}}case "Grep":{let u="grep";return s["-i"]&&(u+=" -i"),s["-n"]&&(u+=" -n"),s["-A"]!==void 0&&(u+=` -A ${s["-A"]}`),s["-B"]!==void 0&&(u+=` -B ${s["-B"]}`),s["-C"]!==void 0&&(u+=` -C ${s["-C"]}`),s.output_mode==="files_with_matches"?u+=" -l":s.output_mode==="count"&&(u+=" -c"),s.head_limit!==void 0&&(u+=` | head -${s.head_limit}`),s.glob&&(u+=` --include="${s.glob}"`),s.type&&(u+=` --type=${s.type}`),s.multiline&&(u+=" -P"),u+=` "${s.pattern??""}"`,s.path&&(u+=` ${s.path}`),{title:u,kind:"search",content:[],rawInput:s}}case "WebFetch":return {title:s.url?`Fetch ${s.url}`:"Fetch",kind:"fetch",content:s.prompt?[{type:"content",content:{type:"text",text:s.prompt}}]:[],rawInput:s};case "WebSearch":{let u=`"${s.query??""}"`;return s.allowed_domains?.length>0&&(u+=` (allowed: ${s.allowed_domains.join(", ")})`),s.blocked_domains?.length>0&&(u+=` (blocked: ${s.blocked_domains.join(", ")})`),{title:u,kind:"fetch",content:[],rawInput:s}}case "TodoWrite":return {title:Array.isArray(s.todos)?`Update TODOs: ${s.todos.map(u=>u.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:s};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:s.plan?[{type:"content",content:{type:"text",text:s.plan}}]:[],rawInput:s};default:if(l?.startsWith("mcp__")){let u=l.split("__"),p=u[1]||"mcp",g=u.slice(2).join("__")||l;return {title:`${p}: ${g}`,kind:"other",content:[],rawInput:s}}return {title:l||"Unknown Tool",kind:"other",content:[],rawInput:s}}}function r(d,l){let s=d.content;switch(l?.name){case "Read":return Array.isArray(s)&&s.length>0?{content:s.map(u=>({type:"content",content:u.type==="text"?{type:"text",text:c(u.text)}:o(u,false)}))}:typeof s=="string"&&s.length>0?{content:[{type:"content",content:{type:"text",text:c(s)}}]}:{};case "Edit":case "Write":case "Bash":return i(s,d.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return i(s,"is_error"in d?d.is_error:false)}}function i(d,l=false){return Array.isArray(d)&&d.length>0?{content:d.map(s=>({type:"content",content:o(s,l)}))}:typeof d=="string"&&d.length>0?{content:[{type:"content",content:{type:"text",text:l?"```\n"+d+"\n```":d}}]}:{}}function o(d,l){if(d.type==="text")return l?{type:"text",text:"```\n"+d.text+"\n```"}:{type:"text",text:d.text};if(d.type==="image"){if(d.data&&d.mimeType)return {type:"image",data:d.data,mimeType:d.mimeType};if(d.source?.type==="base64")return {type:"image",data:d.source.data||"",mimeType:d.source.media_type||""};if(d.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:d.source.url}}return d}function a(d){return d.todos.map(l=>({content:l.content,status:l.status||"pending",priority:"medium"}))}function c(d){let l="```",s=Array.from(d.matchAll(/^```+/gm));for(let[u]of s)for(;u.length>=l.length;)l+="`";return l+`
25
- `+d+(d.endsWith(`
26
- `)?"":`
27
- `)+l}}function je(){return function(d){let l;try{l=JSON.parse(d);}catch{return null}if(l._meta||l._prompt)return null;let s=[];switch(l.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let u=l.item;if(!u)return null;let p=e(u);p&&s.push({update:p});break}case "item.updated":{let u=l.item;if(!u)return null;let p=n(u);p&&s.push({update:p});break}case "item.completed":{let u=l.item;if(!u)return null;let p=r(u);p&&s.push({update:p});break}default:return null}return s.length>0?s:null};function e(c){let d=c.id;switch(c.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${c.server}:${c.tool}`},{sessionUpdate:"tool_call",toolCallId:d,title:`${c.server}: ${c.tool}`,kind:"other",status:"in_progress",rawInput:c.arguments,content:[]};case "command_execution":return {type:"command_execution",name:c.command},{sessionUpdate:"tool_call",toolCallId:d,title:c.command?`\`${c.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:c.command},content:[]};case "web_search":return {type:"web_search",name:c.query},{sessionUpdate:"tool_call",toolCallId:d,title:`Search: ${c.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(c.items)};default:return null}}function n(c){return c.type==="todo_list"?{sessionUpdate:"plan",entries:a(c.items)}:null}function r(c){let d=c.id;switch(c.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c.text??c.summary?.join(`
28
- `)??c.content?.join(`
29
- `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:c.text??""}};case "mcp_tool_call":{let s=i(c.result),u=c.status==="failed"||c.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:d,status:u,content:s}}case "command_execution":{let s=c.aggregated_output?[{type:"content",content:{type:"text",text:c.aggregated_output}}]:[],u=c.status==="completed"||c.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:d,status:u,content:s}}case "file_change":{let s=c.changes??[],u=s.map(g=>({path:g.path})),p=s.length===1?`${s[0].kind==="add"?"Create":"Edit"} ${s[0].path}`:`Edit ${s.length} files`;return {sessionUpdate:"tool_call",toolCallId:d,title:p,kind:"edit",status:c.status==="completed"?"completed":"failed",content:s.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:u}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:d,title:`Search: ${c.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(c.items)};default:return null}}function i(c){return c?.content?Array.isArray(c.content)?c.content.map(d=>({type:"content",content:o(d)})):typeof c.content=="string"?[{type:"content",content:{type:"text",text:c.content}}]:[]:[]}function o(c){return c.type==="text"?{type:"text",text:c.text??""}:c.type==="image"?{type:"image",data:c.data??"",mimeType:c.mime_type??c.mimeType??"",uri:c.uri}:c}function a(c){if(!Array.isArray(c))return [];let d=false;return c.map(l=>{let s;return l.completed?s="completed":d?s="pending":(s="in_progress",d=true),{content:l.text??"",status:s,priority:"medium"}})}}var mi={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"},hi=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 Ve(){let t=new Map,e,n=false,r="",i;return function(a){let c;try{c=JSON.parse(a);}catch{return null}if(!hn(c))return null;let d=yi(c);if(d.sessionId&&(e=d.sessionId),d.errorText)return [V(e,d.errorText)];if(d.resultText)return r=d.resultText,n=true,[V(e,d.resultText)];if(d.handled)return null;let s=wi(c)??c,u=mn(s);u&&(e=u);let p=[],g=x(s,"type");switch(g){case "system":return null;case "message":{let f=x(s,"role"),m=x(s,"text")||xt(s.content);if(!m)break;f==="assistant"&&(n=true,r=m,p.push(V(e,m)));break}case "completion":{let f=x(s,"finalText")||x(s,"result");f&&(!n||f!==r)&&(n=true,r=f,p.push(V(e,f)));break}case "assistant_text_delta":{let f=x(s,"textDelta")||x(s,"text");f&&(n=true,r+=f,p.push(V(e,f)));break}case "thinking_text_delta":{let f=x(s,"textDelta")||x(s,"text");if(f){let m=gn(s,f,i);m&&(i=m.signature,p.push({sessionId:e,update:m.event}));}break}case "reasoning":{let f=x(s,"text");if(f){let m=gn(s,f,i);m&&(i=m.signature,p.push({sessionId:e,update:m.event}));}break}case "assistant":{let f=x(s,"text")||xt(P(s.message)?.content);f&&(n=true,r=f,p.push(V(e,f)));break}case "tool_call":case "tool_call_delta":{let f=P(s.toolUse)??P(s.tool_use)??s,m=fn(f,t);m&&p.push({sessionId:e,update:m});break}case "tool_result":{let f=bi(s,t);f&&p.push({sessionId:e,update:f});break}case "tool_progress_update":case "tool_progress":{let f=Si(s);f&&p.push({sessionId:e,update:f});break}case "create_message":{for(let f of vi(s,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;}p.push({sessionId:e,update:f});}break}case "result":{let f=ue(s.result??s.text??s.error);f&&(n=true,r=f,p.push(V(e,f)));break}case "error":{let f=ue(s.message??s.error??s);f&&p.push(V(e,f));break}default:if(g&&!hi.has(g))return null}return p.length>0&&g!=="reasoning"&&g!=="thinking_text_delta"&&(i=void 0),p.length>0?p:null}}function gn(t,e,n){let r=kt(t,"id")||kt(t,"messageId"),i=kt(t,"blockIndex"),o=`${x(t,"type")}:${r}:${i}:${e}`;return o===n?null:{signature:o,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function yi(t){if(t.type!=="response")return {handled:false};let e=P(t.result),n=P(t.error),r=mn(e??t);if(n)return {handled:true,sessionId:r,errorText:ue(n.message??n)};let i=e?x(e,"finalText")||x(e,"result"):"";return {handled:true,sessionId:r,resultText:i}}function wi(t){return t.method!=="droid.session_notification"?null:P(P(t.params)?.notification)}function vi(t,e){let n=P(t.message);if(!n)return [];let r=[],i=n.content;if(Array.isArray(i))for(let o of i){let a=P(o);if(a&&a.type==="tool_use"){let c=fn(a,e);c&&r.push(c);}}if(n.role==="assistant"){let o=xt(i);o&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}});}return r}function fn(t,e){let n=x(t,"id")||x(t,"toolUseId")||x(t,"tool_use_id"),r=x(t,"name")||x(t,"toolName")||x(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let i=P(t.input)??P(t.toolInput)??P(t.arguments)??{};if(yn(r)==="todowrite"){let l=ki(i);if(l)return l}let{title:o,kind:a,content:c,locations:d}=xi(r,i);return {sessionUpdate:"tool_call",toolCallId:n,title:o,kind:a,status:"pending",rawInput:i,content:c,locations:d}}function bi(t,e){let n=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id");if(!n)return null;let r=x(t,"toolName")||x(t,"tool_name")||e.get(n);return e.delete(n),{sessionUpdate:"tool_call_update",toolCallId:n,status:t.isError===true||t.is_error===true?"failed":"completed",title:r,content:Ct(t.content??t.result??t.error)}}function Si(t){let e=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id");if(!e)return null;let n=P(t.update),r=ue(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?Ct(r):void 0}}function ki(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let i=P(r);if(!i)return [];let o=x(i,"content"),a=Ci(x(i,"status")),c=_i(x(i,"priority"));return o?[{content:o,status:a,priority:c}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function xi(t,e){let n=mi[yn(t)]||"other",r=x(e,"path")||x(e,"filePath")||x(e,"file_path")||x(e,"absolute_path"),i=x(e,"command"),o=x(e,"url"),a=r||i||o;return {title:a?`${t} ${a}`:t,kind:n,content:Object.keys(e).length>0?Ct(e):[],locations:r?[{path:r}]:[]}}function mn(t){if(t)return x(t,"session_id")||x(t,"sessionId")}function V(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function xt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=P(e);return n?x(n,"text")||x(n,"content"):""}).filter(Boolean).join(""):""}function Ct(t){let e=ue(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function ue(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function hn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function P(t){return hn(t)?t:null}function x(t,e){let n=t[e];return typeof n=="string"?n:""}function kt(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function yn(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Ci(t){return t==="in_progress"||t==="completed"?t:"pending"}function _i(t){return t==="high"||t==="low"?t:"medium"}var Ei={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 Ge(){return function(a){let c;try{c=JSON.parse(a);}catch{return null}if(c._meta||c._prompt)return null;let d=c.session_id,l=[];switch(c.type){case "init":case "result":return null;case "message":{let s=t(c);s&&l.push({sessionId:d,update:s});break}case "tool_use":{let s=e(c);s&&l.push({sessionId:d,update:s});break}case "tool_result":{let s=n(c);s&&l.push({sessionId:d,update:s});break}case "error":{let s=r(c);s&&l.push({sessionId:d,update:s});break}default:return null}return l.length>0?l:null};function t(o){let a=o.role,c=o.content;return c?a==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}:a==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:c}}:null:null}function e(o){let a=o.tool_id,c=o.tool_name,d=o.parameters||{},{title:l,kind:s,content:u,locations:p}=i(c,d);return {sessionUpdate:"tool_call",toolCallId:a,title:l,kind:s,status:"pending",rawInput:d,content:u,locations:p}}function n(o){let a=o.tool_id,c=o.status,d=o.output,l=o.error,s=[];return d&&typeof d=="string"&&d.length>0&&s.push({type:"content",content:{type:"text",text:c==="error"?`\`\`\`
30
- ${d}
31
- \`\`\``:d}}),l?.message&&!d&&s.push({type:"content",content:{type:"text",text:`\`\`\`
32
- ${l.message}
33
- \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:a,status:c==="success"?"completed":"failed",content:s}}function r(o){let a=o.severity,c=o.message;return c?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${c}`}}:null}function i(o,a){let c=Ei[o]||"other",d=[],l=[],s=o;switch(o){case "read_file":s=`Read ${a.absolute_path||a.file_path||"file"}`,(a.absolute_path||a.file_path)&&l.push({path:a.absolute_path||a.file_path});break;case "write_file":s=`Write ${a.file_path||"file"}`,a.file_path&&(l.push({path:a.file_path}),d.push({type:"diff",path:a.file_path,oldText:null,newText:a.content||""}));break;case "edit_file":s=`Edit ${a.file_path||"file"}`,a.file_path&&l.push({path:a.file_path});break;case "replace":s=`Edit ${a.file_path||"file"}`,a.file_path&&(l.push({path:a.file_path}),(a.old_string!==void 0||a.new_string!==void 0)&&d.push({type:"diff",path:a.file_path,oldText:a.old_string||"",newText:a.new_string||""}));break;case "run_shell_command":case "shell":s=a.command?`\`${a.command}\``:"Run command",a.description&&d.push({type:"content",content:{type:"text",text:a.description}});break;case "brave_web_search":case "web_search":case "google_web_search":s=a.query?`"${a.query}"`:"Web search";break;case "web_fetch":s=a.prompt?`Fetch: ${a.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":s=`Find ${a.pattern||"files"}`,a.dir_path&&l.push({path:a.dir_path});break;case "grep":case "search_file_content":s=`grep "${a.pattern||a.query||""}"`;break;case "list_directory":s=`List ${a.dir_path||a.path||"directory"}`,(a.dir_path||a.path)&&l.push({path:a.dir_path||a.path});break;case "read_many_files":s=`Read ${a.include?.length||"multiple"} files`,Array.isArray(a.include)&&a.include.forEach(u=>l.push({path:u}));break;case "delegate_to_agent":s=a.agent_name?`Agent: ${a.agent_name}`:"Delegate to agent";break;case "write_todos":s="Update todos";break;case "save_memory":s=a.fact?`Remember: "${a.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":s=a.name?`Activate skill: ${a.name}`:"Activate skill";break;default:s=o;}return {title:s,kind:c,content:d,locations:l}}}var Ti={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function wn(t){return t==="TodoList"||t==="SetTodoList"}function Et(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function bn(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",i=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:i}:null}function Tt(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=bn(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 _t(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=Tt(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=Tt(t);n&&e.push(n);}return e}function Ri(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&Et(e.content.text))}function Pi(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=bn(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 Ii(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function vn(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 i=n.status;return {content:r,status:Ii(i),priority:"medium"}}).filter(n=>n!==null):[]}function Rt(){let t=new Set,e=0;function n(c,d){return typeof c=="string"&&c.length>0?c:(e+=1,`kimi_${d.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(d){let l;try{l=JSON.parse(d);}catch{return null}if(!l||typeof l!="object")return null;let s=l.role;return "_meta"in l||"_prompt"in l||s==="meta"?null:s==="assistant"?r(l):s==="tool"?i(l):typeof l.type=="string"&&"payload"in l?o(l):null};function r(c){let d=[],l=c.content,s=c.tool_calls;if(typeof l=="string"&&l.length>0)d.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}});else if(Array.isArray(l))for(let u of l){let p=Pi(u);p&&d.push(p);}if(Array.isArray(s))for(let u of s){if(!u||typeof u!="object")continue;let p=u.function;if(!p)continue;let g=p.name??"",f=n(u.id,g),m;try{m=p.arguments?JSON.parse(p.arguments):{};}catch{m=p.arguments;}if(wn(g)){let S=vn(m);S.length>0&&d.push({update:{sessionUpdate:"plan",entries:S}}),t.add(f);continue}let{title:h,kind:y,toolContent:w,locations:k}=a(g,typeof m=="object"&&m!==null?m:{});d.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:m,content:w,locations:k}});}return d.length>0?d:null}function i(c){let d=c.tool_call_id;if(typeof d!="string"||d.length===0)return null;if(t.has(d))return t.delete(d),null;let l=c.content,s=[],u=false;if(typeof l=="string")u=Et(l),l.length>0&&s.push({type:"content",content:{type:"text",text:l}});else if(Array.isArray(l))for(let p of l){let g=Tt(p);g&&(g.type==="content"&&g.content.type==="text"&&Et(g.content.text)&&(u=true),s.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:d,status:u?"failed":"completed",content:s}}]}function o(c){let d=c.type,l=c.payload??{},s=[];switch(d){case "TextPart":{let u=l.text;typeof u=="string"&&u.length>0&&s.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u}}});break}case "ThinkPart":{let u=l.think;typeof u=="string"&&u.length>0&&s.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u}}});break}case "ToolCall":{let u=l.function?.name??"",p=n(l.id,u),g=l.function;if(!g)break;let f;try{f=g.arguments?JSON.parse(g.arguments):{};}catch{f=g.arguments;}if(wn(u)){let k=vn(f);k.length>0&&s.push({update:{sessionUpdate:"plan",entries:k}}),t.add(p);break}let{title:m,kind:h,toolContent:y,locations:w}=a(u,typeof f=="object"&&f!==null?f:{});s.push({update:{sessionUpdate:"tool_call",toolCallId:p,title:m,kind:h,status:"pending",rawInput:f,content:y,locations:w}});break}case "ToolResult":{let u=l.tool_call_id;if(typeof u!="string"||u.length===0)break;if(t.has(u)){t.delete(u);break}let p=l.return_value??l.content,g=[],f=l.is_error===true;if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p;f=f||m.type==="ToolError"||m.is_error===true,g.push(..._t(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(..._t(p));}else g.push(..._t(p));f=f||Ri(g),s.push({update:{sessionUpdate:"tool_call_update",toolCallId:u,status:f?"failed":"completed",content:g}});break}default:return null}return s.length>0?s:null}function a(c,d){let l=Ti[c]||"other",s=[],u=[],p=c;switch(c){case "Read":case "ReadFile":{let g=d.path??d.file_path;p=`Read ${g||"file"}`,g&&u.push({path:g});break}case "ReadMediaFile":{let g=d.path??d.file_path;p=`Read media ${g||"file"}`,g&&u.push({path:g});break}case "Write":case "WriteFile":{let g=d.path??d.file_path;p=`Write ${g||"file"}`,g&&(u.push({path:g}),typeof d.content=="string"&&s.push({type:"diff",path:g,oldText:null,newText:d.content}));break}case "Edit":case "StrReplaceFile":{let g=d.path??d.file_path;p=`Edit ${g||"file"}`,g&&u.push({path:g});break}case "Bash":case "Shell":p=d.command?`\`${d.command}\``:"Run command";break;case "Glob":p=`Find ${d.pattern||"files"}`,d.path&&u.push({path:d.path});break;case "Grep":p=`grep "${d.pattern||""}"`,d.path&&u.push({path:d.path});break;case "WebSearch":case "SearchWeb":p=d.query?`"${d.query}"`:"Web search";break;case "FetchURL":p=d.url?`Fetch ${d.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":p=d.description||"Subagent task";break;case "Think":p=d.thought||"Thinking";break;case "CreateSubagent":p=d.name?`Subagent: ${d.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":p="Update todos";break;default:p=c;}return {title:p,kind:l,toolContent:s,locations:u}}}var Oi={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 Ai(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",i=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:i}:null}function Mi(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 Di(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function Sn(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:Mi(e.status),priority:Di(e.priority)}}).filter(e=>e!==null):[]}function $i(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let c=Ai(r);return c?{type:"content",content:{type:"image",data:c.data,mimeType:c.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function Ui(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 Bi(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function Pt(){return function(a){let c;try{c=JSON.parse(a);}catch{return null}if(!c||typeof c!="object")return null;let d=c.sessionID,l=[];switch(c.type){case "step_start":case "step_finish":return null;case "text":{let s=t(c);s&&l.push({sessionId:d,update:s});break}case "reasoning":{let s=e(c);s&&l.push({sessionId:d,update:s});break}case "tool_use":{let s=n(c);for(let u of s)l.push({sessionId:d,update:u});break}case "error":{let s=r(c);s&&l.push({sessionId:d,update:s});break}default:return null}return l.length>0?l:null};function t(o){let a=o.part?.text;return typeof a!="string"||a.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}}function e(o){let a=o.part?.text;return typeof a!="string"||a.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a}}}function n(o){let a=o.part;if(!a)return [];let c=typeof a.callID=="string"?a.callID:"";if(c.length===0)return [];let d=typeof a.tool=="string"?a.tool.toLowerCase():"",l=typeof a.state=="object"&&a.state?a.state:{},s=typeof l.input=="object"&&l.input?l.input:{},u=l.status,p=l.title??l.metadata?.description??d,g=l.metadata?.exit,{kind:f,content:m,locations:h}=i(d,s),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:c,title:p,kind:f,status:"pending",rawInput:s,content:m,locations:h}),d==="todowrite"){let v=Sn(s.todos);if(v.length===0&&typeof l.output=="string")try{v=Sn(JSON.parse(l.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=Bi(u,g);if(w==="pending")return y;let k=Ui(u,l),S=[];if(typeof k=="string"&&k.length>0&&S.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
34
- ${k}
35
- \`\`\``:k}}),Array.isArray(l.attachments))for(let v of l.attachments){let b=$i(v);b&&S.push(b);}return y.push({sessionUpdate:"tool_call_update",toolCallId:c,status:w,content:S}),y}function r(o){let a=o.error?.name??"Error",c=o.error?.data?.message??o.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${a}: ${c}`}}}function i(o,a){let c=Oi[o]||"other",d=[],l=[];switch(o){case "read":{let s=a.filePath??a.path;if(s){let u=a.offset;l.push({path:s,line:typeof u=="number"&&Number.isFinite(u)?Math.max(0,u-1):void 0});}break}case "write":{let s=a.filePath??a.path;s&&(l.push({path:s}),typeof a.content=="string"&&d.push({type:"diff",path:s,oldText:null,newText:a.content}));break}case "edit":case "multiedit":{let s=a.filePath??a.path;s&&(l.push({path:s}),o==="edit"&&(a.oldString!==void 0||a.newString!==void 0)&&d.push({type:"diff",path:s,oldText:a.oldString??"",newText:a.newString??""}));break}case "apply_patch":break;case "bash":{let s=a.command;s&&a.description?d.push({type:"content",content:{type:"text",text:a.description}}):s&&d.push({type:"content",content:{type:"text",text:s}});break}case "glob":case "list":{let s=a.path;s&&l.push({path:s});break}case "grep":{let s=a.path;s&&l.push({path:s});break}case "codesearch":case "websearch":{let s=a.query;s&&d.push({type:"content",content:{type:"text",text:s}});break}case "webfetch":{let s=a.url;s&&d.push({type:"content",content:{type:"text",text:s}});break}case "task":{let s=a.description;s&&d.push({type:"content",content:{type:"text",text:s}});break}}return {kind:c,content:d,locations:l}}}var Li={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 He(){let t=new Map,e=new Map;return function(s){let u;try{u=JSON.parse(s);}catch{return null}if(!u||typeof u!="object")return null;let p=u;if("_meta"in p||"_prompt"in p)return null;let g=p.session_id||void 0,f=[];switch(p.type){case "assistant":{let m=n(p);for(let h of m)f.push({sessionId:g,update:h});break}case "stream_event":{let m=r(p);for(let h of m)f.push({sessionId:g,update:h});break}case "user":{let m=i(p);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(l){let s=[],u=l.message?.content;if(!Array.isArray(u))return s;for(let p of u){let g=o(p);s.push(...g);}return s}function r(l){let s=[],u=l.event;if(!u)return s;switch(u.type){case "content_block_start":{let p=u.index??0,g=u.content_block;g&&(t.set(p,g),g.type==="tool_use"&&e.set(p,""));break}case "content_block_delta":{let p=u.index??0,g=u.delta,f=t.get(p);if(g?.type==="text_delta"&&g.text)s.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:g.text}});else if(g?.type==="thinking_delta"&&g.thinking)s.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(p)||"";e.set(p,m+g.partial_json);}break}case "content_block_stop":{let p=u.index??0,g=t.get(p);if(g&&!(g.type==="text"&&g.text)){if(!(g.type==="thinking"&&g.thinking)){if(g.type==="tool_use"){let f=g,m=e.get(p)||"";e.delete(p);let h=f.input;if(m)try{h=JSON.parse(m);}catch{}let y={...f,input:h},w=a(y);w&&s.push(w);}else if(g.type==="tool_result"){let f=c(g);f&&s.push(f);}}}t.delete(p);break}}return s}function i(l){let s=l.message?.content,u=[];if(typeof s=="string")return u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:s}}),u;if(Array.isArray(s)){for(let p of s)if(p.type==="text")u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:p.text}});else if(p.type==="tool_result"){let g=c(p);g&&u.push(g);}}return u}function o(l){switch(l.type){case "text":return l.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text}}]:[];case "thinking":return l.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.thinking}}]:[];case "tool_use":{let s=a(l);return s?[s]:[]}case "tool_result":{let s=c(l);return s?[s]:[]}}}function a(l){let s=l.id,u=l.name,p=l.input;if(u==="TodoWrite"&&Array.isArray(p?.todos))return {sessionUpdate:"plan",entries:p.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:g,kind:f,content:m,locations:h}=d(u,p||{});return {sessionUpdate:"tool_call",toolCallId:s,title:g,kind:f,status:"pending",rawInput:p,content:m,locations:h}}function c(l){let s=l.tool_use_id,u=l.is_error??false,p=l.content,g=[];if(typeof p=="string"&&p.length>0)g.push({type:"content",content:{type:"text",text:u?`\`\`\`
36
- ${p}
37
- \`\`\``:p}});else if(Array.isArray(p)){for(let f of p)if(f.type==="text"){let m=f.text;g.push({type:"content",content:{type:"text",text:u?`\`\`\`
38
- ${m}
39
- \`\`\``:m}});}}return {sessionUpdate:"tool_call_update",toolCallId:s,status:u?"failed":"completed",content:g}}function d(l,s){let u=Li[l]||"other",p=[],g=[],f=l;switch(l){case "Read":case "read_file":f=`Read ${s.file_path||s.absolute_path||"file"}`,(s.file_path||s.absolute_path)&&g.push({path:s.file_path||s.absolute_path});break;case "Write":case "write_file":f=`Write ${s.file_path||"file"}`,s.file_path&&(g.push({path:s.file_path}),p.push({type:"diff",path:s.file_path,oldText:null,newText:s.content||""}));break;case "Edit":case "edit_file":f=`Edit ${s.file_path||"file"}`,s.file_path&&g.push({path:s.file_path});break;case "Bash":case "shell":case "run_shell_command":f=s.command?`\`${s.command}\``:"Run command",s.description&&p.push({type:"content",content:{type:"text",text:s.description}});break;case "WebFetch":f=s.url?`Fetch ${s.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=s.query?`"${s.query}"`:"Web search";break;case "Glob":f=`Find ${s.pattern||"files"}`,s.path&&g.push({path:s.path});break;case "Grep":f=`grep "${s.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${s.path||"directory"}`,s.path&&g.push({path:s.path});break;case "Task":f=s.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=l;}return {title:f,kind:u,content:p,locations:g}}}function kn(t){return He()(t)}function q(t){switch(t){case "claude":return Ke();case "codex":return je();case "gemini":return Ge();case "qwen":return He();case "kimi":return Rt();case "opencode":return Pt();case "droid":return Ve();default:return ()=>null}}function Ni(t,e){let n=e.trim();return n?q(t)(n):null}function Fi(t,e){let n=[],r=e.split(`
40
- `),i=q(t);for(let o of r){let a=o.trim();if(!a)continue;let c=i(a);c&&n.push(...c);}return n}function $(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function X(t){return JSON.stringify(Ki(t,{target:"jsonSchema7"}),null,2)}function Q(t){return JSON.stringify(t,null,2)}function xn(t,e=false){let n={};function r(i,o){for(let a of U.readdirSync(i)){let c=pe.join(i,a),d=o?`${o}/${a}`:a;U.statSync(c).isDirectory()?e&&r(c,d):n[d]=U.readFileSync(c);}}return r(t,""),n}function Cn(t,e){for(let[n,r]of Object.entries(e)){let i=pe.join(t,n),o=pe.dirname(i);U.mkdirSync(o,{recursive:true});let a;r instanceof ArrayBuffer||r instanceof Uint8Array?a=Buffer.from(r):a=r,U.writeFileSync(i,a);}}function ji(t){let e=t.replace(/^~/,process.env.HOME||"");if(!U.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return U.readFileSync(e,"utf-8")}function qe(t){let e=t?.type??an,n=A(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 a=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,c=t.providerBaseUrl??a??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:c,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort};let r=process.env[R];if(r)return {type:e,apiKey:r,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let c=(t?.model??n.defaultModel)?.split("/")[0],d=c?n.providerEnvMap[c]:void 0,l=d?process.env[d.keyEnv]:void 0;if(l){let u=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:l,baseUrl:u,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let i=process.env[n.apiKeyEnv];if(i){let c=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:i,baseUrl:c,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let a=process.env[n.oauthEnv];if(a){if(n.oauthFileName){let c=ji(a);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:c,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:a,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 ${R} / ${n.apiKeyEnv} env var.`)}function Vi(t){return `e2b_${Buffer.from(t,"utf8").toString("hex")}`}var _n=new WeakSet;function Gi(t){return _n.add(t),t}function ge(t){return _n.has(t)}async function ze(t){let e=t||process.env[R];if(!e)throw new Error(`${R} is required for Evolve-managed sandbox features`);try{let{createE2BProvider:n}=await import('@evolvingmachines/e2b');return Gi(n({apiKey:Vi(e),apiUrl:mt()}))}catch(n){let r=n;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${R} is set but @evolvingmachines/e2b failed to load.
41
- Try reinstalling: npm install @evolvingmachines/sdk`):r}}async function It(){let t=process.env[Ue];if(t)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===mt()&&delete process.env.E2B_API_URL,o({apiKey:t})}catch(o){let a=o;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ue} is set but @evolvingmachines/e2b failed to load.
42
- Try reinstalling: npm install @evolvingmachines/sdk`):a}let e=process.env[Be];if(e)try{let{createDaytonaProvider:o}=await import('@evolvingmachines/daytona');return o({apiKey:e})}catch(o){let a=o;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${Be} is set but @evolvingmachines/daytona failed to load.
43
- Try installing: npm install @evolvingmachines/daytona`):a}let n=process.env[Le],r=process.env[ht];if(n&&r)try{let{createModalProvider:o}=await import('@evolvingmachines/modal');return o({tokenId:n,tokenSecret:r})}catch(o){let a=o;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${Le} is set but @evolvingmachines/modal failed to load.
44
- Try installing: npm install @evolvingmachines/modal`):a}let i=process.env[R];if(i)return ze(i);throw new Error(`No sandbox provider configured. Either:
45
- 1. Set ${R} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
46
- 2. Set ${Ue} environment variable (direct E2B access, get key at https://e2b.dev)
47
- 3. Set ${Be} environment variable (direct Daytona access, get key at https://app.daytona.io)
48
- 4. Set ${Le} and ${ht} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
49
- 5. Pass sandbox explicitly: .withSandbox(provider)`)}function Hi(t){return new Promise(e=>setTimeout(e,t))}async function O(t,e,n=0){let r=Wi(e),i=e?.onItemRetry,o=null,a=0,c=r.backoffMs;for(;a<r.maxAttempts;){if(a++,o=await t(a),!r.retryOn(o))return o;if(a>=r.maxAttempts)break;if(i){let d=o.error??"Unknown error";i(n,a,d);}await Hi(c),c*=r.backoffMultiplier;}return o}function Wi(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var En=`## FILESYSTEM INSTRUCTIONS:
50
-
51
- You are running in a sandbox environment.
52
-
53
- The file system is mounted at \`{{workingDir}}/\`
54
-
55
- Your present working directory: \`{{workingDir}}/\`
56
-
57
- IMPORTANT - Directory structure:
58
- \`\`\`
59
- {{workingDir}}/
60
- \u251C\u2500\u2500 context/ # Input files (read-only) provided by the user
61
- \u251C\u2500\u2500 scripts/ # Your code goes here
62
- \u251C\u2500\u2500 temp/ # Scratch space
63
- \u2514\u2500\u2500 output/ # Where you can save final deliverables
64
- \`\`\`
65
-
66
- ### OUTPUT RULES:
67
-
68
- The \`output/\` folder is how you deliver files to the user\u2014the SDK retrieves everything from there.
69
-
70
- Use your best judgment:
71
- - **Questions, explanations, conversation** \u2192 respond in chat
72
- - **Artifacts** (files, documents, code, charts, data) \u2192 save to \`output/\`
73
-
74
- Examples:
75
- - "What is a binary search?" \u2192 chat
76
- - "Summarize this document" \u2192 chat
77
- - "Create an Excel report" \u2192 \`output/sales_report.xlsx\`
78
- - "Build an HTML dashboard" \u2192 \`output/dashboard.html\`
79
- - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
80
- - "Write a Python script" \u2192 \`output/parser.py\`
81
- - "Convert this to JSON" \u2192 \`output/data.json\`
82
- `;var Tn=`## FILESYSTEM INSTRUCTIONS:
83
-
84
- You are running in a sandbox environment.
85
-
86
- The file system is mounted at \`{{workingDir}}/\`
87
-
88
- Your present working directory: \`{{workingDir}}/\`
89
-
90
- IMPORTANT - Directory structure:
91
- \`\`\`
92
- {{workingDir}}/
93
- \u251C\u2500\u2500 repo/ # Code repository
94
- \u251C\u2500\u2500 context/ # Input files (read-only) provided by the user
95
- \u251C\u2500\u2500 scripts/ # Your code goes here
96
- \u251C\u2500\u2500 temp/ # Scratch space
97
- \u2514\u2500\u2500 output/ # Final deliverables
98
- \`\`\`
99
-
100
- ### OUTPUT RULES:
101
-
102
- The \`output/\` folder is how you deliver files to the user\u2014the SDK retrieves everything from there.
103
-
104
- Use your best judgment:
105
- - **Questions, explanations, conversation** \u2192 respond in chat
106
- - **Artifacts** (files, documents, code, charts, data) \u2192 save to \`output/\`
107
-
108
- Examples:
109
- - "What is a binary search?" \u2192 chat
110
- - "Summarize this document" \u2192 chat
111
- - "Create an Excel report" \u2192 \`output/sales_report.xlsx\`
112
- - "Build an HTML dashboard" \u2192 \`output/dashboard.html\`
113
- - "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
114
- - "Write a Python script" \u2192 \`output/parser.py\`
115
- - "Convert this to JSON" \u2192 \`output/data.json\`
116
- `;var Rn=`## SYSTEM PROMPT
117
-
118
- {{systemPrompt}}`;var Pn=`## STRUCTURED OUTPUT
119
-
120
- Your final result MUST be saved to \`output/result.json\` following this schema:
121
-
122
- \`\`\`json
123
- {{schema}}
124
- \`\`\`
125
-
126
- You are free to:
127
- - Reason through the problem step by step
128
- - Read and analyze context files
129
- - Use any available tools
130
- - Process incrementally
131
- - Create intermediate files in \`temp/\` or \`scripts/\`
132
-
133
- But your final \`output/result.json\` MUST conform to the schema above.
134
-
135
- ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
136
- ### Never just state results as text.`;var In=`## BROWSER AUTOMATION
137
-
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 On=`## Browser Automation
140
-
141
- The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
142
- `;var An=`### 1. YOUR ROLE: BEST OF N JUDGE
143
-
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
-
146
- ### 2. CONTEXT STRUCTURE
147
-
148
- \`\`\`
149
- {{fileTree}}
150
- \`\`\`
151
-
152
- ### 3. YOUR EVALUATION CRITERIA
153
-
154
- You must judge their work based on:
155
-
156
- \`\`\`
157
- {{criteria}}
158
- \`\`\`
159
-
160
- ### 4. YOUR PROCESS
161
-
162
- 1. Read \`worker_task/\` to understand the task:
163
- - Review the worker system prompt and task prompt
164
- - Check the expected output schema (if present)
165
- - Examine the worker input files in \`input/\`
166
- 2. Carefully review EACH solution attempt in \`candidate_i/\`
167
- 3. Compare outputs against the evaluation criteria
168
- 4. Reason through your findings \u2014 perform all necessary evidence-based analyses and verifications before deciding
169
- 5. Pick the best candidate (0-indexed)
170
-
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 Mn=`### 1. YOUR ROLE: OUTPUT VERIFIER
173
-
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
-
176
- ### 2. CONTEXT STRUCTURE
177
-
178
- \`\`\`
179
- {{fileTree}}
180
- \`\`\`
181
-
182
- ### 3. VERIFICATION CRITERIA
183
-
184
- The output must satisfy:
185
-
186
- \`\`\`
187
- {{criteria}}
188
- \`\`\`
189
-
190
- ### 4. YOUR PROCESS
191
-
192
- 1. Read \`worker_task/\` to understand what was asked:
193
- - Review the worker system prompt (if present)
194
- - Review the task prompt
195
- - Check the expected output schema (if present)
196
- - Examine any input files in \`input/\`
197
- 2. Carefully review the worker's output in \`worker_output/\`
198
- 3. Evaluate against the verification criteria
199
- 4. Reason through your findings
200
- 5. Make your decision
201
-
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
-
204
- If failing, provide specific, actionable feedback explaining what needs to be fixed.
205
- `;var Dn=`### CONTEXT STRUCTURE
206
-
207
- \`\`\`
208
- {{fileTree}}
209
- \`\`\`
210
-
211
- Examine all files within each item folder before producing your output.
212
- `;var $n="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 Bn=`{{originalPrompt}}
213
-
214
- ## IMPORTANT: Previous Attempt Failed Verification
215
-
216
- Your previous attempt did not pass quality verification. Please address this feedback:
217
-
218
- {{feedback}}
219
-
220
- Make sure your output addresses all the feedback points above.
221
- `;var Ln=En,Nn=Tn,Fn=Rn,Kn=Pn,Ot=In,jn=On,At=An,Vn=$n,Mt=Mn,Gn=Un,Hn=Dn,Dt=Bn;function F(t,e){let n=t;for(let[r,i]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${r}\\}\\}`,"g"),i);return n}function $t(t){let e=t.mode==="swe"?Nn:Ln,n=F(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
222
-
223
-
224
- ${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
225
-
226
-
227
- ${F(Fn,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=$(t.schema)?X(t.schema):Q(t.schema);n+=`
228
-
229
-
230
- ${F(Kn,{schema:r}).trim()}`;}return n}function Je(t){let e=[...new Set(Object.keys(t).map(d=>d.split("/")[0]))].sort((d,l)=>d==="worker_task"?-1:l==="worker_task"?1:d.localeCompare(l));if(!e.length)return `context/
231
- (empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,i=Object.keys(t).some(d=>d.startsWith("worker_task/input/")),o=[];e.forEach((d,l)=>{let s=l===e.length-1,u=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",p=s?" ":"\u2502 ";if(d==="worker_task"){o.push({line:`${u}${d}/`,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"}),i&&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:`${p}${y}${f.name}`,comment:f.comment});});}else if(d.startsWith("candidate_")){let g=d.replace("candidate_","");o.push({line:`${u}${d}/`,comment:`worker ${g} solution`});}else if(d==="worker_output")o.push({line:`${u}${d}/`,comment:"output to verify"});else if(d.startsWith("item_")){let g=d.replace("item_","");o.push({line:`${u}${d}/`,comment:`input ${g}`});}else o.push({line:`${u}${d}/`,comment:""});});let a=Math.max(...o.map(d=>d.line.length)),c=["context/"];for(let d of o)if(d.comment){let l=" ".repeat(a-d.line.length+3);c.push(`${d.line}${l}# ${d.comment}`);}else c.push(d.line);return c.join(`
232
- `)}var Wn=join(homedir(),ln),fe=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=mkdir(Wn,{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=$e(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${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=join(Wn,r),this.parser=q(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let r of n)this.bufferForDashboard(r);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let r of n)this.bufferForDashboard(r);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),this.isClosed=true,await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
233
- `)?e:e+`
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
- `;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 appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=un){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},pn));}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<=Ne;r++)try{let i=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(i.ok)return;if(i.status===429||i.status===401||i.status>=500){if(r===Ne){console.debug(`[SessionLogger] Dashboard ${i.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(wt*r);continue}console.debug(`[SessionLogger] Dashboard ${i.status}, dropping events`);return}catch(i){r===Ne?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",i),this.requeueEvents(e)):await this.delay(wt*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=$e();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 me(t){return (t||process.env.EVOLVE_DASHBOARD_URL||C).replace(/\/$/,"")}function he(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 ye(t){return await t.text().catch(()=>"")}function Ut(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function ds(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 zn(t){let e=await fetch(`${me(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${he(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Ut(t.userId),apps:ds(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 ye(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 ls(t){let e=await fetch(`${me(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${he(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Ut(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 ye(e)}`);return await e.json()}async function us(t){let e=Array.from(new Set((t.userIds??[]).map(a=>Ut(a))));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 ${he(t.apiKey)}`,accept:"application/json"},i=await fetch(`${me(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!i.ok)throw new Error(`Managed integration status failed (${i.status}): ${await ye(i)}`);return ((await i.json()).accounts??[]).map(a=>({userId:String(a.userId??""),app:String(a.app??""),appName:typeof a.appName=="string"?a.appName:void 0,appIcon:typeof a.appIcon=="string"?a.appIcon:void 0,accountLabel:typeof a.accountLabel=="string"?a.accountLabel:void 0,status:String(a.status??""),accountId:typeof a.accountId=="string"?a.accountId:void 0,updatedAt:typeof a.updatedAt=="string"?a.updatedAt:void 0}))}async function ps(t){let e=await fetch(`${me(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${he(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 ye(e)}`);return await e.json()}async function gs(t){let e=await fetch(`${me(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${he(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 ye(e)}`);return await e.json()}var Jn={auth:ls,accounts:{list:us,update:ps,delete:gs}};promisify(exec);var Kt=promisify(execFile),Qn=Symbol.for("evolve:awsSdkCache"),Zn=Symbol.for("evolve:s3ClientCache");var Cs=3600,_s=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Es(t){if(t.startsWith("s3://")){let i=t.slice(5),o=i.indexOf("/");return o===-1?{bucket:i,prefix:""}:{bucket:i.slice(0,o),prefix:i.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 Xe(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 i=t?.bucket||"",o=t?.prefix||"",a=t?.endpoint;if(t?.url){let c=Es(t.url);i=i||c.bucket,o=o||c.prefix,a=a||c.endpoint;}if(!i)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:i,prefix:o,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:a,credentials:t?.credentials,mode:"byok"}}function Bt(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 Ts(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 we(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Rs(t,e){let n=A(t),r=Ts(e),i=n.checkpointDirs?.length?n.checkpointDirs.map(c=>Bt(c)):[Bt(n.mcpConfig.settingsDir)],o=[..._s.map(c=>`--exclude=${we(c)}`),`--exclude=${we(r+"/temp")}`,...(n.checkpointExcludes??[]).map(c=>`--exclude=${we(Bt(c))}`)].join(" "),a=[we(r+"/"),...i.map(c=>we(c+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${o} ${a}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function ee(){let t=globalThis[Qn];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,i]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[Qn]={s3:r,presigner:i},{s3:r,presigner:i}}catch{throw new Error("Storage requires @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner. Install: npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner")}}async function be(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[Zn];if(r?.key===n)return r.client;let{s3:i}=await ee(),o=new i.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Zn]={client:o,key:n},o}async function cr(t,e,n){let{s3:r,presigner:i}=await ee(),o=await be(t),a=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return i.getSignedUrl(o,a,{expiresIn:Cs})}async function er(t,e){let{s3:n}=await ee(),r=await be(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(i){let o=i?.name||i?.message||"";if(i?.$metadata?.httpStatusCode===404||o==="NotFound"||o==="NoSuchKey")return false;throw i}}async function dr(t,e){let{s3:n}=await ee(),o=await(await(await be(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 Ps(t,e,n){let{s3:r}=await ee();await(await be(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function lr(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function ur(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Is(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function pr(t,e,n,r){let i=await fetch(`${t.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:n,action:r})});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Gateway presign failed (${i.status}): ${o}`)}return i.json()}async function Os(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 As(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 jt(t,e,n,r,i){let o=new Date().toISOString(),a=Rs(n,r),c=await t.commands.run(a,{timeoutMs:12e4});if(c.exitCode!==0)throw new Error(`Checkpoint tar failed: ${c.stderr}`);let d=c.stdout.trim().split(`
237
- `).pop()?.trim();if(!d||d.length!==64)throw new Error(`Invalid checkpoint hash: ${d}`);let l=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}),s=parseInt(l.stdout.trim(),10),u=Number.isNaN(s)?void 0:s,p;try{if(e.mode==="byok"){let g=lr(e,d);if(!await er(e,g)){let h=await cr(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 er(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}p=Is();let m={id:p,hash:d,tag:i.tag,timestamp:o,sizeBytes:u,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment,sandboxId:t.sandboxId};await Ps(e,ur(e,p),m);}else {let g=await pr(e,i.tag,d,"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}`)}p=(await Os(e,{tag:i.tag,hash:d,sizeBytes:u??0,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:p,hash:d,tag:i.tag,timestamp:o,sizeBytes:u,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment}}async function gr(t,e,n){let r=await Gt(e,n),i=r.hash,o={agentType:r.agentType,workspaceMode:r.workspaceMode},a=await yr(e,r),c=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${a}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(c.exitCode!==0)throw new Error(`Checkpoint download failed: ${c.stderr}`);let d=c.stdout.trim().split(`
238
- `).pop()?.trim();if(d!==i)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${i}, got ${d})`);let l=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(l.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${l.stderr}`);return o}function fr(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||C,i=!t.url&&!t.bucket&&!!n;return Xe(t,i,r,n)}async function mr(t,e){let{s3:n}=await ee(),r=await be(t),o=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,a=[],c;do{let p={Bucket:t.bucket,Prefix:o,...c&&{ContinuationToken:c}},g=await r.send(new n.ListObjectsV2Command(p));if(g.Contents)for(let f of g.Contents)f.Key?.endsWith(".json")&&f.LastModified&&a.push({key:f.Key,lastModified:f.LastModified});c=g.IsTruncated?g.NextContinuationToken:void 0;}while(c);if(a.length===0)return [];a.sort((p,g)=>{let f=g.lastModified.getTime()-p.lastModified.getTime();return f!==0?f:g.key<p.key?-1:g.key>p.key?1:0});let l=!!e?.tag?a:e?.limit?a.slice(0,e.limit):a,u=(await Promise.all(l.map(async p=>{try{return await dr(t,p.key)}catch{return null}}))).filter(p=>p!==null);return e?.tag&&(u=u.filter(p=>p.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function hr(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}`:""}`,i=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${i.status}): ${o}`)}return i.json()}function Ms(t){return t&&t>0?Math.min(t,500):100}async function Vt(t,e){return t.mode==="byok"?(await mr(t,{limit:1,tag:e?.tag}))[0]??null:(await hr(t,{limit:1,tag:e?.tag}))[0]??null}async function Gt(t,e){if(t.mode==="byok"){let n=ur(t,e);try{return await dr(t,n)}catch(r){throw Ds(r)?new Error(`Checkpoint ${e} not found`):r}}else return await As(t,e)}async function tr(t,e,n){if(e==="latest"){let r=await Vt(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function yr(t,e){if(t.mode==="byok")return cr(t,lr(t,e.hash),"get");{let n=await pr(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function wr(t){return !(!t||isAbsolute(t)||t.startsWith("-")||normalize(t).startsWith("..")||t.includes("\0"))}function nr(t,e){let n=resolve(t,e),r=resolve(t),i=relative(r,n);if(i.startsWith("..")||isAbsolute(i))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Ds(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Lt(t){let e=t.filter(n=>!wr(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var vr=10*1024*1024,rr=false;async function br(){if(!rr)try{await Kt("tar",["--version"]),rr=!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 ir(t,e){let n=await Gt(t,e),r=await yr(t,n),i=e.replace(/[^a-zA-Z0-9_-]/g,"_"),o=join(tmpdir(),`evolve-dl-${i}-${Date.now()}.tar.gz`),a=await fetch(r);if(!a.ok)throw new Error(`Checkpoint download failed (${a.status})`);if(!a.body)throw new Error("Checkpoint download returned empty body");let c=createHash("sha256"),d=createWriteStream(o);try{let s=a.body.getReader();await new Promise((u,p)=>{d.on("error",p),d.on("finish",u);async function g(){for(;;){let{done:f,value:m}=await s.read();if(f){d.end();break}c.update(m),d.write(m)||await new Promise(h=>d.once("drain",h));}}g().catch(p);});}catch(s){throw d.destroy(),await unlink(o).catch(()=>{}),s}let l=c.digest("hex");if(l!==n.hash)throw await unlink(o).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${l})`);return {tmpPath:o,metadata:n}}async function sr(t){await br();let{stdout:e}=await Kt("tar",["-tvzf",t],{maxBuffer:vr}),n=new Set,r=[],i=[];for(let o of e.trim().split(`
239
- `)){if(!o||o.startsWith("total "))continue;let a=o[0];if(a!=="-"&&a!=="d"&&a!=="l")throw new Error(`Archive contains unsupported entry type: "${a}"`);let c=o.match(/\d{2}:\d{2}\s+(.+)/)??o.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!c)continue;let d=c[1];if(a==="l"){let l=d.indexOf(" -> ");l!==-1&&(d=d.slice(0,l)),n.add(d);}else a==="d"?r.push(d.replace(/\/$/,"")):i.push(d);}return Lt(r),Lt([...n]),Lt(i)}async function Nt(t,e,n){await br(),await mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await Kt("tar",r,{maxBuffer:vr});}function $s(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 Ht(t,e){let n=fr(t,e);return Sr(n)}function Us(t){let e=fr(t||{});return Sr(e)}function Sr(t){return {async listCheckpoints(e){let n=Ms(e?.limit);return t.mode==="byok"?mr(t,{limit:n,tag:e?.tag}):hr(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return Gt(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,i=n?.to||process.cwd(),o=await tr(t,e),{tmpPath:a,metadata:c}=await ir(t,o);try{if(r)return await mkdir(i,{recursive:!0}),await sr(a),await Nt(a,i),i;{await mkdir(i,{recursive:!0});let d=join(i,`checkpoint-${c.id}.tar.gz`);return await copyFile(a,d),d}}finally{await unlink(a).catch(()=>{});}},async downloadFiles(e,n){let r=await tr(t,e),{tmpPath:i}=await ir(t,r),o;try{let a=await sr(i),c;if(n?.files){let l=n.files.filter(u=>!wr(u));if(l.length>0)throw new Error(`Unsafe file path requested: ${l[0]}`);let s=new Set(n.files);c=a.filter(u=>s.has(u));}else if(n?.glob){let l=n.glob.map($s);c=a.filter(s=>l.some(u=>u.test(s)));}else c=a;if(c.length===0)return {};o=join(tmpdir(),`evolve-extract-${Date.now()}`);try{await Nt(i,o,c);}catch(l){let s=l?.message??"";if(!s.includes("E2BIG")&&!s.includes("Argument list too long")&&!s.includes("ENAMETOOLONG"))throw l;await rm(o,{recursive:!0,force:!0}).catch(()=>{}),o=join(tmpdir(),`evolve-extract-${Date.now()}`),await Nt(i,o);}let d={};return await Promise.all(c.map(async l=>{nr(o,l),d[l]=await readFile(join(o,l));})),n?.to&&(await mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(d).map(async([l,s])=>{nr(n.to,l);let u=join(n.to,l);await mkdir(dirname(u),{recursive:!0}),await writeFile(u,s);}))),d}finally{o&&await rm(o,{recursive:true,force:true}).catch(()=>{}),await unlink(i).catch(()=>{});}}}}function K(t){return `'${t.replace(/'/g,"'\\''")}'`}function Qe(t){return typeof t=="string"&&t.length>0}function te(t,e,n){let r=t[e];if(!Qe(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function Bs(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
240
- ${n}`)}function Ls(t,e){switch(t){case "droid":{let n=te(e,"marketplace",t),r=te(e,"plugin",t);return [`droid plugin marketplace add ${K(n)}`,`droid plugin install ${K(r)} --scope user`]}case "claude":{let n=te(e,"marketplace",t),r=te(e,"plugin",t);return [`claude plugin marketplace add ${K(n)} --scope user`,`claude plugin install ${K(r)} --scope user`]}case "gemini":{let n=te(e,"source",t),r=e,i=[`gemini extensions install ${K(n)}`];return Qe(r.ref)&&i.push(`--ref ${K(r.ref)}`),r.autoUpdate===true&&i.push("--auto-update"),r.preRelease===true&&i.push("--pre-release"),i.push("--consent"),r.skipSettings===true&&i.push("--skip-settings"),[i.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=te(e,"marketplace",t),r=e,i=[`codex plugin marketplace add ${K(n)}`];if(Qe(r.ref)&&i.push(`--ref ${K(r.ref)}`),Array.isArray(r.sparse))for(let o of r.sparse){if(!Qe(o))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");i.push(`--sparse ${K(o)}`);}return [i.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function kr(t,e,n){if(n?.length)for(let r of n){let i=Ls(t,r);for(let o of i){let a=await e.commands.run(o,{timeoutMs:12e4});if(a.exitCode!==0)throw Bs(o,a)}}}var Ns=["actionbook","active-research","extract"],Fs=["agent-browser"],Ks={actionbook:Ns,"agent-browser":Fs},Er="/home/user/.agent-browser",xr=`${Er}/config.json`,Tr="/home/user/.actionbook",js=`${Tr}/config.toml`;function Cr(t){return t==="actionbook"||t==="agent-browser"}function Vs(t){return t.remote===true}function _r(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 Rr(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(Cr(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:_r(t.profile)};if(Cr(t.provider))return {provider:t.provider,managed:Vs(t),profile:_r(t.profile)};throw new Error("Unsupported browser configuration")}function Pr(t,e){return Array.from(new Set([...e??[],...Ks[t]]))}function Wt(t,e){return t==="actionbook"?{envs:{},files:[{path:js,data:`version = 1
241
-
242
- [browser]
243
- mode = "cloud"
244
- cdp_endpoint = ${JSON.stringify(e.cdpUrl)}
245
- `}],directories:[Tr]}:{envs:{AGENT_BROWSER_CONFIG:xr},files:[{path:xr,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
246
- `}],directories:[Er]}}function Ir(t){return (t?.dashboardUrl||C).replace(/\/$/,"")}async function Or(t){return await t.text().catch(()=>"")}async function Ar(t,e,n={}){let r=await fetch(`${Ir(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 Or(r)}`);let i=await r.json();if(!i.id||!i.sessionId||!i.cdpUrl||!i.liveUrl)throw new Error("Managed browser session response missing id, sessionId, cdpUrl, or liveUrl");return {id:i.id,sessionId:i.sessionId,sessionTag:i.sessionTag,cdpUrl:i.cdpUrl,liveUrl:i.liveUrl,browserAuthGrantToken:i.browserAuthGrantToken}}async function Mr(t,e){let n=await fetch(`${Ir(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 Or(n)}`)}var Ws="RSA-OAEP-256",qt="browser-login";function qs(t){return (t||process.env.EVOLVE_DASHBOARD_URL||C).replace(/\/$/,"")}function zs(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 Js(t){return await t.text().catch(()=>"")}async function Se(t,e,n={}){let r=await fetch(`${qs(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${zs(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 Js(r)}`);return await r.json()}async function Ys(t,e){let n=await Se(t,"/api/browser-credentials/public-key"),r=publicEncrypt({key:n.publicKey,padding:constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"utf8"));return {algorithm:Ws,keyId:n.id,ciphertext:r.toString("base64url")}}var Ze=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()}`:"",i=await Se(this.config,`/api/browser-credentials${r}`);return {credentials:i.credentials.map(o=>this.toMetadata(o)),total:i.total,count:i.count,offset:i.offset,hasMore:i.has_more??i.offset+i.count<i.total}}async create(e){let n=await Ys(this.config,e.password),r=await Se(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 Se(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function zt(t={}){return new Ze(t)}async function Dr(t){return (await Se({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:Xs(t.config)})})).server}function Xs(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var Jt="x-evolve-provider-runtime-binding";function Qs(t){return (t||process.env.EVOLVE_DASHBOARD_URL||C).replace(/\/$/,"")}async function Zs(t){return await t.text().catch(()=>"")}var ke=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ProviderRuntimeTokenRequestError";}};function $r(t){return t instanceof ke&&t.status===404}async function Yt(t,e,n={}){let r=await fetch(`${Qs(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new ke(r.status,`Provider runtime token request failed (${r.status}): ${await Zs(r)}`);return await r.json()}function eo(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.enabled===true&&(e.provider==="anthropic"||e.provider==="openai"||e.provider==="gemini"||e.provider==="dashscope"||e.provider==="kimi"||e.provider==="openrouter"||e.provider==="droid")&&(e.credentialMode==="provider_key"||e.credentialMode==="evolve_key")&&typeof e.token=="string"&&e.token.length>0&&typeof e.bindingSecret=="string"&&e.bindingSecret.length>0&&typeof e.baseUrl=="string"&&e.baseUrl.length>0&&typeof e.expiresAt=="string"&&e.expiresAt.length>0}async function Ur(t,e){let n=await Yt(t,"/api/provider-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!eo(n))throw new ke(502,"Provider runtime token response was invalid");return n}async function Br(t,e){return (await Yt(t,"/api/provider-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function Lr(t,e){return (await Yt(t,"/api/provider-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}var tt=18181,I="/tmp/evolve-managed-secrets",xe=`${I}/proxy.py`,re=`${I}/config.json`,z=`${I}/ca.crt`,et=`${I}/ca.key`,ne=`${I}/ca-bundle.crt`,Kr=["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","http_proxy","https_proxy","all_proxy","NO_PROXY","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"];function jr(){return [...Kr]}var Vr=String.raw`#!/usr/bin/env python3
247
- import base64
248
- import json
249
- import os
250
- import select
251
- import secrets
252
- import socket
253
- import ssl
254
- import subprocess
255
- import sys
256
- import tempfile
257
- import threading
258
- import urllib.error
259
- import urllib.request
260
-
261
- for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]:
262
- os.environ.pop(key, None)
263
-
264
- CONFIG_PATH = sys.argv[1]
265
- with open(CONFIG_PATH, "r", encoding="utf-8") as f:
266
- CONFIG = json.load(f)
267
- try:
268
- os.unlink(CONFIG_PATH)
269
- except FileNotFoundError:
270
- pass
271
-
272
- MAX_BODY_BYTES = int(CONFIG.get("max_body_bytes", 10 * 1024 * 1024))
273
- CONNECT_TIMEOUT_SECONDS = 15
274
- SOCKET_TIMEOUT_SECONDS = 130
275
- MAX_WORKERS = 100
276
- WORKERS = threading.BoundedSemaphore(MAX_WORKERS)
277
- HOST_PATTERNS = [h.lower() for h in CONFIG["hosts"]]
278
- PLACEHOLDERS = set(CONFIG["placeholders"])
279
- PLACEHOLDER_BYTES = [p.encode("utf-8") for p in CONFIG["placeholders"]]
280
- BASE_DIR = CONFIG["base_dir"]
281
- CERT_DIR = os.path.join(BASE_DIR, "certs")
282
- os.makedirs(CERT_DIR, exist_ok=True)
283
- CHANNEL_SECRET = secrets.token_urlsafe(32)
284
-
285
- def register_channel():
286
- payload = json.dumps({}).encode("utf-8")
287
- req = urllib.request.Request(
288
- CONFIG["channel_url"],
289
- data=payload,
290
- method="POST",
291
- headers={
292
- "content-type": "application/json",
293
- "accept": "application/json",
294
- "x-evolve-managed-secret-token": CONFIG["token"],
295
- "x-evolve-managed-secret-binding": CONFIG["binding"],
296
- "x-evolve-managed-secret-channel": CHANNEL_SECRET,
297
- },
298
- )
299
- with urllib.request.urlopen(req, timeout=30) as resp:
300
- if resp.status < 200 or resp.status >= 300:
301
- raise RuntimeError("managed secret channel registration failed")
302
-
303
- def host_matches(pattern, host):
304
- host = host.lower()
305
- if pattern.startswith("*."):
306
- base = pattern[2:]
307
- return host != base and host.endswith("." + base)
308
- return host == pattern
309
-
310
- def is_managed_host(host):
311
- clean = host.split(":", 1)[0].strip("[]").lower()
312
- return any(host_matches(pattern, clean) for pattern in HOST_PATTERNS)
313
-
314
- def safe_name(host):
315
- return "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in host)[:180]
316
-
317
- def ensure_cert(host):
318
- name = safe_name(host)
319
- cert = os.path.join(CERT_DIR, name + ".crt")
320
- key = os.path.join(CERT_DIR, name + ".key")
321
- if os.path.exists(cert) and os.path.exists(key):
322
- return cert, key
323
- csr = os.path.join(CERT_DIR, name + ".csr")
324
- ext = os.path.join(CERT_DIR, name + ".ext")
325
- san = "IP:" + host if host.replace(".", "").isdigit() else "DNS:" + host
326
- with open(ext, "w", encoding="utf-8") as f:
327
- f.write("basicConstraints=critical,CA:FALSE\n")
328
- f.write("keyUsage=critical,digitalSignature,keyEncipherment\n")
329
- f.write("subjectAltName=" + san + "\n")
330
- f.write("extendedKeyUsage=serverAuth\n")
331
- subprocess.run(
332
- ["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-subj", "/CN=" + host, "-out", csr],
333
- check=True,
334
- stdout=subprocess.DEVNULL,
335
- stderr=subprocess.DEVNULL,
336
- )
337
- subprocess.run(
338
- [
339
- "openssl", "x509", "-req", "-in", csr,
340
- "-CA", CONFIG["ca_cert"], "-CAkey", CONFIG["ca_key"], "-CAcreateserial",
341
- "-out", cert, "-days", "30", "-sha256", "-extfile", ext,
342
- ],
343
- check=True,
344
- stdout=subprocess.DEVNULL,
345
- stderr=subprocess.DEVNULL,
346
- )
347
- return cert, key
348
-
349
- def pipe_raw(client, host, port):
350
- upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS)
351
- client.settimeout(SOCKET_TIMEOUT_SECONDS)
352
- upstream.settimeout(SOCKET_TIMEOUT_SECONDS)
353
- try:
354
- client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
355
- sockets = [client, upstream]
356
- while True:
357
- readable, _, _ = select.select(sockets, [], [], 120)
358
- if not readable:
359
- break
360
- for sock in readable:
361
- data = sock.recv(65536)
362
- if not data:
363
- return
364
- (upstream if sock is client else client).sendall(data)
365
- finally:
366
- upstream.close()
367
-
368
- def recv_until(sock, marker, limit=65536):
369
- data = b""
370
- while marker not in data:
371
- chunk = sock.recv(4096)
372
- if not chunk:
373
- break
374
- data += chunk
375
- if len(data) > limit:
376
- raise RuntimeError("request headers too large")
377
- return data
378
-
379
- def parse_headers(blob):
380
- head, rest = blob.split(b"\r\n\r\n", 1)
381
- lines = head.decode("iso-8859-1").split("\r\n")
382
- request_line = lines[0]
383
- headers = {}
384
- for line in lines[1:]:
385
- if not line or ":" not in line:
386
- continue
387
- name, value = line.split(":", 1)
388
- headers[name.strip()] = value.strip()
389
- return request_line, headers, rest
390
-
391
- def header_value(headers, name):
392
- wanted = name.lower()
393
- for key, value in headers.items():
394
- if key.lower() == wanted:
395
- return value
396
- return None
397
-
398
- def read_chunked_body(sock, initial):
399
- data = initial
400
- body = b""
401
- while True:
402
- while b"\r\n" not in data:
403
- chunk = sock.recv(4096)
404
- if not chunk:
405
- raise RuntimeError("incomplete chunked request")
406
- data += chunk
407
- line, data = data.split(b"\r\n", 1)
408
- size = int((line.split(b";", 1)[0].strip() or b"0"), 16)
409
- if size == 0:
410
- return body
411
- if len(body) + size > MAX_BODY_BYTES:
412
- raise RuntimeError("request body too large")
413
- while len(data) < size + 2:
414
- chunk = sock.recv(65536)
415
- if not chunk:
416
- raise RuntimeError("incomplete chunked request")
417
- data += chunk
418
- body += data[:size]
419
- data = data[size + 2:]
420
-
421
- def read_request(tls_sock):
422
- blob = recv_until(tls_sock, b"\r\n\r\n")
423
- if not blob:
424
- return None
425
- request_line, headers, rest = parse_headers(blob)
426
- transfer_encoding = (header_value(headers, "Transfer-Encoding") or "").lower()
427
- if "chunked" in transfer_encoding:
428
- return request_line, headers, read_chunked_body(tls_sock, rest)
429
- length = int(header_value(headers, "Content-Length") or "0")
430
- if length > MAX_BODY_BYTES:
431
- raise RuntimeError("request body too large")
432
- body = rest
433
- while len(body) < length:
434
- chunk = tls_sock.recv(min(65536, length - len(body)))
435
- if not chunk:
436
- break
437
- body += chunk
438
- return request_line, headers, body[:length]
439
-
440
- def uses_placeholder(path, headers, body):
441
- if any(ph in path for ph in PLACEHOLDERS):
442
- return True
443
- if any(ph in value for ph in PLACEHOLDERS for value in headers.values()):
444
- return True
445
- return any(ph_b in body for ph_b in PLACEHOLDER_BYTES)
446
-
447
- def call_dashboard(method, url, headers, body):
448
- payload = json.dumps({
449
- "method": method,
450
- "url": url,
451
- "headers": headers,
452
- "bodyBase64": base64.b64encode(body).decode("ascii") if body else "",
453
- }).encode("utf-8")
454
- req = urllib.request.Request(
455
- CONFIG["egress_url"],
456
- data=payload,
457
- method="POST",
458
- headers={
459
- "content-type": "application/json",
460
- "accept": "application/json",
461
- "x-evolve-managed-secret-token": CONFIG["token"],
462
- "x-evolve-managed-secret-binding": CONFIG["binding"],
463
- "x-evolve-managed-secret-channel": CHANNEL_SECRET,
464
- },
465
- )
466
- try:
467
- with urllib.request.urlopen(req, timeout=130) as resp:
468
- return resp.status, resp.reason, json.loads(resp.read().decode("utf-8"))
469
- except urllib.error.HTTPError as err:
470
- text = err.read().decode("utf-8", "replace")
471
- return err.code, "Managed Secret Egress Error", {"headers": {"content-type": "application/json"}, "bodyBase64": base64.b64encode(text.encode()).decode("ascii")}
472
-
473
- def read_limited_response(stream):
474
- chunks = []
475
- total = 0
476
- while True:
477
- chunk = stream.read(65536)
478
- if not chunk:
479
- break
480
- total += len(chunk)
481
- if total > MAX_BODY_BYTES:
482
- raise RuntimeError("response body too large")
483
- chunks.append(chunk)
484
- return b"".join(chunks)
485
-
486
- def call_direct(method, url, headers, body):
487
- hop_by_hop = {"connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "host", "content-length"}
488
- request_headers = {k: v for k, v in headers.items() if k.lower() not in hop_by_hop}
489
- req = urllib.request.Request(
490
- url,
491
- data=body if body else None,
492
- method=method,
493
- headers=request_headers,
494
- )
495
- try:
496
- with urllib.request.urlopen(req, timeout=130) as resp:
497
- return resp.status, resp.reason, {
498
- "headers": dict(resp.headers.items()),
499
- "bodyBase64": base64.b64encode(read_limited_response(resp)).decode("ascii"),
500
- }
501
- except urllib.error.HTTPError as err:
502
- return err.code, err.reason, {
503
- "headers": dict(err.headers.items()),
504
- "bodyBase64": base64.b64encode(read_limited_response(err)).decode("ascii"),
505
- }
506
-
507
- def send_response(tls_sock, status, reason, result):
508
- body = base64.b64decode(result.get("bodyBase64") or "")
509
- headers = {str(k): str(v) for k, v in (result.get("headers") or {}).items()}
510
- headers["content-length"] = str(len(body))
511
- headers["connection"] = "close"
512
- status_line = ("HTTP/1.1 %d %s\r\n" % (status, reason or "")).encode("ascii", "replace")
513
- header_blob = b"".join((name + ": " + value + "\r\n").encode("iso-8859-1", "replace") for name, value in headers.items())
514
- tls_sock.sendall(status_line + header_blob + b"\r\n" + body)
515
-
516
- def dispatch_managed_request(method, url, headers, body):
517
- if uses_placeholder(url, headers, body):
518
- return call_dashboard(method, url, headers, body)
519
- return call_direct(method, url, headers, body)
520
-
521
- def handle_managed_connect(client, host, port):
522
- client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
523
- cert, key = ensure_cert(host)
524
- ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
525
- ctx.load_cert_chain(cert, key)
526
- client.settimeout(SOCKET_TIMEOUT_SECONDS)
527
- tls_sock = ctx.wrap_socket(client, server_side=True)
528
- tls_sock.settimeout(SOCKET_TIMEOUT_SECONDS)
529
- try:
530
- request = read_request(tls_sock)
531
- if not request:
532
- return
533
- request_line, headers, body = request
534
- parts = request_line.split()
535
- if len(parts) < 2:
536
- raise RuntimeError("bad request line")
537
- method, path = parts[0].upper(), parts[1]
538
- if path.startswith("http://") or path.startswith("https://"):
539
- url = path
540
- else:
541
- url = "https://%s%s" % (host if port == 443 else host + ":" + str(port), path)
542
- status, reason, result = dispatch_managed_request(method, url, headers, body)
543
- send_response(tls_sock, status, reason, result)
544
- finally:
545
- try:
546
- tls_sock.close()
547
- except Exception:
548
- pass
549
-
550
- def handle_client(client):
551
- try:
552
- client.settimeout(SOCKET_TIMEOUT_SECONDS)
553
- blob = recv_until(client, b"\r\n\r\n")
554
- if not blob:
555
- return
556
- request_line, headers, rest = parse_headers(blob)
557
- parts = request_line.split()
558
- if len(parts) < 3:
559
- return
560
- if parts[0].upper() == "CONNECT":
561
- target = parts[1]
562
- if ":" in target:
563
- host, port_s = target.rsplit(":", 1)
564
- port = int(port_s)
565
- else:
566
- host, port = target, 443
567
- host = host.strip("[]")
568
- if is_managed_host(host):
569
- handle_managed_connect(client, host, port)
570
- else:
571
- pipe_raw(client, host, port)
572
- return
573
- client.sendall(b"HTTP/1.1 501 Not Implemented\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
574
- except Exception as exc:
575
- try:
576
- body = json.dumps({"error": str(exc)}).encode("utf-8")
577
- client.sendall(b"HTTP/1.1 502 Bad Gateway\r\ncontent-type: application/json\r\ncontent-length: " + str(len(body)).encode() + b"\r\nconnection: close\r\n\r\n" + body)
578
- except Exception:
579
- pass
580
- finally:
581
- try:
582
- client.close()
583
- except Exception:
584
- pass
585
-
586
- def serve():
587
- server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
588
- server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
589
- server.bind(("127.0.0.1", int(CONFIG["port"])))
590
- server.listen(100)
591
- while True:
592
- client, _ = server.accept()
593
- if not WORKERS.acquire(blocking=False):
594
- try:
595
- client.sendall(b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
596
- except Exception:
597
- pass
598
- client.close()
599
- continue
600
- def run_client():
601
- try:
602
- handle_client(client)
603
- finally:
604
- WORKERS.release()
605
- thread = threading.Thread(target=run_client, daemon=True)
606
- thread.start()
607
-
608
- if __name__ == "__main__":
609
- register_channel()
610
- serve()
611
- `;function to(t){return (t||process.env.EVOLVE_DASHBOARD_URL||C).replace(/\/$/,"")}function no(t){let e=t.apiKey||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed secrets");return e}async function ro(t){return await t.text().catch(()=>"")}async function nt(t,e,n={}){let r=await fetch(`${to(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${no(t)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Managed secrets request failed (${r.status}): ${await ro(r)}`);return await r.json()}function Xt(t={}){return {async list(){return (await nt(t,"/api/managed-secrets")).secrets??[]}}}function io(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function Nr(t){try{return new URL(t).protocol==="https:"}catch{return false}}function so(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.token=="string"&&e.token.startsWith("evrt_")&&typeof e.bindingSecret=="string"&&e.bindingSecret.startsWith("evrb_")&&typeof e.egressUrl=="string"&&Nr(e.egressUrl)&&typeof e.channelUrl=="string"&&Nr(e.channelUrl)&&typeof e.expiresAt=="string"&&Array.isArray(e.env)&&e.env.every(n=>{if(!n||typeof n!="object"||Array.isArray(n))return false;let r=n;return typeof r.name=="string"&&typeof r.envName=="string"&&typeof r.placeholder=="string"&&r.placeholder.startsWith("evsec_")&&io(r.allowedHosts)})}async function Gr(t,e){let n=await nt(t,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!so(n))throw new Error("Invalid managed secret runtime token response");return n}async function Hr(t,e){return (await nt(t,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function Wr(t,e){return (await nt(t,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}function oo(t){if(!Array.isArray(t)||t.length===0)throw new Error("withManagedSecrets() requires at least one secret");return t.map((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`managedSecrets[${n}] must be an object with a name`);let r=Fr(e.name,`managedSecrets[${n}].name`),i=e.as===void 0?void 0:Fr(e.as,`managedSecrets[${n}].as`);return i?{name:r,as:i}:{name:r}})}function Fr(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} is required`);let n=t.trim().toUpperCase();if(!/^[A-Z_][A-Z0-9_]{0,127}$/.test(n))throw new Error(`${e} must be a valid environment variable name`);if(n.startsWith("EVOLVE_"))throw new Error(`${e} cannot use the reserved EVOLVE_ prefix`);return n}function ao(t){let e=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...Kr]),n=r=>{r&&e.add(r);};n(t.apiKeyEnv),n(t.baseUrlEnv),n(t.customHeadersEnv),n(t.gatewayConfigEnv),t.spendTrackingEnvs&&(n(t.spendTrackingEnvs.sessionTagEnv),n(t.spendTrackingEnvs.runTagEnv));for(let r of Object.values(t.providerEnvMap??{}))n(r.keyEnv);return e}function qr(t,e){if(!t)return;let n=oo(t),r=ao(e),i=new Set;for(let o of n){let a=o.as||o.name;if(r.has(a))throw new Error(`${a} is reserved for Evolve-managed sandbox services and cannot be used as a managed secret env var`);if(i.has(a))throw new Error(`duplicate managed secret env var: ${a}`);i.add(a);}return n}function zr(t){let e={};for(let i of t.env)e[i.envName]=i.placeholder;let n=`http://127.0.0.1:${tt}`;e.HTTPS_PROXY=n,e.https_proxy=n,e.NODE_EXTRA_CA_CERTS=z,e.SSL_CERT_FILE=ne,e.REQUESTS_CA_BUNDLE=ne,e.CURL_CA_BUNDLE=ne,e.GIT_SSL_CAINFO=ne;let r=new URL(t.egressUrl).hostname;return e.NO_PROXY=`localhost,127.0.0.1,::1,${r}`,e.no_proxy=e.NO_PROXY,e}function Jr(t){let e=Array.from(new Set(t.env.flatMap(n=>n.allowedHosts)));return JSON.stringify({egress_url:t.egressUrl,channel_url:t.channelUrl,token:t.token,binding:t.bindingSecret,hosts:e,placeholders:t.env.map(n=>n.placeholder),base_dir:I,ca_cert:z,ca_key:et,port:tt,max_body_bytes:10*1024*1024},null,2)}function Yr(){return ["umask 077",`mkdir -p ${I}/certs`,`chmod 700 ${I} ${I}/certs`,`chmod 700 ${xe} 2>/dev/null || true`,`chmod 600 ${re} 2>/dev/null || true`,`if [ ! -f ${et} ]; then openssl genrsa -out ${et} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${z} ]; then openssl req -x509 -new -nodes -key ${et} -sha256 -days 30 -subj "/CN=Evolve Managed Secrets" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ${z} >/dev/null 2>&1; fi`,`SYSTEM_CA_BUNDLE=""; for p in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem; do if [ -f "$p" ]; then SYSTEM_CA_BUNDLE="$p"; break; fi; done; if [ -n "$SYSTEM_CA_BUNDLE" ]; then cat "$SYSTEM_CA_BUNDLE" ${z} > ${ne}; else cp ${z} ${ne}; fi`,`if command -v update-ca-certificates >/dev/null 2>&1; then cp ${z} /usr/local/share/ca-certificates/evolve-managed-secrets.crt 2>/dev/null && update-ca-certificates >/dev/null 2>&1 || true; fi`].join(" && ")}function Xr(){return `umask 077 && exec python3 ${xe} ${re}`}function Qr(){return `rm -f ${re}`}var Zr="/home/user/.factory/evolve-session.json",rt="EVOLVE_PROVIDER_RUNTIME_BINDING",Qt="gemini-api-key";function Ce(t){switch(t){case "claude":return "anthropic";case "codex":return "openai";case "gemini":return "gemini";case "qwen":return "dashscope";case "kimi":return "kimi";case "opencode":return "openrouter";case "droid":return "droid";default:return null}}function po(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function ei(t){return `${t}-${randomBytes(8).toString("hex")}`}function Zt(t,e,n="newline"){let r=new Map;if(t){let i=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let o of i){let a=o.trim();if(!a)continue;let c=a.indexOf(":");if(c<=0)continue;let d=a.slice(0,c).trim(),l=a.slice(c+1).trim();r.set(d.toLowerCase(),`${d}: ${l}`);}}for(let[i,o]of Object.entries(e)){let a=i.toLowerCase();if(a===N&&r.has(a)&&n==="newline"){let c=r.get(a),d=c.slice(c.indexOf(":")+1).trim();r.set(a,`${i}: ${d},${o}`);}else r.set(a,`${i}: ${o}`);}return Array.from(r.values()).join(n==="comma"?", ":`
612
- `)}var go=262144,fo=new Set(["low","medium","high","xhigh","max"]);function ti(t){if(t)return fo.has(t)?t:void 0}function en(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var _e=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;providerRuntimeToken;managedSecretRuntimeToken;managedSecretProxy;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(n.managedSecrets){if(e.isDirectMode)throw new Error("managed secrets are available only in gateway mode with EVOLVE_API_KEY");if(n.sandboxId)throw new Error("managed secrets cannot be used with an existing sandbox; grants are sandbox-scoped.");if(n.sandboxProvider&&!ge(n.sandboxProvider))throw new Error("managed secrets require an Evolve-managed sandbox provider")}if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||dn,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,this.storage=n.storage,n.schema)if($(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=A(e.type),this.sessionTag=ei(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,i){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,i),o}finalizeOperation(e,n,r,i="idle",o="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=o,this.agentState=i,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,i,o){let a=n==="run"?"run_background_complete":"command_background_complete",c=n==="run"?"run_background_failed":"command_background_failed",d=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async l=>{if(this.interruptedOperations.delete(e)||l.exitCode===130){this.finalizeOperation(e,i,d,"interrupted");return}n==="run"&&o&&await this.writeDroidSessionState(o);let u=l.exitCode===0?a:c,p=l.exitCode===0?"idle":"error";this.finalizeOperation(e,i,u,p);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,i,c,"error");});}createAjvValidator(){let n={...at[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 co({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");let r=false;try{if(this.options.sandboxId)(this.options.mcpServers||this.options.integrations||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser||this.options.browserCredentials)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, integrations, plugins, context, files, systemPrompt, managed browser setup, and browser credentials"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,await this.loadDroidSessionState(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {await this.ensureManagedBrowserSession(e),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let i=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:i,workingDirectory:this.workingDir}),r=!0,await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(i){throw r&&this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),i}return this.sandbox}buildEnvironmentVariables(){let e={},n=this.validatedUserSecretsForEnvironment();if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode){let r=ae(this.agentConfig.reasoningEffort),i=ti(this.agentConfig.reasoningEffort);e.KIMI_MODEL_NAME=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),e.KIMI_MODEL_API_KEY=this.agentConfig.apiKey,e.KIMI_MODEL_PROVIDER_TYPE="kimi",e.KIMI_MODEL_MAX_CONTEXT_SIZE=String(this.registry.spendTrackingTomlProvider?.maxContextSize??go),e.KIMI_MODEL_DEFAULT_THINKING=r?"true":"false",e.KIMI_MODEL_THINKING_MODE=r?"on":"off",i&&(e.KIMI_MODEL_THINKING_EFFORT=i),this.agentConfig.baseUrl&&(e.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl);}else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){if(!(!this.agentConfig.isDirectMode&&Ce(this.agentConfig.type))){if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let r of Object.values(this.registry.providerEnvMap))e[r.keyEnv]=this.agentConfig.apiKey;else {let r=this.agentConfig.model?.split("/")[0],i=r?this.registry.providerEnvMap?.[r]:void 0,o=i?i.keyEnv:this.registry.apiKeyEnv,a=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:o;e[a]=this.agentConfig.apiKey;}}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let r=H(this.registry.gatewayPath),i=this.requireActiveProviderRuntimeToken();if(this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[M]:this.sessionTag,...this.providerRuntimeHeaderUpdates()}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=i?.baseUrl??r),i&&(this.shouldExposeProviderRuntimeTokenEnv()&&(e[this.registry.apiKeyEnv]=i.token),this.agentConfig.type==="gemini"&&(e.GEMINI_DEFAULT_AUTH_TYPE=Qt),this.registry.spendTrackingEnvs&&(e[rt]=i.bindingSecret)),!i){if(Ce(this.agentConfig.type))throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);e[R]=this.agentConfig.apiKey;}}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Wt(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.managedSecretRuntimeToken&&Object.assign(e,zr(this.managedSecretRuntimeToken)),n&&Object.assign(e,n),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,i=this.registry.customHeadersFormat||"newline";e[r]=Zt(e[r],{[M]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},i);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}validatedUserSecretsForEnvironment(){if(!this.options.secrets)return;let e=new Set;this.agentConfig.isDirectMode||(e.add(R),e.add(rt),this.agentConfig.type==="gemini"&&e.add("GEMINI_DEFAULT_AUTH_TYPE"));let n=i=>{i&&e.add(i);};n(this.registry.apiKeyEnv),n(this.registry.baseUrlEnv);for(let i of Object.values(this.registry.providerEnvMap??{}))n(i.keyEnv);if(this.managedSecretRuntimeToken)for(let i of jr())e.add(i);for(let i of this.managedSecretRuntimeToken?.env??[])n(i.envName);let r={};for(let[i,o]of Object.entries(this.options.secrets)){if(e.has(i))throw new Error(`${i} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);i!==this.registry.gatewayConfigEnv&&(r[i]=o);}return r}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await Ar(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async ensureProviderRuntimeToken(){let e=Ce(this.agentConfig.type);if(this.agentConfig.isDirectMode||!e||!this.options.providerRouting||this.providerRuntimeToken)return;let n;try{n=await Ur(this.options.providerRouting,{provider:e,sessionTag:this.sessionTag});}catch(r){throw $r(r)?new Error(`${e} runtime token endpoint is required in gateway mode: ${r.message}`):r}this.providerRuntimeToken=n,this.providerRuntimeToken&&this.sandbox?.sandboxId&&await this.bindProviderRuntimeToken(this.sandbox.sandboxId);}async bindProviderRuntimeToken(e){if(!this.providerRuntimeToken||!this.options.providerRouting)return;if(!await Br(this.options.providerRouting,{token:this.providerRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind provider runtime token to sandbox")}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Wt(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 Mr(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}async closeProviderRuntimeToken(){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let e=this.providerRuntimeToken,n;try{for(let r=0;r<3;r++)try{if(!await Lr(this.options.providerRouting,{token:e.token}))throw new Error("Dashboard returned ok=false");return}catch(i){n=i,r<2&&await new Promise(o=>setTimeout(o,100*(r+1)));}console.warn(`[Evolve] Provider runtime token cleanup failed: ${n.message}`);}finally{this.providerRuntimeToken=void 0;}}async ensureManagedSecretRuntimeToken(){this.managedSecretRuntimeToken||!this.options.managedSecrets||(this.managedSecretRuntimeToken=await Gr({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{sessionTag:this.sessionTag,secrets:this.options.managedSecrets.secrets}));}async bindManagedSecretRuntimeToken(e){if(!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;if(!await Hr({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:this.managedSecretRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind managed secret runtime token to sandbox")}async setupManagedSecretEgress(e){if(!this.managedSecretRuntimeToken)return;if(await e.files.makeDir(I),await e.commands.run(`umask 077 && mkdir -p ${I}/certs && chmod 700 ${I} ${I}/certs`,{timeoutMs:5e3}),await e.files.write(xe,Vr),await e.files.write(re,Jr(this.managedSecretRuntimeToken)),await e.commands.run(`chmod 700 ${xe} && chmod 600 ${re}`,{timeoutMs:5e3}),await e.commands.run(Yr(),{timeoutMs:3e4}),this.managedSecretProxy=await e.commands.spawn(Xr(),{timeoutMs:3e4}),(await e.commands.run(`python3 - <<'PY'
613
- import socket, sys, time
614
- for _ in range(50):
615
- try:
616
- s = socket.create_connection(("127.0.0.1", ${tt}), timeout=0.2)
617
- s.close()
618
- sys.exit(0)
619
- except OSError:
620
- time.sleep(0.1)
621
- sys.exit(1)
622
- PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy failed to start");await e.commands.run(Qr(),{timeoutMs:5e3});}async closeManagedSecretRuntimeToken(){let e=this.managedSecretProxy;if(this.managedSecretProxy=void 0,e&&await e.kill().catch(()=>false),!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;let n=this.managedSecretRuntimeToken,r;try{for(let i=0;i<3;i++)try{if(!await Wr({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:n.token}))throw new Error("Dashboard returned ok=false");return}catch(o){r=o,i<2&&await new Promise(a=>setTimeout(a,100*(i+1)));}console.warn(`[Evolve] Managed secret runtime token cleanup failed: ${r.message}`);}finally{this.managedSecretRuntimeToken=void 0;}}buildGatewayConfigJson(e){let n=this.requireActiveProviderRuntimeToken(),r=n?.baseUrl??en(H(this.registry.gatewayPath)),i=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),o={},a=this.options.secrets?.[this.registry.gatewayConfigEnv];if(a)try{o=JSON.parse(a);}catch{}let c=o.provider??{},d=c.litellm??{},l=d.options??{},s=d.models??{},u=s[i]??{},p=u.headers??{},g=this.agentConfig.type==="opencode"?ct(this.agentConfig.reasoningEffort):void 0,f=u.variants??{},m=g?f[g]??{}:void 0;return o.provider={...c,litellm:{...d,npm:"@ai-sdk/openai-compatible",options:{...l,baseURL:r,apiKey:n?.token??this.agentConfig.apiKey},models:{...s,[i]:{...u,name:i,headers:{...p,...e},...g?{variants:{...f,[g]:{...m,reasoningEffort:g}}}:{}}}}},JSON.stringify(o)}activeProviderRuntimeToken(){let e=Ce(this.agentConfig.type);return e&&this.providerRuntimeToken?.provider===e?this.providerRuntimeToken:void 0}requireActiveProviderRuntimeToken(){let e=Ce(this.agentConfig.type),n=this.activeProviderRuntimeToken();if(!this.agentConfig.isDirectMode&&e&&!n)throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);return n}ensureSessionLogger(e){if(this.sessionLogger)return;let n=this.options.sandboxProvider;this.sessionLogger=new fe({provider:n?.name||n?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:e.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}async flushSessionLoggerWithTimeout(e=2e3){this.sessionLogger&&await Promise.race([this.sessionLogger.flush(),new Promise(n=>setTimeout(n,e))]);}requiresPreRunDashboardIngest(){return !!(this.activeProviderRuntimeToken()||this.managedSecretRuntimeToken)}providerRuntimeHeaderUpdates(){let e=this.activeProviderRuntimeToken();return e?{[Jt]:e.bindingSecret}:{}}shouldExposeProviderRuntimeTokenEnv(){return this.agentConfig.type!=="kimi"&&!this.registry.gatewayConfigEnv}buildProviderRuntimeProcessEnvs(){let e=this.activeProviderRuntimeToken();if(!e)return {};let n={};if(this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.apiKeyEnv]=e.token),this.agentConfig.type==="gemini"&&(n.GEMINI_DEFAULT_AUTH_TYPE=Qt),this.registry.baseUrlEnv&&this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.baseUrlEnv]=e.baseUrl),this.registry.spendTrackingEnvs&&(n[rt]=e.bindingSecret),this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,i=this.registry.customHeadersFormat||"newline";n[r]=Zt(this.options.secrets?.[r],this.providerRuntimeHeaderUpdates(),i);}return n}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.buildProviderRuntimeProcessEnvs(),r=this.registry.customHeadersEnv;if(r){let o=this.options.secrets?.[r],a=this.registry.customHeadersFormat||"newline";return n[r]=Zt(o,{[M]:this.sessionTag,[N]:`${W}${e}`,...this.providerRuntimeHeaderUpdates()},a),n}let i=this.registry.spendTrackingEnvs;return i?{...n,[i.sessionTagEnv]:this.sessionTag,[i.runTagEnv]:`${W}${e}`}:this.registry.gatewayConfigEnv?{...n,[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[M]:this.sessionTag,[N]:`${W}${e}`,...this.providerRuntimeHeaderUpdates()})}:Object.keys(n).length>0?n:void 0}async writeCodexGatewayProviderConfig(e){this.agentConfig.isDirectMode||!this.registry.spendTrackingEnvs||this.agentConfig.type!=="codex"||await vt(e,this.activeProviderRuntimeToken()?.baseUrl||this.agentConfig.baseUrl||H(),this.registry.spendTrackingEnvs,this.activeProviderRuntimeToken()?{[Jt]:rt}:void 0);}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 i=this.extractDroidSessionId(e);i&&(this.droidSessionId=i);}extractDroidSessionId(e){try{return this.findDroidSessionId(JSON.parse(e))}catch{return}}findDroidSessionId(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,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(Zr);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(Zr,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.agentConfig.type==="gemini"&&!this.agentConfig.isDirectMode&&await this.writeGeminiGatewayAuthSettings(e),this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async writeGeminiGatewayAuthSettings(e){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user"),r=`${n}/${this.registry.mcpConfig.filename}`;await e.files.makeDir(n);let i={};try{let c=await e.files.read(r);typeof c=="string"&&c.trim()&&(i=JSON.parse(c));}catch(c){let d=c.message||"";if(!/not found|no such file|does not exist/i.test(d))throw c}let o=typeof i.security=="object"&&i.security!==null?i.security:{},a=typeof o.auth=="object"&&o.auth!==null?o.auth:{};i.security={...o,auth:{...a,selectedType:Qt}},await e.files.write(r,JSON.stringify(i,null,2));}async setupAgentPlugins(e){await kr(this.agentConfig.type,e,this.options.plugins);}assertProviderRuntimeDoesNotExposeGatewayKey(e){if(!this.activeProviderRuntimeToken())return;let n=this.agentConfig.apiKey;for(let[r,i]of Object.entries(e))for(let o of Object.values(i.headers||{}))if(o.includes(n))throw new Error(`MCP server "${r}" would expose the Evolve API key inside the sandbox. Use managed agent-browser or remove this gateway-authenticated MCP server.`)}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge",i=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 ${i}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let a=$t({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),c=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(c,a);}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 a=await zn({...this.options.integrations,sessionTag:this.sessionTag});o={...o,integrations:{type:"http",url:a.url,headers:a.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let a=await 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,[qt]:a};}Object.keys(o).length>0&&(this.assertProviderRuntimeDoesNotExposeGatewayKey(o),await St(this.agentConfig.type,e,this.workingDir,o)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await this.writeCodexGatewayProviderConfig(e),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Ae(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[M]:this.sessionTag,...this.providerRuntimeHeaderUpdates()}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:r,targetDir:i}=n;await e.files.makeDir(i);for(let o of this.skills){let a=`cp -r ${r}/${o} ${i}/ 2>/dev/null || true`;await e.commands.run(a,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([o,a])=>({path:`${this.workingDir}/context/${o}`,data:a}));if(r.length===0)return;let i=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));i.size>0&&await e.commands.run(`mkdir -p ${Array.from(i).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([o,a])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:a}));if(r.length===0)return;let i=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));i.size>0&&await e.commands.run(`mkdir -p ${Array.from(i).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:po(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:i=le,background:o=false,checkpointComment:a}=e,{from:c}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(c&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(c==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await Vt(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');c=v.id;}if(c){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");await this.ensureManagedBrowserSession(n),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir}),await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox);let b=await gr(this.sandbox,this.storage,c);if(await this.setupManagedBrowser(this.sandbox),b.agentType&&b.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${b.agentType}, current: ${this.agentConfig.type})`);let _=this.options.workspaceMode||"knowledge";if(b.workspaceMode&&b.workspaceMode!==_)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${b.workspaceMode}, current: ${_})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let T=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!T}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=c,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(b){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),b}}let d=await this.getSandbox(n);await this.ensureProviderRuntimeToken(),await this.loadDroidSessionState(d),this.lastRunTimestamp=Date.now(),this.ensureSessionLogger(d),this.sessionLogger?.writePrompt(r),this.requiresPreRunDashboardIngest()&&await this.flushSessionLoggerWithTimeout();let l=this.buildCommand(r),s=randomUUID(),u=this.buildRunEnvs(s);if(await this.writeCodexGatewayProviderConfig(d),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Ae(d,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[M]:this.sessionTag,[N]:`${W}${s}`,...this.providerRuntimeHeaderUpdates()}),this.agentConfig.type==="qwen"&&await pt(d,ae(this.agentConfig.reasoningEffort)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider){let v=this.requireActiveProviderRuntimeToken();await bt(d,this.registry.spendTrackingTomlProvider,{[M]:this.sessionTag,[N]:`${W}${s}`,...this.providerRuntimeHeaderUpdates()},{baseUrl:en(v?.baseUrl??H(this.registry.gatewayPath)),apiKey:v?.token??this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:ae(this.agentConfig.reasoningEffort),thinkingEffort:ti(this.agentConfig.reasoningEffort)});}if(!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings){let v=this.requireActiveProviderRuntimeToken();await De(d,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:en(v?.baseUrl??H()),apiKeyEnv:this.registry.apiKeyEnv},{[M]:this.sessionTag,[N]:`${W}${s}`,...this.providerRuntimeHeaderUpdates()});}let p="",g=q(this.agentConfig.type),f=v=>{p+=v;let b=p.split(`
623
- `);p=b.pop()??"";for(let _ of b){if(!_.trim())continue;let T=g(_);if(this.captureDroidSession(_,T),this.sessionLogger?.writeEventParsed(_,T),n?.onStdout?.(_+`
624
- `),T&&n?.onContent)for(let j of T)n.onContent(j);}},m=v=>{n?.onStderr?.(v);},h=await d.commands.spawn(l,{cwd:this.workingDir,timeoutMs:i,envs:u,onStdout:f,onStderr:m}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,o)return this.watchBackgroundOperation(y,"run",h,n,d),{sandboxId:d.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:s,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"),p.trim()){let v=g(p);if(this.captureDroidSession(p,v),this.sessionLogger?.writeEventParsed(p,v),n?.onStdout?.(p+`
625
- `),v&&n?.onContent)for(let b of v)n.onContent(b);}await this.writeDroidSessionState(d),this.sessionLogger&&!o&&await this.flushSessionLoggerWithTimeout();let S;if(this.storage&&!o&&w.exitCode===0)try{S=await jt(d,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:a,parentId:this.lastCheckpointId}),this.lastCheckpointId=S.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:d.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:s,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:S}}async executeCommand(e,n={},r){let{timeoutMs:i=le,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 a=await this.getSandbox(r);await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.requiresPreRunDashboardIngest()&&(this.ensureSessionLogger(a),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let c="",d="",l=h=>{c+=h,r?.onStdout?.(h);},s=h=>{d+=h,r?.onStderr?.(h);},u=this.buildProviderRuntimeProcessEnvs(),p=await a.commands.spawn(e,{cwd:this.workingDir,timeoutMs:i,envs:Object.keys(u).length>0?u:void 0,onStdout:l,onStderr:s}),g=this.beginOperation("command",p,r,"command_start");if(o)return this.watchBackgroundOperation(g,"command",p,r),{sandboxId:a.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let f;try{f=await p.wait();}catch(h){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,r,"command_failed","error"),h}return this.interruptedOperations.delete(g)||f.exitCode===130?this.finalizeOperation(g,r,"command_interrupted","interrupted"):f.exitCode===0?this.finalizeOperation(g,r,"command_complete","idle"):this.finalizeOperation(g,r,"command_failed","error"),{sandboxId:a.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:f.exitCode,stdout:c||f.stdout||"",stderr:d||f.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),r=`${this.workingDir}/output`,i=e?"":"-maxdepth 1",a=(await n.commands.run(`find ${r} ${i} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
626
- `).filter(Boolean),c=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,d=[],l=`${r}/`;for(let f of a){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);c>0&&y<c||d.push(m);}let s={},u=await Promise.all(d.map(async f=>{try{let m=await n.files.read(f);return {relativePath:f.startsWith(l)?f.slice(l.length):f.split("/").pop()||f,content:m}}catch{return null}}));for(let f of u)f&&(s[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:s,data:null};let p=s["result.json"];if(!p)return {files:s,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof p=="string"?p:new TextDecoder().decode(p);try{let f=JSON.parse(g);if(this.zodSchema){let m=this.zodSchema.safeParse(f);return m.success?{files:s,data:m.data}:{files:s,data:null,error:`Schema validation failed: ${m.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:s,data:f};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:s,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:s,data:null}}catch(f){return {files:s,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 jt(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.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,r=this.activeOperationKind,i=false;try{this.activeCommand?i=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(i=await this.sandbox.commands.kill(this.activeProcessId));}catch{i=false;}if(!i)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let o=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,o),i}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(r){n=r;}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession();}if(n)throw n;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=false,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed");}async getHost(e){return (await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return !this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=ei(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||C,i=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!i.ok){let o=await i.text().catch(()=>"");throw new Error(`Spend query failed (${i.status}): ${o}`)}return i}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,n){return {...e,asOf:e.asOf??n.asOf,isComplete:e.isComplete??n.isComplete,truncated:e.truncated??n.truncated}}normalizeSessionCost(e){let n={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),i=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(i)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let a=new URLSearchParams({tag:n,runId:e.runId}),d=await(await this.fetchSpend(a)).json();return this.normalizeRunCost(d,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),i=e.index>0?e.index-1:r.runs.length+e.index,o=r.runs[i];if(!o)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return o}};function mo(t){return (t||process.env.EVOLVE_DASHBOARD_URL||C).replace(/\/$/,"")}function ho(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 yo(t){return await t.text().catch(()=>"")}async function ni(t,e,n={}){let r=await fetch(`${mo(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${ho(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 yo(r)}`);return r.status===204?{}:await r.json()}var it=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await ni(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await ni(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function tn(t={}){return new it(t)}var Ee=class extends EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&($(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=Jn;static browserCredentials=zt;static browserProfiles=tn;static managedSecrets=Xt;async initializeAgent(){let e=qe(this.config.agent),n=A(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let r=qr(this.config.managedSecrets,n);if(r&&this.config.sandbox&&!ge(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let i=this.config.sandbox??(r?await ze(e.apiKey):await It()),o={},a,c,d=this.config.skills,l;if(this.config.browser){let p=Rr(this.config.browser);if(l=p,p.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');o=on(e.apiKey);}if((p.provider==="actionbook"||p.provider==="agent-browser")&&(d=Pr(p.provider,d),p.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${p.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);a=p.provider==="actionbook"?Ot:jn,c={provider:p.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||C,...p.profile?{profile:p.profile}:{}};}if(p.profile&&!p.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!l||l.provider!=="agent-browser"||!l.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 s=this.config.storage!==void 0?Xe(this.config.storage,!e.isDirectMode,C,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:i,secrets:this.config.secrets,managedSecrets:r?{secrets:r,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||C}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...o,...this.config.mcpServers},browserPrompt:a,managedBrowser:c,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||C,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:d,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||C}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||C},storage:s};this.agent=new _e(e,u);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,i=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:i?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:i,checkpointComment:o}){if(i&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let a=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:i,checkpointComment:o},a)}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=qe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:C,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 Ht(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Ht(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var ie=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e;}async use(e){await this.acquire();try{return await e()}finally{this.release();}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++;}};var J=Symbol.for("evolve.SwarmResult"),se=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 nn=class t{config;semaphore;constructor(e={}){let n=e.concurrency??cn;if(n>yt)throw new Error(`concurrency=${n} exceeds max ${yt}. 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??le,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations},this.semaphore=new ie(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:i,verify:o}=e,a=e.retry??this.config.retry,c=this.generateOperationId(),d=e.timeoutMs??this.config.timeoutMs;if(i&&o)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(n.map((s,u)=>i?this.executeMapItemWithBestOf(s,r,u,c,e,d,a):o?this.executeMapItemWithVerify(s,r,u,c,e,d,a):a?O(p=>this.executeMapItem(s,r,u,c,e,d,p),a,u):this.executeMapItem(s,r,u,c,e,d)));return se.from(l)}async filter(e){let{items:n,prompt:r,condition:i,verify:o}=e,a=e.retry??this.config.retry,c=this.generateOperationId(),d=e.timeoutMs??this.config.timeoutMs,l=await Promise.all(n.map((u,p)=>o?this.executeFilterItemWithVerify(u,r,p,c,e,d,a):a?O(g=>this.executeFilterItem(u,r,p,c,e,d,g),a,p):this.executeFilterItem(u,r,p,c,e,d))),s=[];for(let u of l)if(u.status==="error")s.push(u);else if(u.data!==null)try{i(u.data)?s.push(u):s.push({...u,status:"filtered"});}catch(p){s.push({...u,status:"error",data:null,error:`Condition function threw: ${p.message}`});}return se.from(s)}async reduce(e){let{items:n,prompt:r,verify:i}=e,o=e.retry??this.config.retry,a=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=[],l=[];n.forEach((S,v)=>{d.push(this.getFiles(S)),l.push(this.getIndex(S,v));});let s={};d.forEach((S,v)=>{Object.entries(S).forEach(([b,_])=>{s[`item_${l[v]}/${b}`]=_;});});let u=Je(s),p=F(Hn,{fileTree:u}),g=e.systemPrompt?`${p}
627
-
628
- ${e.systemPrompt}`:p,f=(S,v,b)=>({operationId:a,operation:"reduce",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:l,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,_)=>{let T=await this.semaphore.use(()=>this.execute(s,S,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:v,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:e.name,operationId:a,operation:"reduce",role:"worker",errorRetry:b,verifyRetry:_&&_>1?_-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),j=f(T,b,_&&_>1?_-1:void 0);return T.error?{status:"error",data:null,files:T.files,meta:j,error:T.error,rawData:T.rawData}:{status:"success",data:T.data,files:T.files,meta:j}},k=`${this.config.tag}-reduce`;return i?this.runWithVerification((S,v,b)=>w(S,v,void 0,b),{originalPrompt:r,inputFiles:s,verifyConfig:i,timeoutMs:c,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:a,baseTag:k,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?O(S=>{let v=S>1?S-1:void 0,b=v?`${k}-er${v}`:k;return w(r,b,v)},o):w(r,k)}async bestOf(e){let{item:n,prompt:r,config:i}=e,o=e.retry??this.config.retry,a=i.n??i.taskAgents?.length;if(a===void 0)throw new Error("bestOf requires n or taskAgents");if(a<2)throw new Error("bestOf requires n >= 2");let c=this.generateOperationId(),d=e.timeoutMs??this.config.timeoutMs,l=this.getFiles(n),s=i.mcpServers??this.config.mcpServers,u=i.judgeMcpServers??i.mcpServers??this.config.mcpServers,p=i.skills??this.config.skills,g=i.judgeSkills??i.skills??this.config.skills,f=i.integrations??this.config.integrations,m=i.judgeIntegrations??i.integrations??this.config.integrations,h=await Promise.all(Array.from({length:a},async(v,b)=>{let _=o?await O(T=>this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:b,operationId:c,config:i,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:s,skills:p,integrations:f,timeoutMs:d,attempt:T}),o,b):await this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:b,operationId:c,config:i,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:s,skills:p,integrations:f,timeoutMs:d});return i.onCandidateComplete?.(0,b,_.status==="success"?"success":"error"),_})),y=o?await O(v=>this.executeBestOfJudge({inputFiles:l,taskPrompt:r,candidates:h,config:i,timeoutMs:d,operationId:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:g,integrations:m,attempt:v}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:r,candidates:h,config:i,timeoutMs:d,operationId:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:g,integrations:m}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);i.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let S={operationId:c,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:a};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:S,candidates:h}}async execute(e,n,r){let i=null,o="",a=r.tagPrefix,c={},d=null,l,s,u={...this.config.agent,...r.agent};try{i=new Ee().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&i.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&i.withSystemPrompt(r.systemPrompt),r.mcpServers&&i.withMcpServers(r.mcpServers),r.skills?.length&&i.withSkills(r.skills),r.integrations&&i.withIntegrations(r.integrations),r.observability&&i.withObservability(r.observability),Object.keys(e).length>0&&i.withContext(e);let p=await i.run({prompt:n,timeoutMs:r.timeoutMs});o=p.sandboxId,a=i.getSessionTag()??r.tagPrefix;let g=null;try{g=await i.getOutputFiles(!0),c=g.files;}catch{}p.exitCode!==0?l=`Agent exited with code ${p.exitCode}`:r.schema?g?(d=g.data,g.error&&(l=g.error),g.rawData&&(s=g.rawData)):l="Failed to read output files from sandbox":d=c;}catch(p){if(l=p.message,i){a=i.getSessionTag()??r.tagPrefix;try{c=(await i.getOutputFiles(!0)).files;}catch{}}}finally{i&&await i.kill().catch(()=>{});}return {files:c,data:d,tag:a,sandboxId:o,error:l,rawData:s}}async executeMapItem(e,n,r,i,o,a,c=1){let d=this.getFiles(e),l=c>1?`${this.config.tag}-map-${r}-er${c-1}`:`${this.config.tag}-map-${r}`,s=this.evaluatePrompt(n,d,r);if(s instanceof Error)return this.buildErrorResult(`Prompt function threw: ${s.message}`,{operationId:i,operation:"map",tag:l,sandboxId:"",itemIndex:r});let u=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(d,s,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:l,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:i,operation:"map",itemIndex:r,role:"worker",errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),m={operationId:i,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:c>1?c-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,i,o,a,c){let d=this.getFiles(e),l=`${this.config.tag}-map-${r}`,s=o.verify,u=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=this.evaluatePrompt(n,d,r);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:i,operation:"map",tag:l,sandboxId:"",itemIndex:r});let m=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(d,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:y,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:i,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),S={operationId:i,operation:"map",tag:k.tag,sandboxId:k.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(k,S)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:d,verifyConfig:s,timeoutMs:a,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:u,skills:p,integrations:g,operationId:i,baseTag:l,retry:c,itemIndex:r,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,r,i,o,a,c){let d=this.getFiles(e),l=`${this.config.tag}-map-${r}`,s=this.evaluatePrompt(n,d,r);if(s instanceof Error)return this.buildErrorResult(`Prompt function threw: ${s.message}`,{operationId:i,operation:"map",tag:l,sandboxId:"",itemIndex:r});let u=o.bestOf,p=u.n??u.taskAgents?.length;if(p===void 0||p<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:i,operation:"map",tag:l,sandboxId:"",itemIndex:r});let g=o.mcpServers??this.config.mcpServers,f=u.mcpServers??g,m=u.judgeMcpServers??u.mcpServers??g,h=o.skills??this.config.skills,y=u.skills??h,w=u.judgeSkills??u.skills??h,k=o.integrations??this.config.integrations,S=u.integrations??k,v=u.judgeIntegrations??u.integrations??k,b=await Promise.all(Array.from({length:p},async(Te,Re)=>{let sn=c?await O(si=>this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:Re,operationId:i,config:u,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:a,parentIndex:r,attempt:si,_pipelineContext:o._pipelineContext}),c,Re):await this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:Re,operationId:i,config:u,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:a,parentIndex:r,_pipelineContext:o._pipelineContext});return u.onCandidateComplete?.(r,Re,sn.status==="success"?"success":"error"),sn})),_=c?await O(Te=>this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:b,config:u,timeoutMs:a,operationId:i,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:v,parentIndex:r,attempt:Te,_pipelineContext:o._pipelineContext}),{...c,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:b,config:u,timeoutMs:a,operationId:i,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:v,parentIndex:r,_pipelineContext:o._pipelineContext}),T=b.findIndex(Te=>Te.status==="success"),j=_.decision?.winner??(T>=0?T:0),rn=b[j]??b[0];u.onJudgeComplete?.(r,j,_.decision?.reasoning??"Judge failed to provide reasoning");let ii={operationId:i,operation:"bestof-judge",tag:_.tag,sandboxId:_.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:p,...this.pipelineContextToMeta(o._pipelineContext)};return {...rn,meta:{...rn.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:r,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:j,judgeReasoning:_.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:ii,candidates:b}}}async executeFilterItem(e,n,r,i,o,a,c=1){let d=this.getFiles(e),l=c>1?`${this.config.tag}-filter-${r}-er${c-1}`:`${this.config.tag}-filter-${r}`,s=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,p=o.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(d,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:s,skills:u,integrations:p,tagPrefix:l,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:i,operation:"filter",itemIndex:r,role:"worker",errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:i,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:c>1?c-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(g,f,d)}async executeFilterItemWithVerify(e,n,r,i,o,a,c){let d=this.getFiles(e),l=`${this.config.tag}-filter-${r}`,s=o.verify,u=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=async(m,h,y)=>{let w=await this.semaphore.use(()=>this.execute(d,m,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:h,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:i,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),k={operationId:i,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,k,d)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:d,verifyConfig:s,timeoutMs:a,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:u,skills:p,integrations:g,operationId:i,baseTag:l,retry:c,itemIndex:r,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:i,operationId:o,config:a,timeoutMs:c,parentIndex:d,attempt:l=1,_pipelineContext:s}=e,u=d!==void 0?`${this.config.tag}-map-${d}-bestof-cand-${i}`:`${this.config.tag}-bestof-cand-${i}`,p=l>1?`${u}-er${l-1}`:u,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:a.taskAgents?.[i],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:p,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:d,role:"candidate",candidateIndex:i,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s)}})),f={operationId:o,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:i,errorRetry:l>1?l-1:void 0,candidateIndex:i,...this.pipelineContextToMeta(s)};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,i)=>{r.status==="error"&&(n[`candidate_${i}/_failed.txt`]=`STATUS: FAILED
629
-
630
- Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([o,a])=>{n[`candidate_${i}/${o}`]=a;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:i,operationId:o,parentIndex:a,attempt:c=1,_pipelineContext:d}=e,l=a!==void 0?`${this.config.tag}-map-${a}-bestof-judge`:`${this.config.tag}-bestof-judge`,s=c>1?`${l}-er${c-1}`:l,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),p=Je(u),g=F(At,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:p}),f=z$1.object({winner:z$1.number().min(0).max(n.length-1),reasoning:z$1.string()}),m=await this.semaphore.use(()=>this.execute(u,Vn,{systemPrompt:g,schema:f,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:s,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:a,role:"judge",errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(d)}})),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=z$1.object({passed:z$1.boolean(),reasoning:z$1.string(),feedback:z$1.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,i])=>{n[`worker_output/${r}`]=i;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:i,workerTag:o,retryAttempt:a=1,operation:c,itemIndex:d,attemptIndex:l,_pipelineContext:s}=e,u=a>1?`${o}-verifier-er${a-1}`:`${o}-verifier`,p=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=Je(m),y=F(Mt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(m,Gn,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:p,skills:g,integrations:f,tagPrefix:u,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:i,operation:c,itemIndex:d,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(s)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let S=JSON.parse(w.rawData);k={passed:!!S.passed,reasoning:S.reasoning??"Verification completed",feedback:S.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:k?"success":"error",decision:k,tag:w.tag,sandboxId:w.sandboxId,error:k?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return F(Dt,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:i,verifyConfig:o,timeoutMs:a,operationId:c,baseTag:d,retry:l,itemIndex:s=0,operation:u,_pipelineContext:p}=n,g=o.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let w=h>1?`${d}-vr${h-1}`:d,k=l?await O(b=>e(f,b>1?`${w}-er${b-1}`:w,h),l,s):await e(f,w,h);if(o.onWorkerComplete?.(s,h,k.status==="error"?"error":"success"),k.status==="error")return k;m=k;let S=l?await O(b=>this.executeVerify({inputFiles:i,outputFiles:k.files,taskPrompt:f,config:o,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:c,workerTag:w,retryAttempt:b,operation:u,itemIndex:s,attemptIndex:h,_pipelineContext:p}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:i,outputFiles:k.files,taskPrompt:f,config:o,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:c,workerTag:w,operation:u,itemIndex:s,attemptIndex:h,_pipelineContext:p}),v={operationId:c,operation:"verify",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)};if(o.onVerifierComplete?.(s,h,S.decision?.passed??false,S.decision?.feedback),S.decision?.passed)return {...k,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?`${d}-vr${h-1}`:d;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:c,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)},attempts:h}}}generateOperationId(){return 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(i){return i}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=$(e.schema)?X(e.schema):Q(e.schema)),Object.entries(e.inputFiles).forEach(([r,i])=>{n[`worker_task/input/${r}`]=i;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&J in e&&e[J]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,r){let i=r??e.files;return e.error?{[J]:true,status:"error",data:null,files:i,meta:n,error:e.error,rawData:e.rawData}:{[J]:true,status:"success",data:e.data,files:i,meta:n}}buildErrorResult(e,n){return {[J]:true,status:"error",data:null,files:{},meta:n,error:e}}};var st=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new ot(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=randomBytes(8).toString("hex"),r=[],i=e,o=Date.now();for(let c=0;c<this.steps.length;c++){let d=this.steps[c],l=d.config.name,s=Date.now();this.events.onStepStart?.({type:d.type,index:c,name:l,itemCount:i.length});let u={pipelineRunId:n,pipelineStepIndex:c};try{let p=await this.executeStep(d,i,c,l,u),g=Date.now()-s;if(r.push({type:d.type,index:c,durationMs:g,results:p.output}),this.events.onStepComplete?.({type:d.type,index:c,name:l,durationMs:g,successCount:p.successCount,errorCount:p.errorCount,filteredCount:p.filteredCount}),d.type==="reduce")return {pipelineRunId:n,steps:r,output:p.output,totalDurationMs:Date.now()-o};i=p.nextItems;}catch(p){throw this.events.onStepError?.({type:d.type,index:c,name:l,error:p instanceof Error?p:new Error(String(p))}),p}}let a=r[r.length-1];return {pipelineRunId:n,steps:r,output:a?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,r,i,o){if(e.type==="map"){let d=e.config,l=await this.swarm.map({items:n,...d,_pipelineContext:o,retry:this.wrapRetry(d.retry,r,i),verify:this.wrapVerify(d.verify,r,i),bestOf:this.wrapBestOf(d.bestOf,r,i)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let d=e.config,l=await this.swarm.filter({items:n,...d,_pipelineContext:o,retry:this.wrapRetry(d.retry,r,i),verify:this.wrapVerify(d.verify,r,i)}),s=d.emit??"success",u=s==="success"?l.success:s==="filtered"?l.filtered:[...l.success,...l.filtered];return {output:[...l],nextItems:u,successCount:l.success.length,errorCount:l.error.length,filteredCount:l.filtered.length}}let a=e.config,c=await this.swarm.reduce({items:n,...a,_pipelineContext:o,retry:this.wrapRetry(a.retry,r,i),verify:this.wrapVerify(a.verify,r,i)});return {output:c,nextItems:[],successCount:c.status==="success"?1:0,errorCount:c.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(i,o,a)=>{e.onItemRetry?.(i,o,a),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:i,attempt:o,error:a});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(i,o,a)=>{e.onWorkerComplete?.(i,o,a),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:i,attempt:o,status:a});},onVerifierComplete:(i,o,a,c)=>{e.onVerifierComplete?.(i,o,a,c),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:i,attempt:o,passed:a,feedback:c});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(i,o,a)=>{e.onCandidateComplete?.(i,o,a),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:i,candidateIndex:o,status:a});},onJudgeComplete:(i,o,a)=>{e.onJudgeComplete?.(i,o,a),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:i,winnerIndex:o,reasoning:a});}}}},ot=class t extends st{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 Eo=6e5,To=5e3;function ri(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 Ro(t){let e=t?.apiKey||process.env[R];if(!e)throw new Error(`sessions() requires an API key. Set ${R} or pass { apiKey } in config.`);let n=t?.dashboardUrl||C;async function r(c,d){let l=await fetch(`${n}${c}`,{...d,headers:{Authorization:`Bearer ${e}`,...d?.headers}});if(!l.ok){let s=await l.text().catch(()=>"");throw new Error(`Dashboard API error (${l.status}): ${s||l.statusText}`)}return l}function i(c){return {id:c.id,tag:c.tag,agent:c.agent,model:c.model||null,provider:c.provider,sandboxId:c.sandboxId||null,state:c.isEnded?"ended":"live",runtimeStatus:c.runtimeStatus||"unknown",cost:typeof c.cost=="number"?c.cost:null,createdAt:c.createdAt,endedAt:c.endedAt||null,stepCount:c.stepCount||0,toolStats:c.toolStats||null}}function o(c,d){if(c.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(c.status||"unknown")})`);if(typeof c.replayUrl!="string"||typeof c.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:c.sessionId||d,status:"ready",replayUrl:c.replayUrl,downloadUrl:c.downloadUrl,suggestedStartSeconds:typeof c.suggestedStartSeconds=="number"?c.suggestedStartSeconds:void 0,sizeBytes:typeof c.sizeBytes=="number"?c.sizeBytes:void 0,readyAt:typeof c.readyAt=="string"?c.readyAt:void 0}}let a=c=>new Promise(d=>setTimeout(d,c));return {async list(c){let d=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(c?.limit??20,200)),paginated:"true"});if(c?.cursor&&d.set("cursor",c.cursor),c?.state&&c.state!=="all"&&d.set("state",c.state),c?.agent&&d.set("agent",c.agent),c?.tagPrefix&&d.set("tagPrefix",c.tagPrefix),c?.sort){let u={newest:"desc",oldest:"asc",cost:"desc"};d.set("sortDirection",u[c.sort]),c.sort==="cost"?d.set("sortField","cost"):d.set("sortField","timestamp");}let s=await(await r(`/api/sessions?${d}`)).json();return {items:(s.items||[]).map(i),nextCursor:s.nextCursor||null,hasMore:!!s.hasMore}},async get(c){let l=await(await r(`/api/sessions/${encodeURIComponent(c)}`)).json();return i(l)},async events(c,d){let l=new URLSearchParams;d?.since!=null&&l.set("since",String(d.since));let s=l.toString();return (await(await r(`/api/sessions/${encodeURIComponent(c)}/events${s?`?${s}`:""}`)).json()).events||[]},async download(c,d){let u=(await(await r(`/api/sessions/${encodeURIComponent(c)}`)).json()).tag||c,p=await fetch(`${n}/api/sessions/${encodeURIComponent(c)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!p.ok){let h=await p.text().catch(()=>"");throw new Error(`Download failed (${p.status}): ${h||p.statusText}`)}let g=d?.to||process.cwd();await mkdir(g,{recursive:true});let f=join(g,`${u}.jsonl`);if(!p.body)throw new Error("Download response has no body");let m=Readable.fromWeb(p.body);return await pipeline(m,createWriteStream(f)),f},async browserReplay(c,d){let l=ri("timeoutMs",d?.timeoutMs,Eo),s=ri("intervalMs",d?.intervalMs,To),u=Date.now()+l,p=`/api/sessions/${encodeURIComponent(c)}/browser-replay`;for(;;){let g=u-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${l}ms`);let f;try{f=await fetch(`${n}${p}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,g))});}catch(h){let y=h.name;throw y==="AbortError"||y==="TimeoutError"?new Error(`Browser replay timed out after ${l}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,c);if(m.status==="failed"){let h=typeof m.error=="string"?m.error:"unknown error";throw new Error(`Browser replay failed: ${h}`)}if(Date.now()>=u)throw new Error(`Browser replay timed out after ${l}ms`);await a(Math.min(s,Math.max(0,u-Date.now())));}}}}export{dt as AGENT_REGISTRY,oi as AGENT_TYPES,_e as Agent,Ot as BROWSER_ACTIONBOOK_PROMPT,qt as BROWSER_LOGIN_MCP_SERVER_NAME,Ze as BrowserCredentialsClient,it as BrowserProfilesClient,Ee as Evolve,At as JUDGE_PROMPT,st as Pipeline,Dt as RETRY_FEEDBACK_PROMPT,Kn as SCHEMA_PROMPT,J as SWARM_RESULT_BRAND,Fn as SYSTEM_PROMPT,ie as Semaphore,nn as Swarm,se as SwarmResultList,ot as TerminalPipeline,at as VALIDATION_PRESETS,Mt as VERIFY_PROMPT,Ln as WORKSPACE_PROMPT,Nn as WORKSPACE_SWE_PROMPT,F as applyTemplate,zt as browserCredentials,tn as browserProfiles,$t as buildWorkerSystemPrompt,q as createAgentParser,Ke as createClaudeParser,je as createCodexParser,Ve as createDroidParser,Ge as createGeminiParser,O as executeWithRetry,G as expandPath,A as getAgentConfig,L as getMcpSettingsDir,B as getMcpSettingsPath,ci as isValidAgentType,$ as isZodSchema,Q as jsonSchemaToString,Xt as managedSecrets,Ni as parseNdjsonLine,Fi as parseNdjsonOutput,kn as parseQwenOutput,xn as readLocalDir,Xe as resolveStorageConfig,Cn as saveLocalDir,Ro as sessions,Us as storage,Pe as writeClaudeMcpConfig,Fe as writeCodexMcpConfig,De as writeDroidGatewaySettings,Me as writeDroidMcpConfig,Ie as writeGeminiMcpConfig,St as writeMcpConfig,Oe as writeQwenMcpConfig,X as zodSchemaToJson};