@evolvingmachines/sdk 0.0.27 → 0.0.29
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 -48
- package/dist/index.d.cts +199 -21
- package/dist/index.d.ts +199 -21
- package/dist/index.js +66 -48
- package/package.json +4 -2
package/dist/index.cjs
CHANGED
|
@@ -1,34 +1,50 @@
|
|
|
1
|
-
'use strict';var events=require('events'),eo=require('ajv'),bn=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 bn__default=/*#__PURE__*/_interopDefault(bn);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"},be={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(`
|
|
2
|
-
`),
|
|
3
|
-
`)].filter(
|
|
1
|
+
'use strict';var events=require('events'),Vo=require('ajv'),crypto=require('crypto'),Zn=require('zod-to-json-schema'),P=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 Vo__default=/*#__PURE__*/_interopDefault(Vo);var Zn__default=/*#__PURE__*/_interopDefault(Zn);var P__namespace=/*#__PURE__*/_interopNamespace(P);var q__namespace=/*#__PURE__*/_interopNamespace(q);var Pn={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode"},Re={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Pe={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 r=i?` -c model_reasoning_effort="${i}"`:"";return `printf '%s' "${n}" | codex exec --model ${e}${r} --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:r})=>{let s=t?"--continue ":"",a=r?.length?"--experimental-skills ":"",l=i||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${n}" ${s}${a}--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",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 r=t?"--continue ":"",s=e.startsWith("openrouter/")?e:`openrouter/${e}`;return i?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${r}--model ${s} --format json "${n}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${r}--model litellm/${s} --format json "${n}" < /dev/null`}}};function O(n){let e=Pe[n];if(!e)throw new Error(`Unknown agent type: ${n}`);return e}function On(n){return n in Pe}function Oe(n){return n.replace(/^~/,"/home/user")}function A(n){let e=O(n);return `${Oe(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function $(n){let e=O(n);return Oe(e.mcpConfig.settingsDir)}function D(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 Ie(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 ie(n){for(let[e,t]of Object.entries(n))Ie(e,t);}function se(n){return n.type?n.type:n.command?"stdio":"sse"}function In(n){let e=se(n);return {...n,type:e}}function Mn(n){let{type:e,url:t,...i}=n;return se(n)==="http"&&t?{httpUrl:t,...i}:t?{url:t,...i}:i}function An(n){return {type:se(n),...n}}function $n(n){let{type:e,...t}=n;return t.command?{...t,transport:"stdio"}:t.url&&(e==="http"||e==="sse")?{...t,transport:e}:t}async function Me(n,e,t,i){ie(t);let r=$(e),s=A(e);await n.files.makeDir(r);let a={};try{let c=await n.files.read(s);typeof c=="string"&&(a=JSON.parse(c));}catch(c){if(!D(c))throw c}let l=Object.fromEntries(Object.entries(t).map(([c,p])=>[c,i(p)]));await n.files.write(s,JSON.stringify({...a,mcpServers:l},null,2));}async function re(n,e,t){ie(t);let i=$("claude"),r=A("claude"),s=Object.fromEntries(Object.entries(t).map(([l,c])=>[l,An(c)]));await n.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await n.files.makeDir(i);let a={};try{let l=await n.files.read(r);typeof l=="string"&&(a=JSON.parse(l));}catch(l){if(!D(l))throw l}a.enableAllProjectMcpServers=true,await n.files.write(r,JSON.stringify(a,null,2));}async function ae(n,e){await Me(n,"gemini",e,In);}async function ce(n,e){await Me(n,"qwen",e,Mn);}async function Ae(n,e){await Me(n,"kimi",e,$n);}async function $e(n,e,t){ie(t);let i=`${e}/opencode.json`,r={};try{let a=await n.files.read(i);typeof a=="string"&&(r=JSON.parse(a));}catch(a){if(!D(a))throw a}let s=Object.fromEntries(Object.entries(t).map(([a,l])=>[a,Dn(l)]));await n.files.write(i,JSON.stringify({...r,mcp:s},null,2));}function Dn(n){let e=se(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 B(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function dt(){return `${B()}`}function mt(){return `${B()}/e2b`}function ft(n){return {"browser-use":{type:"http",url:`${B()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${n}`}}}}var U="EVOLVE_API_KEY",le="E2B_API_KEY",pe="DAYTONA_API_KEY",ue="MODAL_TOKEN_ID",De="MODAL_TOKEN_SECRET",gt="claude",J=36e5,ht=4,Ue=100,yt="/home/user/workspace",E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",Y="x-litellm-customer-id",H="x-litellm-tags",Fe="run:",wt=".evolve-sdk/observability/sessions",vt=100,xt=5e3,de=3,Le=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 me(n,e){for(let[c,p]of Object.entries(e))Ie(c,p);let t=$("codex"),i=A("codex");await n.files.makeDir(t);let r="";try{let c=await n.files.read(i);typeof c=="string"&&(r=c);}catch(c){if(!D(c))throw c}let s=[],a=[];r.includes("experimental_use_rmcp_client")||(s.push("# Enable improved RMCP client (recommended)"),s.push("experimental_use_rmcp_client = true")),r.includes("[mcp_servers]")||a.push("[mcp_servers]","");for(let[c,p]of Object.entries(e)){if(r.includes(`[mcp_servers.${c}]`))continue;a.push(`[mcp_servers.${c}]`);let o=p.type??(p.command?"stdio":"http");if(o==="http"||o==="sse"||!!p.url){if(!p.url)throw new Error(`MCP server "${c}" is missing url for ${o} transport`);a.push(`url = ${_(p.url)}`),p.bearerTokenEnvVar&&a.push(`bearer_token_env_var = ${_(p.bearerTokenEnvVar)}`);let d=p.httpHeaders??p.headers;d&&Object.keys(d).length>0&&a.push(`http_headers = ${_(d)}`),p.envHttpHeaders&&Object.keys(p.envHttpHeaders).length>0&&a.push(`env_http_headers = ${_(p.envHttpHeaders)}`);}else a.push(`command = ${_(p.command)}`),p.args&&p.args.length>0&&a.push(`args = ${_(p.args)}`),p.cwd&&a.push(`cwd = ${_(p.cwd)}`);p.env&&Object.keys(p.env).length>0&&a.push(`env = ${_(p.env)}`),p.envVars&&p.envVars.length>0&&a.push(`env_vars = ${_(p.envVars)}`),a.push("");}let l=[r.trim(),s.join(`
|
|
2
|
+
`),a.join(`
|
|
3
|
+
`)].filter(c=>c.length>0);await n.files.write(i,l.join(`
|
|
4
4
|
|
|
5
5
|
`)+`
|
|
6
|
-
`);}async function
|
|
7
|
-
|
|
6
|
+
`);}async function Ne(n,e,t){let i=$("codex"),r=A("codex");await n.files.makeDir(i);let s="";try{let g=await n.files.read(r);typeof g=="string"&&(s=g);}catch(g){if(!D(g))throw g}let a=s.search(/^\[/m),l=a>=0?s.slice(0,a):s,c=a>=0?s.slice(a):"",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
|
+
`)+c).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 = ${_({[Y]:t.sessionTagEnv,[H]:t.runTagEnv})}`].join(`
|
|
9
|
+
`),f;if(!s.trim())f=m?`${d}
|
|
10
|
+
|
|
11
|
+
${m}
|
|
12
|
+
`:`${d}
|
|
13
|
+
`;else {let g=s.search(/^\[/m);g>0?f=s.slice(0,g)+d+`
|
|
14
|
+
|
|
15
|
+
`+s.slice(g).trimEnd():g===0?f=d+`
|
|
16
|
+
|
|
17
|
+
`+s.trimEnd():f=s.trimEnd()+`
|
|
18
|
+
|
|
19
|
+
`+d,m&&(f=f.trimEnd()+`
|
|
20
|
+
|
|
21
|
+
`+m),f+=`
|
|
22
|
+
`;}await n.files.write(r,f);}async function Be(n,e,t,i){if(!(!i||Object.keys(i).length===0))switch(n){case "claude":await re(e,t,i);break;case "codex":await me(e,i);break;case "gemini":await ae(e,i);break;case "qwen":await ce(e,i);break;case "kimi":await Ae(e,i);break;case "opencode":await $e(e,t,i);break;default:throw new Error(`Unknown agent type for MCP config: ${n}`)}}function fe(){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(c,p,o){if(typeof c=="string")return p==="user"?null:[{sessionId:o,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let u=[];for(let d of c){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:a(d.input)});else {let f=t(d);m={sessionUpdate:"tool_call",toolCallId:d.id,status:"pending",...f};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let f=n[d.tool_use_id];if(!f||(delete n[d.tool_use_id],f.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,f)};break}}m&&u.push({sessionId:o,update:m});}return u.length>0?u:null}function t(c){let p=c.name,o=c.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(c,p){let o=c.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 r(o,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return r(o,"is_error"in c?c.is_error:false)}}function r(c,p=false){return Array.isArray(c)&&c.length>0?{content:c.map(o=>({type:"content",content:s(o,p)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:p?"```\n"+c+"\n```":c}}]}:{}}function s(c,p){if(c.type==="text")return p?{type:"text",text:"```\n"+c.text+"\n```"}:{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return {type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return {type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function a(c){return c.todos.map(p=>({content:p.content,status:p.status||"pending",priority:"medium"}))}function l(c){let p="```",o=Array.from(c.matchAll(/^```+/gm));for(let[u]of o)for(;u.length>=p.length;)p+="`";return p+`
|
|
23
|
+
`+c+(c.endsWith(`
|
|
8
24
|
`)?"":`
|
|
9
|
-
`)+
|
|
10
|
-
`)??
|
|
11
|
-
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:
|
|
12
|
-
${
|
|
13
|
-
\`\`\``:
|
|
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 k=tt(o.todos);if(k.length===0&&typeof l.output=="string")try{k=tt(JSON.parse(l.output));}catch{}k.length>0&&w.push({sessionUpdate:"plan",entries:k});}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
|
-
\`\`\``:
|
|
25
|
+
`)+p}}function ge(){return function(c){let p;try{p=JSON.parse(c);}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 c=l.id;switch(l.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${l.server}:${l.tool}`},{sessionUpdate:"tool_call",toolCallId:c,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:c,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:c,title:`Search: ${l.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(l.items)};default:return null}}function t(l){return l.type==="todo_list"?{sessionUpdate:"plan",entries:a(l.items)}:null}function i(l){let c=l.id;switch(l.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.text??l.summary?.join(`
|
|
26
|
+
`)??l.content?.join(`
|
|
27
|
+
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text??""}};case "mcp_tool_call":{let o=r(l.result),u=l.status==="failed"||l.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,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:c,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:c,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:c,title:`Search: ${l.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(l.items)};default:return null}}function r(l){return l?.content?Array.isArray(l.content)?l.content.map(c=>({type:"content",content:s(c)})):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 a(l){if(!Array.isArray(l))return [];let c=false;return l.map(p=>{let o;return p.completed?o="completed":c?o="pending":(o="in_progress",c=true),{content:p.text??"",status:o,priority:"medium"}})}}var Un={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 he(){return function(a){let l;try{l=JSON.parse(a);}catch{return null}if(l._meta||l._prompt)return null;let c=l.session_id,p=[];switch(l.type){case "init":case "result":return null;case "message":{let o=n(l);o&&p.push({sessionId:c,update:o});break}case "tool_use":{let o=e(l);o&&p.push({sessionId:c,update:o});break}case "tool_result":{let o=t(l);o&&p.push({sessionId:c,update:o});break}case "error":{let o=i(l);o&&p.push({sessionId:c,update:o});break}default:return null}return p.length>0?p:null};function n(s){let a=s.role,l=s.content;return l?a==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}:a==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:l}}:null:null}function e(s){let a=s.tool_id,l=s.tool_name,c=s.parameters||{},{title:p,kind:o,content:u,locations:d}=r(l,c);return {sessionUpdate:"tool_call",toolCallId:a,title:p,kind:o,status:"pending",rawInput:c,content:u,locations:d}}function t(s){let a=s.tool_id,l=s.status,c=s.output,p=s.error,o=[];return c&&typeof c=="string"&&c.length>0&&o.push({type:"content",content:{type:"text",text:l==="error"?`\`\`\`
|
|
28
|
+
${c}
|
|
29
|
+
\`\`\``:c}}),p?.message&&!c&&o.push({type:"content",content:{type:"text",text:`\`\`\`
|
|
30
|
+
${p.message}
|
|
31
|
+
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:a,status:l==="success"?"completed":"failed",content:o}}function i(s){let a=s.severity,l=s.message;return l?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${l}`}}:null}function r(s,a){let l=Un[s]||"other",c=[],p=[],o=s;switch(s){case "read_file":o=`Read ${a.absolute_path||a.file_path||"file"}`,(a.absolute_path||a.file_path)&&p.push({path:a.absolute_path||a.file_path});break;case "write_file":o=`Write ${a.file_path||"file"}`,a.file_path&&(p.push({path:a.file_path}),c.push({type:"diff",path:a.file_path,oldText:null,newText:a.content||""}));break;case "edit_file":o=`Edit ${a.file_path||"file"}`,a.file_path&&p.push({path:a.file_path});break;case "replace":o=`Edit ${a.file_path||"file"}`,a.file_path&&(p.push({path:a.file_path}),(a.old_string!==void 0||a.new_string!==void 0)&&c.push({type:"diff",path:a.file_path,oldText:a.old_string||"",newText:a.new_string||""}));break;case "run_shell_command":case "shell":o=a.command?`\`${a.command}\``:"Run command",a.description&&c.push({type:"content",content:{type:"text",text:a.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=a.query?`"${a.query}"`:"Web search";break;case "web_fetch":o=a.prompt?`Fetch: ${a.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${a.pattern||"files"}`,a.dir_path&&p.push({path:a.dir_path});break;case "grep":case "search_file_content":o=`grep "${a.pattern||a.query||""}"`;break;case "list_directory":o=`List ${a.dir_path||a.path||"directory"}`,(a.dir_path||a.path)&&p.push({path:a.dir_path||a.path});break;case "read_many_files":o=`Read ${a.include?.length||"multiple"} files`,Array.isArray(a.include)&&a.include.forEach(u=>p.push({path:u}));break;case "delegate_to_agent":o=a.agent_name?`Agent: ${a.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=a.fact?`Remember: "${a.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=a.name?`Activate skill: ${a.name}`:"Activate skill";break;default:o=s;}return {title:o,kind:l,content:c,locations:p}}}var Fn={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 je(n){return /<system>\s*ERROR:/i.test(n)||n.includes("<error>")||n.includes("ToolError")}function kt(n){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(n);if(!e)return null;let t=e[1]||"",i=e[2]||"",r=e[3]||"";return /;base64/i.test(i)?{mimeType:t,data:r}:null}function Ve(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=kt(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 Ke(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=Ve(t);i&&e.push(i);}return e}if(n&&typeof n=="object"){let t=Ve(n);t&&e.push(t);}return e}function Ln(n){return n.some(e=>e.type==="content"&&e.content.type==="text"&&je(e.content.text))}function Nn(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=kt(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 Bn(n){return n==="in_progress"?"in_progress":n==="done"||n==="completed"?"completed":"pending"}function Ct(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 r=t.status;return {content:i,status:Bn(r),priority:"medium"}}).filter(t=>t!==null):[]}function We(){let n=new Set,e=0;function t(l,c){return typeof l=="string"&&l.length>0?l:(e+=1,`kimi_${c.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(c){let p;try{p=JSON.parse(c);}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"?r(p):typeof p.type=="string"&&"payload"in p?s(p):null};function i(l){let c=[],p=l.content,o=l.tool_calls;if(typeof p=="string"&&p.length>0)c.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});else if(Array.isArray(p))for(let u of p){let d=Nn(u);d&&c.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 C=Ct(g);C.length>0&&c.push({update:{sessionUpdate:"plan",entries:C}}),n.add(f);continue}let{title:h,kind:y,toolContent:w,locations:k}=a(m,typeof g=="object"&&g!==null?g:{});c.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:g,content:w,locations:k}});}return c.length>0?c:null}function r(l){let c=l.tool_call_id;if(typeof c!="string"||c.length===0)return null;if(n.has(c))return n.delete(c),null;let p=l.content,o=[],u=false;if(typeof p=="string")u=je(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=Ve(d);m&&(m.type==="content"&&m.content.type==="text"&&je(m.content.text)&&(u=true),o.push(m));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:c,status:u?"failed":"completed",content:o}}]}function s(l){let c=l.type,p=l.payload??{},o=[];switch(c){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 f;try{f=m.arguments?JSON.parse(m.arguments):{};}catch{f=m.arguments;}if(u==="SetTodoList"){let k=Ct(f);k.length>0&&o.push({update:{sessionUpdate:"plan",entries:k}}),n.add(d);break}let{title:g,kind:h,toolContent:y,locations:w}=a(u,typeof f=="object"&&f!==null?f:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:d,title:g,kind:h,status:"pending",rawInput:f,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=[],f=p.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(...Ke(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(...Ke(d));}else m.push(...Ke(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 a(l,c){let p=Fn[l]||"other",o=[],u=[],d=l;switch(l){case "ReadFile":{let m=c.path??c.file_path;d=`Read ${m||"file"}`,m&&u.push({path:m});break}case "ReadMediaFile":{let m=c.path??c.file_path;d=`Read media ${m||"file"}`,m&&u.push({path:m});break}case "WriteFile":{let m=c.path??c.file_path;d=`Write ${m||"file"}`,m&&(u.push({path:m}),typeof c.content=="string"&&o.push({type:"diff",path:m,oldText:null,newText:c.content}));break}case "StrReplaceFile":{let m=c.path??c.file_path;d=`Edit ${m||"file"}`,m&&u.push({path:m});break}case "Shell":d=c.command?`\`${c.command}\``:"Run command";break;case "Glob":d=`Find ${c.pattern||"files"}`,c.path&&u.push({path:c.path});break;case "Grep":d=`grep "${c.pattern||""}"`,c.path&&u.push({path:c.path});break;case "SearchWeb":d=c.query?`"${c.query}"`:"Web search";break;case "FetchURL":d=c.url?`Fetch ${c.url}`:"Web fetch";break;case "Task":d=c.description||"Subagent task";break;case "Think":d=c.thought||"Thinking";break;case "CreateSubagent":d=c.name?`Subagent: ${c.name}`:"Create subagent";break;case "SetTodoList":d="Update todos";break;default:d=l;}return {title:d,kind:p,toolContent:o,locations:u}}}var Kn={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 jn(n){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(n);if(!e)return null;let t=e[1]||"",i=e[2]||"",r=e[3]||"";return /;base64/i.test(i)?{mimeType:t,data:r}:null}function Vn(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 Wn(n){return n==="high"||n==="medium"||n==="low"?n:"medium"}function bt(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:Vn(e.status),priority:Wn(e.priority)}}).filter(e=>e!==null):[]}function zn(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=jn(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 Gn(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 Jn(n,e){return n==="error"?"failed":n==="running"?"in_progress":n==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function ze(){return function(a){let l;try{l=JSON.parse(a);}catch{return null}if(!l||typeof l!="object")return null;let c=l.sessionID,p=[];switch(l.type){case "step_start":case "step_finish":return null;case "text":{let o=n(l);o&&p.push({sessionId:c,update:o});break}case "reasoning":{let o=e(l);o&&p.push({sessionId:c,update:o});break}case "tool_use":{let o=t(l);for(let u of o)p.push({sessionId:c,update:u});break}case "error":{let o=i(l);o&&p.push({sessionId:c,update:o});break}default:return null}return p.length>0?p:null};function n(s){let a=s.part?.text;return typeof a!="string"||a.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}}function e(s){let a=s.part?.text;return typeof a!="string"||a.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a}}}function t(s){let a=s.part;if(!a)return [];let l=typeof a.callID=="string"?a.callID:"";if(l.length===0)return [];let c=typeof a.tool=="string"?a.tool.toLowerCase():"",p=typeof a.state=="object"&&a.state?a.state:{},o=typeof p.input=="object"&&p.input?p.input:{},u=p.status,d=p.title??p.metadata?.description??c,m=p.metadata?.exit,{kind:f,content:g,locations:h}=r(c,o),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:l,title:d,kind:f,status:"pending",rawInput:o,content:g,locations:h}),c==="todowrite"){let v=bt(o.todos);if(v.length===0&&typeof p.output=="string")try{v=bt(JSON.parse(p.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=Jn(u,m);if(w==="pending")return y;let k=Gn(u,p),C=[];if(typeof k=="string"&&k.length>0&&C.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
|
|
32
|
+
${k}
|
|
33
|
+
\`\`\``:k}}),Array.isArray(p.attachments))for(let v of p.attachments){let x=zn(v);x&&C.push(x);}return y.push({sessionUpdate:"tool_call_update",toolCallId:l,status:w,content:C}),y}function i(s){let a=s.error?.name??"Error",l=s.error?.data?.message??s.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${a}: ${l}`}}}function r(s,a){let l=Kn[s]||"other",c=[],p=[];switch(s){case "read":{let o=a.filePath??a.path;if(o){let u=a.offset;p.push({path:o,line:typeof u=="number"&&Number.isFinite(u)?Math.max(0,u-1):void 0});}break}case "write":{let o=a.filePath??a.path;o&&(p.push({path:o}),typeof a.content=="string"&&c.push({type:"diff",path:o,oldText:null,newText:a.content}));break}case "edit":case "multiedit":{let o=a.filePath??a.path;o&&(p.push({path:o}),s==="edit"&&(a.oldString!==void 0||a.newString!==void 0)&&c.push({type:"diff",path:o,oldText:a.oldString??"",newText:a.newString??""}));break}case "apply_patch":break;case "bash":{let o=a.command;o&&a.description?c.push({type:"content",content:{type:"text",text:a.description}}):o&&c.push({type:"content",content:{type:"text",text:o}});break}case "glob":case "list":{let o=a.path;o&&p.push({path:o});break}case "grep":{let o=a.path;o&&p.push({path:o});break}case "codesearch":case "websearch":{let o=a.query;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "webfetch":{let o=a.url;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "task":{let o=a.description;o&&c.push({type:"content",content:{type:"text",text:o}});break}}return {kind:l,content:c,locations:p}}}var Yn={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 ye(){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,f=[];switch(d.type){case "assistant":{let g=t(d);for(let h of g)f.push({sessionId:m,update:h});break}case "stream_event":{let g=i(d);for(let h of g)f.push({sessionId:m,update:h});break}case "user":{let g=r(d);for(let h of g)f.push({sessionId:m,update:h});break}case "system":case "result":return null;default:return null}return f.length>0?f: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,f=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&&f?.type==="tool_use"){let g=e.get(d)||"";e.set(d,g+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 f=m,g=e.get(d)||"";e.delete(d);let h=f.input;if(g)try{h=JSON.parse(g);}catch{}let y={...f,input:h},w=a(y);w&&o.push(w);}else if(m.type==="tool_result"){let f=l(m);f&&o.push(f);}}}n.delete(d);break}}return o}function r(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=a(p);return o?[o]:[]}case "tool_result":{let o=l(p);return o?[o]:[]}}}function a(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:f,content:g,locations:h}=c(u,d||{});return {sessionUpdate:"tool_call",toolCallId:o,title:m,kind:f,status:"pending",rawInput:d,content:g,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
34
|
${d}
|
|
19
35
|
\`\`\``:d}});else if(Array.isArray(d)){for(let f of d)if(f.type==="text"){let g=f.text;m.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
20
36
|
${g}
|
|
21
|
-
\`\`\``:g}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:m}}function
|
|
22
|
-
`),
|
|
23
|
-
Try reinstalling: npm install @evolvingmachines/sdk`):
|
|
24
|
-
Try installing: npm install @evolvingmachines/daytona`):
|
|
25
|
-
Try installing: npm install @evolvingmachines/modal`):
|
|
26
|
-
Try reinstalling: npm install @evolvingmachines/sdk`):
|
|
27
|
-
1. Set ${
|
|
28
|
-
2. Set ${
|
|
29
|
-
3. Set ${
|
|
30
|
-
4. Set ${
|
|
31
|
-
5. Pass sandbox explicitly: .withSandbox(provider)`)}function
|
|
37
|
+
\`\`\``:g}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:m}}function c(p,o){let u=Yn[p]||"other",d=[],m=[],f=p;switch(p){case "Read":case "read_file":f=`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":f=`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":f=`Edit ${o.file_path||"file"}`,o.file_path&&m.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":f=o.command?`\`${o.command}\``:"Run command",o.description&&d.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":f=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=o.query?`"${o.query}"`:"Web search";break;case "Glob":f=`Find ${o.pattern||"files"}`,o.path&&m.push({path:o.path});break;case "Grep":f=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${o.path||"directory"}`,o.path&&m.push({path:o.path});break;case "Task":f=o.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=p;}return {title:f,kind:u,content:d,locations:m}}}function St(n){return ye()(n)}function F(n){switch(n){case "claude":return fe();case "codex":return ge();case "gemini":return he();case "qwen":return ye();case "kimi":return We();case "opencode":return ze();default:return ()=>null}}function Hn(n,e){let t=e.trim();return t?F(n)(t):null}function qn(n,e){let t=[],i=e.split(`
|
|
38
|
+
`),r=F(n);for(let s of i){let a=s.trim();if(!a)continue;let l=r(a);l&&t.push(...l);}return t}function R(n){return n!==null&&typeof n=="object"&&"safeParse"in n&&typeof n.safeParse=="function"}function K(n){return JSON.stringify(Zn__default.default(n,{target:"jsonSchema7"}),null,2)}function j(n){return JSON.stringify(n,null,2)}function _t(n,e=false){let t={};function i(r,s){for(let a of P__namespace.readdirSync(r)){let l=q__namespace.join(r,a),c=s?`${s}/${a}`:a;P__namespace.statSync(l).isDirectory()?e&&i(l,c):t[c]=P__namespace.readFileSync(l);}}return i(n,""),t}function Et(n,e){for(let[t,i]of Object.entries(e)){let r=q__namespace.join(n,t),s=q__namespace.dirname(r);P__namespace.mkdirSync(s,{recursive:true});let a;i instanceof ArrayBuffer||i instanceof Uint8Array?a=Buffer.from(i):a=i,P__namespace.writeFileSync(r,a);}}function Qn(n){let e=n.replace(/^~/,process.env.HOME||"");if(!P__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return P__namespace.readFileSync(e,"utf-8")}function ve(n){let e=n?.type??gt,t=O(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 a=n.providerBaseUrl??process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:n.providerApiKey,baseUrl:a,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[U];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],c=l?t.providerEnvMap[l]:void 0,p=c?process.env[c.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 r=process.env[t.apiKeyEnv];if(r){let a=process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:r,baseUrl:a,isDirectMode:true,model:n?.model,reasoningEffort:n?.reasoningEffort}}if(t.oauthEnv){let a=process.env[t.oauthEnv];if(a){if(t.oauthFileName){let l=Qn(a);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:l,model:n?.model,reasoningEffort:n?.reasoningEffort}}return {type:e,apiKey:a,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 ${U} / ${t.apiKeyEnv} env var.`)}async function Ge(){let n=process.env[le];if(n)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return s({apiKey:n})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${le} is set but @evolvingmachines/e2b failed to load.
|
|
39
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):a}let e=process.env[pe];if(e)try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return s({apiKey:e})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${pe} is set but @evolvingmachines/daytona failed to load.
|
|
40
|
+
Try installing: npm install @evolvingmachines/daytona`):a}let t=process.env[ue],i=process.env[De];if(t&&i)try{let{createModalProvider:s}=await import('@evolvingmachines/modal');return s({tokenId:t,tokenSecret:i})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${ue} is set but @evolvingmachines/modal failed to load.
|
|
41
|
+
Try installing: npm install @evolvingmachines/modal`):a}let r=process.env[U];if(r)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=mt(),s({apiKey:r})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${U} is set but @evolvingmachines/e2b failed to load.
|
|
42
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):a}throw new Error(`No sandbox provider configured. Either:
|
|
43
|
+
1. Set ${U} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
44
|
+
2. Set ${le} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
45
|
+
3. Set ${pe} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
46
|
+
4. Set ${ue} and ${De} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
47
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function Xn(n){return new Promise(e=>setTimeout(e,n))}async function T(n,e,t=0){let i=eo(e),r=e?.onItemRetry,s=null,a=0,l=i.backoffMs;for(;a<i.maxAttempts;){if(a++,s=await n(a),!i.retryOn(s))return s;if(a>=i.maxAttempts)break;if(r){let c=s.error??"Unknown error";r(t,a,c);}await Xn(l),l*=i.backoffMultiplier;}return s}function eo(n){return {maxAttempts:n?.maxAttempts??3,backoffMs:n?.backoffMs??1e3,backoffMultiplier:n?.backoffMultiplier??2,retryOn:n?.retryOn??(e=>e.status==="error")}}var Tt=`## FILESYSTEM INSTRUCTIONS:
|
|
32
48
|
|
|
33
49
|
You are running in a sandbox environment.
|
|
34
50
|
|
|
@@ -61,7 +77,7 @@ Examples:
|
|
|
61
77
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
62
78
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
63
79
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
64
|
-
`;var
|
|
80
|
+
`;var Rt=`## FILESYSTEM INSTRUCTIONS:
|
|
65
81
|
|
|
66
82
|
You are running in a sandbox environment.
|
|
67
83
|
|
|
@@ -95,9 +111,9 @@ Examples:
|
|
|
95
111
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
96
112
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
97
113
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
98
|
-
`;var
|
|
114
|
+
`;var Pt=`## SYSTEM PROMPT
|
|
99
115
|
|
|
100
|
-
{{systemPrompt}}`;var
|
|
116
|
+
{{systemPrompt}}`;var Ot=`## STRUCTURED OUTPUT
|
|
101
117
|
|
|
102
118
|
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
103
119
|
|
|
@@ -115,7 +131,7 @@ You are free to:
|
|
|
115
131
|
But your final \`output/result.json\` MUST conform to the schema above.
|
|
116
132
|
|
|
117
133
|
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
118
|
-
### Never just state results as text.`;var
|
|
134
|
+
### Never just state results as text.`;var It=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
119
135
|
|
|
120
136
|
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
137
|
|
|
@@ -145,7 +161,7 @@ You must judge their work based on:
|
|
|
145
161
|
5. Pick the best candidate (0-indexed)
|
|
146
162
|
|
|
147
163
|
**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
|
|
164
|
+
`;var Mt=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
149
165
|
|
|
150
166
|
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
167
|
|
|
@@ -178,14 +194,14 @@ The output must satisfy:
|
|
|
178
194
|
**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
195
|
|
|
180
196
|
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
181
|
-
`;var
|
|
197
|
+
`;var At=`### CONTEXT STRUCTURE
|
|
182
198
|
|
|
183
199
|
\`\`\`
|
|
184
200
|
{{fileTree}}
|
|
185
201
|
\`\`\`
|
|
186
202
|
|
|
187
203
|
Examine all files within each item folder before producing your output.
|
|
188
|
-
`;var
|
|
204
|
+
`;var $t="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var Dt="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var Ut=`{{originalPrompt}}
|
|
189
205
|
|
|
190
206
|
## IMPORTANT: Previous Attempt Failed Verification
|
|
191
207
|
|
|
@@ -194,26 +210,28 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
194
210
|
{{feedback}}
|
|
195
211
|
|
|
196
212
|
Make sure your output addresses all the feedback points above.
|
|
197
|
-
`;var
|
|
213
|
+
`;var Ft=Tt,Lt=Rt,Nt=Pt,Bt=Ot,Je=It,Kt=$t,Ye=Mt,jt=Dt,Vt=At,He=Ut;function I(n,e){let t=n;for(let[i,r]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${i}\\}\\}`,"g"),r);return t}function qe(n){let e=n.mode==="swe"?Lt:Ft,t=I(e,{workingDir:n.workingDir}).trim();if(n.systemPrompt&&(t+=`
|
|
198
214
|
|
|
199
215
|
|
|
200
|
-
${I(
|
|
216
|
+
${I(Nt,{systemPrompt:n.systemPrompt}).trim()}`),n.schema){let i=R(n.schema)?K(n.schema):j(n.schema);t+=`
|
|
201
217
|
|
|
202
218
|
|
|
203
|
-
${I(
|
|
204
|
-
(empty)`;let t="worker_task/system_prompt.txt"in n,i="worker_task/schema.json"in n,
|
|
205
|
-
`)}var
|
|
219
|
+
${I(Bt,{schema:i}).trim()}`;}return t}function xe(n){let e=[...new Set(Object.keys(n).map(c=>c.split("/")[0]))].sort((c,p)=>c==="worker_task"?-1:p==="worker_task"?1:c.localeCompare(p));if(!e.length)return `context/
|
|
220
|
+
(empty)`;let t="worker_task/system_prompt.txt"in n,i="worker_task/schema.json"in n,r=Object.keys(n).some(c=>c.startsWith("worker_task/input/")),s=[];e.forEach((c,p)=>{let o=p===e.length-1,u=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=o?" ":"\u2502 ";if(c==="worker_task"){s.push({line:`${u}${c}/`,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"}),r&&m.push({name:"input/",comment:"worker input files"}),m.forEach((f,g)=>{let y=g===m.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";s.push({line:`${d}${y}${f.name}`,comment:f.comment});});}else if(c.startsWith("candidate_")){let m=c.replace("candidate_","");s.push({line:`${u}${c}/`,comment:`worker ${m} solution`});}else if(c==="worker_output")s.push({line:`${u}${c}/`,comment:"output to verify"});else if(c.startsWith("item_")){let m=c.replace("item_","");s.push({line:`${u}${c}/`,comment:`input ${m}`});}else s.push({line:`${u}${c}/`,comment:""});});let a=Math.max(...s.map(c=>c.line.length)),l=["context/"];for(let c of s)if(c.comment){let p=" ".repeat(a-c.line.length+3);l.push(`${c.line}${p}# ${c.comment}`);}else l.push(c.line);return l.join(`
|
|
221
|
+
`)}var Wt=q.join(os.homedir(),wt),Z=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(Wt,{recursive:true}).catch(()=>{});eventBuffer=[];dashboardQueue=Promise.resolve();flushTimer;constructor(e){this.validateConfig(e),this.provider=e.provider,this.agent=e.agent,this.model=e.model,this.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=E,this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${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(Wt,i),this.parser=F(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
222
|
`)?e:e+`
|
|
207
223
|
`;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
224
|
`;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(!
|
|
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={...be[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 k=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==k)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${k})`);await this.setupAgentAuth(this.sandbox);let b=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!b}),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
|
-
`),b&&t?.onContent)for(let C of b)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}};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}};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,k)=>{a.push(this.getFiles(v)),l.push(this.getIndex(v,k));});let o={};a.forEach((v,k)=>{Object.entries(v).forEach(([b,C])=>{o[`item_${l[k]}/${b}`]=C;});});let u=ge(o),d=I(Ot,{fileTree:u}),m=e.systemPrompt?`${d}
|
|
216
|
-
|
|
217
|
-
${e.systemPrompt}`:d,f=(v,k,b)=>({operationId:r,operation:"reduce",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:t.length,inputIndices:l,errorRetry:k,verifyRetry:b,...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,k,b,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:k,timeoutMs:p,observability:{swarmName:this.config.tag,operationName:e.name,operationId:r,operation:"reduce",role:"worker",errorRetry:b,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),U=f(S,b,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,k,b)=>x(v,k,void 0,b),{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 k=v>1?v-1:void 0,b=k?`${y}-er${k}`:y;return x(i,b,k)},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(k,b)=>{let C=s?await _(S=>this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:b,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a,attempt:S}),s,b):await this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:b,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,b,C.status==="success"?"success":"error"),C})),w=s?await _(k=>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:k}),{...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(k=>k.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,k=u.judgeComposio??u.composio??y,b=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:b,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:k,parentIndex:i,attempt:Q,_pipelineContext:s._pipelineContext}),{...p,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:b,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:k,parentIndex:i,_pipelineContext:s._pipelineContext}),S=b.findIndex(Q=>Q.status==="success"),U=C.decision?.winner??(S>=0?S:0),Ze=b[U]??b[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:b}}}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 _(b=>e(f,b>1?`${x}-er${b-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 _(b=>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:b,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}),k={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:k,attempts:h}};if(h<m){let b=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=n.buildRetryPromptWithFeedback(i,b);}}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 ke(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});}}}},ke=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=ke;exports.VALIDATION_PRESETS=be;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=kn;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;
|
|
225
|
+
`;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>=vt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},xt));}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<=de;i++)try{let r=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(r.ok)return;if(r.status===429||r.status===401||r.status>=500){if(i===de){console.debug(`[SessionLogger] Dashboard ${r.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Le*i);continue}console.debug(`[SessionLogger] Dashboard ${r.status}, dropping events`);return}catch(r){i===de?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",r),this.requeueEvents(e)):await this.delay(Le*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!E.startsWith("https://")&&!E.includes("localhost")&&!E.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 Ce="COMPOSIO_API_KEY";function Gt(n){return new core.Composio({apiKey:process.env[Ce]})}function Ze(n){if(!n?.trim())throw new Error("userId is required and cannot be empty")}async function ke(n,e,t){Ze(n);let i=Gt(),r={};return e?.toolkits&&(r.toolkits=e.toolkits),e?.tools&&(r.tools=e.tools),e?.authConfigs&&(r.authConfigs=e.authConfigs),e?.connectedAccounts&&(r.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(r.manageConnections=e.manageConnections),await i.create(n,Object.keys(r).length>0?r:void 0)}async function Jt(n,e,t,i){Ze(n);let r=Gt(),l=(await r.toolkits.get(e)).authConfigDetails?.find(c=>c.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 r.connectedAccounts.initiate(n,l.name,{config:core.AuthScheme.APIKey({api_key:t})});}async function Qe(n,e){if(Ze(n),e?.keys)for(let[i,r]of Object.entries(e.keys))try{await Jt(n,i,r);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let t=await ke(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 Yt(n){if(!n?.trim())throw new Error("userId is required and cannot be empty")}function vo(){return new core.Composio({apiKey:process.env[Ce]})}async function Ht(n,e){Yt(n);let i=await(await ke(n,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function qt(n,e){let t=await Xe(n),i={};for(let r of t)i[r.toolkit]=r.connected;return e?i[e]??false:i}async function Xe(n){return Yt(n),(await vo().connectedAccounts.list({userIds:[n],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var et={auth:Ht,status:qt,connections:Xe};util.promisify(child_process.exec);var it=util.promisify(child_process.execFile),Xt=Symbol.for("evolve:awsSdkCache"),en=Symbol.for("evolve:s3ClientCache");var Oo=3600,Io=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Mo(n){if(n.startsWith("s3://")){let r=n.slice(5),s=r.indexOf("/");return s===-1?{bucket:r,prefix:""}:{bucket:r.slice(0,s),prefix:r.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 _e(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 r=n?.bucket||"",s=n?.prefix||"",a=n?.endpoint;if(n?.url){let l=Mo(n.url);r=r||l.bucket,s=s||l.prefix,a=a||l.endpoint;}if(!r)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:r,prefix:s,region:n?.region||process.env.AWS_REGION||"us-east-1",endpoint:a,credentials:n?.credentials,mode:"byok"}}function tn(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 Ao(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 be(n){return "'"+n.replace(/'/g,"'\\''")+"'"}function $o(n,e){let t=O(n),i=Ao(e),r=t.checkpointDirs?.length?t.checkpointDirs.map(l=>tn(l)):[tn(t.mcpConfig.settingsDir)],s=[...Io.map(l=>`--exclude=${be(l)}`),`--exclude=${be(i+"/temp")}`].join(" "),a=[be(i+"/"),...r.map(l=>be(l+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${s} ${a}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function W(){let n=globalThis[Xt];if(n)return n;let e="@aws-sdk/client-s3",t="@aws-sdk/s3-request-presigner";try{let[i,r]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(t)]);return globalThis[Xt]={s3:i,presigner:r},{s3:i,presigner:r}}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 X(n){let e=n.credentials?`${n.credentials.accessKeyId}:${n.credentials.secretAccessKey.slice(-4)}`:"env",t=`${n.bucket}:${n.region}:${n.endpoint||""}:${e}`,i=globalThis[en];if(i?.key===t)return i.client;let{s3:r}=await W(),s=new r.S3Client({region:n.region,...n.endpoint&&{endpoint:n.endpoint,forcePathStyle:true},...n.credentials&&{credentials:n.credentials}});return globalThis[en]={client:s,key:t},s}async function un(n,e,t){let{s3:i,presigner:r}=await W(),s=await X(n),a=t==="put"?new i.PutObjectCommand({Bucket:n.bucket,Key:e,ContentType:"application/gzip"}):new i.GetObjectCommand({Bucket:n.bucket,Key:e});return r.getSignedUrl(s,a,{expiresIn:Oo})}async function nn(n,e){let{s3:t}=await W(),i=await X(n);try{return await i.send(new t.HeadObjectCommand({Bucket:n.bucket,Key:e})),!0}catch(r){let s=r?.name||r?.message||"";if(r?.$metadata?.httpStatusCode===404||s==="NotFound"||s==="NoSuchKey")return false;throw r}}async function dn(n,e){let{s3:t}=await W(),s=await(await(await X(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 Do(n,e,t){let{s3:i}=await W();await(await X(n)).send(new i.PutObjectCommand({Bucket:n.bucket,Key:e,Body:JSON.stringify(t,null,2),ContentType:"application/json"}));}function mn(n,e){return `${n.prefix?`${n.prefix}/`:""}data/${e}/archive.tar.gz`}function fn(n,e){return `${n.prefix?`${n.prefix}/`:""}checkpoints/${e}.json`}function Uo(){let n=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${n}_${e}`}async function gn(n,e,t,i){let r=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(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Gateway presign failed (${r.status}): ${s}`)}return r.json()}async function Fo(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 Lo(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 st(n,e,t,i,r){let s=new Date().toISOString(),a=$o(t,i),l=await n.commands.run(a,{timeoutMs:12e4});if(l.exitCode!==0)throw new Error(`Checkpoint tar failed: ${l.stderr}`);let c=l.stdout.trim().split(`
|
|
226
|
+
`).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);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=mn(e,c);if(!await nn(e,m)){let h=await un(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 nn(e,m))throw new Error("Checkpoint upload verification failed (HeadObject)")}d=Uo();let g={id:d,hash:c,tag:r.tag,timestamp:s,sizeBytes:u,agentType:t,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment,sandboxId:n.sandboxId};await Do(e,fn(e,d),g);}else {let m=await gn(e,r.tag,c,"put");if(!m.alreadyExists){let g=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(g.exitCode!==0)throw new Error(`Checkpoint upload failed: ${g.stderr}`)}d=(await Fo(e,{tag:r.tag,hash:c,sizeBytes:u??0,agentType:t,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment})).id;}}finally{await n.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:d,hash:c,tag:r.tag,timestamp:s,sizeBytes:u,agentType:t,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment}}async function hn(n,e,t){let i=await at(e,t),r=i.hash,s={agentType:i.agentType,workspaceMode:i.workspaceMode},a=await xn(e,i),l=await n.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${a}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(l.exitCode!==0)throw new Error(`Checkpoint download failed: ${l.stderr}`);let c=l.stdout.trim().split(`
|
|
227
|
+
`).pop()?.trim();if(c!==r)throw await n.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${r}, got ${c})`);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 yn(n,e){let t=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,i=e?.gatewayUrl||E,r=!n.url&&!n.bucket&&!!t;return _e(n,r,i,t)}async function wn(n,e){let{s3:t}=await W(),i=await X(n),s=`${n.prefix?`${n.prefix}/`:""}checkpoints/`,a=[],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 f of m.Contents)f.Key?.endsWith(".json")&&f.LastModified&&a.push({key:f.Key,lastModified:f.LastModified});l=m.IsTruncated?m.NextContinuationToken:void 0;}while(l);if(a.length===0)return [];a.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 p=!!e?.tag?a:e?.limit?a.slice(0,e.limit):a,u=(await Promise.all(p.map(async d=>{try{return await dn(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 vn(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}`:""}`,r=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${n.gatewayApiKey}`}});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${r.status}): ${s}`)}return r.json()}function No(n){return n&&n>0?Math.min(n,500):100}async function rt(n,e){return n.mode==="byok"?(await wn(n,{limit:1,tag:e?.tag}))[0]??null:(await vn(n,{limit:1,tag:e?.tag}))[0]??null}async function at(n,e){if(n.mode==="byok"){let t=fn(n,e);try{return await dn(n,t)}catch(i){throw Bo(i)?new Error(`Checkpoint ${e} not found`):i}}else return await Lo(n,e)}async function on(n,e,t){if(e==="latest"){let i=await rt(n,{tag:t});if(!i)throw new Error("No checkpoints found");return i.id}return e}async function xn(n,e){if(n.mode==="byok")return un(n,mn(n,e.hash),"get");{let t=await gn(n,e.tag,e.hash,"get");if(!t.url)throw new Error("Gateway presign returned no download URL");return t.url}}function Cn(n){return !(!n||q.isAbsolute(n)||n.startsWith("-")||q.normalize(n).startsWith("..")||n.includes("\0"))}function sn(n,e){let t=q.resolve(n,e),i=q.resolve(n),r=q.relative(i,t);if(r.startsWith("..")||q.isAbsolute(r))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Bo(n){let e=n.name,t=n.message;return n?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||t==="NoSuchKey"}function tt(n){let e=n.filter(t=>!Cn(t));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return n}var kn=10*1024*1024,rn=false;async function bn(){if(!rn)try{await it("tar",["--version"]),rn=!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 an(n,e){let t=await at(n,e),i=await xn(n,t),r=e.replace(/[^a-zA-Z0-9_-]/g,"_"),s=q.join(os.tmpdir(),`evolve-dl-${r}-${Date.now()}.tar.gz`),a=await fetch(i);if(!a.ok)throw new Error(`Checkpoint download failed (${a.status})`);if(!a.body)throw new Error("Checkpoint download returned empty body");let l=crypto.createHash("sha256"),c=P.createWriteStream(s);try{let o=a.body.getReader();await new Promise((u,d)=>{c.on("error",d),c.on("finish",u);async function m(){for(;;){let{done:f,value:g}=await o.read();if(f){c.end();break}l.update(g),c.write(g)||await new Promise(h=>c.once("drain",h));}}m().catch(d);});}catch(o){throw c.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 cn(n){await bn();let{stdout:e}=await it("tar",["-tvzf",n],{maxBuffer:kn}),t=new Set,i=[],r=[];for(let s of e.trim().split(`
|
|
228
|
+
`)){if(!s||s.startsWith("total "))continue;let a=s[0];if(a!=="-"&&a!=="d"&&a!=="l")throw new Error(`Archive contains unsupported entry type: "${a}"`);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 c=l[1];if(a==="l"){let p=c.indexOf(" -> ");p!==-1&&(c=c.slice(0,p)),t.add(c);}else a==="d"?i.push(c.replace(/\/$/,"")):r.push(c);}return tt(i),tt([...t]),tt(r)}async function nt(n,e,t){await bn(),await promises.mkdir(e,{recursive:true});let i=["-xzf",n,"--no-same-owner","--no-same-permissions","-C",e];t?.length&&i.push("--",...t),await it("tar",i,{maxBuffer:kn});}function Ko(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 ct(n,e){let t=yn(n,e);return Sn(t)}function jo(n){let e=yn(n||{});return Sn(e)}function Sn(n){return {async listCheckpoints(e){let t=No(e?.limit);return n.mode==="byok"?wn(n,{limit:t,tag:e?.tag}):vn(n,{limit:t,tag:e?.tag})},async getCheckpoint(e){return at(n,e)},async downloadCheckpoint(e,t){let i=t?.extract!==false,r=t?.to||process.cwd(),s=await on(n,e),{tmpPath:a,metadata:l}=await an(n,s);try{if(i)return await promises.mkdir(r,{recursive:!0}),await cn(a),await nt(a,r),r;{await promises.mkdir(r,{recursive:!0});let c=q.join(r,`checkpoint-${l.id}.tar.gz`);return await promises.copyFile(a,c),c}}finally{await promises.unlink(a).catch(()=>{});}},async downloadFiles(e,t){let i=await on(n,e),{tmpPath:r}=await an(n,i),s;try{let a=await cn(r),l;if(t?.files){let p=t.files.filter(u=>!Cn(u));if(p.length>0)throw new Error(`Unsafe file path requested: ${p[0]}`);let o=new Set(t.files);l=a.filter(u=>o.has(u));}else if(t?.glob){let p=t.glob.map(Ko);l=a.filter(o=>p.some(u=>u.test(o)));}else l=a;if(l.length===0)return {};s=q.join(os.tmpdir(),`evolve-extract-${Date.now()}`);try{await nt(r,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 nt(r,s);}let c={};return await Promise.all(l.map(async p=>{sn(s,p),c[p]=await promises.readFile(q.join(s,p));})),t?.to&&(await promises.mkdir(t.to,{recursive:!0}),await Promise.all(Object.entries(c).map(async([p,o])=>{sn(t.to,p);let u=q.join(t.to,p);await promises.mkdir(q.dirname(u),{recursive:!0}),await promises.writeFile(u,o);}))),c}finally{s&&await promises.rm(s,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(r).catch(()=>{});}}}}function Go(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function _n(n){return `${n}-${crypto.randomBytes(8).toString("hex")}`}function En(n,e){let t=new Map;if(n)for(let i of n.split(/\r?\n/)){let r=i.trim();if(!r)continue;let s=r.indexOf(":");if(s<=0)continue;let a=r.slice(0,s).trim(),l=r.slice(s+1).trim();t.set(a.toLowerCase(),`${a}: ${l}`);}for(let[i,r]of Object.entries(e)){let s=i.toLowerCase();if(s===H&&t.has(s)){let a=t.get(s),l=a.slice(a.indexOf(":")+1).trim();t.set(s,`${i}: ${l},${r}`);}else t.set(s,`${i}: ${r}`);}return Array.from(t.values()).join(`
|
|
229
|
+
`)}var ee=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||yt,this.sandboxState=t.sandboxId?"ready":"stopped",this.skills=t.skills,this.storage=t.storage,t.schema)if(R(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=O(e.type),this.sessionTag=_n(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,r){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,r),s}finalizeOperation(e,t,i,r="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=r,this.emitLifecycle(t,i),true)}watchBackgroundOperation(e,t,i,r){let s=t==="run"?"run_background_complete":"command_background_complete",a=t==="run"?"run_background_failed":"command_background_failed",l=t==="run"?"run_interrupted":"command_interrupted";i.wait().then(c=>{if(this.interruptedOperations.delete(e)||c.exitCode===130){this.finalizeOperation(e,r,l,"interrupted");return}let o=c.exitCode===0?s:a,u=c.exitCode===0?"idle":"error";this.finalizeOperation(e,r,o,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,r,a,"error");});}createAjvValidator(){let t={...Re[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 Vo__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,r=i?i.keyEnv:this.registry.apiKeyEnv,s=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:r;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?dt():B();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;}if(this.options.secrets&&Object.assign(e,this.options.secrets),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let t=this.registry.customHeadersEnv;e[t]=En(e[t],{[Y]:this.sessionTag});}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let t=this.registry.customHeadersEnv;if(t){let r=this.options.secrets?.[t];return {[t]:En(r,{[Y]:this.sessionTag,[H]:`${Fe}${e}`})}}let i=this.registry.spendTrackingEnvs;if(i)return {[i.sessionTagEnv]:this.sessionTag,[i.runTagEnv]:`${Fe}${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",r=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 ${r}`,{timeoutMs:3e4}),!t?.skipSystemPrompt){let a=qe({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,a);}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 a=await Qe(this.options.composio.userId,this.options.composio.config);s={...s,composio:{type:"http",url:a.url,headers:a.headers}};}Object.keys(s).length>0&&await Be(this.agentConfig.type,e,this.workingDir,s),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await Ne(e,this.agentConfig.baseUrl||B(),this.registry.spendTrackingEnvs),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:t}=this.registry,{sourceDir:i,targetDir:r}=t;await e.files.makeDir(r);for(let s of this.skills){let a=`cp -r ${i}/${s} ${r}/ 2>/dev/null || true`;await e.commands.run(a,{timeoutMs:3e4});}}async uploadContextFiles(e,t){let i=Object.entries(t).map(([s,a])=>({path:`${this.workingDir}/context/${s}`,data:a}));if(i.length===0)return;let r=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,t){let i=Object.entries(t).map(([s,a])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:a}));if(i.length===0)return;let r=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:Go(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:r=J,background:s=false,checkpointComment:a}=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 rt(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 x=await hn(this.sandbox,this.storage,l);if(x.agentType&&x.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${x.agentType}, current: ${this.agentConfig.type})`);let b=this.options.workspaceMode||"knowledge";if(x.workspaceMode&&x.workspaceMode!==b)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${x.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(x){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(t,"sandbox_error"),x}}let c=await this.getSandbox(t);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new Z({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:c.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(i);let p=this.buildCommand(i),o=crypto.randomUUID(),u=this.buildRunEnvs(o),d="",m=F(this.agentConfig.type),f=v=>{d+=v;let x=d.split(`
|
|
230
|
+
`);d=x.pop()??"";for(let b of x){if(!b.trim())continue;let S=m(b);if(this.sessionLogger?.writeEventParsed(b,S),t?.onStdout?.(b+`
|
|
231
|
+
`),S&&t?.onContent)for(let M of S)t.onContent(M);}},g=v=>{t?.onStderr?.(v);},h=await c.commands.spawn(p,{cwd:this.workingDir,timeoutMs:r,envs:u,onStdout:f,onStderr:g}),y=this.beginOperation("run",h,t,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(y,"run",h,t),{sandboxId:c.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+`
|
|
232
|
+
`),v&&t?.onContent)for(let x of v)t.onContent(x);}this.sessionLogger&&!s&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let C;if(this.storage&&!s&&w.exitCode===0)try{C=await st(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:a,parentId:this.lastCheckpointId}),this.lastCheckpointId=C.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.sandboxId,runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:C}}async executeCommand(e,t={},i){let{timeoutMs:r=J,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 a=await this.getSandbox(i);this.lastRunTimestamp=Date.now();let l="",c="",p=g=>{l+=g,i?.onStdout?.(g);},o=g=>{c+=g,i?.onStderr?.(g);},u=await a.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,onStdout:p,onStderr:o}),d=this.beginOperation("command",u,i,"command_start");if(s)return this.watchBackgroundOperation(d,"command",u,i),{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with ID ${u.processId}`,stderr:""};let m;try{m=await u.wait();}catch(g){throw this.interruptedOperations.delete(d),this.finalizeOperation(d,i,"command_failed","error"),g}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:a.sandboxId,exitCode:m.exitCode,stdout:l||m.stdout||"",stderr:c||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`,r=e?"":"-maxdepth 1",a=(await t.commands.run(`find ${i} ${r} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
233
|
+
`).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],p=`${i}/`;for(let f of a){let[g,h]=f.split("|");if(!g||!h)continue;let y=parseInt(h,10);l>0&&y<l||c.push(g);}let o={},u=await Promise.all(c.map(async f=>{try{let g=await t.files.read(f);return {relativePath:f.startsWith(p)?f.slice(p.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(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(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 st(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,r=false;try{this.activeCommand?r=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(r=await this.sandbox.commands.kill(this.activeProcessId));}catch{r=false;}if(!r)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),r}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=_n(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||E,r=await fetch(`${i}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Spend query failed (${r.status}): ${s}`)}return r}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}),r=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(r)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let a=new URLSearchParams({tag:t,runId:e.runId}),c=await(await this.fetchSpend(a)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let i=await this.getSessionCost(),r=e.index>0?e.index-1:i.runs.length+e.index,s=i.runs[r];if(!s)throw new Error(`Run index ${e.index} out of range. Session has ${i.runs.length} run(s).`);return s}};var te=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&&(R(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=et;async initializeAgent(){let e=ve(this.config.agent),t=this.config.sandbox??await Ge(),i=e.isDirectMode?{}:ft(e.apiKey),r=this.config.storage!==void 0?_e(this.config.storage,!e.isDirectMode,E,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:r};this.agent=new ee(e,s);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,i=this.listenerCount("content")>0,r=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:r?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:r,checkpointComment:s}){if(r&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let a=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:i,from:r,checkpointComment:s},a)}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=ve(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:E,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return ct(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return ct(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 z=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 L=Symbol.for("evolve.SwarmResult"),G=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 lt=class n{config;semaphore;constructor(e={}){let t=e.concurrency??ht;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 z(this.config.concurrency);}async map(e){let{items:t,prompt:i,bestOf:r,verify:s}=e,a=e.retry??this.config.retry,l=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(r&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let p=await Promise.all(t.map((o,u)=>r?this.executeMapItemWithBestOf(o,i,u,l,e,c,a):s?this.executeMapItemWithVerify(o,i,u,l,e,c,a):a?T(d=>this.executeMapItem(o,i,u,l,e,c,d),a,u):this.executeMapItem(o,i,u,l,e,c)));return G.from(p)}async filter(e){let{items:t,prompt:i,condition:r,verify:s}=e,a=e.retry??this.config.retry,l=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,p=await Promise.all(t.map((u,d)=>s?this.executeFilterItemWithVerify(u,i,d,l,e,c,a):a?T(m=>this.executeFilterItem(u,i,d,l,e,c,m),a,d):this.executeFilterItem(u,i,d,l,e,c))),o=[];for(let u of p)if(u.status==="error")o.push(u);else if(u.data!==null)try{r(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 G.from(o)}async reduce(e){let{items:t,prompt:i,verify:r}=e,s=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,c=[],p=[];t.forEach((C,v)=>{c.push(this.getFiles(C)),p.push(this.getIndex(C,v));});let o={};c.forEach((C,v)=>{Object.entries(C).forEach(([x,b])=>{o[`item_${p[v]}/${x}`]=b;});});let u=xe(o),d=I(Vt,{fileTree:u}),m=e.systemPrompt?`${d}
|
|
234
|
+
|
|
235
|
+
${e.systemPrompt}`:d,f=(C,v,x)=>({operationId:a,operation:"reduce",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:t.length,inputIndices:p,errorRetry:v,verifyRetry:x,...this.pipelineContextToMeta(e._pipelineContext)}),g=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(C,v,x,b)=>{let S=await this.semaphore.use(()=>this.execute(o,C,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:g,skills:h,composio:y,tagPrefix:v,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:e.name,operationId:a,operation:"reduce",role:"worker",errorRetry:x,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),M=f(S,x,b&&b>1?b-1:void 0);return S.error?{status:"error",data:null,files:S.files,meta:M,error:S.error,rawData:S.rawData}:{status:"success",data:S.data,files:S.files,meta:M}},k=`${this.config.tag}-reduce`;return r?this.runWithVerification((C,v,x)=>w(C,v,void 0,x),{originalPrompt:i,inputFiles:o,verifyConfig:r,timeoutMs:l,systemPrompt:m,schema:e.schema,mcpServers:g,skills:h,composio:y,operationId:a,baseTag:k,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?T(C=>{let v=C>1?C-1:void 0,x=v?`${k}-er${v}`:k;return w(i,x,v)},s):w(i,k)}async bestOf(e){let{item:t,prompt:i,config:r}=e,s=e.retry??this.config.retry,a=r.n??r.taskAgents?.length;if(a===void 0)throw new Error("bestOf requires n or taskAgents");if(a<2)throw new Error("bestOf requires n >= 2");let l=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,p=this.getFiles(t),o=r.mcpServers??this.config.mcpServers,u=r.judgeMcpServers??r.mcpServers??this.config.mcpServers,d=r.skills??this.config.skills,m=r.judgeSkills??r.skills??this.config.skills,f=r.composio??this.config.composio,g=r.judgeComposio??r.composio??this.config.composio,h=await Promise.all(Array.from({length:a},async(v,x)=>{let b=s?await T(S=>this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:x,operationId:l,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:c,attempt:S}),s,x):await this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:x,operationId:l,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:c});return r.onCandidateComplete?.(0,x,b.status==="success"?"success":"error"),b})),y=s?await T(v=>this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:h,config:r,timeoutMs:c,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g,attempt:v}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:h,config:r,timeoutMs:c,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);r.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let C={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:a};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:C,candidates:h}}async execute(e,t,i){let r=null,s="",a=i.tagPrefix,l={},c=null,p,o,u={...this.config.agent,...i.agent};try{r=new te().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&r.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&r.withSystemPrompt(i.systemPrompt),i.mcpServers&&r.withMcpServers(i.mcpServers),i.skills?.length&&r.withSkills(i.skills),i.composio&&r.withComposio(i.composio.userId,i.composio.config),i.observability&&r.withObservability(i.observability),Object.keys(e).length>0&&r.withContext(e);let d=await r.run({prompt:t,timeoutMs:i.timeoutMs});s=d.sandboxId,a=r.getSessionTag()??i.tagPrefix;let m=null;try{m=await r.getOutputFiles(!0),l=m.files;}catch{}d.exitCode!==0?p=`Agent exited with code ${d.exitCode}`:i.schema?m?(c=m.data,m.error&&(p=m.error),m.rawData&&(o=m.rawData)):p="Failed to read output files from sandbox":c=l;}catch(d){if(p=d.message,r){a=r.getSessionTag()??i.tagPrefix;try{l=(await r.getOutputFiles(!0)).files;}catch{}}}finally{r&&await r.kill().catch(()=>{});}return {files:l,data:c,tag:a,sandboxId:s,error:p,rawData:o}}async executeMapItem(e,t,i,r,s,a,l=1){let c=this.getFiles(e),p=l>1?`${this.config.tag}-map-${i}-er${l-1}`:`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(t,c,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:r,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,f=await this.semaphore.use(()=>this.execute(c,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"map",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),g={operationId:r,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(f,g)}async executeMapItemWithVerify(e,t,i,r,s,a,l){let c=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,f=this.evaluatePrompt(t,c,i);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:i});let g=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:y,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"map",itemIndex:i,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),C={operationId:r,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,C)};return this.runWithVerification(g,{originalPrompt:f,inputFiles:c,verifyConfig:o,timeoutMs:a,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:r,baseTag:p,retry:l,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,t,i,r,s,a,l){let c=this.getFiles(e),p=`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(t,c,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:r,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:r,operation:"map",tag:p,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,y=u.skills??h,w=u.judgeSkills??u.skills??h,k=s.composio??this.config.composio,C=u.composio??k,v=u.judgeComposio??u.composio??k,x=await Promise.all(Array.from({length:d},async(ne,oe)=>{let ut=l?await T(Rn=>this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:oe,operationId:r,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:y,composio:C,timeoutMs:a,parentIndex:i,attempt:Rn,_pipelineContext:s._pipelineContext}),l,oe):await this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:oe,operationId:r,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:y,composio:C,timeoutMs:a,parentIndex:i,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(i,oe,ut.status==="success"?"success":"error"),ut})),b=l?await T(ne=>this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:x,config:u,timeoutMs:a,operationId:r,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:w,composio:v,parentIndex:i,attempt:ne,_pipelineContext:s._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:x,config:u,timeoutMs:a,operationId:r,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:w,composio:v,parentIndex:i,_pipelineContext:s._pipelineContext}),S=x.findIndex(ne=>ne.status==="success"),M=b.decision?.winner??(S>=0?S:0),pt=x[M]??x[0];u.onJudgeComplete?.(i,M,b.decision?.reasoning??"Judge failed to provide reasoning");let Tn={operationId:r,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...pt,meta:{...pt.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:M,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Tn,candidates:x}}}async executeFilterItem(e,t,i,r,s,a,l=1){let c=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(c,t,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:u,composio:d,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"filter",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:r,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,f,c)}async executeFilterItemWithVerify(e,t,i,r,s,a,l){let c=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,f=async(g,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,g,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:h,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"filter",itemIndex:i,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),k={operationId:r,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,c)};return this.runWithVerification(f,{originalPrompt:t,inputFiles:c,verifyConfig:o,timeoutMs:a,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:r,baseTag:p,retry:l,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:t,prompt:i,candidateIndex:r,operationId:s,config:a,timeoutMs:l,parentIndex:c,attempt:p=1,_pipelineContext:o}=e,u=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${r}`:`${this.config.tag}-bestof-cand-${r}`,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:a.taskAgents?.[r],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:c,role:"candidate",candidateIndex:r,errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(o)}})),f={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:r,errorRetry:p>1?p-1:void 0,candidateIndex:r,...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,r)=>{i.status==="error"&&(t[`candidate_${r}/_failed.txt`]=`STATUS: FAILED
|
|
236
|
+
|
|
237
|
+
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,a])=>{t[`candidate_${r}/${s}`]=a;});}),t}async executeBestOfJudge(e){let{candidates:t,config:i,timeoutMs:r,operationId:s,parentIndex:a,attempt:l=1,_pipelineContext:c}=e,p=a!==void 0?`${this.config.tag}-map-${a}-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=xe(u),m=I(Je,{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,Kt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(c)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let y=JSON.parse(g.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: ${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,r])=>{t[`worker_output/${i}`]=r;}),t}async executeVerify(e){let{config:t,timeoutMs:i,operationId:r,workerTag:s,retryAttempt:a=1,operation:l,itemIndex:c,attemptIndex:p,_pipelineContext:o}=e,u=a>1?`${s}-verifier-er${a-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=xe(g),y=I(Ye,{criteria:t.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(g,jt,{systemPrompt:y,schema:n.VerifyDecisionSchema,agent:t.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:r,operation:l,itemIndex:c,role:"verifier",verifyRetry:p&&p>1?p-1:void 0,errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let C=JSON.parse(w.rawData);k={passed:!!C.passed,reasoning:C.reasoning??"Verification completed",feedback:C.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 I(He,{originalPrompt:e,feedback:t})}async runWithVerification(e,t){let{originalPrompt:i,inputFiles:r,verifyConfig:s,timeoutMs:a,operationId:l,baseTag:c,retry:p,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 w=h>1?`${c}-vr${h-1}`:c,k=p?await T(x=>e(f,x>1?`${w}-er${x-1}`:w,h),p,o):await e(f,w,h);if(s.onWorkerComplete?.(o,h,k.status==="error"?"error":"success"),k.status==="error")return k;g=k;let C=p?await T(x=>this.executeVerify({inputFiles:r,outputFiles:k.files,taskPrompt:f,config:s,timeoutMs:a,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:l,workerTag:w,retryAttempt:x,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...p,retryOn:void 0}):await this.executeVerify({inputFiles:r,outputFiles:k.files,taskPrompt:f,config:s,timeoutMs:a,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:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,C.decision?.passed??false,C.decision?.feedback),C.decision?.passed)return {...k,verify:{passed:true,reasoning:C.decision.reasoning,verifyMeta:v,attempts:h}};if(h<m){let x=C.decision?.feedback??C.decision?.reasoning??"Output did not meet criteria";f=n.buildRetryPromptWithFeedback(i,x);}}let y=h>1?`${c}-vr${h-1}`:c;return {...g,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(r){return r}}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"]=R(e.schema)?K(e.schema):j(e.schema)),Object.entries(e.inputFiles).forEach(([i,r])=>{t[`worker_task/input/${i}`]=r;}),t}isSwarmResult(e){return typeof e=="object"&&e!==null&&L in e&&e[L]===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 r=i??e.files;return e.error?{[L]:true,status:"error",data:null,files:r,meta:t,error:e.error,rawData:e.rawData}:{[L]:true,status:"success",data:e.data,files:r,meta:t}}buildErrorResult(e,t){return {[L]:true,status:"error",data:null,files:{},meta:t,error:e}}};var Ee=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 Te(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=[],r=e,s=Date.now();for(let l=0;l<this.steps.length;l++){let c=this.steps[l],p=c.config.name,o=Date.now();this.events.onStepStart?.({type:c.type,index:l,name:p,itemCount:r.length});let u={pipelineRunId:t,pipelineStepIndex:l};try{let d=await this.executeStep(c,r,l,p,u),m=Date.now()-o;if(i.push({type:c.type,index:l,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:c.type,index:l,name:p,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),c.type==="reduce")return {pipelineRunId:t,steps:i,output:d.output,totalDurationMs:Date.now()-s};r=d.nextItems;}catch(d){throw this.events.onStepError?.({type:c.type,index:l,name:p,error:d instanceof Error?d:new Error(String(d))}),d}}let a=i[i.length-1];return {pipelineRunId:t,steps:i,output:a?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,t,i,r,s){if(e.type==="map"){let c=e.config,p=await this.swarm.map({items:t,...c,_pipelineContext:s,retry:this.wrapRetry(c.retry,i,r),verify:this.wrapVerify(c.verify,i,r),bestOf:this.wrapBestOf(c.bestOf,i,r)});return {output:[...p],nextItems:p.success,successCount:p.success.length,errorCount:p.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,p=await this.swarm.filter({items:t,...c,_pipelineContext:s,retry:this.wrapRetry(c.retry,i,r),verify:this.wrapVerify(c.verify,i,r)}),o=c.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 a=e.config,l=await this.swarm.reduce({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,r),verify:this.wrapVerify(a.verify,i,r)});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:(r,s,a)=>{e.onItemRetry?.(r,s,a),this.events.onItemRetry?.({stepIndex:t,stepName:i,itemIndex:r,attempt:s,error:a});}}}wrapVerify(e,t,i){if(e)return {...e,onWorkerComplete:(r,s,a)=>{e.onWorkerComplete?.(r,s,a),this.events.onWorkerComplete?.({stepIndex:t,stepName:i,itemIndex:r,attempt:s,status:a});},onVerifierComplete:(r,s,a,l)=>{e.onVerifierComplete?.(r,s,a,l),this.events.onVerifierComplete?.({stepIndex:t,stepName:i,itemIndex:r,attempt:s,passed:a,feedback:l});}}}wrapBestOf(e,t,i){if(e)return {...e,onCandidateComplete:(r,s,a)=>{e.onCandidateComplete?.(r,s,a),this.events.onCandidateComplete?.({stepIndex:t,stepName:i,itemIndex:r,candidateIndex:s,status:a});},onJudgeComplete:(r,s,a)=>{e.onJudgeComplete?.(r,s,a),this.events.onJudgeComplete?.({stepIndex:t,stepName:i,itemIndex:r,winnerIndex:s,reasoning:a});}}}},Te=class n extends Ee{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=Pe;exports.AGENT_TYPES=Pn;exports.Agent=ee;exports.Evolve=te;exports.JUDGE_PROMPT=Je;exports.Pipeline=Ee;exports.RETRY_FEEDBACK_PROMPT=He;exports.SCHEMA_PROMPT=Bt;exports.SWARM_RESULT_BRAND=L;exports.SYSTEM_PROMPT=Nt;exports.Semaphore=z;exports.Swarm=lt;exports.SwarmResultList=G;exports.TerminalPipeline=Te;exports.VALIDATION_PRESETS=Re;exports.VERIFY_PROMPT=Ye;exports.WORKSPACE_PROMPT=Ft;exports.WORKSPACE_SWE_PROMPT=Lt;exports.applyTemplate=I;exports.buildWorkerSystemPrompt=qe;exports.createAgentParser=F;exports.createClaudeParser=fe;exports.createCodexParser=ge;exports.createGeminiParser=he;exports.executeWithRetry=T;exports.expandPath=Oe;exports.getAgentConfig=O;exports.getMcpSettingsDir=$;exports.getMcpSettingsPath=A;exports.isValidAgentType=On;exports.isZodSchema=R;exports.jsonSchemaToString=j;exports.parseNdjsonLine=Hn;exports.parseNdjsonOutput=qn;exports.parseQwenOutput=St;exports.readLocalDir=_t;exports.resolveStorageConfig=_e;exports.saveLocalDir=Et;exports.storage=jo;exports.writeClaudeMcpConfig=re;exports.writeCodexMcpConfig=me;exports.writeGeminiMcpConfig=ae;exports.writeMcpConfig=Be;exports.writeQwenMcpConfig=ce;exports.zodSchemaToJson=K;
|