@evolvingmachines/sdk 0.0.28 → 0.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +66 -46
- package/dist/index.d.cts +232 -21
- package/dist/index.d.ts +232 -21
- package/dist/index.js +66 -46
- package/package.json +4 -2
package/dist/index.cjs
CHANGED
|
@@ -1,34 +1,52 @@
|
|
|
1
|
-
'use strict';var events=require('events'),eo=require('ajv'),kn=require('zod-to-json-schema'),R=require('fs'),G=require('path'),promises=require('fs/promises'),os=require('os'),crypto=require('crypto'),core=require('@composio/core'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var eo__default=/*#__PURE__*/_interopDefault(eo);var kn__default=/*#__PURE__*/_interopDefault(kn);var R__namespace=/*#__PURE__*/_interopNamespace(R);var G__namespace=/*#__PURE__*/_interopNamespace(G);var Xt={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode"},ke={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Ce={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-6",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-5-20250929",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:n,model:e,isResume:t})=>`echo "${n}" | claude -p ${t?"--continue ":""}--model ${e} --output-format stream-json --verbose --dangerously-skip-permissions`},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.2",models:[{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Base model"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Code-optimized"},{alias:"gpt-5.1-codex-max",modelId:"gpt-5.1-codex-max",description:"Best reasoning (xhigh effort)"},{alias:"gpt-5.1-mini",modelId:"gpt-5.1-mini",description:"Smaller/faster"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.codex/skills"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:n,model:e,isResume:t,reasoningEffort:i})=>{let c=i?` -c model_reasoning_effort="${i}"`:"";return `printf '%s' "${n}" | codex exec --model ${e}${c} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${t?" 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-flash-preview",models:[{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro preview"},{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Pro preview"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Latest flash preview"},{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"},usePassthroughGateway:true,buildCommand:({prompt:n,model:e,isResume:t})=>`gemini "${n}" ${t?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3.5-plus",models:[{alias:"qwen3.5-plus",modelId:"qwen3.5-plus",description:"Latest flagship, code + reasoning"},{alias:"qwen3-coder-plus",modelId:"qwen3-coder-plus",description:"Code generation, debugging"},{alias:"qwen3-vl-plus",modelId:"qwen3-vl-plus",description:"Vision + language, multimodal"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.qwen/skills",enableFlag:"--experimental-skills"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:n,model:e,isResume:t,isDirectMode:i,skills:c})=>{let s=t?"--continue ":"",r=c?.length?"--experimental-skills ":"",p=i||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${n}" ${s}${r}--auth-type openai --model ${p} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"moonshot/kimi-k2.5",models:[{alias:"moonshot/kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Latest multimodal, Agent Swarm capable"},{alias:"moonshot/kimi-k2-turbo-preview",modelId:"moonshot/kimi-k2-turbo-preview",description:"Fast turbo model"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",buildCommand:({prompt:n,model:e,isResume:t})=>`printf '%s' "${n}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${t?"--continue ":""}`},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-sonnet-4.6",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-sonnet-4.6",modelId:"openrouter/anthropic/claude-sonnet-4.6",description:"Anthropic Sonnet via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-4.6",modelId:"openrouter/anthropic/claude-opus-4.6",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.2",modelId:"openrouter/openai/gpt-5.2",description:"OpenAI GPT-5.2 via OpenRouter"},{alias:"openrouter/openai/gpt-5.2-codex",modelId:"openrouter/openai/gpt-5.2-codex",description:"OpenAI Codex via OpenRouter"},{alias:"openrouter/openai/gpt-5.1-codex-max",modelId:"openrouter/openai/gpt-5.1-codex-max",description:"OpenAI Codex Max 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-pro-preview",modelId:"openrouter/google/gemini-3-pro-preview",description:"Gemini 3 Pro 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-plus",modelId:"openrouter/qwen/qwen3-coder-plus",description:"Qwen Coder 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:n,model:e,isResume:t,isDirectMode:i})=>{let c=t?"--continue ":"",s=e.startsWith("openrouter/")?e:`openrouter/${e}`;return i?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model ${s} --format json "${n}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model litellm/${s} --format json "${n}" < /dev/null`}}};function P(n){let e=Ce[n];if(!e)throw new Error(`Unknown agent type: ${n}`);return e}function en(n){return n in Ce}function Se(n){return n.replace(/^~/,"/home/user")}function F(n){let e=P(n);return `${Se(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function L(n){let e=P(n);return Se(e.mcpConfig.settingsDir)}function N(n){if(n instanceof Error){let e=n.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function _e(n,e){let t=[e.command,e.url].filter(Boolean);if(t.length===0)throw new Error(`MCP server "${n}" must specify command or url`);if(t.length>1)throw new Error(`MCP server "${n}" cannot specify both command and url`)}function ee(n){for(let[e,t]of Object.entries(n))_e(e,t);}function te(n){return n.type?n.type:n.command?"stdio":"sse"}function tn(n){let e=te(n);return {...n,type:e}}function nn(n){let{type:e,url:t,...i}=n;return te(n)==="http"&&t?{httpUrl:t,...i}:t?{url:t,...i}:i}function on(n){return {type:te(n),...n}}function sn(n){let{type:e,...t}=n;return t.command?{...t,transport:"stdio"}:t.url&&(e==="http"||e==="sse")?{...t,transport:e}:t}async function Te(n,e,t,i){ee(t);let c=L(e),s=F(e);await n.files.makeDir(c);let r={};try{let a=await n.files.read(s);typeof a=="string"&&(r=JSON.parse(a));}catch(a){if(!N(a))throw a}let p=Object.fromEntries(Object.entries(t).map(([a,l])=>[a,i(l)]));await n.files.write(s,JSON.stringify({...r,mcpServers:p},null,2));}async function ne(n,e,t){ee(t);let i=L("claude"),c=F("claude"),s=Object.fromEntries(Object.entries(t).map(([p,a])=>[p,on(a)]));await n.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await n.files.makeDir(i);let r={};try{let p=await n.files.read(c);typeof p=="string"&&(r=JSON.parse(p));}catch(p){if(!N(p))throw p}r.enableAllProjectMcpServers=true,await n.files.write(c,JSON.stringify(r,null,2));}async function oe(n,e){await Te(n,"gemini",e,tn);}async function ie(n,e){await Te(n,"qwen",e,nn);}async function Ee(n,e){await Te(n,"kimi",e,sn);}async function Re(n,e,t){ee(t);let i=`${e}/opencode.json`,c={};try{let r=await n.files.read(i);typeof r=="string"&&(c=JSON.parse(r));}catch(r){if(!N(r))throw r}let s=Object.fromEntries(Object.entries(t).map(([r,p])=>[r,rn(p)]));await n.files.write(i,JSON.stringify({...c,mcp:s},null,2));}function rn(n){let e=te(n);if(e==="stdio"&&n.command){let i={type:"local",command:n.args?[n.command,...n.args]:[n.command]};return n.env&&Object.keys(n.env).length>0&&(i.environment=n.env),i}if(n.url){let t={type:"remote",url:n.url};return n.headers&&Object.keys(n.headers).length>0&&(t.headers=n.headers),t}return {type:e==="stdio"?"local":"remote",...n}}function T(n){return typeof n=="string"?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(n)?`[${n.map(e=>T(e)).join(", ")}]`:typeof n=="object"&&n!==null?`{ ${Object.entries(n).map(([t,i])=>`${t} = ${T(i)}`).join(", ")} }`:typeof n=="boolean"?n?"true":"false":String(n)}async function se(n,e){for(let[a,l]of Object.entries(e))_e(a,l);let t=L("codex"),i=F("codex");await n.files.makeDir(t);let c="";try{let a=await n.files.read(i);typeof a=="string"&&(c=a);}catch(a){if(!N(a))throw a}let s=[],r=[];c.includes("experimental_use_rmcp_client")||(s.push("# Enable improved RMCP client (recommended)"),s.push("experimental_use_rmcp_client = true")),c.includes("[mcp_servers]")||r.push("[mcp_servers]","");for(let[a,l]of Object.entries(e)){if(c.includes(`[mcp_servers.${a}]`))continue;r.push(`[mcp_servers.${a}]`);let o=l.type??(l.command?"stdio":"http");if(o==="http"||o==="sse"||!!l.url){if(!l.url)throw new Error(`MCP server "${a}" is missing url for ${o} transport`);r.push(`url = ${T(l.url)}`),l.bearerTokenEnvVar&&r.push(`bearer_token_env_var = ${T(l.bearerTokenEnvVar)}`);let d=l.httpHeaders??l.headers;d&&Object.keys(d).length>0&&r.push(`http_headers = ${T(d)}`),l.envHttpHeaders&&Object.keys(l.envHttpHeaders).length>0&&r.push(`env_http_headers = ${T(l.envHttpHeaders)}`);}else r.push(`command = ${T(l.command)}`),l.args&&l.args.length>0&&r.push(`args = ${T(l.args)}`),l.cwd&&r.push(`cwd = ${T(l.cwd)}`);l.env&&Object.keys(l.env).length>0&&r.push(`env = ${T(l.env)}`),l.envVars&&l.envVars.length>0&&r.push(`env_vars = ${T(l.envVars)}`),r.push("");}let p=[c.trim(),s.join(`
|
|
1
|
+
'use strict';var events=require('events'),Wi=require('ajv'),crypto=require('crypto'),Xn=require('zod-to-json-schema'),O=require('fs'),Q=require('path'),promises=require('fs/promises'),os=require('os'),core=require('@composio/core'),child_process=require('child_process'),util=require('util'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Wi__default=/*#__PURE__*/_interopDefault(Wi);var Xn__default=/*#__PURE__*/_interopDefault(Xn);var O__namespace=/*#__PURE__*/_interopNamespace(O);var Q__namespace=/*#__PURE__*/_interopNamespace(Q);var In={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode"},Ie={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Me={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-6",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-5-20250929",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:n,model:e,isResume:t})=>`echo "${n}" | claude -p ${t?"--continue ":""}--model ${e} --output-format stream-json --verbose --dangerously-skip-permissions`},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.2",models:[{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Base model"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Code-optimized"},{alias:"gpt-5.1-codex-max",modelId:"gpt-5.1-codex-max",description:"Best reasoning (xhigh effort)"},{alias:"gpt-5.1-mini",modelId:"gpt-5.1-mini",description:"Smaller/faster"}],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:n,model:e,isResume:t,reasoningEffort:i})=>{let c=i?` -c model_reasoning_effort="${i}"`:"";return `printf '%s' "${n}" | codex exec --model ${e}${c} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${t?" 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-flash-preview",models:[{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro preview"},{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Pro preview"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Latest flash preview"},{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",usePassthroughGateway:true,buildCommand:({prompt:n,model:e,isResume:t})=>`gemini "${n}" ${t?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3.5-plus",models:[{alias:"qwen3.5-plus",modelId:"qwen3.5-plus",description:"Latest flagship, code + reasoning"},{alias:"qwen3-coder-plus",modelId:"qwen3-coder-plus",description:"Code generation, debugging"},{alias:"qwen3-vl-plus",modelId:"qwen3-vl-plus",description:"Vision + language, multimodal"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.qwen/skills",enableFlag:"--experimental-skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:n,model:e,isResume:t,isDirectMode:i,skills:c})=>{let s=t?"--continue ":"",r=c?.length?"--experimental-skills ":"",l=i||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${n}" ${s}${r}--auth-type openai --model ${l} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"moonshot/kimi-k2.5",models:[{alias:"moonshot/kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Latest multimodal, Agent Swarm capable"},{alias:"moonshot/kimi-k2-turbo-preview",modelId:"moonshot/kimi-k2-turbo-preview",description:"Fast turbo model"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},buildCommand:({prompt:n,model:e,isResume:t,isDirectMode:i})=>`printf '%s' "${n}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${i?"":"--config-file /home/user/.kimi/evolve-config.toml "}${t?"--continue ":""}`},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-sonnet-4.6",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-sonnet-4.6",modelId:"openrouter/anthropic/claude-sonnet-4.6",description:"Anthropic Sonnet via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-4.6",modelId:"openrouter/anthropic/claude-opus-4.6",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.2",modelId:"openrouter/openai/gpt-5.2",description:"OpenAI GPT-5.2 via OpenRouter"},{alias:"openrouter/openai/gpt-5.2-codex",modelId:"openrouter/openai/gpt-5.2-codex",description:"OpenAI Codex via OpenRouter"},{alias:"openrouter/openai/gpt-5.1-codex-max",modelId:"openrouter/openai/gpt-5.1-codex-max",description:"OpenAI Codex Max 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-pro-preview",modelId:"openrouter/google/gemini-3-pro-preview",description:"Gemini 3 Pro 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-plus",modelId:"openrouter/qwen/qwen3-coder-plus",description:"Qwen Coder 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:n,model:e,isResume:t,isDirectMode:i})=>{let c=t?"--continue ":"",s=e.startsWith("openrouter/")?e:`openrouter/${e}`;return i?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model ${s} --format json "${n}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model litellm/${s} --format json "${n}" < /dev/null`}}};function I(n){let e=Me[n];if(!e)throw new Error(`Unknown agent type: ${n}`);return e}function Mn(n){return n in Me}function q(n){return n.replace(/^~/,"/home/user")}function $(n){let e=I(n);return `${q(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function D(n){let e=I(n);return q(e.mcpConfig.settingsDir)}function U(n){if(n instanceof Error){let e=n.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function Ae(n,e){let t=[e.command,e.url].filter(Boolean);if(t.length===0)throw new Error(`MCP server "${n}" must specify command or url`);if(t.length>1)throw new Error(`MCP server "${n}" cannot specify both command and url`)}function re(n){for(let[e,t]of Object.entries(n))Ae(e,t);}function ae(n){return n.type?n.type:n.command?"stdio":"sse"}function An(n){let e=ae(n);return {...n,type:e}}function $n(n){let{type:e,url:t,...i}=n;return ae(n)==="http"&&t?{httpUrl:t,...i}:t?{url:t,...i}:i}function Dn(n){return {type:ae(n),...n}}function Un(n){let{type:e,...t}=n;return t.command?{...t,transport:"stdio"}:t.url&&(e==="http"||e==="sse")?{...t,transport:e}:t}async function $e(n,e,t,i){re(t);let c=D(e),s=$(e);await n.files.makeDir(c);let r={};try{let a=await n.files.read(s);typeof a=="string"&&(r=JSON.parse(a));}catch(a){if(!U(a))throw a}let l=Object.fromEntries(Object.entries(t).map(([a,p])=>[a,i(p)]));await n.files.write(s,JSON.stringify({...r,mcpServers:l},null,2));}async function ce(n,e,t){re(t);let i=D("claude"),c=$("claude"),s=Object.fromEntries(Object.entries(t).map(([l,a])=>[l,Dn(a)]));await n.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await n.files.makeDir(i);let r={};try{let l=await n.files.read(c);typeof l=="string"&&(r=JSON.parse(l));}catch(l){if(!U(l))throw l}r.enableAllProjectMcpServers=true,await n.files.write(c,JSON.stringify(r,null,2));}async function le(n,e){await $e(n,"gemini",e,An);}async function pe(n,e){await $e(n,"qwen",e,$n);}async function ue(n,e,t,i){let c=D(e),s=$(e);await n.files.makeDir(c);let r={};try{let u=await n.files.read(s);typeof u=="string"&&(r=JSON.parse(u));}catch(u){if(!U(u))throw u}let l=t.split("."),a=r;for(let u=0;u<l.length-1;u++){let d=l[u];(typeof a[d]!="object"||a[d]===null)&&(a[d]={}),a=a[d];}let p=l[l.length-1],o=typeof a[p]=="object"&&a[p]!==null?a[p]:{};a[p]={...o,...i},await n.files.write(s,JSON.stringify(r,null,2));}async function De(n,e){await $e(n,"kimi",e,Un);}async function Ue(n,e,t){re(t);let i=`${e}/opencode.json`,c={};try{let r=await n.files.read(i);typeof r=="string"&&(c=JSON.parse(r));}catch(r){if(!U(r))throw r}let s=Object.fromEntries(Object.entries(t).map(([r,l])=>[r,Fn(l)]));await n.files.write(i,JSON.stringify({...c,mcp:s},null,2));}function Fn(n){let e=ae(n);if(e==="stdio"&&n.command){let i={type:"local",command:n.args?[n.command,...n.args]:[n.command]};return n.env&&Object.keys(n.env).length>0&&(i.environment=n.env),i}if(n.url){let t={type:"remote",url:n.url};return n.headers&&Object.keys(n.headers).length>0&&(t.headers=n.headers),t}return {type:e==="stdio"?"local":"remote",...n}}function L(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function Fe(){return `${L()}`}function ft(){return `${L()}/e2b`}function ht(n){return {"browser-use":{type:"http",url:`${L()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${n}`}}}}var N="EVOLVE_API_KEY",de="E2B_API_KEY",me="DAYTONA_API_KEY",ge="MODAL_TOKEN_ID",Le="MODAL_TOKEN_SECRET",yt="claude",Z=36e5,wt=4,Ne=100,vt="/home/user/workspace",T=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",R="x-litellm-customer-id",F="x-litellm-tags",V="run:",Ct=".evolve-sdk/observability/sessions",xt=100,kt=5e3,fe=3,Ke=1e3;function _(n){return typeof n=="string"?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(n)?`[${n.map(e=>_(e)).join(", ")}]`:typeof n=="object"&&n!==null?`{ ${Object.entries(n).map(([t,i])=>`${t} = ${_(i)}`).join(", ")} }`:typeof n=="boolean"?n?"true":"false":String(n)}async function he(n,e){for(let[a,p]of Object.entries(e))Ae(a,p);let t=D("codex"),i=$("codex");await n.files.makeDir(t);let c="";try{let a=await n.files.read(i);typeof a=="string"&&(c=a);}catch(a){if(!U(a))throw a}let s=[],r=[];c.includes("experimental_use_rmcp_client")||(s.push("# Enable improved RMCP client (recommended)"),s.push("experimental_use_rmcp_client = true")),c.includes("[mcp_servers]")||r.push("[mcp_servers]","");for(let[a,p]of Object.entries(e)){if(c.includes(`[mcp_servers.${a}]`))continue;r.push(`[mcp_servers.${a}]`);let o=p.type??(p.command?"stdio":"http");if(o==="http"||o==="sse"||!!p.url){if(!p.url)throw new Error(`MCP server "${a}" is missing url for ${o} transport`);r.push(`url = ${_(p.url)}`),p.bearerTokenEnvVar&&r.push(`bearer_token_env_var = ${_(p.bearerTokenEnvVar)}`);let d=p.httpHeaders??p.headers;d&&Object.keys(d).length>0&&r.push(`http_headers = ${_(d)}`),p.envHttpHeaders&&Object.keys(p.envHttpHeaders).length>0&&r.push(`env_http_headers = ${_(p.envHttpHeaders)}`);}else r.push(`command = ${_(p.command)}`),p.args&&p.args.length>0&&r.push(`args = ${_(p.args)}`),p.cwd&&r.push(`cwd = ${_(p.cwd)}`);p.env&&Object.keys(p.env).length>0&&r.push(`env = ${_(p.env)}`),p.envVars&&p.envVars.length>0&&r.push(`env_vars = ${_(p.envVars)}`),r.push("");}let l=[c.trim(),s.join(`
|
|
2
2
|
`),r.join(`
|
|
3
|
-
`)].filter(a=>a.length>0);await n.files.write(i,
|
|
3
|
+
`)].filter(a=>a.length>0);await n.files.write(i,l.join(`
|
|
4
4
|
|
|
5
5
|
`)+`
|
|
6
|
-
`);}async function
|
|
6
|
+
`);}async function Be(n,e,t){let i=D("codex"),c=$("codex");await n.files.makeDir(i);let s="";try{let f=await n.files.read(c);typeof f=="string"&&(s=f);}catch(f){if(!U(f))throw f}let r=s.search(/^\[/m),l=r>=0?s.slice(0,r):s,a=r>=0?s.slice(r):"",p=s.includes("[model_providers.evolve-gateway]"),o=/^model_provider\s*=\s*"evolve-gateway"/m.test(l);if(p&&o)return;s=(l.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
|
|
7
|
+
|
|
8
|
+
`)+a).replace(/^\n+/,"");let d='model_provider = "evolve-gateway"',m=p?"":["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${_(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${_({[R]:t.sessionTagEnv,[F]:t.runTagEnv})}`].join(`
|
|
9
|
+
`),g;if(!s.trim())g=m?`${d}
|
|
10
|
+
|
|
11
|
+
${m}
|
|
12
|
+
`:`${d}
|
|
13
|
+
`;else {let f=s.search(/^\[/m);f>0?g=s.slice(0,f)+d+`
|
|
14
|
+
|
|
15
|
+
`+s.slice(f).trimEnd():f===0?g=d+`
|
|
16
|
+
|
|
17
|
+
`+s.trimEnd():g=s.trimEnd()+`
|
|
18
|
+
|
|
19
|
+
`+d,m&&(g=g.trimEnd()+`
|
|
20
|
+
|
|
21
|
+
`+m),g+=`
|
|
22
|
+
`;}await n.files.write(c,g);}async function je(n,e,t){let i=q(e.configPath),c=i.slice(0,i.lastIndexOf("/"));await n.files.makeDir(c);let s=[`default_model = ${_(e.modelName)}`,"",`[providers.${e.providerName}]`,'type = "kimi"','base_url = ""','api_key = ""',`custom_headers = ${_(t)}`,"",`[models.${e.modelName}]`,`provider = ${_(e.providerName)}`,'model = ""',`max_context_size = ${e.maxContextSize}`].join(`
|
|
23
|
+
`)+`
|
|
24
|
+
`;await n.files.write(i,s);}async function Ve(n,e,t,i){if(!(!i||Object.keys(i).length===0))switch(n){case "claude":await ce(e,t,i);break;case "codex":await he(e,i);break;case "gemini":await le(e,i);break;case "qwen":await pe(e,i);break;case "kimi":await De(e,i);break;case "opencode":await Ue(e,t,i);break;default:throw new Error(`Unknown agent type for MCP config: ${n}`)}}function ye(){let n={};return function(p){let o;try{o=JSON.parse(p);}catch{return null}if(o._meta||o._prompt)return null;let u=o.session_id;switch(o.type){case "system":return null;case "assistant":return e(o.message?.content,"assistant",u);case "user":{let d=o.message?.content;return typeof d=="string"||Array.isArray(d)&&d.length===1&&d[0].type==="text"?null:e(d,"user",u)}case "result":return null;default:return null}};function e(a,p,o){if(typeof a=="string")return p==="user"?null:[{sessionId:o,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}}];if(!a||!Array.isArray(a))return null;let u=[];for(let d of a){let m=null;switch(d.type){case "text":case "text_delta":if(p==="user")break;m={sessionUpdate:"agent_message_chunk",content:{type:"text",text:d.text}};break;case "image":if(p==="user")break;m={sessionUpdate:"agent_message_chunk",content:{type:"image",data:d.source?.type==="base64"?d.source.data:"",mimeType:d.source?.type==="base64"?d.source.media_type:"",uri:d.source?.type==="url"?d.source.url:void 0}};break;case "thinking":case "thinking_delta":m={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:d.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(n[d.id]=d,d.name==="TodoWrite")Array.isArray(d.input?.todos)&&(m={sessionUpdate:"plan",entries:r(d.input)});else {let g=t(d);m={sessionUpdate:"tool_call",toolCallId:d.id,status:"pending",...g};}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 g=n[d.tool_use_id];if(!g||(delete n[d.tool_use_id],g.name==="TodoWrite"))break;m={sessionUpdate:"tool_call_update",toolCallId:d.tool_use_id,status:"is_error"in d&&d.is_error?"failed":"completed",...i(d,g)};break}}m&&u.push({sessionId:o,update:m});}return u.length>0?u:null}function t(a){let p=a.name,o=a.input||{};switch(p){case "Task":return {title:o.description||"Task",kind:"think",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "NotebookRead":return {title:o.notebook_path?`Read Notebook ${o.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "NotebookEdit":return {title:o.notebook_path?`Edit Notebook ${o.notebook_path}`:"Edit Notebook",kind:"edit",content:o.new_source?[{type:"content",content:{type:"text",text:o.new_source}}]:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "Bash":return {title:o.command?"`"+o.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:o.description?[{type:"content",content:{type:"text",text:o.description}}]:[],rawInput:o};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:o};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:o};case "Read":{let u="";return o.limit?u=" ("+((o.offset??0)+1)+" - "+((o.offset??0)+o.limit)+")":o.offset&&(u=" (from line "+(o.offset+1)+")"),{title:"Read "+(o.file_path??"File")+u,kind:"read",content:[],locations:o.file_path?[{path:o.file_path,line:o.offset??0}]:[],rawInput:o}}case "LS":return {title:o.path?`List \`${o.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:o};case "Edit":{let u=o.file_path;return {title:u?`Edit \`${u}\``:"Edit",kind:"edit",content:u?[{type:"diff",path:u,oldText:o.old_string??null,newText:o.new_string??""}]:[],locations:u?[{path:u}]:[],rawInput:o}}case "Write":return {title:o.file_path?`Write ${o.file_path}`:"Write",kind:"edit",content:o.file_path?[{type:"diff",path:o.file_path,oldText:null,newText:o.content??""}]:[],locations:o.file_path?[{path:o.file_path}]:[],rawInput:o};case "Glob":{let u="Find";return o.path&&(u+=` \`${o.path}\``),o.pattern&&(u+=` \`${o.pattern}\``),{title:u,kind:"search",content:[],locations:o.path?[{path:o.path}]:[],rawInput:o}}case "Grep":{let u="grep";return o["-i"]&&(u+=" -i"),o["-n"]&&(u+=" -n"),o["-A"]!==void 0&&(u+=` -A ${o["-A"]}`),o["-B"]!==void 0&&(u+=` -B ${o["-B"]}`),o["-C"]!==void 0&&(u+=` -C ${o["-C"]}`),o.output_mode==="files_with_matches"?u+=" -l":o.output_mode==="count"&&(u+=" -c"),o.head_limit!==void 0&&(u+=` | head -${o.head_limit}`),o.glob&&(u+=` --include="${o.glob}"`),o.type&&(u+=` --type=${o.type}`),o.multiline&&(u+=" -P"),u+=` "${o.pattern??""}"`,o.path&&(u+=` ${o.path}`),{title:u,kind:"search",content:[],rawInput:o}}case "WebFetch":return {title:o.url?`Fetch ${o.url}`:"Fetch",kind:"fetch",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "WebSearch":{let u=`"${o.query??""}"`;return o.allowed_domains?.length>0&&(u+=` (allowed: ${o.allowed_domains.join(", ")})`),o.blocked_domains?.length>0&&(u+=` (blocked: ${o.blocked_domains.join(", ")})`),{title:u,kind:"fetch",content:[],rawInput:o}}case "TodoWrite":return {title:Array.isArray(o.todos)?`Update TODOs: ${o.todos.map(u=>u.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:o};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:o.plan?[{type:"content",content:{type:"text",text:o.plan}}]:[],rawInput:o};default:if(p?.startsWith("mcp__")){let u=p.split("__"),d=u[1]||"mcp",m=u.slice(2).join("__")||p;return {title:`${d}: ${m}`,kind:"other",content:[],rawInput:o}}return {title:p||"Unknown Tool",kind:"other",content:[],rawInput:o}}}function i(a,p){let o=a.content;switch(p?.name){case "Read":return Array.isArray(o)&&o.length>0?{content:o.map(u=>({type:"content",content:u.type==="text"?{type:"text",text:l(u.text)}:s(u,false)}))}:typeof o=="string"&&o.length>0?{content:[{type:"content",content:{type:"text",text:l(o)}}]}:{};case "Edit":case "Write":case "Bash":return c(o,a.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return c(o,"is_error"in a?a.is_error:false)}}function c(a,p=false){return Array.isArray(a)&&a.length>0?{content:a.map(o=>({type:"content",content:s(o,p)}))}:typeof a=="string"&&a.length>0?{content:[{type:"content",content:{type:"text",text:p?"```\n"+a+"\n```":a}}]}:{}}function s(a,p){if(a.type==="text")return p?{type:"text",text:"```\n"+a.text+"\n```"}:{type:"text",text:a.text};if(a.type==="image"){if(a.data&&a.mimeType)return {type:"image",data:a.data,mimeType:a.mimeType};if(a.source?.type==="base64")return {type:"image",data:a.source.data||"",mimeType:a.source.media_type||""};if(a.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:a.source.url}}return a}function r(a){return a.todos.map(p=>({content:p.content,status:p.status||"pending",priority:"medium"}))}function l(a){let p="```",o=Array.from(a.matchAll(/^```+/gm));for(let[u]of o)for(;u.length>=p.length;)p+="`";return p+`
|
|
7
25
|
`+a+(a.endsWith(`
|
|
8
26
|
`)?"":`
|
|
9
|
-
`)+
|
|
10
|
-
`)??
|
|
11
|
-
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:
|
|
27
|
+
`)+p}}function we(){return function(a){let p;try{p=JSON.parse(a);}catch{return null}if(p._meta||p._prompt)return null;let o=[];switch(p.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let u=p.item;if(!u)return null;let d=e(u);d&&o.push({update:d});break}case "item.updated":{let u=p.item;if(!u)return null;let d=t(u);d&&o.push({update:d});break}case "item.completed":{let u=p.item;if(!u)return null;let d=i(u);d&&o.push({update:d});break}default:return null}return o.length>0?o:null};function e(l){let a=l.id;switch(l.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${l.server}:${l.tool}`},{sessionUpdate:"tool_call",toolCallId:a,title:`${l.server}: ${l.tool}`,kind:"other",status:"in_progress",rawInput:l.arguments,content:[]};case "command_execution":return {type:"command_execution",name:l.command},{sessionUpdate:"tool_call",toolCallId:a,title:l.command?`\`${l.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:l.command},content:[]};case "web_search":return {type:"web_search",name:l.query},{sessionUpdate:"tool_call",toolCallId:a,title:`Search: ${l.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:r(l.items)};default:return null}}function t(l){return l.type==="todo_list"?{sessionUpdate:"plan",entries:r(l.items)}:null}function i(l){let a=l.id;switch(l.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.text??l.summary?.join(`
|
|
28
|
+
`)??l.content?.join(`
|
|
29
|
+
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text??""}};case "mcp_tool_call":{let o=c(l.result),u=l.status==="failed"||l.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:a,status:u,content:o}}case "command_execution":{let o=l.aggregated_output?[{type:"content",content:{type:"text",text:l.aggregated_output}}]:[],u=l.status==="completed"||l.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:a,status:u,content:o}}case "file_change":{let o=l.changes??[],u=o.map(m=>({path:m.path})),d=o.length===1?`${o[0].kind==="add"?"Create":"Edit"} ${o[0].path}`:`Edit ${o.length} files`;return {sessionUpdate:"tool_call",toolCallId:a,title:d,kind:"edit",status:l.status==="completed"?"completed":"failed",content:o.map(m=>({type:"diff",path:m.path,oldText:m.kind==="add"?null:"",newText:""})),locations:u}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:a,title:`Search: ${l.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:r(l.items)};default:return null}}function c(l){return l?.content?Array.isArray(l.content)?l.content.map(a=>({type:"content",content:s(a)})):typeof l.content=="string"?[{type:"content",content:{type:"text",text:l.content}}]:[]:[]}function s(l){return l.type==="text"?{type:"text",text:l.text??""}:l.type==="image"?{type:"image",data:l.data??"",mimeType:l.mime_type??l.mimeType??"",uri:l.uri}:l}function r(l){if(!Array.isArray(l))return [];let a=false;return l.map(p=>{let o;return p.completed?o="completed":a?o="pending":(o="in_progress",a=true),{content:p.text??"",status:o,priority:"medium"}})}}var Ln={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 ve(){return function(r){let l;try{l=JSON.parse(r);}catch{return null}if(l._meta||l._prompt)return null;let a=l.session_id,p=[];switch(l.type){case "init":case "result":return null;case "message":{let o=n(l);o&&p.push({sessionId:a,update:o});break}case "tool_use":{let o=e(l);o&&p.push({sessionId:a,update:o});break}case "tool_result":{let o=t(l);o&&p.push({sessionId:a,update:o});break}case "error":{let o=i(l);o&&p.push({sessionId:a,update:o});break}default:return null}return p.length>0?p:null};function n(s){let r=s.role,l=s.content;return l?r==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}:r==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:l}}:null:null}function e(s){let r=s.tool_id,l=s.tool_name,a=s.parameters||{},{title:p,kind:o,content:u,locations:d}=c(l,a);return {sessionUpdate:"tool_call",toolCallId:r,title:p,kind:o,status:"pending",rawInput:a,content:u,locations:d}}function t(s){let r=s.tool_id,l=s.status,a=s.output,p=s.error,o=[];return a&&typeof a=="string"&&a.length>0&&o.push({type:"content",content:{type:"text",text:l==="error"?`\`\`\`
|
|
12
30
|
${a}
|
|
13
|
-
\`\`\``:a}}),
|
|
14
|
-
${
|
|
15
|
-
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:r,status:p==="success"?"completed":"failed",content:o}}function i(s){let r=s.severity,p=s.message;return p?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${r==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${p}`}}:null}function c(s,r){let p=an[s]||"other",a=[],l=[],o=s;switch(s){case "read_file":o=`Read ${r.absolute_path||r.file_path||"file"}`,(r.absolute_path||r.file_path)&&l.push({path:r.absolute_path||r.file_path});break;case "write_file":o=`Write ${r.file_path||"file"}`,r.file_path&&(l.push({path:r.file_path}),a.push({type:"diff",path:r.file_path,oldText:null,newText:r.content||""}));break;case "edit_file":o=`Edit ${r.file_path||"file"}`,r.file_path&&l.push({path:r.file_path});break;case "replace":o=`Edit ${r.file_path||"file"}`,r.file_path&&(l.push({path:r.file_path}),(r.old_string!==void 0||r.new_string!==void 0)&&a.push({type:"diff",path:r.file_path,oldText:r.old_string||"",newText:r.new_string||""}));break;case "run_shell_command":case "shell":o=r.command?`\`${r.command}\``:"Run command",r.description&&a.push({type:"content",content:{type:"text",text:r.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=r.query?`"${r.query}"`:"Web search";break;case "web_fetch":o=r.prompt?`Fetch: ${r.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${r.pattern||"files"}`,r.dir_path&&l.push({path:r.dir_path});break;case "grep":case "search_file_content":o=`grep "${r.pattern||r.query||""}"`;break;case "list_directory":o=`List ${r.dir_path||r.path||"directory"}`,(r.dir_path||r.path)&&l.push({path:r.dir_path||r.path});break;case "read_many_files":o=`Read ${r.include?.length||"multiple"} files`,Array.isArray(r.include)&&r.include.forEach(u=>l.push({path:u}));break;case "delegate_to_agent":o=r.agent_name?`Agent: ${r.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=r.fact?`Remember: "${r.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=r.name?`Activate skill: ${r.name}`:"Activate skill";break;default:o=s;}return {title:o,kind:p,content:a,locations:l}}}var cn={ReadFile:"read",ReadMediaFile:"read",WriteFile:"edit",StrReplaceFile:"edit",Shell:"execute",Glob:"search",Grep:"search",SearchWeb:"fetch",FetchURL:"fetch",Task:"think",Think:"think",CreateSubagent:"think",SetTodoList:"other"};function Ie(n){return /<system>\s*ERROR:/i.test(n)||n.includes("<error>")||n.includes("ToolError")}function et(n){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(n);if(!e)return null;let t=e[1]||"",i=e[2]||"",c=e[3]||"";return /;base64/i.test(i)?{mimeType:t,data:c}:null}function Me(n){if(!n||typeof n!="object")return null;if(n.type==="text"&&typeof n.text=="string"&&n.text.length>0)return {type:"content",content:{type:"text",text:n.text}};if(n.type==="image_url"&&typeof n.image_url?.url=="string"){let e=n.image_url.url,t=et(e);return t?{type:"content",content:{type:"image",data:t.data,mimeType:t.mimeType}}:{type:"content",content:{type:"image",data:"",mimeType:"",uri:e}}}return n.type==="video_url"&&typeof n.video_url?.url=="string"?{type:"content",content:{type:"text",text:`[video] ${n.video_url.url}`}}:n.type==="audio_url"&&typeof n.audio_url?.url=="string"?{type:"content",content:{type:"text",text:`[audio] ${n.audio_url.url}`}}:null}function Oe(n){let e=[];if(typeof n=="string")return n.length>0&&e.push({type:"content",content:{type:"text",text:n}}),e;if(Array.isArray(n)){for(let t of n){if(typeof t=="string"&&t.length>0){e.push({type:"content",content:{type:"text",text:t}});continue}let i=Me(t);i&&e.push(i);}return e}if(n&&typeof n=="object"){let t=Me(n);t&&e.push(t);}return e}function ln(n){return n.some(e=>e.type==="content"&&e.content.type==="text"&&Ie(e.content.text))}function pn(n){if(!n||typeof n!="object")return null;if(n.type==="think"&&typeof n.think=="string"&&n.think.length>0)return {update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.think}}};if(n.type==="text"&&typeof n.text=="string"&&n.text.length>0)return {update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.text}}};if(n.type==="image_url"&&typeof n.image_url?.url=="string"){let e=n.image_url.url,t=et(e);return t?{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:t.data,mimeType:t.mimeType}}}:{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:"",mimeType:"",uri:e}}}}return n.type==="video_url"&&typeof n.video_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[video] ${n.video_url.url}`}}}:n.type==="audio_url"&&typeof n.audio_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[audio] ${n.audio_url.url}`}}}:null}function un(n){return n==="in_progress"?"in_progress":n==="done"||n==="completed"?"completed":"pending"}function Xe(n){if(!n||typeof n!="object")return [];let e=n.todos;return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return null;let i=t.title;if(typeof i!="string"||i.length===0)return null;let c=t.status;return {content:i,status:un(c),priority:"medium"}}).filter(t=>t!==null):[]}function Ae(){let n=new Set,e=0;function t(p,a){return typeof p=="string"&&p.length>0?p:(e+=1,`kimi_${a.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(a){let l;try{l=JSON.parse(a);}catch{return null}if(!l||typeof l!="object"||"_meta"in l||"_prompt"in l)return null;let o=l.role;return o==="assistant"?i(l):o==="tool"?c(l):typeof l.type=="string"&&"payload"in l?s(l):null};function i(p){let a=[],l=p.content,o=p.tool_calls;if(typeof l=="string"&&l.length>0)a.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}});else if(Array.isArray(l))for(let u of l){let d=pn(u);d&&a.push(d);}if(Array.isArray(o))for(let u of o){if(!u||typeof u!="object")continue;let d=u.function;if(!d)continue;let m=d.name??"",f=t(u.id,m),g;try{g=d.arguments?JSON.parse(d.arguments):{};}catch{g=d.arguments;}if(m==="SetTodoList"){let v=Xe(g);v.length>0&&a.push({update:{sessionUpdate:"plan",entries:v}}),n.add(f);continue}let{title:h,kind:w,toolContent:x,locations:y}=r(m,typeof g=="object"&&g!==null?g:{});a.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:w,status:"pending",rawInput:g,content:x,locations:y}});}return a.length>0?a:null}function c(p){let a=p.tool_call_id;if(typeof a!="string"||a.length===0)return null;if(n.has(a))return n.delete(a),null;let l=p.content,o=[],u=false;if(typeof l=="string")u=Ie(l),l.length>0&&o.push({type:"content",content:{type:"text",text:l}});else if(Array.isArray(l))for(let d of l){let m=Me(d);m&&(m.type==="content"&&m.content.type==="text"&&Ie(m.content.text)&&(u=true),o.push(m));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:a,status:u?"failed":"completed",content:o}}]}function s(p){let a=p.type,l=p.payload??{},o=[];switch(a){case "TextPart":{let u=l.text;typeof u=="string"&&u.length>0&&o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u}}});break}case "ThinkPart":{let u=l.think;typeof u=="string"&&u.length>0&&o.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u}}});break}case "ToolCall":{let u=l.function?.name??"",d=t(l.id,u),m=l.function;if(!m)break;let f;try{f=m.arguments?JSON.parse(m.arguments):{};}catch{f=m.arguments;}if(u==="SetTodoList"){let y=Xe(f);y.length>0&&o.push({update:{sessionUpdate:"plan",entries:y}}),n.add(d);break}let{title:g,kind:h,toolContent:w,locations:x}=r(u,typeof f=="object"&&f!==null?f:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:d,title:g,kind:h,status:"pending",rawInput:f,content:w,locations:x}});break}case "ToolResult":{let u=l.tool_call_id;if(typeof u!="string"||u.length===0)break;if(n.has(u)){n.delete(u);break}let d=l.return_value??l.content,m=[],f=l.is_error===true;if(d&&typeof d=="object"&&!Array.isArray(d)){let g=d;f=f||g.type==="ToolError"||g.is_error===true,m.push(...Oe(g.output)),m.length===0&&typeof g.message=="string"&&g.message.length>0&&m.push({type:"content",content:{type:"text",text:g.message}}),m.length===0&&m.push(...Oe(d));}else m.push(...Oe(d));f=f||ln(m),o.push({update:{sessionUpdate:"tool_call_update",toolCallId:u,status:f?"failed":"completed",content:m}});break}default:return null}return o.length>0?o:null}function r(p,a){let l=cn[p]||"other",o=[],u=[],d=p;switch(p){case "ReadFile":{let m=a.path??a.file_path;d=`Read ${m||"file"}`,m&&u.push({path:m});break}case "ReadMediaFile":{let m=a.path??a.file_path;d=`Read media ${m||"file"}`,m&&u.push({path:m});break}case "WriteFile":{let m=a.path??a.file_path;d=`Write ${m||"file"}`,m&&(u.push({path:m}),typeof a.content=="string"&&o.push({type:"diff",path:m,oldText:null,newText:a.content}));break}case "StrReplaceFile":{let m=a.path??a.file_path;d=`Edit ${m||"file"}`,m&&u.push({path:m});break}case "Shell":d=a.command?`\`${a.command}\``:"Run command";break;case "Glob":d=`Find ${a.pattern||"files"}`,a.path&&u.push({path:a.path});break;case "Grep":d=`grep "${a.pattern||""}"`,a.path&&u.push({path:a.path});break;case "SearchWeb":d=a.query?`"${a.query}"`:"Web search";break;case "FetchURL":d=a.url?`Fetch ${a.url}`:"Web fetch";break;case "Task":d=a.description||"Subagent task";break;case "Think":d=a.thought||"Thinking";break;case "CreateSubagent":d=a.name?`Subagent: ${a.name}`:"Create subagent";break;case "SetTodoList":d="Update todos";break;default:d=p;}return {title:d,kind:l,toolContent:o,locations:u}}}var dn={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 mn(n){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(n);if(!e)return null;let t=e[1]||"",i=e[2]||"",c=e[3]||"";return /;base64/i.test(i)?{mimeType:t,data:c}:null}function fn(n){if(typeof n!="string")return "pending";switch(n.toLowerCase()){case "in_progress":case "in-progress":case "running":return "in_progress";case "completed":case "done":case "cancelled":return "completed";default:return "pending"}}function gn(n){return n==="high"||n==="medium"||n==="low"?n:"medium"}function tt(n){return Array.isArray(n)?n.map(e=>{if(!e||typeof e!="object")return null;let t=e.content;return typeof t!="string"||t.length===0?null:{content:t,status:fn(e.status),priority:gn(e.priority)}}).filter(e=>e!==null):[]}function hn(n){if(!n||typeof n!="object")return null;let e=n,t=typeof e.mime=="string"?e.mime:"",i=typeof e.url=="string"?e.url:"";if(t.startsWith("image/")){if(i.length>0){let p=mn(i);return p?{type:"content",content:{type:"image",data:p.data,mimeType:p.mimeType||t}}:{type:"content",content:{type:"image",data:"",mimeType:t,uri:i}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${t||"file"})`}}}function yn(n,e){if(n==="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 vn(n,e){return n==="error"?"failed":n==="running"?"in_progress":n==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function $e(){return function(r){let p;try{p=JSON.parse(r);}catch{return null}if(!p||typeof p!="object")return null;let a=p.sessionID,l=[];switch(p.type){case "step_start":case "step_finish":return null;case "text":{let o=n(p);o&&l.push({sessionId:a,update:o});break}case "reasoning":{let o=e(p);o&&l.push({sessionId:a,update:o});break}case "tool_use":{let o=t(p);for(let u of o)l.push({sessionId:a,update:u});break}case "error":{let o=i(p);o&&l.push({sessionId:a,update:o});break}default:return null}return l.length>0?l:null};function n(s){let r=s.part?.text;return typeof r!="string"||r.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}}function e(s){let r=s.part?.text;return typeof r!="string"||r.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:r}}}function t(s){let r=s.part;if(!r)return [];let p=typeof r.callID=="string"?r.callID:"";if(p.length===0)return [];let a=typeof r.tool=="string"?r.tool.toLowerCase():"",l=typeof r.state=="object"&&r.state?r.state:{},o=typeof l.input=="object"&&l.input?l.input:{},u=l.status,d=l.title??l.metadata?.description??a,m=l.metadata?.exit,{kind:f,content:g,locations:h}=c(a,o),w=[];if(w.push({sessionUpdate:"tool_call",toolCallId:p,title:d,kind:f,status:"pending",rawInput:o,content:g,locations:h}),a==="todowrite"){let b=tt(o.todos);if(b.length===0&&typeof l.output=="string")try{b=tt(JSON.parse(l.output));}catch{}b.length>0&&w.push({sessionUpdate:"plan",entries:b});}let x=vn(u,m);if(x==="pending")return w;let y=yn(u,l),v=[];if(typeof y=="string"&&y.length>0&&v.push({type:"content",content:{type:"text",text:x==="failed"?`\`\`\`
|
|
16
|
-
${
|
|
17
|
-
\`\`\``:
|
|
31
|
+
\`\`\``:a}}),p?.message&&!a&&o.push({type:"content",content:{type:"text",text:`\`\`\`
|
|
32
|
+
${p.message}
|
|
33
|
+
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:r,status:l==="success"?"completed":"failed",content:o}}function i(s){let r=s.severity,l=s.message;return l?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${r==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${l}`}}:null}function c(s,r){let l=Ln[s]||"other",a=[],p=[],o=s;switch(s){case "read_file":o=`Read ${r.absolute_path||r.file_path||"file"}`,(r.absolute_path||r.file_path)&&p.push({path:r.absolute_path||r.file_path});break;case "write_file":o=`Write ${r.file_path||"file"}`,r.file_path&&(p.push({path:r.file_path}),a.push({type:"diff",path:r.file_path,oldText:null,newText:r.content||""}));break;case "edit_file":o=`Edit ${r.file_path||"file"}`,r.file_path&&p.push({path:r.file_path});break;case "replace":o=`Edit ${r.file_path||"file"}`,r.file_path&&(p.push({path:r.file_path}),(r.old_string!==void 0||r.new_string!==void 0)&&a.push({type:"diff",path:r.file_path,oldText:r.old_string||"",newText:r.new_string||""}));break;case "run_shell_command":case "shell":o=r.command?`\`${r.command}\``:"Run command",r.description&&a.push({type:"content",content:{type:"text",text:r.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=r.query?`"${r.query}"`:"Web search";break;case "web_fetch":o=r.prompt?`Fetch: ${r.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${r.pattern||"files"}`,r.dir_path&&p.push({path:r.dir_path});break;case "grep":case "search_file_content":o=`grep "${r.pattern||r.query||""}"`;break;case "list_directory":o=`List ${r.dir_path||r.path||"directory"}`,(r.dir_path||r.path)&&p.push({path:r.dir_path||r.path});break;case "read_many_files":o=`Read ${r.include?.length||"multiple"} files`,Array.isArray(r.include)&&r.include.forEach(u=>p.push({path:u}));break;case "delegate_to_agent":o=r.agent_name?`Agent: ${r.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=r.fact?`Remember: "${r.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=r.name?`Activate skill: ${r.name}`:"Activate skill";break;default:o=s;}return {title:o,kind:l,content:a,locations:p}}}var Nn={ReadFile:"read",ReadMediaFile:"read",WriteFile:"edit",StrReplaceFile:"edit",Shell:"execute",Glob:"search",Grep:"search",SearchWeb:"fetch",FetchURL:"fetch",Task:"think",Think:"think",CreateSubagent:"think",SetTodoList:"other"};function ze(n){return /<system>\s*ERROR:/i.test(n)||n.includes("<error>")||n.includes("ToolError")}function St(n){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(n);if(!e)return null;let t=e[1]||"",i=e[2]||"",c=e[3]||"";return /;base64/i.test(i)?{mimeType:t,data:c}:null}function Je(n){if(!n||typeof n!="object")return null;if(n.type==="text"&&typeof n.text=="string"&&n.text.length>0)return {type:"content",content:{type:"text",text:n.text}};if(n.type==="image_url"&&typeof n.image_url?.url=="string"){let e=n.image_url.url,t=St(e);return t?{type:"content",content:{type:"image",data:t.data,mimeType:t.mimeType}}:{type:"content",content:{type:"image",data:"",mimeType:"",uri:e}}}return n.type==="video_url"&&typeof n.video_url?.url=="string"?{type:"content",content:{type:"text",text:`[video] ${n.video_url.url}`}}:n.type==="audio_url"&&typeof n.audio_url?.url=="string"?{type:"content",content:{type:"text",text:`[audio] ${n.audio_url.url}`}}:null}function We(n){let e=[];if(typeof n=="string")return n.length>0&&e.push({type:"content",content:{type:"text",text:n}}),e;if(Array.isArray(n)){for(let t of n){if(typeof t=="string"&&t.length>0){e.push({type:"content",content:{type:"text",text:t}});continue}let i=Je(t);i&&e.push(i);}return e}if(n&&typeof n=="object"){let t=Je(n);t&&e.push(t);}return e}function Kn(n){return n.some(e=>e.type==="content"&&e.content.type==="text"&&ze(e.content.text))}function Bn(n){if(!n||typeof n!="object")return null;if(n.type==="think"&&typeof n.think=="string"&&n.think.length>0)return {update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.think}}};if(n.type==="text"&&typeof n.text=="string"&&n.text.length>0)return {update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.text}}};if(n.type==="image_url"&&typeof n.image_url?.url=="string"){let e=n.image_url.url,t=St(e);return t?{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:t.data,mimeType:t.mimeType}}}:{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:"",mimeType:"",uri:e}}}}return n.type==="video_url"&&typeof n.video_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[video] ${n.video_url.url}`}}}:n.type==="audio_url"&&typeof n.audio_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[audio] ${n.audio_url.url}`}}}:null}function jn(n){return n==="in_progress"?"in_progress":n==="done"||n==="completed"?"completed":"pending"}function bt(n){if(!n||typeof n!="object")return [];let e=n.todos;return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return null;let i=t.title;if(typeof i!="string"||i.length===0)return null;let c=t.status;return {content:i,status:jn(c),priority:"medium"}}).filter(t=>t!==null):[]}function Ge(){let n=new Set,e=0;function t(l,a){return typeof l=="string"&&l.length>0?l:(e+=1,`kimi_${a.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(a){let p;try{p=JSON.parse(a);}catch{return null}if(!p||typeof p!="object"||"_meta"in p||"_prompt"in p)return null;let o=p.role;return o==="assistant"?i(p):o==="tool"?c(p):typeof p.type=="string"&&"payload"in p?s(p):null};function i(l){let a=[],p=l.content,o=l.tool_calls;if(typeof p=="string"&&p.length>0)a.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});else if(Array.isArray(p))for(let u of p){let d=Bn(u);d&&a.push(d);}if(Array.isArray(o))for(let u of o){if(!u||typeof u!="object")continue;let d=u.function;if(!d)continue;let m=d.name??"",g=t(u.id,m),f;try{f=d.arguments?JSON.parse(d.arguments):{};}catch{f=d.arguments;}if(m==="SetTodoList"){let x=bt(f);x.length>0&&a.push({update:{sessionUpdate:"plan",entries:x}}),n.add(g);continue}let{title:h,kind:y,toolContent:w,locations:k}=r(m,typeof f=="object"&&f!==null?f:{});a.push({update:{sessionUpdate:"tool_call",toolCallId:g,title:h,kind:y,status:"pending",rawInput:f,content:w,locations:k}});}return a.length>0?a:null}function c(l){let a=l.tool_call_id;if(typeof a!="string"||a.length===0)return null;if(n.has(a))return n.delete(a),null;let p=l.content,o=[],u=false;if(typeof p=="string")u=ze(p),p.length>0&&o.push({type:"content",content:{type:"text",text:p}});else if(Array.isArray(p))for(let d of p){let m=Je(d);m&&(m.type==="content"&&m.content.type==="text"&&ze(m.content.text)&&(u=true),o.push(m));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:a,status:u?"failed":"completed",content:o}}]}function s(l){let a=l.type,p=l.payload??{},o=[];switch(a){case "TextPart":{let u=p.text;typeof u=="string"&&u.length>0&&o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u}}});break}case "ThinkPart":{let u=p.think;typeof u=="string"&&u.length>0&&o.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u}}});break}case "ToolCall":{let u=p.function?.name??"",d=t(p.id,u),m=p.function;if(!m)break;let g;try{g=m.arguments?JSON.parse(m.arguments):{};}catch{g=m.arguments;}if(u==="SetTodoList"){let k=bt(g);k.length>0&&o.push({update:{sessionUpdate:"plan",entries:k}}),n.add(d);break}let{title:f,kind:h,toolContent:y,locations:w}=r(u,typeof g=="object"&&g!==null?g:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:d,title:f,kind:h,status:"pending",rawInput:g,content:y,locations:w}});break}case "ToolResult":{let u=p.tool_call_id;if(typeof u!="string"||u.length===0)break;if(n.has(u)){n.delete(u);break}let d=p.return_value??p.content,m=[],g=p.is_error===true;if(d&&typeof d=="object"&&!Array.isArray(d)){let f=d;g=g||f.type==="ToolError"||f.is_error===true,m.push(...We(f.output)),m.length===0&&typeof f.message=="string"&&f.message.length>0&&m.push({type:"content",content:{type:"text",text:f.message}}),m.length===0&&m.push(...We(d));}else m.push(...We(d));g=g||Kn(m),o.push({update:{sessionUpdate:"tool_call_update",toolCallId:u,status:g?"failed":"completed",content:m}});break}default:return null}return o.length>0?o:null}function r(l,a){let p=Nn[l]||"other",o=[],u=[],d=l;switch(l){case "ReadFile":{let m=a.path??a.file_path;d=`Read ${m||"file"}`,m&&u.push({path:m});break}case "ReadMediaFile":{let m=a.path??a.file_path;d=`Read media ${m||"file"}`,m&&u.push({path:m});break}case "WriteFile":{let m=a.path??a.file_path;d=`Write ${m||"file"}`,m&&(u.push({path:m}),typeof a.content=="string"&&o.push({type:"diff",path:m,oldText:null,newText:a.content}));break}case "StrReplaceFile":{let m=a.path??a.file_path;d=`Edit ${m||"file"}`,m&&u.push({path:m});break}case "Shell":d=a.command?`\`${a.command}\``:"Run command";break;case "Glob":d=`Find ${a.pattern||"files"}`,a.path&&u.push({path:a.path});break;case "Grep":d=`grep "${a.pattern||""}"`,a.path&&u.push({path:a.path});break;case "SearchWeb":d=a.query?`"${a.query}"`:"Web search";break;case "FetchURL":d=a.url?`Fetch ${a.url}`:"Web fetch";break;case "Task":d=a.description||"Subagent task";break;case "Think":d=a.thought||"Thinking";break;case "CreateSubagent":d=a.name?`Subagent: ${a.name}`:"Create subagent";break;case "SetTodoList":d="Update todos";break;default:d=l;}return {title:d,kind:p,toolContent:o,locations:u}}}var Vn={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 Wn(n){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(n);if(!e)return null;let t=e[1]||"",i=e[2]||"",c=e[3]||"";return /;base64/i.test(i)?{mimeType:t,data:c}:null}function zn(n){if(typeof n!="string")return "pending";switch(n.toLowerCase()){case "in_progress":case "in-progress":case "running":return "in_progress";case "completed":case "done":case "cancelled":return "completed";default:return "pending"}}function Jn(n){return n==="high"||n==="medium"||n==="low"?n:"medium"}function _t(n){return Array.isArray(n)?n.map(e=>{if(!e||typeof e!="object")return null;let t=e.content;return typeof t!="string"||t.length===0?null:{content:t,status:zn(e.status),priority:Jn(e.priority)}}).filter(e=>e!==null):[]}function Gn(n){if(!n||typeof n!="object")return null;let e=n,t=typeof e.mime=="string"?e.mime:"",i=typeof e.url=="string"?e.url:"";if(t.startsWith("image/")){if(i.length>0){let l=Wn(i);return l?{type:"content",content:{type:"image",data:l.data,mimeType:l.mimeType||t}}:{type:"content",content:{type:"image",data:"",mimeType:t,uri:i}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${t||"file"})`}}}function Hn(n,e){if(n==="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 Yn(n,e){return n==="error"?"failed":n==="running"?"in_progress":n==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function He(){return function(r){let l;try{l=JSON.parse(r);}catch{return null}if(!l||typeof l!="object")return null;let a=l.sessionID,p=[];switch(l.type){case "step_start":case "step_finish":return null;case "text":{let o=n(l);o&&p.push({sessionId:a,update:o});break}case "reasoning":{let o=e(l);o&&p.push({sessionId:a,update:o});break}case "tool_use":{let o=t(l);for(let u of o)p.push({sessionId:a,update:u});break}case "error":{let o=i(l);o&&p.push({sessionId:a,update:o});break}default:return null}return p.length>0?p:null};function n(s){let r=s.part?.text;return typeof r!="string"||r.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:r}}}function e(s){let r=s.part?.text;return typeof r!="string"||r.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:r}}}function t(s){let r=s.part;if(!r)return [];let l=typeof r.callID=="string"?r.callID:"";if(l.length===0)return [];let a=typeof r.tool=="string"?r.tool.toLowerCase():"",p=typeof r.state=="object"&&r.state?r.state:{},o=typeof p.input=="object"&&p.input?p.input:{},u=p.status,d=p.title??p.metadata?.description??a,m=p.metadata?.exit,{kind:g,content:f,locations:h}=c(a,o),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:l,title:d,kind:g,status:"pending",rawInput:o,content:f,locations:h}),a==="todowrite"){let v=_t(o.todos);if(v.length===0&&typeof p.output=="string")try{v=_t(JSON.parse(p.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=Yn(u,m);if(w==="pending")return y;let k=Hn(u,p),x=[];if(typeof k=="string"&&k.length>0&&x.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
|
|
34
|
+
${k}
|
|
35
|
+
\`\`\``:k}}),Array.isArray(p.attachments))for(let v of p.attachments){let C=Gn(v);C&&x.push(C);}return y.push({sessionUpdate:"tool_call_update",toolCallId:l,status:w,content:x}),y}function i(s){let r=s.error?.name??"Error",l=s.error?.data?.message??s.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${r}: ${l}`}}}function c(s,r){let l=Vn[s]||"other",a=[],p=[];switch(s){case "read":{let o=r.filePath??r.path;if(o){let u=r.offset;p.push({path:o,line:typeof u=="number"&&Number.isFinite(u)?Math.max(0,u-1):void 0});}break}case "write":{let o=r.filePath??r.path;o&&(p.push({path:o}),typeof r.content=="string"&&a.push({type:"diff",path:o,oldText:null,newText:r.content}));break}case "edit":case "multiedit":{let o=r.filePath??r.path;o&&(p.push({path:o}),s==="edit"&&(r.oldString!==void 0||r.newString!==void 0)&&a.push({type:"diff",path:o,oldText:r.oldString??"",newText:r.newString??""}));break}case "apply_patch":break;case "bash":{let o=r.command;o&&r.description?a.push({type:"content",content:{type:"text",text:r.description}}):o&&a.push({type:"content",content:{type:"text",text:o}});break}case "glob":case "list":{let o=r.path;o&&p.push({path:o});break}case "grep":{let o=r.path;o&&p.push({path:o});break}case "codesearch":case "websearch":{let o=r.query;o&&a.push({type:"content",content:{type:"text",text:o}});break}case "webfetch":{let o=r.url;o&&a.push({type:"content",content:{type:"text",text:o}});break}case "task":{let o=r.description;o&&a.push({type:"content",content:{type:"text",text:o}});break}}return {kind:l,content:a,locations:p}}}var qn={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 Ce(){let n=new Map,e=new Map;return function(o){let u;try{u=JSON.parse(o);}catch{return null}if(!u||typeof u!="object")return null;let d=u;if("_meta"in d||"_prompt"in d)return null;let m=d.session_id||void 0,g=[];switch(d.type){case "assistant":{let f=t(d);for(let h of f)g.push({sessionId:m,update:h});break}case "stream_event":{let f=i(d);for(let h of f)g.push({sessionId:m,update:h});break}case "user":{let f=c(d);for(let h of f)g.push({sessionId:m,update:h});break}case "system":case "result":return null;default:return null}return g.length>0?g:null};function t(p){let o=[],u=p.message?.content;if(!Array.isArray(u))return o;for(let d of u){let m=s(d);o.push(...m);}return o}function i(p){let o=[],u=p.event;if(!u)return o;switch(u.type){case "content_block_start":{let d=u.index??0,m=u.content_block;m&&(n.set(d,m),m.type==="tool_use"&&e.set(d,""));break}case "content_block_delta":{let d=u.index??0,m=u.delta,g=n.get(d);if(m?.type==="text_delta"&&m.text)o.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:m.text}});else if(m?.type==="thinking_delta"&&m.thinking)o.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:m.thinking}});else if(m?.type==="input_json_delta"&&m.partial_json&&g?.type==="tool_use"){let f=e.get(d)||"";e.set(d,f+m.partial_json);}break}case "content_block_stop":{let d=u.index??0,m=n.get(d);if(m&&!(m.type==="text"&&m.text)){if(!(m.type==="thinking"&&m.thinking)){if(m.type==="tool_use"){let g=m,f=e.get(d)||"";e.delete(d);let h=g.input;if(f)try{h=JSON.parse(f);}catch{}let y={...g,input:h},w=r(y);w&&o.push(w);}else if(m.type==="tool_result"){let g=l(m);g&&o.push(g);}}}n.delete(d);break}}return o}function c(p){let o=p.message?.content,u=[];if(typeof o=="string")return u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:o}}),u;if(Array.isArray(o)){for(let d of o)if(d.type==="text")u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:d.text}});else if(d.type==="tool_result"){let m=l(d);m&&u.push(m);}}return u}function s(p){switch(p.type){case "text":return p.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}}]:[];case "thinking":return p.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.thinking}}]:[];case "tool_use":{let o=r(p);return o?[o]:[]}case "tool_result":{let o=l(p);return o?[o]:[]}}}function r(p){let o=p.id,u=p.name,d=p.input;if(u==="TodoWrite"&&Array.isArray(d?.todos))return {sessionUpdate:"plan",entries:d.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:m,kind:g,content:f,locations:h}=a(u,d||{});return {sessionUpdate:"tool_call",toolCallId:o,title:m,kind:g,status:"pending",rawInput:d,content:f,locations:h}}function l(p){let o=p.tool_use_id,u=p.is_error??false,d=p.content,m=[];if(typeof d=="string"&&d.length>0)m.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
18
36
|
${d}
|
|
19
|
-
\`\`\``:d}});else if(Array.isArray(d)){for(let
|
|
20
|
-
${
|
|
21
|
-
\`\`\``:
|
|
22
|
-
`),c=
|
|
23
|
-
Try reinstalling: npm install @evolvingmachines/sdk`):r}let e=process.env[
|
|
24
|
-
Try installing: npm install @evolvingmachines/daytona`):r}let t=process.env[
|
|
25
|
-
Try installing: npm install @evolvingmachines/modal`):r}let c=process.env[
|
|
37
|
+
\`\`\``:d}});else if(Array.isArray(d)){for(let g of d)if(g.type==="text"){let f=g.text;m.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
38
|
+
${f}
|
|
39
|
+
\`\`\``:f}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:m}}function a(p,o){let u=qn[p]||"other",d=[],m=[],g=p;switch(p){case "Read":case "read_file":g=`Read ${o.file_path||o.absolute_path||"file"}`,(o.file_path||o.absolute_path)&&m.push({path:o.file_path||o.absolute_path});break;case "Write":case "write_file":g=`Write ${o.file_path||"file"}`,o.file_path&&(m.push({path:o.file_path}),d.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":g=`Edit ${o.file_path||"file"}`,o.file_path&&m.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":g=o.command?`\`${o.command}\``:"Run command",o.description&&d.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":g=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":g=o.query?`"${o.query}"`:"Web search";break;case "Glob":g=`Find ${o.pattern||"files"}`,o.path&&m.push({path:o.path});break;case "Grep":g=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":g=`List ${o.path||"directory"}`,o.path&&m.push({path:o.path});break;case "Task":g=o.description||"Subagent task";break;case "TodoWrite":g="Update todos";break;case "ExitPlanMode":g="Exit plan mode";break;default:g=p;}return {title:g,kind:u,content:d,locations:m}}}function Tt(n){return Ce()(n)}function K(n){switch(n){case "claude":return ye();case "codex":return we();case "gemini":return ve();case "qwen":return Ce();case "kimi":return Ge();case "opencode":return He();default:return ()=>null}}function Zn(n,e){let t=e.trim();return t?K(n)(t):null}function Qn(n,e){let t=[],i=e.split(`
|
|
40
|
+
`),c=K(n);for(let s of i){let r=s.trim();if(!r)continue;let l=c(r);l&&t.push(...l);}return t}function P(n){return n!==null&&typeof n=="object"&&"safeParse"in n&&typeof n.safeParse=="function"}function W(n){return JSON.stringify(Xn__default.default(n,{target:"jsonSchema7"}),null,2)}function z(n){return JSON.stringify(n,null,2)}function Et(n,e=false){let t={};function i(c,s){for(let r of O__namespace.readdirSync(c)){let l=Q__namespace.join(c,r),a=s?`${s}/${r}`:r;O__namespace.statSync(l).isDirectory()?e&&i(l,a):t[a]=O__namespace.readFileSync(l);}}return i(n,""),t}function Rt(n,e){for(let[t,i]of Object.entries(e)){let c=Q__namespace.join(n,t),s=Q__namespace.dirname(c);O__namespace.mkdirSync(s,{recursive:true});let r;i instanceof ArrayBuffer||i instanceof Uint8Array?r=Buffer.from(i):r=i,O__namespace.writeFileSync(c,r);}}function ei(n){let e=n.replace(/^~/,process.env.HOME||"");if(!O__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return O__namespace.readFileSync(e,"utf-8")}function ke(n){let e=n?.type??yt,t=I(e);if(n?.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:n.oauthToken,isDirectMode:true,isOAuth:true,model:n.model,reasoningEffort:n.reasoningEffort}}if(n?.providerApiKey){let r=n.providerBaseUrl??process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:n.providerApiKey,baseUrl:r,isDirectMode:true,model:n.model,reasoningEffort:n.reasoningEffort}}if(n?.apiKey)return {type:e,apiKey:n.apiKey,isDirectMode:false,model:n.model,reasoningEffort:n.reasoningEffort};let i=process.env[N];if(i)return {type:e,apiKey:i,isDirectMode:false,model:n?.model,reasoningEffort:n?.reasoningEffort};if(t.providerEnvMap){let l=(n?.model??t.defaultModel)?.split("/")[0],a=l?t.providerEnvMap[l]:void 0,p=a?process.env[a.keyEnv]:void 0;if(p){let o=process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:p,baseUrl:o,isDirectMode:true,model:n?.model,reasoningEffort:n?.reasoningEffort}}}let c=process.env[t.apiKeyEnv];if(c){let r=process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:c,baseUrl:r,isDirectMode:true,model:n?.model,reasoningEffort:n?.reasoningEffort}}if(t.oauthEnv){let r=process.env[t.oauthEnv];if(r){if(t.oauthFileName){let l=ei(r);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:l,model:n?.model,reasoningEffort:n?.reasoningEffort}}return {type:e,apiKey:r,isDirectMode:true,isOAuth:true,model:n?.model,reasoningEffort:n?.reasoningEffort}}}let s=t.oauthEnv?t.oauthFileName?`, or ${t.oauthEnv}`:`, oauthToken, or ${t.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${s}, or ${N} / ${t.apiKeyEnv} env var.`)}async function Ye(){let n=process.env[de];if(n)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return s({apiKey:n})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${de} is set but @evolvingmachines/e2b failed to load.
|
|
41
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):r}let e=process.env[me];if(e)try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return s({apiKey:e})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${me} is set but @evolvingmachines/daytona failed to load.
|
|
42
|
+
Try installing: npm install @evolvingmachines/daytona`):r}let t=process.env[ge],i=process.env[Le];if(t&&i)try{let{createModalProvider:s}=await import('@evolvingmachines/modal');return s({tokenId:t,tokenSecret:i})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${ge} is set but @evolvingmachines/modal failed to load.
|
|
43
|
+
Try installing: npm install @evolvingmachines/modal`):r}let c=process.env[N];if(c)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=ft(),s({apiKey:c})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${N} is set but @evolvingmachines/e2b failed to load.
|
|
26
44
|
Try reinstalling: npm install @evolvingmachines/sdk`):r}throw new Error(`No sandbox provider configured. Either:
|
|
27
|
-
1. Set ${
|
|
28
|
-
2. Set ${
|
|
29
|
-
3. Set ${
|
|
30
|
-
4. Set ${
|
|
31
|
-
5. Pass sandbox explicitly: .withSandbox(provider)`)}function
|
|
45
|
+
1. Set ${N} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
46
|
+
2. Set ${de} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
47
|
+
3. Set ${me} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
48
|
+
4. Set ${ge} and ${Le} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
49
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function ti(n){return new Promise(e=>setTimeout(e,n))}async function E(n,e,t=0){let i=ni(e),c=e?.onItemRetry,s=null,r=0,l=i.backoffMs;for(;r<i.maxAttempts;){if(r++,s=await n(r),!i.retryOn(s))return s;if(r>=i.maxAttempts)break;if(c){let a=s.error??"Unknown error";c(t,r,a);}await ti(l),l*=i.backoffMultiplier;}return s}function ni(n){return {maxAttempts:n?.maxAttempts??3,backoffMs:n?.backoffMs??1e3,backoffMultiplier:n?.backoffMultiplier??2,retryOn:n?.retryOn??(e=>e.status==="error")}}var Pt=`## FILESYSTEM INSTRUCTIONS:
|
|
32
50
|
|
|
33
51
|
You are running in a sandbox environment.
|
|
34
52
|
|
|
@@ -61,7 +79,7 @@ Examples:
|
|
|
61
79
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
62
80
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
63
81
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
64
|
-
`;var
|
|
82
|
+
`;var Ot=`## FILESYSTEM INSTRUCTIONS:
|
|
65
83
|
|
|
66
84
|
You are running in a sandbox environment.
|
|
67
85
|
|
|
@@ -95,9 +113,9 @@ Examples:
|
|
|
95
113
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
96
114
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
97
115
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
98
|
-
`;var
|
|
116
|
+
`;var It=`## SYSTEM PROMPT
|
|
99
117
|
|
|
100
|
-
{{systemPrompt}}`;var
|
|
118
|
+
{{systemPrompt}}`;var Mt=`## STRUCTURED OUTPUT
|
|
101
119
|
|
|
102
120
|
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
103
121
|
|
|
@@ -115,7 +133,7 @@ You are free to:
|
|
|
115
133
|
But your final \`output/result.json\` MUST conform to the schema above.
|
|
116
134
|
|
|
117
135
|
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
118
|
-
### Never just state results as text.`;var
|
|
136
|
+
### Never just state results as text.`;var At=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
119
137
|
|
|
120
138
|
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.
|
|
121
139
|
|
|
@@ -145,7 +163,7 @@ You must judge their work based on:
|
|
|
145
163
|
5. Pick the best candidate (0-indexed)
|
|
146
164
|
|
|
147
165
|
**IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
|
|
148
|
-
`;var
|
|
166
|
+
`;var $t=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
149
167
|
|
|
150
168
|
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.
|
|
151
169
|
|
|
@@ -178,14 +196,14 @@ The output must satisfy:
|
|
|
178
196
|
**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.
|
|
179
197
|
|
|
180
198
|
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
181
|
-
`;var
|
|
199
|
+
`;var Dt=`### CONTEXT STRUCTURE
|
|
182
200
|
|
|
183
201
|
\`\`\`
|
|
184
202
|
{{fileTree}}
|
|
185
203
|
\`\`\`
|
|
186
204
|
|
|
187
205
|
Examine all files within each item folder before producing your output.
|
|
188
|
-
`;var
|
|
206
|
+
`;var Ut="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var Ft="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var Lt=`{{originalPrompt}}
|
|
189
207
|
|
|
190
208
|
## IMPORTANT: Previous Attempt Failed Verification
|
|
191
209
|
|
|
@@ -194,26 +212,28 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
194
212
|
{{feedback}}
|
|
195
213
|
|
|
196
214
|
Make sure your output addresses all the feedback points above.
|
|
197
|
-
`;var
|
|
215
|
+
`;var Nt=Pt,Kt=Ot,Bt=It,jt=Mt,qe=At,Vt=Ut,Ze=$t,Wt=Ft,zt=Dt,Qe=Lt;function M(n,e){let t=n;for(let[i,c]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${i}\\}\\}`,"g"),c);return t}function Xe(n){let e=n.mode==="swe"?Kt:Nt,t=M(e,{workingDir:n.workingDir}).trim();if(n.systemPrompt&&(t+=`
|
|
198
216
|
|
|
199
217
|
|
|
200
|
-
${
|
|
218
|
+
${M(Bt,{systemPrompt:n.systemPrompt}).trim()}`),n.schema){let i=P(n.schema)?W(n.schema):z(n.schema);t+=`
|
|
201
219
|
|
|
202
220
|
|
|
203
|
-
${
|
|
204
|
-
(empty)`;let t="worker_task/system_prompt.txt"in n,i="worker_task/schema.json"in n,c=Object.keys(n).some(a=>a.startsWith("worker_task/input/")),s=[];e.forEach((a,
|
|
205
|
-
`)}var
|
|
221
|
+
${M(jt,{schema:i}).trim()}`;}return t}function be(n){let e=[...new Set(Object.keys(n).map(a=>a.split("/")[0]))].sort((a,p)=>a==="worker_task"?-1:p==="worker_task"?1:a.localeCompare(p));if(!e.length)return `context/
|
|
222
|
+
(empty)`;let t="worker_task/system_prompt.txt"in n,i="worker_task/schema.json"in n,c=Object.keys(n).some(a=>a.startsWith("worker_task/input/")),s=[];e.forEach((a,p)=>{let o=p===e.length-1,u=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=o?" ":"\u2502 ";if(a==="worker_task"){s.push({line:`${u}${a}/`,comment:"task given to worker"});let m=[];t&&m.push({name:"system_prompt.txt",comment:"worker system prompt"}),m.push({name:"user_prompt.txt",comment:"worker task prompt"}),i&&m.push({name:"schema.json",comment:"expected output schema"}),c&&m.push({name:"input/",comment:"worker input files"}),m.forEach((g,f)=>{let y=f===m.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";s.push({line:`${d}${y}${g.name}`,comment:g.comment});});}else if(a.startsWith("candidate_")){let m=a.replace("candidate_","");s.push({line:`${u}${a}/`,comment:`worker ${m} solution`});}else if(a==="worker_output")s.push({line:`${u}${a}/`,comment:"output to verify"});else if(a.startsWith("item_")){let m=a.replace("item_","");s.push({line:`${u}${a}/`,comment:`input ${m}`});}else s.push({line:`${u}${a}/`,comment:""});});let r=Math.max(...s.map(a=>a.line.length)),l=["context/"];for(let a of s)if(a.comment){let p=" ".repeat(r-a.line.length+3);l.push(`${a.line}${p}# ${a.comment}`);}else l.push(a.line);return l.join(`
|
|
223
|
+
`)}var Jt=Q.join(os.homedir(),Ct),X=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(Jt,{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=T,this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let t=this.timestamp.replace(/[:.]/g,"-"),i=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${t}.jsonl`;this.localFilePath=Q.join(Jt,i),this.parser=K(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,t){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&t))for(let i of t)this.bufferForDashboard(i);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let t=this.parser(e);if(t)for(let i of t)this.bufferForDashboard(i);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.isClosed=true,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let t=e.endsWith(`
|
|
206
224
|
`)?e:e+`
|
|
207
225
|
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(t)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let t=JSON.stringify(e)+`
|
|
208
226
|
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(t)).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)}},t=JSON.stringify(e)+`
|
|
209
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(t)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(t){console.debug("[SessionLogger] Local write failed:",t);}}scheduleFlush(){if(this.eventBuffer.length>=
|
|
210
|
-
`).pop()?.trim();if(!a||a.length!==64)throw new Error(`Invalid checkpoint hash: ${a}`);let
|
|
211
|
-
`).pop()?.trim();if(p!==i)throw await n.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${i}, got ${p})`);let a=await n.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${a.stderr}`);return s}function Xn(n){let e=process.env.EVOLVE_API_KEY,t=!n.url&&!n.bucket&&!!e;return we(n,t,O,e)}async function Yt(n,e){let{s3:t}=await K(),i=await H(n),s=`${n.prefix?`${n.prefix}/`:""}checkpoints/`,r=[],p;do{let d={Bucket:n.bucket,Prefix:s,...p&&{ContinuationToken:p}},m=await i.send(new t.ListObjectsV2Command(d));if(m.Contents)for(let f of m.Contents)f.Key?.endsWith(".json")&&f.LastModified&&r.push({key:f.Key,lastModified:f.LastModified});p=m.IsTruncated?m.NextContinuationToken:void 0;}while(p);if(r.length===0)return [];r.sort((d,m)=>{let f=m.lastModified.getTime()-d.lastModified.getTime();return f!==0?f:m.key<d.key?-1:m.key>d.key?1:0});let l=!!e?.tag?r:e?.limit?r.slice(0,e.limit):r,u=(await Promise.all(l.map(async d=>{try{return await Vt(n,d.key)}catch{return null}}))).filter(d=>d!==null);return e?.tag&&(u=u.filter(d=>d.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function Ht(n,e){let t=new URLSearchParams;e?.limit&&t.set("limit",String(e.limit)),e?.tag&&t.set("tag",e.tag);let i=`${n.gatewayUrl}/api/checkpoints${t.toString()?`?${t}`:""}`,c=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${n.gatewayApiKey}`}});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${c.status}): ${s}`)}return c.json()}async function He(n,e){let t=Xn(n),i=e?.limit&&e.limit>0?Math.min(e.limit,500):100;return t.mode==="byok"?Yt(t,{limit:i,tag:e?.tag}):Ht(t,{limit:i,tag:e?.tag})}async function qt(n){return n.mode==="byok"?(await Yt(n,{limit:1}))[0]??null:(await Ht(n,{limit:1}))[0]??null}function to(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}var q=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,t={}){if(this.agentConfig=e,this.options=t,this.workingDir=t.workingDirectory||ct,this.sandboxState=t.sandboxId?"ready":"stopped",this.skills=t.skills,this.storage=t.storage,t.schema)if(E(t.schema))this.zodSchema=t.schema,t.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=t.schema,this.schemaOptions=t.schemaOptions;try{let i=this.createAjvValidator();this.compiledValidator=i.compile(this.jsonSchema);}catch(i){throw new Error(`Invalid JSON Schema: ${i.message}`)}}this.registry=P(e.type);}emitLifecycle(e,t){e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:t});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,t,i,c){let s=++this.nextOperationId;return this.activeOperationId=s,this.activeOperationKind=e,this.activeCommand=t,this.activeProcessId=t.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(i,c),s}finalizeOperation(e,t,i,c="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=c,this.emitLifecycle(t,i),true)}watchBackgroundOperation(e,t,i,c){let s=t==="run"?"run_background_complete":"command_background_complete",r=t==="run"?"run_background_failed":"command_background_failed",p=t==="run"?"run_interrupted":"command_interrupted";i.wait().then(a=>{if(this.interruptedOperations.delete(e)||a.exitCode===130){this.finalizeOperation(e,c,p,"interrupted");return}let o=a.exitCode===0?s:r,u=a.exitCode===0?"idle":"error";this.finalizeOperation(e,c,o,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,c,r,"error");});}createAjvValidator(){let t={...ke[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 eo__default.default({...t,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let t=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, context, files, and systemPrompt"),this.sandbox=await t.connect(this.options.sandboxId),this.hasRun=!0,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {let i=this.buildEnvironmentVariables();this.sandbox=await t.create({envs:i,workingDirectory:this.workingDir}),await this.setupAgentAuth(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(i){throw this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),i}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let t of Object.values(this.registry.providerEnvMap))e[t.keyEnv]=this.agentConfig.apiKey;else {let t=this.agentConfig.model?.split("/")[0],i=t?this.registry.providerEnvMap?.[t]:void 0,c=i?i.keyEnv:this.registry.apiKeyEnv,s=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:c;e[s]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let t=this.registry.usePassthroughGateway?ot():z();if(this.registry.gatewayConfigEnv){let i=this.agentConfig.model||this.registry.defaultModel;e[this.registry.gatewayConfigEnv]=JSON.stringify({provider:{litellm:{npm:"@ai-sdk/openai-compatible",options:{baseURL:`${t}/v1`,apiKey:this.agentConfig.apiKey},models:{[i]:{name:i}}}}});}else e[this.registry.baseUrlEnv]=t;e.EVOLVE_API_KEY=this.agentConfig.apiKey;}return this.options.secrets&&Object.assign(e,this.options.secrets),e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let t=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(t),await e.files.write(`${t}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e,t){let i=this.options.workspaceMode||"knowledge",c=i==="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 ${c}`,{timeoutMs:3e4}),!t?.skipSystemPrompt){let r=Ve({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:i}),p=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(p,r);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let s={...this.options.mcpServers};if(this.options.composio){let r=await ze(this.options.composio.userId,this.options.composio.config);s={...s,composio:{type:"http",url:r.url,headers:r.headers}};}Object.keys(s).length>0&&await Pe(this.agentConfig.type,e,this.workingDir,s),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:t}=this.registry,{sourceDir:i,targetDir:c}=t;await e.files.makeDir(c);for(let s of this.skills){let r=`cp -r ${i}/${s} ${c}/ 2>/dev/null || true`;await e.commands.run(r,{timeoutMs:3e4});}}async uploadContextFiles(e,t){let i=Object.entries(t).map(([s,r])=>({path:`${this.workingDir}/context/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,t){let i=Object.entries(t).map(([s,r])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:to(e),model:this.agentConfig.model||this.registry.defaultModel,isResume:this.hasRun,reasoningEffort:this.agentConfig.reasoningEffort,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,t){let{prompt:i,timeoutMs:c=J,background:s=false,checkpointComment:r}=e,{from:p}=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(p&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(p==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let y=await qt(this.storage);if(!y)throw new Error('No checkpoints found for from: "latest".');p=y.id;}if(p){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");let y=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(t,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:y,workingDirectory:this.workingDir});let v=await Gt(this.sandbox,this.storage,p);if(v.agentType&&v.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${v.agentType}, current: ${this.agentConfig.type})`);let b=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==b)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${b})`);await this.setupAgentAuth(this.sandbox);let k=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!k}),this.hasRun=!0,this.lastCheckpointId=p,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(t,"sandbox_ready");}catch(v){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(t,"sandbox_error"),v}}let a=await this.getSandbox(t);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let y=this.options.sandboxProvider;this.sessionLogger=new Y({provider:y?.name||y?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:a.sandboxId,tagPrefix:this.options.sessionTagPrefix,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(i);let l=this.buildCommand(i),o="",u=M(this.agentConfig.type),d=y=>{o+=y;let v=o.split(`
|
|
212
|
-
`);
|
|
213
|
-
`),k&&t?.onContent)for(let C of k)t.onContent(C);}},m=y=>{t?.onStderr?.(y);},f=await a.commands.spawn(l,{cwd:this.workingDir,timeoutMs:c,onStdout:d,onStderr:m}),g=this.beginOperation("run",f,t,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(g,"run",f,t),{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with ID ${f.processId}`,stderr:""};let h;try{h=await f.wait();}catch(y){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,t,"run_failed","error"),y}if(this.interruptedOperations.delete(g)||h.exitCode===130?this.finalizeOperation(g,t,"run_interrupted","interrupted"):h.exitCode===0?this.finalizeOperation(g,t,"run_complete","idle"):this.finalizeOperation(g,t,"run_failed","error"),o.trim()){let y=u(o);if(this.sessionLogger?.writeEventParsed(o,y),t?.onStdout?.(o+`
|
|
214
|
-
`)
|
|
215
|
-
`).filter(Boolean),p=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,a=[],l=`${i}/`;for(let f of r){let[g,h]=f.split("|");if(!g||!h)continue;let w=parseInt(h,10);p>0&&w<p||a.push(g);}let o={},u=await Promise.all(a.map(async f=>{try{let g=await t.files.read(f);return {relativePath:f.startsWith(l)?f.slice(l.length):f.split("/").pop()||f,content:g}}catch{return null}}));for(let f of u)f&&(o[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let d=o["result.json"];if(!d)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let m=typeof d=="string"?d:new TextDecoder().decode(d);try{let f=JSON.parse(m);if(this.zodSchema){let g=this.zodSchema.safeParse(f);return g.success?{files:o,data:g.data}:{files:o,data:null,error:`Schema validation failed: ${g.error.message}`,rawData:m}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:o,data:f};{let h=this.compiledValidator.errors?.map(w=>`${w.instancePath} ${w.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:m}}}return {files:o,data:null}}catch(f){return {files:o,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:m}}}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 t=await Ye(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionLogger?.getTag()||"unknown",model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=t.id,t}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),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 t=this.activeOperationId,i=this.activeOperationKind,c=false;try{this.activeCommand?c=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(c=await this.sandbox.commands.kill(this.activeProcessId));}catch{c=false;}if(!c)return this.sandboxState="running",this.agentState="running",false;t!==null&&this.interruptedOperations.add(t),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let s=i==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,s),c}status(){return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString()}}async kill(e){this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0),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.sessionLogger?.getTag()||null}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}};var Z=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(this.config.agent=e),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withSkills(e){return this.config.skills=e,this}withSchema(e,t){return this.config.schema=e,t&&(E(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=t),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,t){return this.config.composio={userId:e,config:t},this}withStorage(e){return this.config.storage=e||{},this}static composio=Ge;async initializeAgent(){let e=Le(this.config.agent),t=this.config.sandbox??await Ne(),i=e.isDirectMode?{}:st(e.apiKey),c=this.config.storage!==void 0?we(this.config.storage,!e.isDirectMode,O,e.isDirectMode?void 0:e.apiKey):void 0,s={sandboxProvider:t,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...i,...this.config.mcpServers},skills:this.config.skills,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:c};this.agent=new q(e,s);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,i=this.listenerCount("content")>0,c=this.listenerCount("lifecycle")>0;return {onStdout:e?s=>this.emit("stdout",s):void 0,onStderr:t?s=>this.emit("stderr",s):void 0,onContent:i?s=>this.emit("content",s):void 0,onLifecycle:c?s=>this.emit("lifecycle",s):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let t=this.status();this.emit("lifecycle",{sandboxId:t.sandboxId,sandbox:t.sandbox,agent:t.agent,timestamp:new Date().toISOString(),reason:e});}async run({prompt:e,timeoutMs:t,background:i,from:c,checkpointComment:s}){if(c&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:i,from:c,checkpointComment:s},r)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let i=this.createStreamCallbacks();return this.agent.executeCommand(e,t,i)}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)}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return He(this.config.storage,e)}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}};var V=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 $=Symbol.for("evolve.SwarmResult"),W=class n 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 t=new n;return t.push(...e),t}};var qe=class n{config;semaphore;constructor(e={}){let t=e.concurrency??at;if(t>Ue)throw new Error(`concurrency=${t} exceeds max ${Ue}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:t,timeoutMs:e.timeoutMs??J,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new V(this.config.concurrency);}async map(e){let{items:t,prompt:i,bestOf:c,verify:s}=e,r=e.retry??this.config.retry,p=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs;if(c&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(t.map((o,u)=>c?this.executeMapItemWithBestOf(o,i,u,p,e,a,r):s?this.executeMapItemWithVerify(o,i,u,p,e,a,r):r?_(d=>this.executeMapItem(o,i,u,p,e,a,d),r,u):this.executeMapItem(o,i,u,p,e,a)));return W.from(l)}async filter(e){let{items:t,prompt:i,condition:c,verify:s}=e,r=e.retry??this.config.retry,p=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,l=await Promise.all(t.map((u,d)=>s?this.executeFilterItemWithVerify(u,i,d,p,e,a,r):r?_(m=>this.executeFilterItem(u,i,d,p,e,a,m),r,d):this.executeFilterItem(u,i,d,p,e,a))),o=[];for(let u of l)if(u.status==="error")o.push(u);else if(u.data!==null)try{c(u.data)?o.push(u):o.push({...u,status:"filtered"});}catch(d){o.push({...u,status:"error",data:null,error:`Condition function threw: ${d.message}`});}return W.from(o)}async reduce(e){let{items:t,prompt:i,verify:c}=e,s=e.retry??this.config.retry,r=this.generateOperationId(),p=e.timeoutMs??this.config.timeoutMs,a=[],l=[];t.forEach((v,b)=>{a.push(this.getFiles(v)),l.push(this.getIndex(v,b));});let o={};a.forEach((v,b)=>{Object.entries(v).forEach(([k,C])=>{o[`item_${l[b]}/${k}`]=C;});});let u=ge(o),d=I(Ot,{fileTree:u}),m=e.systemPrompt?`${d}
|
|
216
|
-
|
|
217
|
-
${e.systemPrompt}`:d,f=(v,b,k)=>({operationId:r,operation:"reduce",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:t.length,inputIndices:l,errorRetry:b,verifyRetry:k,...this.pipelineContextToMeta(e._pipelineContext)}),g=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,w=e.composio??this.config.composio,x=async(v,b,k,C)=>{let S=await this.semaphore.use(()=>this.execute(o,v,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:g,skills:h,composio:w,tagPrefix:b,timeoutMs:p,observability:{swarmName:this.config.tag,operationName:e.name,operationId:r,operation:"reduce",role:"worker",errorRetry:k,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),U=f(S,k,C&&C>1?C-1:void 0);return S.error?{status:"error",data:null,files:S.files,meta:U,error:S.error,rawData:S.rawData}:{status:"success",data:S.data,files:S.files,meta:U}},y=`${this.config.tag}-reduce`;return c?this.runWithVerification((v,b,k)=>x(v,b,void 0,k),{originalPrompt:i,inputFiles:o,verifyConfig:c,timeoutMs:p,systemPrompt:m,schema:e.schema,mcpServers:g,skills:h,composio:w,operationId:r,baseTag:y,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?_(v=>{let b=v>1?v-1:void 0,k=b?`${y}-er${b}`:y;return x(i,k,b)},s):x(i,y)}async bestOf(e){let{item:t,prompt:i,config:c}=e,s=e.retry??this.config.retry,r=c.n??c.taskAgents?.length;if(r===void 0)throw new Error("bestOf requires n or taskAgents");if(r<2)throw new Error("bestOf requires n >= 2");let p=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,l=this.getFiles(t),o=c.mcpServers??this.config.mcpServers,u=c.judgeMcpServers??c.mcpServers??this.config.mcpServers,d=c.skills??this.config.skills,m=c.judgeSkills??c.skills??this.config.skills,f=c.composio??this.config.composio,g=c.judgeComposio??c.composio??this.config.composio,h=await Promise.all(Array.from({length:r},async(b,k)=>{let C=s?await _(S=>this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:k,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a,attempt:S}),s,k):await this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:k,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a});return c.onCandidateComplete?.(0,k,C.status==="success"?"success":"error"),C})),w=s?await _(b=>this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g,attempt:b}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g}),x=h.findIndex(b=>b.status==="success"),y=w.decision?.winner??(x>=0?x:0);c.onJudgeComplete?.(0,y,w.decision?.reasoning??"Judge failed to provide reasoning");let v={operationId:p,operation:"bestof-judge",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:r};return {winner:h[y]??h[0],winnerIndex:y,judgeReasoning:w.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:v,candidates:h}}async execute(e,t,i){let c=null,s="",r=i.tagPrefix,p={},a=null,l,o,u={...this.config.agent,...i.agent};try{c=new Z().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&c.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&c.withSystemPrompt(i.systemPrompt),i.mcpServers&&c.withMcpServers(i.mcpServers),i.skills?.length&&c.withSkills(i.skills),i.composio&&c.withComposio(i.composio.userId,i.composio.config),i.observability&&c.withObservability(i.observability),Object.keys(e).length>0&&c.withContext(e);let d=await c.run({prompt:t,timeoutMs:i.timeoutMs});s=d.sandboxId,r=c.getSessionTag()??i.tagPrefix;let m=null;try{m=await c.getOutputFiles(!0),p=m.files;}catch{}d.exitCode!==0?l=`Agent exited with code ${d.exitCode}`:i.schema?m?(a=m.data,m.error&&(l=m.error),m.rawData&&(o=m.rawData)):l="Failed to read output files from sandbox":a=p;}catch(d){if(l=d.message,c){r=c.getSessionTag()??i.tagPrefix;try{p=(await c.getOutputFiles(!0)).files;}catch{}}}finally{c&&await c.kill().catch(()=>{});}return {files:p,data:a,tag:r,sandboxId:s,error:l,rawData:o}}async executeMapItem(e,t,i,c,s,r,p=1){let a=this.getFiles(e),l=p>1?`${this.config.tag}-map-${i}-er${p-1}`:`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(t,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=await this.semaphore.use(()=>this.execute(a,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:l,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),g={operationId:c,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(f,g)}async executeMapItemWithVerify(e,t,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-map-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=this.evaluatePrompt(t,a,i);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let g=async(h,w,x)=>{let y=await this.semaphore.use(()=>this.execute(a,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:w,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),v={operationId:c,operation:"map",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(y,v)};return this.runWithVerification(g,{originalPrompt:f,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:l,retry:p,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,t,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(t,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let u=s.bestOf,d=u.n??u.taskAgents?.length;if(d===void 0||d<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let m=s.mcpServers??this.config.mcpServers,f=u.mcpServers??m,g=u.judgeMcpServers??u.mcpServers??m,h=s.skills??this.config.skills,w=u.skills??h,x=u.judgeSkills??u.skills??h,y=s.composio??this.config.composio,v=u.composio??y,b=u.judgeComposio??u.composio??y,k=await Promise.all(Array.from({length:d},async(Q,X)=>{let Qe=p?await _(Qt=>this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:X,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,timeoutMs:r,parentIndex:i,attempt:Qt,_pipelineContext:s._pipelineContext}),p,X):await this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:X,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,timeoutMs:r,parentIndex:i,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(i,X,Qe.status==="success"?"success":"error"),Qe})),C=p?await _(Q=>this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:k,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:b,parentIndex:i,attempt:Q,_pipelineContext:s._pipelineContext}),{...p,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:k,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:b,parentIndex:i,_pipelineContext:s._pipelineContext}),S=k.findIndex(Q=>Q.status==="success"),U=C.decision?.winner??(S>=0?S:0),Ze=k[U]??k[0];u.onJudgeComplete?.(i,U,C.decision?.reasoning??"Judge failed to provide reasoning");let Zt={operationId:c,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...Ze,meta:{...Ze.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:U,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Zt,candidates:k}}}async executeFilterItem(e,t,i,c,s,r,p=1){let a=this.getFiles(e),l=p>1?`${this.config.tag}-filter-${i}-er${p-1}`:`${this.config.tag}-filter-${i}`,o=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,d=s.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(a,t,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:u,composio:d,tagPrefix:l,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:c,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(m,f,a)}async executeFilterItemWithVerify(e,t,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-filter-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=async(g,h,w)=>{let x=await this.semaphore.use(()=>this.execute(a,g,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:h,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),y={operationId:c,operation:"filter",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(x,y,a)};return this.runWithVerification(f,{originalPrompt:t,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:l,retry:p,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:t,prompt:i,candidateIndex:c,operationId:s,config:r,timeoutMs:p,parentIndex:a,attempt:l=1,_pipelineContext:o}=e,u=a!==void 0?`${this.config.tag}-map-${a}-bestof-cand-${c}`:`${this.config.tag}-bestof-cand-${c}`,d=l>1?`${u}-er${l-1}`:u,m=await this.semaphore.use(()=>this.execute(t,i,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:r.taskAgents?.[c],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:p,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"candidate",candidateIndex:c,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o)}})),f={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:c,errorRetry:l>1?l-1:void 0,candidateIndex:c,...this.pipelineContextToMeta(o)};return this.buildResult(m,f)}buildJudgeContext(e){let t=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((i,c)=>{i.status==="error"&&(t[`candidate_${c}/_failed.txt`]=`STATUS: FAILED
|
|
218
|
-
|
|
219
|
-
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,r])=>{t[`candidate_${c}/${s}`]=r;});}),t}async executeBestOfJudge(e){let{candidates:t,config:i,timeoutMs:c,operationId:s,parentIndex:r,attempt:p=1,_pipelineContext:a}=e,l=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=p>1?`${l}-er${p-1}`:l,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:t,systemPrompt:e.systemPrompt,schema:e.schema}),d=ge(u),m=I(Be,{candidateCount:String(t.length),criteria:i.judgeCriteria,fileTree:d}),f=zod.z.object({winner:zod.z.number().min(0).max(t.length-1),reasoning:zod.z.string()}),g=await this.semaphore.use(()=>this.execute(u,Rt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let w=JSON.parse(g.rawData);console.warn(`Judge returned invalid winner ${w.winner}, defaulting to candidate 0`),h={winner:0,reasoning:w.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${g.error}`);}return {status:h?"success":"error",decision:h,tag:g.tag,sandboxId:g.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let t=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,c])=>{t[`worker_output/${i}`]=c;}),t}async executeVerify(e){let{config:t,timeoutMs:i,operationId:c,workerTag:s,retryAttempt:r=1,operation:p,itemIndex:a,attemptIndex:l,_pipelineContext:o}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=t.verifierMcpServers??e.mcpServers,m=t.verifierSkills??e.skills,f=t.verifierComposio??e.composio,g=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=ge(g),w=I(je,{criteria:t.criteria,fileTree:h}),x=await this.semaphore.use(()=>this.execute(g,Pt,{systemPrompt:w,schema:n.VerifyDecisionSchema,agent:t.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:c,operation:p,itemIndex:a,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(o)}})),y=null;if(x.data&&!x.error)y=x.data;else if(x.rawData)try{let v=JSON.parse(x.rawData);y={passed:!!v.passed,reasoning:v.reasoning??"Verification completed",feedback:v.feedback};}catch{console.warn(`Verify validation failed: ${x.error}`);}return {status:y?"success":"error",decision:y,tag:x.tag,sandboxId:x.sandboxId,error:y?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,t){return I(Ke,{originalPrompt:e,feedback:t})}async runWithVerification(e,t){let{originalPrompt:i,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:p,baseTag:a,retry:l,itemIndex:o=0,operation:u,_pipelineContext:d}=t,m=s.maxAttempts??n.DEFAULT_VERIFY_MAX_ATTEMPTS,f=i,g=null,h=0;for(;h<m;){h++;let x=h>1?`${a}-vr${h-1}`:a,y=l?await _(k=>e(f,k>1?`${x}-er${k-1}`:x,h),l,o):await e(f,x,h);if(s.onWorkerComplete?.(o,h,y.status==="error"?"error":"success"),y.status==="error")return y;g=y;let v=l?await _(k=>this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:p,workerTag:x,retryAttempt:k,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:p,workerTag:x,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),b={operationId:p,operation:"verify",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,v.decision?.passed??false,v.decision?.feedback),v.decision?.passed)return {...y,verify:{passed:true,reasoning:v.decision.reasoning,verifyMeta:b,attempts:h}};if(h<m){let k=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=n.buildRetryPromptWithFeedback(i,k);}}let w=h>1?`${a}-vr${h-1}`:a;return {...g,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:p,operation:"verify",tag:`${w}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,t,i){if(typeof e=="string")return e;try{return e(t,i)}catch(c){return c}}buildEvaluatorContext(e){let t={};return e.systemPrompt&&(t["worker_task/system_prompt.txt"]=e.systemPrompt),t["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(t["worker_task/schema.json"]=E(e.schema)?B(e.schema):j(e.schema)),Object.entries(e.inputFiles).forEach(([i,c])=>{t[`worker_task/input/${i}`]=c;}),t}isSwarmResult(e){return typeof e=="object"&&e!==null&&$ in e&&e[$]===true}getFiles(e){if(this.isSwarmResult(e)){let t={...e.files};return t["result.json"]&&(t["data.json"]=t["result.json"],delete t["result.json"]),t}return e}getIndex(e,t){return this.isSwarmResult(e)?e.meta.itemIndex:t}buildResult(e,t,i){let c=i??e.files;return e.error?{[$]:true,status:"error",data:null,files:c,meta:t,error:e.error,rawData:e.rawData}:{[$]:true,status:"success",data:e.data,files:c,meta:t}}buildErrorResult(e,t){return {[$]:true,status:"error",data:null,files:{},meta:t,error:e}}};var xe=class n{swarm;steps;events;constructor(e,t=[],i={}){this.swarm=e,this.steps=t,this.events=i;}map(e){return new n(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new n(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new be(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,t){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new n(this.swarm,this.steps,{...this.events,[i]:t})}return new n(this.swarm,this.steps,{...this.events,...e})}async run(e){let t=crypto.randomBytes(8).toString("hex"),i=[],c=e,s=Date.now();for(let p=0;p<this.steps.length;p++){let a=this.steps[p],l=a.config.name,o=Date.now();this.events.onStepStart?.({type:a.type,index:p,name:l,itemCount:c.length});let u={pipelineRunId:t,pipelineStepIndex:p};try{let d=await this.executeStep(a,c,p,l,u),m=Date.now()-o;if(i.push({type:a.type,index:p,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:p,name:l,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:t,steps:i,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:p,name:l,error:d instanceof Error?d:new Error(String(d))}),d}}let r=i[i.length-1];return {pipelineRunId:t,steps:i,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,t,i,c,s){if(e.type==="map"){let a=e.config,l=await this.swarm.map({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c),bestOf:this.wrapBestOf(a.bestOf,i,c)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,l=await this.swarm.filter({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c)}),o=a.emit??"success",u=o==="success"?l.success:o==="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 r=e.config,p=await this.swarm.reduce({items:t,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,c),verify:this.wrapVerify(r.verify,i,c)});return {output:p,nextItems:[],successCount:p.status==="success"?1:0,errorCount:p.status==="error"?1:0,filteredCount:0}}wrapRetry(e,t,i){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:t,stepName:i,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,t,i){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:t,stepName:i,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,p)=>{e.onVerifierComplete?.(c,s,r,p),this.events.onVerifierComplete?.({stepIndex:t,stepName:i,itemIndex:c,attempt:s,passed:r,feedback:p});}}}wrapBestOf(e,t,i){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:t,stepName:i,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:t,stepName:i,itemIndex:c,winnerIndex:s,reasoning:r});}}}},be=class n extends xe{constructor(e,t,i){super(e,t,i);}on(e,t){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new n(this.swarm,this.steps,{...this.events,[i]:t})}return new n(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")}};Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Ce;exports.AGENT_TYPES=Xt;exports.Agent=q;exports.Evolve=Z;exports.JUDGE_PROMPT=Be;exports.Pipeline=xe;exports.RETRY_FEEDBACK_PROMPT=Ke;exports.SCHEMA_PROMPT=Et;exports.SWARM_RESULT_BRAND=$;exports.SYSTEM_PROMPT=Tt;exports.Semaphore=V;exports.Swarm=qe;exports.SwarmResultList=W;exports.TerminalPipeline=be;exports.VALIDATION_PRESETS=ke;exports.VERIFY_PROMPT=je;exports.WORKSPACE_PROMPT=St;exports.WORKSPACE_SWE_PROMPT=_t;exports.applyTemplate=I;exports.buildWorkerSystemPrompt=Ve;exports.createAgentParser=M;exports.createClaudeParser=re;exports.createCodexParser=ae;exports.createGeminiParser=ce;exports.executeWithRetry=_;exports.expandPath=Se;exports.getAgentConfig=P;exports.getMcpSettingsDir=L;exports.getMcpSettingsPath=F;exports.isValidAgentType=en;exports.isZodSchema=E;exports.jsonSchemaToString=j;exports.listCheckpoints=He;exports.parseNdjsonLine=xn;exports.parseNdjsonOutput=bn;exports.parseQwenOutput=nt;exports.readLocalDir=dt;exports.resolveStorageConfig=we;exports.saveLocalDir=mt;exports.writeClaudeMcpConfig=ne;exports.writeCodexMcpConfig=se;exports.writeGeminiMcpConfig=oe;exports.writeMcpConfig=Pe;exports.writeQwenMcpConfig=ie;exports.zodSchemaToJson=B;
|
|
227
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(t)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(t){console.debug("[SessionLogger] Local write failed:",t);}}scheduleFlush(){if(this.eventBuffer.length>=xt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},kt));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let t={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 i=1;i<=fe;i++)try{let c=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)});if(c.ok)return;if(c.status===429||c.status===401||c.status>=500){if(i===fe){console.debug(`[SessionLogger] Dashboard ${c.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Ke*i);continue}console.debug(`[SessionLogger] Dashboard ${c.status}, dropping events`);return}catch(c){i===fe?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",c),this.requeueEvents(e)):await this.delay(Ke*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!T.startsWith("https://")&&!T.includes("localhost")&&!T.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(t=>setTimeout(t,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)):{}}};var Se="COMPOSIO_API_KEY";function Ht(n){return new core.Composio({apiKey:process.env[Se]})}function et(n){if(!n?.trim())throw new Error("userId is required and cannot be empty")}async function _e(n,e,t){et(n);let i=Ht(),c={};return e?.toolkits&&(c.toolkits=e.toolkits),e?.tools&&(c.tools=e.tools),e?.authConfigs&&(c.authConfigs=e.authConfigs),e?.connectedAccounts&&(c.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(c.manageConnections=e.manageConnections),await i.create(n,Object.keys(c).length>0?c:void 0)}async function Yt(n,e,t,i){et(n);let c=Ht(),l=(await c.toolkits.get(e)).authConfigDetails?.find(a=>a.mode==="API_KEY");if(!l)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await c.connectedAccounts.initiate(n,l.name,{config:core.AuthScheme.APIKey({api_key:t})});}async function tt(n,e){if(et(n),e?.keys)for(let[i,c]of Object.entries(e.keys))try{await Yt(n,i,c);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let t=await _e(n,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:t.mcp.url,headers:t.mcp.headers}}function qt(n){if(!n?.trim())throw new Error("userId is required and cannot be empty")}function Ci(){return new core.Composio({apiKey:process.env[Se]})}async function Zt(n,e){qt(n);let i=await(await _e(n,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function Qt(n,e){let t=await nt(n),i={};for(let c of t)i[c.toolkit]=c.connected;return e?i[e]??false:i}async function nt(n){return qt(n),(await Ci().connectedAccounts.list({userIds:[n],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var it={auth:Zt,status:Qt,connections:nt};util.promisify(child_process.exec);var at=util.promisify(child_process.execFile),tn=Symbol.for("evolve:awsSdkCache"),nn=Symbol.for("evolve:s3ClientCache");var Ii=3600,Mi=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Ai(n){if(n.startsWith("s3://")){let c=n.slice(5),s=c.indexOf("/");return s===-1?{bucket:c,prefix:""}:{bucket:c.slice(0,s),prefix:c.slice(s+1).replace(/\/+$/,"")}}let e=new URL(n),t=e.hostname,i=e.pathname.split("/").filter(Boolean);if(t.includes(".s3.")&&t.endsWith(".amazonaws.com"))return {bucket:t.split(".s3.")[0],prefix:i.join("/")};if(i.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${n}`);return {bucket:i[0],prefix:i.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function Re(n,e,t,i){if(!n?.url&&!n?.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:n?.region||"us-east-1",mode:"gateway",gatewayUrl:t,gatewayApiKey:i}}let c=n?.bucket||"",s=n?.prefix||"",r=n?.endpoint;if(n?.url){let l=Ai(n.url);c=c||l.bucket,s=s||l.prefix,r=r||l.endpoint;}if(!c)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:c,prefix:s,region:n?.region||process.env.AWS_REGION||"us-east-1",endpoint:r,credentials:n?.credentials,mode:"byok"}}function on(n){if(n.includes(".."))throw new Error(`settingsDir must not contain '..': ${n}`);let e;if(n.startsWith("~/"))e=n.slice(2);else if(n.startsWith("/home/user/"))e=n.slice(11);else if(n.startsWith("."))e=n;else throw new Error(`Unexpected settingsDir: ${n}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${n}`);return e}function $i(n){if(n.includes(".."))throw new Error(`workingDir must not contain '..': ${n}`);if(!n.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${n}. Must start with /home/user/.`);let e=n.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${n}`);return e}function Te(n){return "'"+n.replace(/'/g,"'\\''")+"'"}function Di(n,e){let t=I(n),i=$i(e),c=t.checkpointDirs?.length?t.checkpointDirs.map(l=>on(l)):[on(t.mcpConfig.settingsDir)],s=[...Mi.map(l=>`--exclude=${Te(l)}`),`--exclude=${Te(i+"/temp")}`].join(" "),r=[Te(i+"/"),...c.map(l=>Te(l+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${s} ${r}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function G(){let n=globalThis[tn];if(n)return n;let e="@aws-sdk/client-s3",t="@aws-sdk/s3-request-presigner";try{let[i,c]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(t)]);return globalThis[tn]={s3:i,presigner:c},{s3:i,presigner:c}}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 te(n){let e=n.credentials?`${n.credentials.accessKeyId}:${n.credentials.secretAccessKey.slice(-4)}`:"env",t=`${n.bucket}:${n.region}:${n.endpoint||""}:${e}`,i=globalThis[nn];if(i?.key===t)return i.client;let{s3:c}=await G(),s=new c.S3Client({region:n.region,...n.endpoint&&{endpoint:n.endpoint,forcePathStyle:true},...n.credentials&&{credentials:n.credentials}});return globalThis[nn]={client:s,key:t},s}async function mn(n,e,t){let{s3:i,presigner:c}=await G(),s=await te(n),r=t==="put"?new i.PutObjectCommand({Bucket:n.bucket,Key:e,ContentType:"application/gzip"}):new i.GetObjectCommand({Bucket:n.bucket,Key:e});return c.getSignedUrl(s,r,{expiresIn:Ii})}async function sn(n,e){let{s3:t}=await G(),i=await te(n);try{return await i.send(new t.HeadObjectCommand({Bucket:n.bucket,Key:e})),!0}catch(c){let s=c?.name||c?.message||"";if(c?.$metadata?.httpStatusCode===404||s==="NotFound"||s==="NoSuchKey")return false;throw c}}async function gn(n,e){let{s3:t}=await G(),s=await(await(await te(n)).send(new t.GetObjectCommand({Bucket:n.bucket,Key:e}))).Body?.transformToString();if(!s)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(s)}async function Ui(n,e,t){let{s3:i}=await G();await(await te(n)).send(new i.PutObjectCommand({Bucket:n.bucket,Key:e,Body:JSON.stringify(t,null,2),ContentType:"application/json"}));}function fn(n,e){return `${n.prefix?`${n.prefix}/`:""}data/${e}/archive.tar.gz`}function hn(n,e){return `${n.prefix?`${n.prefix}/`:""}checkpoints/${e}.json`}function Fi(){let n=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${n}_${e}`}async function yn(n,e,t,i){let c=await fetch(`${n.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:t,action:i})});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway presign failed (${c.status}): ${s}`)}return c.json()}async function Li(n,e){let t=await fetch(`${n.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.gatewayApiKey}`},body:JSON.stringify(e)});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${t.status}): ${i}`)}return t.json()}async function Ni(n,e){let t=await fetch(`${n.gatewayUrl}/api/checkpoints/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${n.gatewayApiKey}`}});if(!t.ok){if(t.status===404)throw new Error(`Checkpoint ${e} not found`);let i=await t.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${t.status}): ${i}`)}return t.json()}async function ct(n,e,t,i,c){let s=new Date().toISOString(),r=Di(t,i),l=await n.commands.run(r,{timeoutMs:12e4});if(l.exitCode!==0)throw new Error(`Checkpoint tar failed: ${l.stderr}`);let a=l.stdout.trim().split(`
|
|
228
|
+
`).pop()?.trim();if(!a||a.length!==64)throw new Error(`Invalid checkpoint hash: ${a}`);let p=await n.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(p.stdout.trim(),10),u=Number.isNaN(o)?void 0:o,d;try{if(e.mode==="byok"){let m=fn(e,a);if(!await sn(e,m)){let h=await mn(e,m,"put"),y=await n.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 sn(e,m))throw new Error("Checkpoint upload verification failed (HeadObject)")}d=Fi();let f={id:d,hash:a,tag:c.tag,timestamp:s,sizeBytes:u,agentType:t,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment,sandboxId:n.sandboxId};await Ui(e,hn(e,d),f);}else {let m=await yn(e,c.tag,a,"put");if(!m.alreadyExists){let f=await n.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${m.url}"`,{timeoutMs:3e5});if(f.exitCode!==0)throw new Error(`Checkpoint upload failed: ${f.stderr}`)}d=(await Li(e,{tag:c.tag,hash:a,sizeBytes:u??0,agentType:t,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment})).id;}}finally{await n.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:d,hash:a,tag:c.tag,timestamp:s,sizeBytes:u,agentType:t,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment}}async function wn(n,e,t){let i=await pt(e,t),c=i.hash,s={agentType:i.agentType,workspaceMode:i.workspaceMode},r=await kn(e,i),l=await n.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${r}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(l.exitCode!==0)throw new Error(`Checkpoint download failed: ${l.stderr}`);let a=l.stdout.trim().split(`
|
|
229
|
+
`).pop()?.trim();if(a!==c)throw await n.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${c}, got ${a})`);let p=await n.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(p.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${p.stderr}`);return s}function vn(n,e){let t=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,i=e?.gatewayUrl||T,c=!n.url&&!n.bucket&&!!t;return Re(n,c,i,t)}async function Cn(n,e){let{s3:t}=await G(),i=await te(n),s=`${n.prefix?`${n.prefix}/`:""}checkpoints/`,r=[],l;do{let d={Bucket:n.bucket,Prefix:s,...l&&{ContinuationToken:l}},m=await i.send(new t.ListObjectsV2Command(d));if(m.Contents)for(let g of m.Contents)g.Key?.endsWith(".json")&&g.LastModified&&r.push({key:g.Key,lastModified:g.LastModified});l=m.IsTruncated?m.NextContinuationToken:void 0;}while(l);if(r.length===0)return [];r.sort((d,m)=>{let g=m.lastModified.getTime()-d.lastModified.getTime();return g!==0?g:m.key<d.key?-1:m.key>d.key?1:0});let p=!!e?.tag?r:e?.limit?r.slice(0,e.limit):r,u=(await Promise.all(p.map(async d=>{try{return await gn(n,d.key)}catch{return null}}))).filter(d=>d!==null);return e?.tag&&(u=u.filter(d=>d.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function xn(n,e){let t=new URLSearchParams;e?.limit&&t.set("limit",String(e.limit)),e?.tag&&t.set("tag",e.tag);let i=`${n.gatewayUrl}/api/checkpoints${t.toString()?`?${t}`:""}`,c=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${n.gatewayApiKey}`}});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${c.status}): ${s}`)}return c.json()}function Ki(n){return n&&n>0?Math.min(n,500):100}async function lt(n,e){return n.mode==="byok"?(await Cn(n,{limit:1,tag:e?.tag}))[0]??null:(await xn(n,{limit:1,tag:e?.tag}))[0]??null}async function pt(n,e){if(n.mode==="byok"){let t=hn(n,e);try{return await gn(n,t)}catch(i){throw Bi(i)?new Error(`Checkpoint ${e} not found`):i}}else return await Ni(n,e)}async function rn(n,e,t){if(e==="latest"){let i=await lt(n,{tag:t});if(!i)throw new Error("No checkpoints found");return i.id}return e}async function kn(n,e){if(n.mode==="byok")return mn(n,fn(n,e.hash),"get");{let t=await yn(n,e.tag,e.hash,"get");if(!t.url)throw new Error("Gateway presign returned no download URL");return t.url}}function bn(n){return !(!n||Q.isAbsolute(n)||n.startsWith("-")||Q.normalize(n).startsWith("..")||n.includes("\0"))}function an(n,e){let t=Q.resolve(n,e),i=Q.resolve(n),c=Q.relative(i,t);if(c.startsWith("..")||Q.isAbsolute(c))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Bi(n){let e=n.name,t=n.message;return n?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||t==="NoSuchKey"}function ot(n){let e=n.filter(t=>!bn(t));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return n}var Sn=10*1024*1024,cn=false;async function _n(){if(!cn)try{await at("tar",["--version"]),cn=!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 ln(n,e){let t=await pt(n,e),i=await kn(n,t),c=e.replace(/[^a-zA-Z0-9_-]/g,"_"),s=Q.join(os.tmpdir(),`evolve-dl-${c}-${Date.now()}.tar.gz`),r=await fetch(i);if(!r.ok)throw new Error(`Checkpoint download failed (${r.status})`);if(!r.body)throw new Error("Checkpoint download returned empty body");let l=crypto.createHash("sha256"),a=O.createWriteStream(s);try{let o=r.body.getReader();await new Promise((u,d)=>{a.on("error",d),a.on("finish",u);async function m(){for(;;){let{done:g,value:f}=await o.read();if(g){a.end();break}l.update(f),a.write(f)||await new Promise(h=>a.once("drain",h));}}m().catch(d);});}catch(o){throw a.destroy(),await promises.unlink(s).catch(()=>{}),o}let p=l.digest("hex");if(p!==t.hash)throw await promises.unlink(s).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${t.hash}, got ${p})`);return {tmpPath:s,metadata:t}}async function pn(n){await _n();let{stdout:e}=await at("tar",["-tvzf",n],{maxBuffer:Sn}),t=new Set,i=[],c=[];for(let s of e.trim().split(`
|
|
230
|
+
`)){if(!s||s.startsWith("total "))continue;let r=s[0];if(r!=="-"&&r!=="d"&&r!=="l")throw new Error(`Archive contains unsupported entry type: "${r}"`);let l=s.match(/\d{2}:\d{2}\s+(.+)/)??s.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!l)continue;let a=l[1];if(r==="l"){let p=a.indexOf(" -> ");p!==-1&&(a=a.slice(0,p)),t.add(a);}else r==="d"?i.push(a.replace(/\/$/,"")):c.push(a);}return ot(i),ot([...t]),ot(c)}async function st(n,e,t){await _n(),await promises.mkdir(e,{recursive:true});let i=["-xzf",n,"--no-same-owner","--no-same-permissions","-C",e];t?.length&&i.push("--",...t),await at("tar",i,{maxBuffer:Sn});}function ji(n){let e="^",t=0;for(;t<n.length;){let i=n[t];i==="*"&&n[t+1]==="*"?n[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):i==="*"?(e+="[^/]*",t++):i==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(i)?(e+="\\"+i,t++):(e+=i,t++);}return e+="$",new RegExp(e)}function ut(n,e){let t=vn(n,e);return Tn(t)}function Vi(n){let e=vn(n||{});return Tn(e)}function Tn(n){return {async listCheckpoints(e){let t=Ki(e?.limit);return n.mode==="byok"?Cn(n,{limit:t,tag:e?.tag}):xn(n,{limit:t,tag:e?.tag})},async getCheckpoint(e){return pt(n,e)},async downloadCheckpoint(e,t){let i=t?.extract!==false,c=t?.to||process.cwd(),s=await rn(n,e),{tmpPath:r,metadata:l}=await ln(n,s);try{if(i)return await promises.mkdir(c,{recursive:!0}),await pn(r),await st(r,c),c;{await promises.mkdir(c,{recursive:!0});let a=Q.join(c,`checkpoint-${l.id}.tar.gz`);return await promises.copyFile(r,a),a}}finally{await promises.unlink(r).catch(()=>{});}},async downloadFiles(e,t){let i=await rn(n,e),{tmpPath:c}=await ln(n,i),s;try{let r=await pn(c),l;if(t?.files){let p=t.files.filter(u=>!bn(u));if(p.length>0)throw new Error(`Unsafe file path requested: ${p[0]}`);let o=new Set(t.files);l=r.filter(u=>o.has(u));}else if(t?.glob){let p=t.glob.map(ji);l=r.filter(o=>p.some(u=>u.test(o)));}else l=r;if(l.length===0)return {};s=Q.join(os.tmpdir(),`evolve-extract-${Date.now()}`);try{await st(c,s,l);}catch(p){let o=p?.message??"";if(!o.includes("E2BIG")&&!o.includes("Argument list too long")&&!o.includes("ENAMETOOLONG"))throw p;await promises.rm(s,{recursive:!0,force:!0}).catch(()=>{}),s=Q.join(os.tmpdir(),`evolve-extract-${Date.now()}`),await st(c,s);}let a={};return await Promise.all(l.map(async p=>{an(s,p),a[p]=await promises.readFile(Q.join(s,p));})),t?.to&&(await promises.mkdir(t.to,{recursive:!0}),await Promise.all(Object.entries(a).map(async([p,o])=>{an(t.to,p);let u=Q.join(t.to,p);await promises.mkdir(Q.dirname(u),{recursive:!0}),await promises.writeFile(u,o);}))),a}finally{s&&await promises.rm(s,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(c).catch(()=>{});}}}}function Gi(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function En(n){return `${n}-${crypto.randomBytes(8).toString("hex")}`}function Rn(n,e,t="newline"){let i=new Map;if(n){let c=t==="comma"?n.split(/,(?=\s*[^,:]+:)/):n.split(/\r?\n/);for(let s of c){let r=s.trim();if(!r)continue;let l=r.indexOf(":");if(l<=0)continue;let a=r.slice(0,l).trim(),p=r.slice(l+1).trim();i.set(a.toLowerCase(),`${a}: ${p}`);}}for(let[c,s]of Object.entries(e)){let r=c.toLowerCase();if(r===F&&i.has(r)&&t==="newline"){let l=i.get(r),a=l.slice(l.indexOf(":")+1).trim();i.set(r,`${c}: ${a},${s}`);}else i.set(r,`${c}: ${s}`);}return Array.from(i.values()).join(t==="comma"?", ":`
|
|
231
|
+
`)}var ne=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";skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,t={}){if(this.agentConfig=e,this.options=t,this.workingDir=t.workingDirectory||vt,this.sandboxState=t.sandboxId?"ready":"stopped",this.skills=t.skills,this.storage=t.storage,t.schema)if(P(t.schema))this.zodSchema=t.schema,t.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=t.schema,this.schemaOptions=t.schemaOptions;try{let i=this.createAjvValidator();this.compiledValidator=i.compile(this.jsonSchema);}catch(i){throw new Error(`Invalid JSON Schema: ${i.message}`)}}this.registry=I(e.type),this.sessionTag=En(t.sessionTagPrefix||"evolve");}emitLifecycle(e,t){e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:t});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,t,i,c){let s=++this.nextOperationId;return this.activeOperationId=s,this.activeOperationKind=e,this.activeCommand=t,this.activeProcessId=t.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(i,c),s}finalizeOperation(e,t,i,c="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=c,this.emitLifecycle(t,i),true)}watchBackgroundOperation(e,t,i,c){let s=t==="run"?"run_background_complete":"command_background_complete",r=t==="run"?"run_background_failed":"command_background_failed",l=t==="run"?"run_interrupted":"command_interrupted";i.wait().then(a=>{if(this.interruptedOperations.delete(e)||a.exitCode===130){this.finalizeOperation(e,c,l,"interrupted");return}let o=a.exitCode===0?s:r,u=a.exitCode===0?"idle":"error";this.finalizeOperation(e,c,o,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,c,r,"error");});}createAjvValidator(){let t={...Ie[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 Wi__default.default({...t,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let t=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, context, files, and systemPrompt"),this.sandbox=await t.connect(this.options.sandboxId),this.hasRun=!0,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {let i=this.buildEnvironmentVariables();this.sandbox=await t.create({envs:i,workingDirectory:this.workingDir}),await this.setupAgentAuth(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(i){throw this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),i}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let t of Object.values(this.registry.providerEnvMap))e[t.keyEnv]=this.agentConfig.apiKey;else {let t=this.agentConfig.model?.split("/")[0],i=t?this.registry.providerEnvMap?.[t]:void 0,c=i?i.keyEnv:this.registry.apiKeyEnv,s=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:c;e[s]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let t=this.registry.usePassthroughGateway?Fe():L();this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[R]:this.sessionTag}):e[this.registry.baseUrlEnv]=t,e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.options.secrets&&Object.assign(e,this.options.secrets),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let t=this.registry.customHeadersEnv,i=this.registry.customHeadersFormat||"newline";e[t]=Rn(e[t],{[R]:this.sessionTag},i);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildGatewayConfigJson(e){let t=this.registry.usePassthroughGateway?Fe():L(),i=this.agentConfig.model||this.registry.defaultModel,c={},s=this.options.secrets?.[this.registry.gatewayConfigEnv];if(s)try{c=JSON.parse(s);}catch{}let r=c.provider??{},l=r.litellm??{},a=l.options??{},p=l.models??{},o=p[i]??{},u=o.headers??{};return c.provider={...r,litellm:{...l,npm:"@ai-sdk/openai-compatible",options:{...a,baseURL:`${t}/v1`,apiKey:this.agentConfig.apiKey},models:{...p,[i]:{...o,name:i,headers:{...u,...e}}}}},JSON.stringify(c)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let t=this.registry.customHeadersEnv;if(t){let c=this.options.secrets?.[t],s=this.registry.customHeadersFormat||"newline";return {[t]:Rn(c,{[R]:this.sessionTag,[F]:`${V}${e}`},s)}}let i=this.registry.spendTrackingEnvs;if(i)return {[i.sessionTagEnv]:this.sessionTag,[i.runTagEnv]:`${V}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[R]:this.sessionTag,[F]:`${V}${e}`})}}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let t=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(t),await e.files.write(`${t}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e,t){let i=this.options.workspaceMode||"knowledge",c=i==="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 ${c}`,{timeoutMs:3e4}),!t?.skipSystemPrompt){let r=Xe({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:i}),l=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(l,r);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let s={...this.options.mcpServers};if(this.options.composio){let r=await tt(this.options.composio.userId,this.options.composio.config);s={...s,composio:{type:"http",url:r.url,headers:r.headers}};}Object.keys(s).length>0&&await Ve(this.agentConfig.type,e,this.workingDir,s),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await Be(e,this.agentConfig.baseUrl||L(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ue(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[R]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:t}=this.registry,{sourceDir:i,targetDir:c}=t;await e.files.makeDir(c);for(let s of this.skills){let r=`cp -r ${i}/${s} ${c}/ 2>/dev/null || true`;await e.commands.run(r,{timeoutMs:3e4});}}async uploadContextFiles(e,t){let i=Object.entries(t).map(([s,r])=>({path:`${this.workingDir}/context/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,t){let i=Object.entries(t).map(([s,r])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:Gi(e),model:this.agentConfig.model||this.registry.defaultModel,isResume:this.hasRun,reasoningEffort:this.agentConfig.reasoningEffort,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,t){let{prompt:i,timeoutMs:c=Z,background:s=false,checkpointComment:r}=e,{from:l}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(l&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(l==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await lt(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');l=v.id;}if(l){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(t,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir});let C=await wn(this.sandbox,this.storage,l);if(C.agentType&&C.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${C.agentType}, current: ${this.agentConfig.type})`);let b=this.options.workspaceMode||"knowledge";if(C.workspaceMode&&C.workspaceMode!==b)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${C.workspaceMode}, current: ${b})`);await this.setupAgentAuth(this.sandbox);let S=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!S}),this.hasRun=!0,this.lastCheckpointId=l,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(t,"sandbox_ready");}catch(C){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(t,"sandbox_error"),C}}let a=await this.getSandbox(t);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new X({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:a.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(i);let p=this.buildCommand(i),o=crypto.randomUUID(),u=this.buildRunEnvs(o);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ue(a,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[R]:this.sessionTag,[F]:`${V}${o}`}),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await je(a,this.registry.spendTrackingTomlProvider,{[R]:this.sessionTag,[F]:`${V}${o}`});let d="",m=K(this.agentConfig.type),g=v=>{d+=v;let C=d.split(`
|
|
232
|
+
`);d=C.pop()??"";for(let b of C){if(!b.trim())continue;let S=m(b);if(this.sessionLogger?.writeEventParsed(b,S),t?.onStdout?.(b+`
|
|
233
|
+
`),S&&t?.onContent)for(let A of S)t.onContent(A);}},f=v=>{t?.onStderr?.(v);},h=await a.commands.spawn(p,{cwd:this.workingDir,timeoutMs:c,envs:u,onStdout:g,onStderr:f}),y=this.beginOperation("run",h,t,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(y,"run",h,t),{sandboxId:a.sandboxId,runId:o,exitCode:0,stdout:`Background process started with ID ${h.processId}`,stderr:""};let w;try{w=await h.wait();}catch(v){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,t,"run_failed","error"),v}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,t,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,t,"run_complete","idle"):this.finalizeOperation(y,t,"run_failed","error"),d.trim()){let v=m(d);if(this.sessionLogger?.writeEventParsed(d,v),t?.onStdout?.(d+`
|
|
234
|
+
`),v&&t?.onContent)for(let C of v)t.onContent(C);}this.sessionLogger&&!s&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let x;if(this.storage&&!s&&w.exitCode===0)try{x=await ct(a,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:r,parentId:this.lastCheckpointId}),this.lastCheckpointId=x.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:a.sandboxId,runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:x}}async executeCommand(e,t={},i){let{timeoutMs:c=Z,background:s=false}=t;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 r=await this.getSandbox(i);this.lastRunTimestamp=Date.now();let l="",a="",p=f=>{l+=f,i?.onStdout?.(f);},o=f=>{a+=f,i?.onStderr?.(f);},u=await r.commands.spawn(e,{cwd:this.workingDir,timeoutMs:c,onStdout:p,onStderr:o}),d=this.beginOperation("command",u,i,"command_start");if(s)return this.watchBackgroundOperation(d,"command",u,i),{sandboxId:r.sandboxId,exitCode:0,stdout:`Background process started with ID ${u.processId}`,stderr:""};let m;try{m=await u.wait();}catch(f){throw this.interruptedOperations.delete(d),this.finalizeOperation(d,i,"command_failed","error"),f}return this.interruptedOperations.delete(d)||m.exitCode===130?this.finalizeOperation(d,i,"command_interrupted","interrupted"):m.exitCode===0?this.finalizeOperation(d,i,"command_complete","idle"):this.finalizeOperation(d,i,"command_failed","error"),{sandboxId:r.sandboxId,exitCode:m.exitCode,stdout:l||m.stdout||"",stderr:a||m.stderr||""}}async uploadContext(e){let t=await this.getSandbox();await this.uploadContextFiles(t,e);}async uploadFiles(e){let t=await this.getSandbox();await this.uploadWorkspaceFiles(t,e);}async getOutputFiles(e=false){let t=await this.getSandbox(),i=`${this.workingDir}/output`,c=e?"":"-maxdepth 1",r=(await t.commands.run(`find ${i} ${c} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
235
|
+
`).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,a=[],p=`${i}/`;for(let g of r){let[f,h]=g.split("|");if(!f||!h)continue;let y=parseInt(h,10);l>0&&y<l||a.push(f);}let o={},u=await Promise.all(a.map(async g=>{try{let f=await t.files.read(g);return {relativePath:g.startsWith(p)?g.slice(p.length):g.split("/").pop()||g,content:f}}catch{return null}}));for(let g of u)g&&(o[g.relativePath]=g.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let d=o["result.json"];if(!d)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let m=typeof d=="string"?d:new TextDecoder().decode(d);try{let g=JSON.parse(m);if(this.zodSchema){let f=this.zodSchema.safeParse(g);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:m}}if(this.compiledValidator){if(this.compiledValidator(g))return {files:o,data:g};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:m}}}return {files:o,data:null}}catch(g){return {files:o,data:null,error:`Failed to parse result.json: ${g.message}`,rawData:m}}}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 t=await ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=t.id,t}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),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 t=this.activeOperationId,i=this.activeOperationKind,c=false;try{this.activeCommand?c=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(c=await this.sandbox.commands.kill(this.activeProcessId));}catch{c=false;}if(!c)return this.sandboxState="running",this.agentState="running",false;t!==null&&this.interruptedOperations.add(t),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let s=i==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,s),c}status(){return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString()}}async kill(e){await this.rotateSession(),this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0),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=En(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let t=this.agentConfig.apiKey;if(!t)throw new Error("Cost tracking requires an API key.");let i=process.env.EVOLVE_DASHBOARD_URL||T,c=await fetch(`${i}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Spend query failed (${c.status}): ${s}`)}return c}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,t){return {...e,asOf:e.asOf??t.asOf,isComplete:e.isComplete??t.isComplete,truncated:e.truncated??t.truncated}}normalizeSessionCost(e){let t={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(i=>this.normalizeRunCost(i,t))}}async getSessionCost(){let e=this.resolveSpendTag(),t=new URLSearchParams({tag:e}),c=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(c)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let r=new URLSearchParams({tag:t,runId:e.runId}),a=await(await this.fetchSpend(r)).json();return this.normalizeRunCost(a,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let i=await this.getSessionCost(),c=e.index>0?e.index-1:i.runs.length+e.index,s=i.runs[c];if(!s)throw new Error(`Run index ${e.index} out of range. Session has ${i.runs.length} run(s).`);return s}};var ie=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withSkills(e){return this.config.skills=e,this}withSchema(e,t){return this.config.schema=e,t&&(P(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=t),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,t){return this.config.composio={userId:e,config:t},this}withStorage(e){return this.config.storage=e||{},this}static composio=it;async initializeAgent(){let e=ke(this.config.agent),t=this.config.sandbox??await Ye(),i=e.isDirectMode?{}:ht(e.apiKey),c=this.config.storage!==void 0?Re(this.config.storage,!e.isDirectMode,T,e.isDirectMode?void 0:e.apiKey):void 0,s={sandboxProvider:t,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...i,...this.config.mcpServers},skills:this.config.skills,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:c};this.agent=new ne(e,s);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,i=this.listenerCount("content")>0,c=this.listenerCount("lifecycle")>0;return {onStdout:e?s=>this.emit("stdout",s):void 0,onStderr:t?s=>this.emit("stderr",s):void 0,onContent:i?s=>this.emit("content",s):void 0,onLifecycle:c?s=>this.emit("lifecycle",s):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let t=this.status();this.emit("lifecycle",{sandboxId:t.sandboxId,sandbox:t.sandbox,agent:t.agent,timestamp:new Date().toISOString(),reason:e});}async run({prompt:e,timeoutMs:t,background:i,from:c,checkpointComment:s}){if(c&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:i,from:c,checkpointComment:s},r)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let i=this.createStreamCallbacks();return this.agent.executeCommand(e,t,i)}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=ke(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:T,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 ut(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return ut(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var H=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 B=Symbol.for("evolve.SwarmResult"),Y=class n 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 t=new n;return t.push(...e),t}};var dt=class n{config;semaphore;constructor(e={}){let t=e.concurrency??wt;if(t>Ne)throw new Error(`concurrency=${t} exceeds max ${Ne}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:t,timeoutMs:e.timeoutMs??Z,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new H(this.config.concurrency);}async map(e){let{items:t,prompt:i,bestOf:c,verify:s}=e,r=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs;if(c&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let p=await Promise.all(t.map((o,u)=>c?this.executeMapItemWithBestOf(o,i,u,l,e,a,r):s?this.executeMapItemWithVerify(o,i,u,l,e,a,r):r?E(d=>this.executeMapItem(o,i,u,l,e,a,d),r,u):this.executeMapItem(o,i,u,l,e,a)));return Y.from(p)}async filter(e){let{items:t,prompt:i,condition:c,verify:s}=e,r=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,p=await Promise.all(t.map((u,d)=>s?this.executeFilterItemWithVerify(u,i,d,l,e,a,r):r?E(m=>this.executeFilterItem(u,i,d,l,e,a,m),r,d):this.executeFilterItem(u,i,d,l,e,a))),o=[];for(let u of p)if(u.status==="error")o.push(u);else if(u.data!==null)try{c(u.data)?o.push(u):o.push({...u,status:"filtered"});}catch(d){o.push({...u,status:"error",data:null,error:`Condition function threw: ${d.message}`});}return Y.from(o)}async reduce(e){let{items:t,prompt:i,verify:c}=e,s=e.retry??this.config.retry,r=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,a=[],p=[];t.forEach((x,v)=>{a.push(this.getFiles(x)),p.push(this.getIndex(x,v));});let o={};a.forEach((x,v)=>{Object.entries(x).forEach(([C,b])=>{o[`item_${p[v]}/${C}`]=b;});});let u=be(o),d=M(zt,{fileTree:u}),m=e.systemPrompt?`${d}
|
|
236
|
+
|
|
237
|
+
${e.systemPrompt}`:d,g=(x,v,C)=>({operationId:r,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:t.length,inputIndices:p,errorRetry:v,verifyRetry:C,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(x,v,C,b)=>{let S=await this.semaphore.use(()=>this.execute(o,x,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:e.name,operationId:r,operation:"reduce",role:"worker",errorRetry:C,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),A=g(S,C,b&&b>1?b-1:void 0);return S.error?{status:"error",data:null,files:S.files,meta:A,error:S.error,rawData:S.rawData}:{status:"success",data:S.data,files:S.files,meta:A}},k=`${this.config.tag}-reduce`;return c?this.runWithVerification((x,v,C)=>w(x,v,void 0,C),{originalPrompt:i,inputFiles:o,verifyConfig:c,timeoutMs:l,systemPrompt:m,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:r,baseTag:k,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?E(x=>{let v=x>1?x-1:void 0,C=v?`${k}-er${v}`:k;return w(i,C,v)},s):w(i,k)}async bestOf(e){let{item:t,prompt:i,config:c}=e,s=e.retry??this.config.retry,r=c.n??c.taskAgents?.length;if(r===void 0)throw new Error("bestOf requires n or taskAgents");if(r<2)throw new Error("bestOf requires n >= 2");let l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,p=this.getFiles(t),o=c.mcpServers??this.config.mcpServers,u=c.judgeMcpServers??c.mcpServers??this.config.mcpServers,d=c.skills??this.config.skills,m=c.judgeSkills??c.skills??this.config.skills,g=c.composio??this.config.composio,f=c.judgeComposio??c.composio??this.config.composio,h=await Promise.all(Array.from({length:r},async(v,C)=>{let b=s?await E(S=>this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:C,operationId:l,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:g,timeoutMs:a,attempt:S}),s,C):await this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:C,operationId:l,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:g,timeoutMs:a});return c.onCandidateComplete?.(0,C,b.status==="success"?"success":"error"),b})),y=s?await E(v=>this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:f,attempt:v}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:f}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);c.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:r};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:h}}async execute(e,t,i){let c=null,s="",r=i.tagPrefix,l={},a=null,p,o,u={...this.config.agent,...i.agent};try{c=new ie().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&c.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&c.withSystemPrompt(i.systemPrompt),i.mcpServers&&c.withMcpServers(i.mcpServers),i.skills?.length&&c.withSkills(i.skills),i.composio&&c.withComposio(i.composio.userId,i.composio.config),i.observability&&c.withObservability(i.observability),Object.keys(e).length>0&&c.withContext(e);let d=await c.run({prompt:t,timeoutMs:i.timeoutMs});s=d.sandboxId,r=c.getSessionTag()??i.tagPrefix;let m=null;try{m=await c.getOutputFiles(!0),l=m.files;}catch{}d.exitCode!==0?p=`Agent exited with code ${d.exitCode}`:i.schema?m?(a=m.data,m.error&&(p=m.error),m.rawData&&(o=m.rawData)):p="Failed to read output files from sandbox":a=l;}catch(d){if(p=d.message,c){r=c.getSessionTag()??i.tagPrefix;try{l=(await c.getOutputFiles(!0)).files;}catch{}}}finally{c&&await c.kill().catch(()=>{});}return {files:l,data:a,tag:r,sandboxId:s,error:p,rawData:o}}async executeMapItem(e,t,i,c,s,r,l=1){let a=this.getFiles(e),p=l>1?`${this.config.tag}-map-${i}-er${l-1}`:`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(t,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:i});let u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(a,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:p,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:c,operation:"map",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(g,f)}async executeMapItemWithVerify(e,t,i,c,s,r,l){let a=this.getFiles(e),p=`${this.config.tag}-map-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,g=this.evaluatePrompt(t,a,i);if(g instanceof Error)return this.buildErrorResult(`Prompt function threw: ${g.message}`,{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:i});let f=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(a,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:y,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),x={operationId:c,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(k,x)};return this.runWithVerification(f,{originalPrompt:g,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:p,retry:l,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,t,i,c,s,r,l){let a=this.getFiles(e),p=`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(t,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:i});let u=s.bestOf,d=u.n??u.taskAgents?.length;if(d===void 0||d<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:i});let m=s.mcpServers??this.config.mcpServers,g=u.mcpServers??m,f=u.judgeMcpServers??u.mcpServers??m,h=s.skills??this.config.skills,y=u.skills??h,w=u.judgeSkills??u.skills??h,k=s.composio??this.config.composio,x=u.composio??k,v=u.judgeComposio??u.composio??k,C=await Promise.all(Array.from({length:d},async(oe,se)=>{let gt=l?await E(On=>this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:se,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:y,composio:x,timeoutMs:r,parentIndex:i,attempt:On,_pipelineContext:s._pipelineContext}),l,se):await this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:se,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:y,composio:x,timeoutMs:r,parentIndex:i,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(i,se,gt.status==="success"?"success":"error"),gt})),b=l?await E(oe=>this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:C,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:i,attempt:oe,_pipelineContext:s._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:C,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:i,_pipelineContext:s._pipelineContext}),S=C.findIndex(oe=>oe.status==="success"),A=b.decision?.winner??(S>=0?S:0),mt=C[A]??C[0];u.onJudgeComplete?.(i,A,b.decision?.reasoning??"Judge failed to provide reasoning");let Pn={operationId:c,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...mt,meta:{...mt.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:A,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Pn,candidates:C}}}async executeFilterItem(e,t,i,c,s,r,l=1){let a=this.getFiles(e),p=l>1?`${this.config.tag}-filter-${i}-er${l-1}`:`${this.config.tag}-filter-${i}`,o=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,d=s.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(a,t,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:u,composio:d,tagPrefix:p,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),g={operationId:c,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(m,g,a)}async executeFilterItemWithVerify(e,t,i,c,s,r,l){let a=this.getFiles(e),p=`${this.config.tag}-filter-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,g=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(a,f,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:h,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),k={operationId:c,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(w,k,a)};return this.runWithVerification(g,{originalPrompt:t,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:p,retry:l,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:t,prompt:i,candidateIndex:c,operationId:s,config:r,timeoutMs:l,parentIndex:a,attempt:p=1,_pipelineContext:o}=e,u=a!==void 0?`${this.config.tag}-map-${a}-bestof-cand-${c}`:`${this.config.tag}-bestof-cand-${c}`,d=p>1?`${u}-er${p-1}`:u,m=await this.semaphore.use(()=>this.execute(t,i,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:r.taskAgents?.[c],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"candidate",candidateIndex:c,errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(o)}})),g={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:c,errorRetry:p>1?p-1:void 0,candidateIndex:c,...this.pipelineContextToMeta(o)};return this.buildResult(m,g)}buildJudgeContext(e){let t=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((i,c)=>{i.status==="error"&&(t[`candidate_${c}/_failed.txt`]=`STATUS: FAILED
|
|
238
|
+
|
|
239
|
+
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,r])=>{t[`candidate_${c}/${s}`]=r;});}),t}async executeBestOfJudge(e){let{candidates:t,config:i,timeoutMs:c,operationId:s,parentIndex:r,attempt:l=1,_pipelineContext:a}=e,p=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=l>1?`${p}-er${l-1}`:p,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:t,systemPrompt:e.systemPrompt,schema:e.schema}),d=be(u),m=M(qe,{candidateCount:String(t.length),criteria:i.judgeCriteria,fileTree:d}),g=zod.z.object({winner:zod.z.number().min(0).max(t.length-1),reasoning:zod.z.string()}),f=await this.semaphore.use(()=>this.execute(u,Vt,{systemPrompt:m,schema:g,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(f.data&&!f.error)h=f.data;else if(f.rawData)try{let y=JSON.parse(f.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${f.error}`);}return {status:h?"success":"error",decision:h,tag:f.tag,sandboxId:f.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let t=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,c])=>{t[`worker_output/${i}`]=c;}),t}async executeVerify(e){let{config:t,timeoutMs:i,operationId:c,workerTag:s,retryAttempt:r=1,operation:l,itemIndex:a,attemptIndex:p,_pipelineContext:o}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=t.verifierMcpServers??e.mcpServers,m=t.verifierSkills??e.skills,g=t.verifierComposio??e.composio,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=be(f),y=M(Ze,{criteria:t.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(f,Wt,{systemPrompt:y,schema:n.VerifyDecisionSchema,agent:t.verifierAgent,mcpServers:d,skills:m,composio:g,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:c,operation:l,itemIndex:a,role:"verifier",verifyRetry:p&&p>1?p-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(o)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let x=JSON.parse(w.rawData);k={passed:!!x.passed,reasoning:x.reasoning??"Verification completed",feedback:x.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:k?"success":"error",decision:k,tag:w.tag,sandboxId:w.sandboxId,error:k?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,t){return M(Qe,{originalPrompt:e,feedback:t})}async runWithVerification(e,t){let{originalPrompt:i,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:l,baseTag:a,retry:p,itemIndex:o=0,operation:u,_pipelineContext:d}=t,m=s.maxAttempts??n.DEFAULT_VERIFY_MAX_ATTEMPTS,g=i,f=null,h=0;for(;h<m;){h++;let w=h>1?`${a}-vr${h-1}`:a,k=p?await E(C=>e(g,C>1?`${w}-er${C-1}`:w,h),p,o):await e(g,w,h);if(s.onWorkerComplete?.(o,h,k.status==="error"?"error":"success"),k.status==="error")return k;f=k;let x=p?await E(C=>this.executeVerify({inputFiles:c,outputFiles:k.files,taskPrompt:g,config:s,timeoutMs:r,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:l,workerTag:w,retryAttempt:C,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...p,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:k.files,taskPrompt:g,config:s,timeoutMs:r,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:l,workerTag:w,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),v={operationId:l,operation:"verify",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,x.decision?.passed??false,x.decision?.feedback),x.decision?.passed)return {...k,verify:{passed:true,reasoning:x.decision.reasoning,verifyMeta:v,attempts:h}};if(h<m){let C=x.decision?.feedback??x.decision?.reasoning??"Output did not meet criteria";g=n.buildRetryPromptWithFeedback(i,C);}}let y=h>1?`${a}-vr${h-1}`:a;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:l,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,t,i){if(typeof e=="string")return e;try{return e(t,i)}catch(c){return c}}buildEvaluatorContext(e){let t={};return e.systemPrompt&&(t["worker_task/system_prompt.txt"]=e.systemPrompt),t["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(t["worker_task/schema.json"]=P(e.schema)?W(e.schema):z(e.schema)),Object.entries(e.inputFiles).forEach(([i,c])=>{t[`worker_task/input/${i}`]=c;}),t}isSwarmResult(e){return typeof e=="object"&&e!==null&&B in e&&e[B]===true}getFiles(e){if(this.isSwarmResult(e)){let t={...e.files};return t["result.json"]&&(t["data.json"]=t["result.json"],delete t["result.json"]),t}return e}getIndex(e,t){return this.isSwarmResult(e)?e.meta.itemIndex:t}buildResult(e,t,i){let c=i??e.files;return e.error?{[B]:true,status:"error",data:null,files:c,meta:t,error:e.error,rawData:e.rawData}:{[B]:true,status:"success",data:e.data,files:c,meta:t}}buildErrorResult(e,t){return {[B]:true,status:"error",data:null,files:{},meta:t,error:e}}};var Pe=class n{swarm;steps;events;constructor(e,t=[],i={}){this.swarm=e,this.steps=t,this.events=i;}map(e){return new n(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new n(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new Oe(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,t){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new n(this.swarm,this.steps,{...this.events,[i]:t})}return new n(this.swarm,this.steps,{...this.events,...e})}async run(e){let t=crypto.randomBytes(8).toString("hex"),i=[],c=e,s=Date.now();for(let l=0;l<this.steps.length;l++){let a=this.steps[l],p=a.config.name,o=Date.now();this.events.onStepStart?.({type:a.type,index:l,name:p,itemCount:c.length});let u={pipelineRunId:t,pipelineStepIndex:l};try{let d=await this.executeStep(a,c,l,p,u),m=Date.now()-o;if(i.push({type:a.type,index:l,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:l,name:p,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:t,steps:i,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:l,name:p,error:d instanceof Error?d:new Error(String(d))}),d}}let r=i[i.length-1];return {pipelineRunId:t,steps:i,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,t,i,c,s){if(e.type==="map"){let a=e.config,p=await this.swarm.map({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c),bestOf:this.wrapBestOf(a.bestOf,i,c)});return {output:[...p],nextItems:p.success,successCount:p.success.length,errorCount:p.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,p=await this.swarm.filter({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c)}),o=a.emit??"success",u=o==="success"?p.success:o==="filtered"?p.filtered:[...p.success,...p.filtered];return {output:[...p],nextItems:u,successCount:p.success.length,errorCount:p.error.length,filteredCount:p.filtered.length}}let r=e.config,l=await this.swarm.reduce({items:t,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,c),verify:this.wrapVerify(r.verify,i,c)});return {output:l,nextItems:[],successCount:l.status==="success"?1:0,errorCount:l.status==="error"?1:0,filteredCount:0}}wrapRetry(e,t,i){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:t,stepName:i,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,t,i){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:t,stepName:i,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,l)=>{e.onVerifierComplete?.(c,s,r,l),this.events.onVerifierComplete?.({stepIndex:t,stepName:i,itemIndex:c,attempt:s,passed:r,feedback:l});}}}wrapBestOf(e,t,i){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:t,stepName:i,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:t,stepName:i,itemIndex:c,winnerIndex:s,reasoning:r});}}}},Oe=class n extends Pe{constructor(e,t,i){super(e,t,i);}on(e,t){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new n(this.swarm,this.steps,{...this.events,[i]:t})}return new n(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")}};Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Me;exports.AGENT_TYPES=In;exports.Agent=ne;exports.Evolve=ie;exports.JUDGE_PROMPT=qe;exports.Pipeline=Pe;exports.RETRY_FEEDBACK_PROMPT=Qe;exports.SCHEMA_PROMPT=jt;exports.SWARM_RESULT_BRAND=B;exports.SYSTEM_PROMPT=Bt;exports.Semaphore=H;exports.Swarm=dt;exports.SwarmResultList=Y;exports.TerminalPipeline=Oe;exports.VALIDATION_PRESETS=Ie;exports.VERIFY_PROMPT=Ze;exports.WORKSPACE_PROMPT=Nt;exports.WORKSPACE_SWE_PROMPT=Kt;exports.applyTemplate=M;exports.buildWorkerSystemPrompt=Xe;exports.createAgentParser=K;exports.createClaudeParser=ye;exports.createCodexParser=we;exports.createGeminiParser=ve;exports.executeWithRetry=E;exports.expandPath=q;exports.getAgentConfig=I;exports.getMcpSettingsDir=D;exports.getMcpSettingsPath=$;exports.isValidAgentType=Mn;exports.isZodSchema=P;exports.jsonSchemaToString=z;exports.parseNdjsonLine=Zn;exports.parseNdjsonOutput=Qn;exports.parseQwenOutput=Tt;exports.readLocalDir=Et;exports.resolveStorageConfig=Re;exports.saveLocalDir=Rt;exports.storage=Vi;exports.writeClaudeMcpConfig=ce;exports.writeCodexMcpConfig=he;exports.writeGeminiMcpConfig=le;exports.writeMcpConfig=Ve;exports.writeQwenMcpConfig=pe;exports.zodSchemaToJson=W;
|