@evolvingmachines/sdk 0.0.21 → 0.0.23
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 +55 -49
- package/dist/index.d.cts +194 -6
- package/dist/index.d.ts +194 -6
- package/dist/index.js +55 -49
- package/package.json +20 -2
package/dist/index.cjs
CHANGED
|
@@ -1,32 +1,36 @@
|
|
|
1
|
-
'use strict';var events=require('events'),tn=require('ajv'),At=require('zod-to-json-schema'),P=require('fs'),Y=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 tn__default=/*#__PURE__*/_interopDefault(tn);var At__default=/*#__PURE__*/_interopDefault(At);var P__namespace=/*#__PURE__*/_interopNamespace(P);var Y__namespace=/*#__PURE__*/_interopNamespace(Y);var kt={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen"},he={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var ye={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"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},availableBetas:{CONTEXT_1M:"context-1m-2025-08-07"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.claude/skills"},buildCommand:({prompt:c,model:e,isResume:n,betas:i})=>{let a=n?"--continue ":"",s=i?.length?`--betas ${i.join(",")} `:"";return `echo "${c}" | claude -p ${a}${s}--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:c,model:e,isResume:n,reasoningEffort:i})=>{let a=i?` -c model_reasoning_effort="${i}"`:"";return `printf '%s' "${c}" | codex exec --model ${e}${a} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3-flash-preview",models:[{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Latest 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:c,model:e,isResume:n})=>`gemini "${c}" ${n?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3-coder-plus",models:[{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:c,model:e,isResume:n,isDirectMode:i,skills:a})=>{let s=n?"--continue ":"",o=a?.length?"--experimental-skills ":"",l=i||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${c}" ${s}${o}--auth-type openai --model ${l} --yolo --output-format stream-json`}}};function O(c){let e=ye[c];if(!e)throw new Error(`Unknown agent type: ${c}`);return e}function _t(c){return c in ye}function ve(c){return c.replace(/^~/,"/home/user")}function $(c){let e=O(c);return `${ve(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function U(c){let e=O(c);return ve(e.mcpConfig.settingsDir)}function V(c){if(c instanceof Error){let e=c.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function be(c,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${c}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${c}" cannot specify both command and url`)}function xe(c){for(let[e,n]of Object.entries(c))be(e,n);}function Se(c){return c.type?c.type:c.command?"stdio":"sse"}function Tt(c){let e=Se(c);return {...c,type:e}}function Rt(c){let{type:e,url:n,...i}=c;return Se(c)==="http"&&n?{httpUrl:n,...i}:n?{url:n,...i}:i}function Pt(c){return {type:Se(c),...c}}async function Be(c,e,n,i){xe(n);let a=U(e),s=$(e);await c.files.makeDir(a);let o={};try{let r=await c.files.read(s);typeof r=="string"&&(o=JSON.parse(r));}catch(r){if(!V(r))throw r}let l=Object.fromEntries(Object.entries(n).map(([r,p])=>[r,i(p)]));await c.files.write(s,JSON.stringify({...o,mcpServers:l},null,2));}async function Q(c,e,n){xe(n);let i=U("claude"),a=$("claude"),s=Object.fromEntries(Object.entries(n).map(([l,r])=>[l,Pt(r)]));await c.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await c.files.makeDir(i);let o={};try{let l=await c.files.read(a);typeof l=="string"&&(o=JSON.parse(l));}catch(l){if(!V(l))throw l}o.enableAllProjectMcpServers=true,await c.files.write(a,JSON.stringify(o,null,2));}async function X(c,e){await Be(c,"gemini",e,Tt);}async function ee(c,e){await Be(c,"qwen",e,Rt);}function T(c){return typeof c=="string"?`"${c.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(c)?`[${c.map(e=>T(e)).join(", ")}]`:typeof c=="object"&&c!==null?`{ ${Object.entries(c).map(([n,i])=>`${n} = ${T(i)}`).join(", ")} }`:typeof c=="boolean"?c?"true":"false":String(c)}async function te(c,e){for(let[r,p]of Object.entries(e))be(r,p);let n=U("codex"),i=$("codex");await c.files.makeDir(n);let a="";try{let r=await c.files.read(i);typeof r=="string"&&(a=r);}catch(r){if(!V(r))throw r}let s=[],o=[];a.includes("experimental_use_rmcp_client")||(s.push("# Enable improved RMCP client (recommended)"),s.push("experimental_use_rmcp_client = true")),a.includes("[mcp_servers]")||o.push("[mcp_servers]","");for(let[r,p]of Object.entries(e)){if(a.includes(`[mcp_servers.${r}]`))continue;o.push(`[mcp_servers.${r}]`);let t=p.type??(p.command?"stdio":"http");if(t==="http"||t==="sse"||!!p.url){if(!p.url)throw new Error(`MCP server "${r}" is missing url for ${t} transport`);o.push(`url = ${T(p.url)}`),p.bearerTokenEnvVar&&o.push(`bearer_token_env_var = ${T(p.bearerTokenEnvVar)}`);let d=p.httpHeaders??p.headers;d&&Object.keys(d).length>0&&o.push(`http_headers = ${T(d)}`),p.envHttpHeaders&&Object.keys(p.envHttpHeaders).length>0&&o.push(`env_http_headers = ${T(p.envHttpHeaders)}`);}else o.push(`command = ${T(p.command)}`),p.args&&p.args.length>0&&o.push(`args = ${T(p.args)}`),p.cwd&&o.push(`cwd = ${T(p.cwd)}`);p.env&&Object.keys(p.env).length>0&&o.push(`env = ${T(p.env)}`),p.envVars&&p.envVars.length>0&&o.push(`env_vars = ${T(p.envVars)}`),o.push("");}let l=[a.trim(),s.join(`
|
|
2
|
-
`),
|
|
3
|
-
`)].filter(
|
|
1
|
+
'use strict';var events=require('events'),Ln=require('ajv'),rn=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 Ln__default=/*#__PURE__*/_interopDefault(Ln);var rn__default=/*#__PURE__*/_interopDefault(rn);var R__namespace=/*#__PURE__*/_interopNamespace(R);var G__namespace=/*#__PURE__*/_interopNamespace(G);var Yt={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode"},ke={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Ce={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-6",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-5-20250929",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},availableBetas:{CONTEXT_1M:"context-1m-2025-08-07"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.claude/skills"},buildCommand:({prompt:o,model:e,isResume:t,betas:s})=>{let r=t?"--continue ":"",n=s?.length?`--betas ${s.join(",")} `:"";return `echo "${o}" | claude -p ${r}${n}--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:o,model:e,isResume:t,reasoningEffort:s})=>{let r=s?` -c model_reasoning_effort="${s}"`:"";return `printf '%s' "${o}" | 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-pro-preview",modelId:"gemini-3-pro-preview",description:"Latest 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:o,model:e,isResume:t})=>`gemini "${o}" ${t?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3-coder-plus",models:[{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:o,model:e,isResume:t,isDirectMode:s,skills:r})=>{let n=t?"--continue ":"",a=r?.length?"--experimental-skills ":"",p=s||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${o}" ${n}${a}--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:o,model:e,isResume:t})=>`KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${t?"--continue ":""}--prompt "${o}"`},opencode:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openai/gpt-5.2",providerEnvMap:{anthropic:{keyEnv:"ANTHROPIC_API_KEY"},openai:{keyEnv:"OPENAI_API_KEY"},google:{keyEnv:"GEMINI_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"anthropic/claude-sonnet-4-5",modelId:"anthropic/claude-sonnet-4-5",description:"Balanced coding, features, tests"},{alias:"anthropic/claude-opus-4-6",modelId:"anthropic/claude-opus-4-6",description:"Complex reasoning, R&D"},{alias:"openai/gpt-5.2",modelId:"openai/gpt-5.2",description:"OpenAI flagship"},{alias:"google/gemini-3-pro-preview",modelId:"google/gemini-3-pro-preview",description:"Google latest reasoning"}],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:o,model:e,isResume:t})=>`OPENCODE_PERMISSION='{"*":"allow"}' opencode run "${o}" ${t?"--continue ":""}--model ${e} --format json < /dev/null`}};function P(o){let e=Ce[o];if(!e)throw new Error(`Unknown agent type: ${o}`);return e}function Ht(o){return o in Ce}function Se(o){return o.replace(/^~/,"/home/user")}function F(o){let e=P(o);return `${Se(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function L(o){let e=P(o);return Se(e.mcpConfig.settingsDir)}function N(o){if(o instanceof Error){let e=o.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function _e(o,e){let t=[e.command,e.url].filter(Boolean);if(t.length===0)throw new Error(`MCP server "${o}" must specify command or url`);if(t.length>1)throw new Error(`MCP server "${o}" cannot specify both command and url`)}function ee(o){for(let[e,t]of Object.entries(o))_e(e,t);}function te(o){return o.type?o.type:o.command?"stdio":"sse"}function qt(o){let e=te(o);return {...o,type:e}}function Zt(o){let{type:e,url:t,...s}=o;return te(o)==="http"&&t?{httpUrl:t,...s}:t?{url:t,...s}:s}function qe(o){return {type:te(o),...o}}async function Te(o,e,t,s){ee(t);let r=L(e),n=F(e);await o.files.makeDir(r);let a={};try{let c=await o.files.read(n);typeof c=="string"&&(a=JSON.parse(c));}catch(c){if(!N(c))throw c}let p=Object.fromEntries(Object.entries(t).map(([c,l])=>[c,s(l)]));await o.files.write(n,JSON.stringify({...a,mcpServers:p},null,2));}async function ne(o,e,t){ee(t);let s=L("claude"),r=F("claude"),n=Object.fromEntries(Object.entries(t).map(([p,c])=>[p,qe(c)]));await o.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:n},null,2)),await o.files.makeDir(s);let a={};try{let p=await o.files.read(r);typeof p=="string"&&(a=JSON.parse(p));}catch(p){if(!N(p))throw p}a.enableAllProjectMcpServers=true,await o.files.write(r,JSON.stringify(a,null,2));}async function ie(o,e){await Te(o,"gemini",e,qt);}async function oe(o,e){await Te(o,"qwen",e,Zt);}async function Ee(o,e){await Te(o,"kimi",e,qe);}async function Re(o,e,t){ee(t);let s=`${e}/opencode.json`,r={};try{let a=await o.files.read(s);typeof a=="string"&&(r=JSON.parse(a));}catch(a){if(!N(a))throw a}let n=Object.fromEntries(Object.entries(t).map(([a,p])=>[a,Qt(p)]));await o.files.write(s,JSON.stringify({...r,mcp:n},null,2));}function Qt(o){let e=te(o);if(e==="stdio"&&o.command){let s={type:"local",command:o.args?[o.command,...o.args]:[o.command]};return o.env&&Object.keys(o.env).length>0&&(s.environment=o.env),s}if(o.url){let t={type:"remote",url:o.url};return o.headers&&Object.keys(o.headers).length>0&&(t.headers=o.headers),t}return {type:e==="stdio"?"local":"remote",...o}}function T(o){return typeof o=="string"?`"${o.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(o)?`[${o.map(e=>T(e)).join(", ")}]`:typeof o=="object"&&o!==null?`{ ${Object.entries(o).map(([t,s])=>`${t} = ${T(s)}`).join(", ")} }`:typeof o=="boolean"?o?"true":"false":String(o)}async function se(o,e){for(let[c,l]of Object.entries(e))_e(c,l);let t=L("codex"),s=F("codex");await o.files.makeDir(t);let r="";try{let c=await o.files.read(s);typeof c=="string"&&(r=c);}catch(c){if(!N(c))throw c}let n=[],a=[];r.includes("experimental_use_rmcp_client")||(n.push("# Enable improved RMCP client (recommended)"),n.push("experimental_use_rmcp_client = true")),r.includes("[mcp_servers]")||a.push("[mcp_servers]","");for(let[c,l]of Object.entries(e)){if(r.includes(`[mcp_servers.${c}]`))continue;a.push(`[mcp_servers.${c}]`);let i=l.type??(l.command?"stdio":"http");if(i==="http"||i==="sse"||!!l.url){if(!l.url)throw new Error(`MCP server "${c}" is missing url for ${i} transport`);a.push(`url = ${T(l.url)}`),l.bearerTokenEnvVar&&a.push(`bearer_token_env_var = ${T(l.bearerTokenEnvVar)}`);let u=l.httpHeaders??l.headers;u&&Object.keys(u).length>0&&a.push(`http_headers = ${T(u)}`),l.envHttpHeaders&&Object.keys(l.envHttpHeaders).length>0&&a.push(`env_http_headers = ${T(l.envHttpHeaders)}`);}else a.push(`command = ${T(l.command)}`),l.args&&l.args.length>0&&a.push(`args = ${T(l.args)}`),l.cwd&&a.push(`cwd = ${T(l.cwd)}`);l.env&&Object.keys(l.env).length>0&&a.push(`env = ${T(l.env)}`),l.envVars&&l.envVars.length>0&&a.push(`env_vars = ${T(l.envVars)}`),a.push("");}let p=[r.trim(),n.join(`
|
|
2
|
+
`),a.join(`
|
|
3
|
+
`)].filter(c=>c.length>0);await o.files.write(s,p.join(`
|
|
4
4
|
|
|
5
5
|
`)+`
|
|
6
|
-
`);}async function
|
|
7
|
-
`+
|
|
6
|
+
`);}async function Pe(o,e,t,s){if(!(!s||Object.keys(s).length===0))switch(o){case "claude":await ne(e,t,s);break;case "codex":await se(e,s);break;case "gemini":await ie(e,s);break;case "qwen":await oe(e,s);break;case "kimi":await Ee(e,s);break;case "opencode":await Re(e,t,s);break;default:throw new Error(`Unknown agent type for MCP config: ${o}`)}}function re(){let o={};return function(l){let i;try{i=JSON.parse(l);}catch{return null}if(i._meta||i._prompt)return null;let d=i.session_id;switch(i.type){case "system":return null;case "assistant":return e(i.message?.content,"assistant",d);case "user":{let u=i.message?.content;return typeof u=="string"||Array.isArray(u)&&u.length===1&&u[0].type==="text"?null:e(u,"user",d)}case "result":return null;default:return null}};function e(c,l,i){if(typeof c=="string")return l==="user"?null:[{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let d=[];for(let u of c){let m=null;switch(u.type){case "text":case "text_delta":if(l==="user")break;m={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(l==="user")break;m={sessionUpdate:"agent_message_chunk",content:{type:"image",data:u.source?.type==="base64"?u.source.data:"",mimeType:u.source?.type==="base64"?u.source.media_type:"",uri:u.source?.type==="url"?u.source.url:void 0}};break;case "thinking":case "thinking_delta":m={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(o[u.id]=u,u.name==="TodoWrite")Array.isArray(u.input?.todos)&&(m={sessionUpdate:"plan",entries:a(u.input)});else {let f=t(u);m={sessionUpdate:"tool_call",toolCallId:u.id,status:"pending",...f};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let f=o[u.tool_use_id];if(!f||(delete o[u.tool_use_id],f.name==="TodoWrite"))break;m={sessionUpdate:"tool_call_update",toolCallId:u.tool_use_id,status:"is_error"in u&&u.is_error?"failed":"completed",...s(u,f)};break}}m&&d.push({sessionId:i,update:m});}return d.length>0?d:null}function t(c){let l=c.name,i=c.input||{};switch(l){case "Task":return {title:i.description||"Task",kind:"think",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "NotebookRead":return {title:i.notebook_path?`Read Notebook ${i.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "NotebookEdit":return {title:i.notebook_path?`Edit Notebook ${i.notebook_path}`:"Edit Notebook",kind:"edit",content:i.new_source?[{type:"content",content:{type:"text",text:i.new_source}}]:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "Bash":return {title:i.command?"`"+i.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:i.description?[{type:"content",content:{type:"text",text:i.description}}]:[],rawInput:i};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:i};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:i};case "Read":{let d="";return i.limit?d=" ("+((i.offset??0)+1)+" - "+((i.offset??0)+i.limit)+")":i.offset&&(d=" (from line "+(i.offset+1)+")"),{title:"Read "+(i.file_path??"File")+d,kind:"read",content:[],locations:i.file_path?[{path:i.file_path,line:i.offset??0}]:[],rawInput:i}}case "LS":return {title:i.path?`List \`${i.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:i};case "Edit":{let d=i.file_path;return {title:d?`Edit \`${d}\``:"Edit",kind:"edit",content:d?[{type:"diff",path:d,oldText:i.old_string??null,newText:i.new_string??""}]:[],locations:d?[{path:d}]:[],rawInput:i}}case "Write":return {title:i.file_path?`Write ${i.file_path}`:"Write",kind:"edit",content:i.file_path?[{type:"diff",path:i.file_path,oldText:null,newText:i.content??""}]:[],locations:i.file_path?[{path:i.file_path}]:[],rawInput:i};case "Glob":{let d="Find";return i.path&&(d+=` \`${i.path}\``),i.pattern&&(d+=` \`${i.pattern}\``),{title:d,kind:"search",content:[],locations:i.path?[{path:i.path}]:[],rawInput:i}}case "Grep":{let d="grep";return i["-i"]&&(d+=" -i"),i["-n"]&&(d+=" -n"),i["-A"]!==void 0&&(d+=` -A ${i["-A"]}`),i["-B"]!==void 0&&(d+=` -B ${i["-B"]}`),i["-C"]!==void 0&&(d+=` -C ${i["-C"]}`),i.output_mode==="files_with_matches"?d+=" -l":i.output_mode==="count"&&(d+=" -c"),i.head_limit!==void 0&&(d+=` | head -${i.head_limit}`),i.glob&&(d+=` --include="${i.glob}"`),i.type&&(d+=` --type=${i.type}`),i.multiline&&(d+=" -P"),d+=` "${i.pattern??""}"`,i.path&&(d+=` ${i.path}`),{title:d,kind:"search",content:[],rawInput:i}}case "WebFetch":return {title:i.url?`Fetch ${i.url}`:"Fetch",kind:"fetch",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "WebSearch":{let d=`"${i.query??""}"`;return i.allowed_domains?.length>0&&(d+=` (allowed: ${i.allowed_domains.join(", ")})`),i.blocked_domains?.length>0&&(d+=` (blocked: ${i.blocked_domains.join(", ")})`),{title:d,kind:"fetch",content:[],rawInput:i}}case "TodoWrite":return {title:Array.isArray(i.todos)?`Update TODOs: ${i.todos.map(d=>d.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:i};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:i.plan?[{type:"content",content:{type:"text",text:i.plan}}]:[],rawInput:i};default:if(l?.startsWith("mcp__")){let d=l.split("__"),u=d[1]||"mcp",m=d.slice(2).join("__")||l;return {title:`${u}: ${m}`,kind:"other",content:[],rawInput:i}}return {title:l||"Unknown Tool",kind:"other",content:[],rawInput:i}}}function s(c,l){let i=c.content;switch(l?.name){case "Read":return Array.isArray(i)&&i.length>0?{content:i.map(d=>({type:"content",content:d.type==="text"?{type:"text",text:p(d.text)}:n(d,false)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:p(i)}}]}:{};case "Edit":case "Write":case "Bash":return r(i,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return r(i,"is_error"in c?c.is_error:false)}}function r(c,l=false){return Array.isArray(c)&&c.length>0?{content:c.map(i=>({type:"content",content:n(i,l)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:l?"```\n"+c+"\n```":c}}]}:{}}function n(c,l){if(c.type==="text")return l?{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(l=>({content:l.content,status:l.status||"pending",priority:"medium"}))}function p(c){let l="```",i=Array.from(c.matchAll(/^```+/gm));for(let[d]of i)for(;d.length>=l.length;)l+="`";return l+`
|
|
7
|
+
`+c+(c.endsWith(`
|
|
8
8
|
`)?"":`
|
|
9
|
-
`)+
|
|
10
|
-
`)??
|
|
11
|
-
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:
|
|
12
|
-
${
|
|
13
|
-
\`\`\``:
|
|
14
|
-
${
|
|
15
|
-
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:
|
|
16
|
-
${
|
|
17
|
-
\`\`\``:d}});
|
|
18
|
-
${
|
|
19
|
-
\`\`\``:
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
9
|
+
`)+l}}function ae(){return function(c){let l;try{l=JSON.parse(c);}catch{return null}if(l._meta||l._prompt)return null;let i=[];switch(l.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let d=l.item;if(!d)return null;let u=e(d);u&&i.push({update:u});break}case "item.updated":{let d=l.item;if(!d)return null;let u=t(d);u&&i.push({update:u});break}case "item.completed":{let d=l.item;if(!d)return null;let u=s(d);u&&i.push({update:u});break}default:return null}return i.length>0?i:null};function e(p){let c=p.id;switch(p.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${p.server}:${p.tool}`},{sessionUpdate:"tool_call",toolCallId:c,title:`${p.server}: ${p.tool}`,kind:"other",status:"in_progress",rawInput:p.arguments,content:[]};case "command_execution":return {type:"command_execution",name:p.command},{sessionUpdate:"tool_call",toolCallId:c,title:p.command?`\`${p.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:p.command},content:[]};case "web_search":return {type:"web_search",name:p.query},{sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${p.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(p.items)};default:return null}}function t(p){return p.type==="todo_list"?{sessionUpdate:"plan",entries:a(p.items)}:null}function s(p){let c=p.id;switch(p.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.text??p.summary?.join(`
|
|
10
|
+
`)??p.content?.join(`
|
|
11
|
+
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text??""}};case "mcp_tool_call":{let i=r(p.result),d=p.status==="failed"||p.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:d,content:i}}case "command_execution":{let i=p.aggregated_output?[{type:"content",content:{type:"text",text:p.aggregated_output}}]:[],d=p.status==="completed"||p.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:d,content:i}}case "file_change":{let i=p.changes??[],d=i.map(m=>({path:m.path})),u=i.length===1?`${i[0].kind==="add"?"Create":"Edit"} ${i[0].path}`:`Edit ${i.length} files`;return {sessionUpdate:"tool_call",toolCallId:c,title:u,kind:"edit",status:p.status==="completed"?"completed":"failed",content:i.map(m=>({type:"diff",path:m.path,oldText:m.kind==="add"?null:"",newText:""})),locations:d}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${p.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(p.items)};default:return null}}function r(p){return p?.content?Array.isArray(p.content)?p.content.map(c=>({type:"content",content:n(c)})):typeof p.content=="string"?[{type:"content",content:{type:"text",text:p.content}}]:[]:[]}function n(p){return p.type==="text"?{type:"text",text:p.text??""}:p.type==="image"?{type:"image",data:p.data??"",mimeType:p.mime_type??p.mimeType??"",uri:p.uri}:p}function a(p){if(!Array.isArray(p))return [];let c=false;return p.map(l=>{let i;return l.completed?i="completed":c?i="pending":(i="in_progress",c=true),{content:l.text??"",status:i,priority:"medium"}})}}var Xt={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 ce(){return function(a){let p;try{p=JSON.parse(a);}catch{return null}if(p._meta||p._prompt)return null;let c=p.session_id,l=[];switch(p.type){case "init":case "result":return null;case "message":{let i=o(p);i&&l.push({sessionId:c,update:i});break}case "tool_use":{let i=e(p);i&&l.push({sessionId:c,update:i});break}case "tool_result":{let i=t(p);i&&l.push({sessionId:c,update:i});break}case "error":{let i=s(p);i&&l.push({sessionId:c,update:i});break}default:return null}return l.length>0?l:null};function o(n){let a=n.role,p=n.content;return p?a==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}:a==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:p}}:null:null}function e(n){let a=n.tool_id,p=n.tool_name,c=n.parameters||{},{title:l,kind:i,content:d,locations:u}=r(p,c);return {sessionUpdate:"tool_call",toolCallId:a,title:l,kind:i,status:"pending",rawInput:c,content:d,locations:u}}function t(n){let a=n.tool_id,p=n.status,c=n.output,l=n.error,i=[];return c&&typeof c=="string"&&c.length>0&&i.push({type:"content",content:{type:"text",text:p==="error"?`\`\`\`
|
|
12
|
+
${c}
|
|
13
|
+
\`\`\``:c}}),l?.message&&!c&&i.push({type:"content",content:{type:"text",text:`\`\`\`
|
|
14
|
+
${l.message}
|
|
15
|
+
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:a,status:p==="success"?"completed":"failed",content:i}}function s(n){let a=n.severity,p=n.message;return p?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${p}`}}:null}function r(n,a){let p=Xt[n]||"other",c=[],l=[],i=n;switch(n){case "read_file":i=`Read ${a.absolute_path||a.file_path||"file"}`,(a.absolute_path||a.file_path)&&l.push({path:a.absolute_path||a.file_path});break;case "write_file":i=`Write ${a.file_path||"file"}`,a.file_path&&(l.push({path:a.file_path}),c.push({type:"diff",path:a.file_path,oldText:null,newText:a.content||""}));break;case "edit_file":i=`Edit ${a.file_path||"file"}`,a.file_path&&l.push({path:a.file_path});break;case "replace":i=`Edit ${a.file_path||"file"}`,a.file_path&&(l.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":i=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":i=a.query?`"${a.query}"`:"Web search";break;case "web_fetch":i=a.prompt?`Fetch: ${a.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${a.pattern||"files"}`,a.dir_path&&l.push({path:a.dir_path});break;case "grep":case "search_file_content":i=`grep "${a.pattern||a.query||""}"`;break;case "list_directory":i=`List ${a.dir_path||a.path||"directory"}`,(a.dir_path||a.path)&&l.push({path:a.dir_path||a.path});break;case "read_many_files":i=`Read ${a.include?.length||"multiple"} files`,Array.isArray(a.include)&&a.include.forEach(d=>l.push({path:d}));break;case "delegate_to_agent":i=a.agent_name?`Agent: ${a.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=a.fact?`Remember: "${a.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=a.name?`Activate skill: ${a.name}`:"Activate skill";break;default:i=n;}return {title:i,kind:p,content:c,locations:l}}}var en={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(){return function(n){let a;try{a=JSON.parse(n);}catch{return null}if(!a||typeof a!="object"||"_meta"in a||"_prompt"in a)return null;let p=a.role;return p==="assistant"?o(a):p==="tool"?e(a):typeof a.type=="string"&&"payload"in a?t(a):null};function o(r){let n=[],a=r.content,p=r.tool_calls;if(typeof a=="string"&&a.length>0)n.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}});else if(Array.isArray(a))for(let c of a)!c||typeof c!="object"||(c.type==="think"&&typeof c.think=="string"&&c.think.length>0?n.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c.think}}}):c.type==="text"&&typeof c.text=="string"&&c.text.length>0&&n.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c.text}}}));if(Array.isArray(p))for(let c of p){if(!c||typeof c!="object")continue;let l=c.function;if(!l)continue;let i=c.id??"",d=l.name??"",u;try{u=l.arguments?JSON.parse(l.arguments):{};}catch{u=l.arguments;}let{title:m,kind:f,toolContent:g,locations:h}=s(d,typeof u=="object"&&u!==null?u:{});n.push({update:{sessionUpdate:"tool_call",toolCallId:i,title:m,kind:f,status:"pending",rawInput:u,content:g,locations:h}});}return n.length>0?n:null}function e(r){let n=r.tool_call_id;if(!n)return null;let a=r.content,p=[],c=false;if(typeof a=="string")c=a.includes("<error>")||a.includes("ToolError"),a.length>0&&p.push({type:"content",content:{type:"text",text:a}});else if(Array.isArray(a))for(let l of a)!l||typeof l!="object"||l.type==="text"&&typeof l.text=="string"&&l.text.length>0&&((l.text.includes("<error>")||l.text.includes("ToolError"))&&(c=true),p.push({type:"content",content:{type:"text",text:l.text}}));return [{update:{sessionUpdate:"tool_call_update",toolCallId:n,status:c?"failed":"completed",content:p}}]}function t(r){let n=r.type,a=r.payload??{},p=[];switch(n){case "TextPart":{let c=a.text;typeof c=="string"&&c.length>0&&p.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}});break}case "ThinkPart":{let c=a.think;typeof c=="string"&&c.length>0&&p.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c}}});break}case "ToolCall":{let c=a.id,l=a.function;if(!l)break;let i=l.name??"",d;try{d=l.arguments?JSON.parse(l.arguments):{};}catch{d=l.arguments;}let{title:u,kind:m,toolContent:f,locations:g}=s(i,typeof d=="object"&&d!==null?d:{});p.push({update:{sessionUpdate:"tool_call",toolCallId:c,title:u,kind:m,status:"pending",rawInput:d,content:f,locations:g}});break}case "ToolResult":{let c=a.tool_call_id;if(!c)break;let l=a.return_value??a.content,i=l?.type==="ToolError"||a.is_error===true,d=[],u=l?.output??l?.message??"";typeof u=="string"&&u.length>0&&d.push({type:"content",content:{type:"text",text:i?`\`\`\`
|
|
16
|
+
${u}
|
|
17
|
+
\`\`\``:u}}),p.push({update:{sessionUpdate:"tool_call_update",toolCallId:c,status:i?"failed":"completed",content:d}});break}default:return null}return p.length>0?p:null}function s(r,n){let a=en[r]||"other",p=[],c=[],l=r;switch(r){case "ReadFile":{let i=n.path??n.file_path;l=`Read ${i||"file"}`,i&&c.push({path:i});break}case "ReadMediaFile":{let i=n.path??n.file_path;l=`Read media ${i||"file"}`,i&&c.push({path:i});break}case "WriteFile":{let i=n.path??n.file_path;l=`Write ${i||"file"}`,i&&(c.push({path:i}),typeof n.content=="string"&&p.push({type:"diff",path:i,oldText:null,newText:n.content}));break}case "StrReplaceFile":{let i=n.path??n.file_path;l=`Edit ${i||"file"}`,i&&c.push({path:i});break}case "Shell":l=n.command?`\`${n.command}\``:"Run command";break;case "Glob":l=`Find ${n.pattern||"files"}`,n.path&&c.push({path:n.path});break;case "Grep":l=`grep "${n.pattern||""}"`,n.path&&c.push({path:n.path});break;case "SearchWeb":l=n.query?`"${n.query}"`:"Web search";break;case "FetchURL":l=n.url?`Fetch ${n.url}`:"Web fetch";break;case "Task":l=n.description||"Subagent task";break;case "Think":l=n.thought||"Thinking";break;case "CreateSubagent":l=n.name?`Subagent: ${n.name}`:"Create subagent";break;case "SetTodoList":l="Update todos";break;default:l=r;}return {title:l,kind:a,toolContent:p,locations:c}}}var tn={read:"read",write:"edit",edit:"edit",apply_patch:"edit",bash:"execute",glob:"search",grep:"search",list:"search",codesearch:"search",webfetch:"fetch",websearch:"fetch",task:"think",todoread:"other",todowrite:"other",skill:"other"};function Oe(){return function(n){let a;try{a=JSON.parse(n);}catch{return null}if(!a||typeof a!="object")return null;let p=a.sessionID,c=[];switch(a.type){case "step_start":case "step_finish":return null;case "text":{let l=o(a);l&&c.push({sessionId:p,update:l});break}case "tool_use":{let l=e(a);for(let i of l)c.push({sessionId:p,update:i});break}case "error":{let l=t(a);l&&c.push({sessionId:p,update:l});break}default:return null}return c.length>0?c:null};function o(r){let n=r.part?.text;return typeof n!="string"||n.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:n}}}function e(r){let n=r.part;if(!n)return [];let a=n.callID,p=n.tool??"",c=n.state??{},l=c.input??{},i=c.output,d=c.title??c.metadata?.description??p,u=c.status,m=c.metadata?.exit,{kind:f,content:g,locations:h}=s(p,l),b=[];b.push({sessionUpdate:"tool_call",toolCallId:a,title:d,kind:f,status:"pending",rawInput:l,content:g,locations:h});let x=u==="error"||m!==void 0&&m!==0,y=[];return typeof i=="string"&&i.length>0&&y.push({type:"content",content:{type:"text",text:x?`\`\`\`
|
|
18
|
+
${i}
|
|
19
|
+
\`\`\``:i}}),b.push({sessionUpdate:"tool_call_update",toolCallId:a,status:x?"failed":"completed",content:y}),b}function t(r){let n=r.error?.name??"Error",a=r.error?.data?.message??r.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${n}: ${a}`}}}function s(r,n){let a=tn[r]||"other",p=[],c=[];switch(r){case "read":{let l=n.filePath??n.path;l&&c.push({path:l});break}case "write":{let l=n.filePath??n.path;l&&(c.push({path:l}),typeof n.content=="string"&&p.push({type:"diff",path:l,oldText:null,newText:n.content}));break}case "edit":{let l=n.filePath??n.path;l&&(c.push({path:l}),(n.oldString!==void 0||n.newString!==void 0)&&p.push({type:"diff",path:l,oldText:n.oldString??"",newText:n.newString??""}));break}case "apply_patch":break;case "bash":{n.command&&n.description&&p.push({type:"content",content:{type:"text",text:n.description}});break}case "glob":case "list":{let l=n.path;l&&c.push({path:l});break}case "grep":case "codesearch":{let l=n.path;l&&c.push({path:l});break}}return {kind:a,content:p,locations:c}}}var nn={Read:"read",read_file:"read",Write:"edit",Edit:"edit",write_file:"edit",edit_file:"edit",Bash:"execute",BashOutput:"execute",KillShell:"execute",shell:"execute",run_shell_command:"execute",WebFetch:"fetch",WebSearch:"fetch",brave_web_search:"fetch",Glob:"search",Grep:"search",LS:"search",list_directory:"search",Task:"think",TodoWrite:"other",ExitPlanMode:"switch_mode"};function le(){let o=new Map,e=new Map;return function(i){let d;try{d=JSON.parse(i);}catch{return null}if(!d||typeof d!="object")return null;let u=d;if("_meta"in u||"_prompt"in u)return null;let m=u.session_id||void 0,f=[];switch(u.type){case "assistant":{let g=t(u);for(let h of g)f.push({sessionId:m,update:h});break}case "stream_event":{let g=s(u);for(let h of g)f.push({sessionId:m,update:h});break}case "user":{let g=r(u);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(l){let i=[],d=l.message?.content;if(!Array.isArray(d))return i;for(let u of d){let m=n(u);i.push(...m);}return i}function s(l){let i=[],d=l.event;if(!d)return i;switch(d.type){case "content_block_start":{let u=d.index??0,m=d.content_block;m&&(o.set(u,m),m.type==="tool_use"&&e.set(u,""));break}case "content_block_delta":{let u=d.index??0,m=d.delta,f=o.get(u);if(m?.type==="text_delta"&&m.text)i.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:m.text}});else if(m?.type==="thinking_delta"&&m.thinking)i.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(u)||"";e.set(u,g+m.partial_json);}break}case "content_block_stop":{let u=d.index??0,m=o.get(u);if(m&&!(m.type==="text"&&m.text)){if(!(m.type==="thinking"&&m.thinking)){if(m.type==="tool_use"){let f=m,g=e.get(u)||"";e.delete(u);let h=f.input;if(g)try{h=JSON.parse(g);}catch{}let b={...f,input:h},x=a(b);x&&i.push(x);}else if(m.type==="tool_result"){let f=p(m);f&&i.push(f);}}}o.delete(u);break}}return i}function r(l){let i=l.message?.content,d=[];if(typeof i=="string")return d.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:i}}),d;if(Array.isArray(i)){for(let u of i)if(u.type==="text")d.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:u.text}});else if(u.type==="tool_result"){let m=p(u);m&&d.push(m);}}return d}function n(l){switch(l.type){case "text":return l.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text}}]:[];case "thinking":return l.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.thinking}}]:[];case "tool_use":{let i=a(l);return i?[i]:[]}case "tool_result":{let i=p(l);return i?[i]:[]}}}function a(l){let i=l.id,d=l.name,u=l.input;if(d==="TodoWrite"&&Array.isArray(u?.todos))return {sessionUpdate:"plan",entries:u.todos.map(b=>({content:b.content,status:b.status||"pending",priority:"medium"}))};let{title:m,kind:f,content:g,locations:h}=c(d,u||{});return {sessionUpdate:"tool_call",toolCallId:i,title:m,kind:f,status:"pending",rawInput:u,content:g,locations:h}}function p(l){let i=l.tool_use_id,d=l.is_error??false,u=l.content,m=[];if(typeof u=="string"&&u.length>0)m.push({type:"content",content:{type:"text",text:d?`\`\`\`
|
|
20
|
+
${u}
|
|
21
|
+
\`\`\``:u}});else if(Array.isArray(u)){for(let f of u)if(f.type==="text"){let g=f.text;m.push({type:"content",content:{type:"text",text:d?`\`\`\`
|
|
22
|
+
${g}
|
|
23
|
+
\`\`\``:g}});}}return {sessionUpdate:"tool_call_update",toolCallId:i,status:d?"failed":"completed",content:m}}function c(l,i){let d=nn[l]||"other",u=[],m=[],f=l;switch(l){case "Read":case "read_file":f=`Read ${i.file_path||i.absolute_path||"file"}`,(i.file_path||i.absolute_path)&&m.push({path:i.file_path||i.absolute_path});break;case "Write":case "write_file":f=`Write ${i.file_path||"file"}`,i.file_path&&(m.push({path:i.file_path}),u.push({type:"diff",path:i.file_path,oldText:null,newText:i.content||""}));break;case "Edit":case "edit_file":f=`Edit ${i.file_path||"file"}`,i.file_path&&m.push({path:i.file_path});break;case "Bash":case "shell":case "run_shell_command":f=i.command?`\`${i.command}\``:"Run command",i.description&&u.push({type:"content",content:{type:"text",text:i.description}});break;case "WebFetch":f=i.url?`Fetch ${i.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=i.query?`"${i.query}"`:"Web search";break;case "Glob":f=`Find ${i.pattern||"files"}`,i.path&&m.push({path:i.path});break;case "Grep":f=`grep "${i.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${i.path||"directory"}`,i.path&&m.push({path:i.path});break;case "Task":f=i.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=l;}return {title:f,kind:d,content:u,locations:m}}}function Ze(o){return le()(o)}function M(o){switch(o){case "claude":return re();case "codex":return ae();case "gemini":return ce();case "qwen":return le();case "kimi":return Ie();case "opencode":return Oe();default:return ()=>null}}function on(o,e){let t=e.trim();return t?M(o)(t):null}function sn(o,e){let t=[],s=e.split(`
|
|
24
|
+
`),r=M(o);for(let n of s){let a=n.trim();if(!a)continue;let p=r(a);p&&t.push(...p);}return t}function J(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function Qe(){return `${J()}`}function Xe(){return `${J()}/e2b`}function et(o){return {"browser-use":{type:"http",url:`${J()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${o}`}}}}var A="EVOLVE_API_KEY",pe="E2B_API_KEY",de="DAYTONA_API_KEY",ue="MODAL_TOKEN_ID",Me="MODAL_TOKEN_SECRET",tt="claude",z=36e5,nt=4,Ae=100,it="/home/user/workspace",I=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",ot=".evolve-sdk/observability/sessions",st=100,rt=5e3,me=3,$e=1e3;function E(o){return o!==null&&typeof o=="object"&&"safeParse"in o&&typeof o.safeParse=="function"}function B(o){return JSON.stringify(rn__default.default(o,{target:"jsonSchema7"}),null,2)}function K(o){return JSON.stringify(o,null,2)}function at(o,e=false){let t={};function s(r,n){for(let a of R__namespace.readdirSync(r)){let p=G__namespace.join(r,a),c=n?`${n}/${a}`:a;R__namespace.statSync(p).isDirectory()?e&&s(p,c):t[c]=R__namespace.readFileSync(p);}}return s(o,""),t}function ct(o,e){for(let[t,s]of Object.entries(e)){let r=G__namespace.join(o,t),n=G__namespace.dirname(r);R__namespace.mkdirSync(n,{recursive:true});let a;s instanceof ArrayBuffer||s instanceof Uint8Array?a=Buffer.from(s):a=s,R__namespace.writeFileSync(r,a);}}function an(o){let e=o.replace(/^~/,process.env.HOME||"");if(!R__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return R__namespace.readFileSync(e,"utf-8")}function De(o){let e=o?.type??tt,t=P(e);if(o?.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:o.oauthToken,isDirectMode:true,isOAuth:true,model:o.model,reasoningEffort:o.reasoningEffort,betas:o.betas}}if(o?.providerApiKey){let a=o.providerBaseUrl??process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:o.providerApiKey,baseUrl:a,isDirectMode:true,model:o.model,reasoningEffort:o.reasoningEffort,betas:o.betas}}if(o?.apiKey)return {type:e,apiKey:o.apiKey,isDirectMode:false,model:o.model,reasoningEffort:o.reasoningEffort,betas:o.betas};let s=process.env[A];if(s)return {type:e,apiKey:s,isDirectMode:false,model:o?.model,reasoningEffort:o?.reasoningEffort,betas:o?.betas};if(t.providerEnvMap){let p=(o?.model??t.defaultModel)?.split("/")[0],c=p?t.providerEnvMap[p]:void 0,l=c?process.env[c.keyEnv]:void 0;if(l){let i=process.env[t.baseUrlEnv]??t.defaultBaseUrl;return {type:e,apiKey:l,baseUrl:i,isDirectMode:true,model:o?.model,reasoningEffort:o?.reasoningEffort,betas:o?.betas}}}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:o?.model,reasoningEffort:o?.reasoningEffort,betas:o?.betas}}if(t.oauthEnv){let a=process.env[t.oauthEnv];if(a){if(t.oauthFileName){let p=an(a);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:p,model:o?.model,reasoningEffort:o?.reasoningEffort,betas:o?.betas}}return {type:e,apiKey:a,isDirectMode:true,isOAuth:true,model:o?.model,reasoningEffort:o?.reasoningEffort,betas:o?.betas}}}let n=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)${n}, or ${A} / ${t.apiKeyEnv} env var.`)}async function Ue(){let o=process.env[pe];if(o)try{let{createE2BProvider:n}=await import('@evolvingmachines/e2b');return n({apiKey:o})}catch(n){let a=n;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${pe} is set but @evolvingmachines/e2b failed to load.
|
|
25
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):a}let e=process.env[de];if(e)try{let{createDaytonaProvider:n}=await import('@evolvingmachines/daytona');return n({apiKey:e})}catch(n){let a=n;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${de} is set but @evolvingmachines/daytona failed to load.
|
|
26
|
+
Try installing: npm install @evolvingmachines/daytona`):a}let t=process.env[ue],s=process.env[Me];if(t&&s)try{let{createModalProvider:n}=await import('@evolvingmachines/modal');return n({tokenId:t,tokenSecret:s})}catch(n){let a=n;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${ue} is set but @evolvingmachines/modal failed to load.
|
|
27
|
+
Try installing: npm install @evolvingmachines/modal`):a}let r=process.env[A];if(r)try{let{createE2BProvider:n}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=Xe(),n({apiKey:r})}catch(n){let a=n;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${A} is set but @evolvingmachines/e2b failed to load.
|
|
28
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):a}throw new Error(`No sandbox provider configured. Either:
|
|
29
|
+
1. Set ${A} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
30
|
+
2. Set ${pe} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
31
|
+
3. Set ${de} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
32
|
+
4. Set ${ue} and ${Me} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
33
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function cn(o){return new Promise(e=>setTimeout(e,o))}async function _(o,e,t=0){let s=ln(e),r=e?.onItemRetry,n=null,a=0,p=s.backoffMs;for(;a<s.maxAttempts;){if(a++,n=await o(a),!s.retryOn(n))return n;if(a>=s.maxAttempts)break;if(r){let c=n.error??"Unknown error";r(t,a,c);}await cn(p),p*=s.backoffMultiplier;}return n}function ln(o){return {maxAttempts:o?.maxAttempts??3,backoffMs:o?.backoffMs??1e3,backoffMultiplier:o?.backoffMultiplier??2,retryOn:o?.retryOn??(e=>e.status==="error")}}var lt=`## FILESYSTEM INSTRUCTIONS:
|
|
30
34
|
|
|
31
35
|
You are running in a sandbox environment.
|
|
32
36
|
|
|
@@ -59,7 +63,7 @@ Examples:
|
|
|
59
63
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
60
64
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
61
65
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
62
|
-
`;var
|
|
66
|
+
`;var pt=`## FILESYSTEM INSTRUCTIONS:
|
|
63
67
|
|
|
64
68
|
You are running in a sandbox environment.
|
|
65
69
|
|
|
@@ -93,9 +97,9 @@ Examples:
|
|
|
93
97
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
94
98
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
95
99
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
96
|
-
`;var
|
|
100
|
+
`;var dt=`## SYSTEM PROMPT
|
|
97
101
|
|
|
98
|
-
{{systemPrompt}}`;var
|
|
102
|
+
{{systemPrompt}}`;var ut=`## STRUCTURED OUTPUT
|
|
99
103
|
|
|
100
104
|
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
101
105
|
|
|
@@ -113,7 +117,7 @@ You are free to:
|
|
|
113
117
|
But your final \`output/result.json\` MUST conform to the schema above.
|
|
114
118
|
|
|
115
119
|
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
116
|
-
### Never just state results as text.`;var
|
|
120
|
+
### Never just state results as text.`;var mt=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
117
121
|
|
|
118
122
|
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.
|
|
119
123
|
|
|
@@ -143,7 +147,7 @@ You must judge their work based on:
|
|
|
143
147
|
5. Pick the best candidate (0-indexed)
|
|
144
148
|
|
|
145
149
|
**IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
|
|
146
|
-
`;var
|
|
150
|
+
`;var ft=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
147
151
|
|
|
148
152
|
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.
|
|
149
153
|
|
|
@@ -176,14 +180,14 @@ The output must satisfy:
|
|
|
176
180
|
**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.
|
|
177
181
|
|
|
178
182
|
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
179
|
-
`;var
|
|
183
|
+
`;var gt=`### CONTEXT STRUCTURE
|
|
180
184
|
|
|
181
185
|
\`\`\`
|
|
182
186
|
{{fileTree}}
|
|
183
187
|
\`\`\`
|
|
184
188
|
|
|
185
189
|
Examine all files within each item folder before producing your output.
|
|
186
|
-
`;var
|
|
190
|
+
`;var ht="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var yt="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var vt=`{{originalPrompt}}
|
|
187
191
|
|
|
188
192
|
## IMPORTANT: Previous Attempt Failed Verification
|
|
189
193
|
|
|
@@ -192,24 +196,26 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
192
196
|
{{feedback}}
|
|
193
197
|
|
|
194
198
|
Make sure your output addresses all the feedback points above.
|
|
195
|
-
`;var
|
|
199
|
+
`;var bt=lt,xt=pt,wt=dt,kt=ut,Fe=mt,Ct=ht,Le=ft,St=yt,_t=gt,Ne=vt;function O(o,e){let t=o;for(let[s,r]of Object.entries(e))t=t.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),r);return t}function Be(o){let e=o.mode==="swe"?xt:bt,t=O(e,{workingDir:o.workingDir}).trim();if(o.systemPrompt&&(t+=`
|
|
196
200
|
|
|
197
201
|
|
|
198
|
-
${
|
|
202
|
+
${O(wt,{systemPrompt:o.systemPrompt}).trim()}`),o.schema){let s=E(o.schema)?B(o.schema):K(o.schema);t+=`
|
|
199
203
|
|
|
200
204
|
|
|
201
|
-
${
|
|
202
|
-
(empty)`;let
|
|
203
|
-
`)}var
|
|
205
|
+
${O(kt,{schema:s}).trim()}`;}return t}function ge(o){let e=[...new Set(Object.keys(o).map(c=>c.split("/")[0]))].sort((c,l)=>c==="worker_task"?-1:l==="worker_task"?1:c.localeCompare(l));if(!e.length)return `context/
|
|
206
|
+
(empty)`;let t="worker_task/system_prompt.txt"in o,s="worker_task/schema.json"in o,r=Object.keys(o).some(c=>c.startsWith("worker_task/input/")),n=[];e.forEach((c,l)=>{let i=l===e.length-1,d=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=i?" ":"\u2502 ";if(c==="worker_task"){n.push({line:`${d}${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"}),s&&m.push({name:"schema.json",comment:"expected output schema"}),r&&m.push({name:"input/",comment:"worker input files"}),m.forEach((f,g)=>{let b=g===m.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";n.push({line:`${u}${b}${f.name}`,comment:f.comment});});}else if(c.startsWith("candidate_")){let m=c.replace("candidate_","");n.push({line:`${d}${c}/`,comment:`worker ${m} solution`});}else if(c==="worker_output")n.push({line:`${d}${c}/`,comment:"output to verify"});else if(c.startsWith("item_")){let m=c.replace("item_","");n.push({line:`${d}${c}/`,comment:`input ${m}`});}else n.push({line:`${d}${c}/`,comment:""});});let a=Math.max(...n.map(c=>c.line.length)),p=["context/"];for(let c of n)if(c.comment){let l=" ".repeat(a-c.line.length+3);p.push(`${c.line}${l}# ${c.comment}`);}else p.push(c.line);return p.join(`
|
|
207
|
+
`)}var Tt=G.join(os.homedir(),ot),Y=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(Tt,{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=I,this.observability=e.observability;let t=e.tagPrefix||"evolve";this.tag=`${t}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let s=this.timestamp.replace(/[:.]/g,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${s}.jsonl`;this.localFilePath=G.join(Tt,r),this.parser=M(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 s of t)this.bufferForDashboard(s);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let t=this.parser(e);if(t)for(let s of t)this.bufferForDashboard(s);}}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(`
|
|
204
208
|
`)?e:e+`
|
|
205
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(
|
|
206
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(
|
|
207
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=Ge){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},He));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let i=1;i<=le;i++)try{let a=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(a.ok)return;if(a.status===429||a.status===401||a.status>=500){if(i===le){console.debug(`[SessionLogger] Dashboard ${a.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(_e*i);continue}console.debug(`[SessionLogger] Dashboard ${a.status}, dropping events`);return}catch(a){i===le?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",a),this.requeueEvents(e)):await this.delay(_e*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!J.startsWith("https://")&&!J.includes("localhost")&&!J.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var de="COMPOSIO_API_KEY";function yt(c){return new core.Composio({apiKey:process.env[de]})}function Me(c){if(!c?.trim())throw new Error("userId is required and cannot be empty")}async function me(c,e,n){Me(c);let i=yt(),a={};return e?.toolkits&&(a.toolkits=e.toolkits),e?.tools&&(a.tools=e.tools),e?.authConfigs&&(a.authConfigs=e.authConfigs),e?.connectedAccounts&&(a.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(a.manageConnections=e.manageConnections),await i.create(c,Object.keys(a).length>0?a:void 0)}async function vt(c,e,n,i){Me(c);let a=yt(),l=(await a.toolkits.get(e)).authConfigDetails?.find(r=>r.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 a.connectedAccounts.initiate(c,l.name,{config:core.AuthScheme.APIKey({api_key:n})});}async function Ae(c,e){if(Me(c),e?.keys)for(let[i,a]of Object.entries(e.keys))try{await vt(c,i,a);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let n=await me(c,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function bt(c){if(!c?.trim())throw new Error("userId is required and cannot be empty")}function en(){return new core.Composio({apiKey:process.env[de]})}async function xt(c,e){bt(c);let i=await(await me(c,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function St(c,e){let n=await De(c),i={};for(let a of n)i[a.toolkit]=a.connected;return e?i[e]??false:i}async function De(c){return bt(c),(await en().connectedAccounts.list({userIds:[c],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var Fe={auth:xt,status:St,connections:De};function nn(c){return c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}var G=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;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||Ye,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,n.schema)if(R(n.schema))this.zodSchema=n.schema,n.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=n.schema,this.schemaOptions=n.schemaOptions;try{let i=this.createAjvValidator();this.compiledValidator=i.compile(this.jsonSchema);}catch(i){throw new Error(`Invalid JSON Schema: ${i.message}`)}}this.registry=O(e.type);}emitLifecycle(e,n){e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,i,a){let s=++this.nextOperationId;return this.activeOperationId=s,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(i,a),s}finalizeOperation(e,n,i,a="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=a,this.emitLifecycle(n,i),true)}watchBackgroundOperation(e,n,i,a){let s=n==="run"?"run_background_complete":"command_background_complete",o=n==="run"?"run_background_failed":"command_background_failed",l=n==="run"?"run_interrupted":"command_interrupted";i.wait().then(r=>{if(this.interruptedOperations.delete(e)||r.exitCode===130){this.finalizeOperation(e,a,l,"interrupted");return}let t=r.exitCode===0?s:o,u=r.exitCode===0?"idle":"error";this.finalizeOperation(e,a,t,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,a,o,"error");});}createAjvValidator(){let n={...he[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 tn__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, context, files, and systemPrompt"),this.sandbox=await n.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 n.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 {let n=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:this.registry.apiKeyEnv;e[n]=this.agentConfig.apiKey;}return this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth?this.agentConfig.baseUrl&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl):this.agentConfig.isDirectMode||(e[this.registry.baseUrlEnv]=this.registry.usePassthroughGateway?je():K(),e.EVOLVE_API_KEY=this.agentConfig.apiKey),this.options.secrets&&Object.assign(e,this.options.secrets),e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e){let n=this.options.workspaceMode||"knowledge",i=n==="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`;await e.commands.run(`mkdir -p ${i}`,{timeoutMs:3e4});let a=Ie({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:n}),s=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(s,a),this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let o={...this.options.mcpServers};if(this.options.composio){let l=await Ae(this.options.composio.userId,this.options.composio.config);o={...o,composio:{type:"http",url:l.url,headers:l.headers}};}Object.keys(o).length>0&&await Ce(this.agentConfig.type,e,this.workingDir,o),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:i,targetDir:a}=n;await e.files.makeDir(a);for(let s of this.skills){let o=`cp -r ${i}/${s} ${a}/ 2>/dev/null || true`;await e.commands.run(o,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let i=Object.entries(n).map(([s,o])=>({path:`${this.workingDir}/context/${s}`,data:o}));if(i.length===0)return;let a=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));a.size>0&&await e.commands.run(`mkdir -p ${Array.from(a).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,n){let i=Object.entries(n).map(([s,o])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:o}));if(i.length===0)return;let a=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));a.size>0&&await e.commands.run(`mkdir -p ${Array.from(a).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:nn(e),model:this.agentConfig.model||this.registry.defaultModel,isResume:this.hasRun,reasoningEffort:this.agentConfig.reasoningEffort,betas:this.agentConfig.betas,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,n){let{prompt:i,timeoutMs:a=W,background:s=false}=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.");let o=await this.getSandbox(n);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let g=this.options.sandboxProvider;this.sessionLogger=new z({provider:g?.name||g?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:o.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),r="",p=I(this.agentConfig.type),t=g=>{r+=g;let y=r.split(`
|
|
208
|
-
`);
|
|
209
|
-
`),x&&n?.onContent)for(let b of x)n.onContent(b);}},u=g=>{n?.onStderr?.(g);},d=await o.commands.spawn(l,{cwd:this.workingDir,timeoutMs:a,onStdout:t,onStderr:u}),m=this.beginOperation("run",d,n,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(m,"run",d,n),{sandboxId:o.sandboxId,exitCode:0,stdout:`Background process started with ID ${d.processId}`,stderr:""};let f;try{f=await d.wait();}catch(g){throw this.interruptedOperations.delete(m),this.finalizeOperation(m,n,"run_failed","error"),g}if(this.interruptedOperations.delete(m)||f.exitCode===130?this.finalizeOperation(m,n,"run_interrupted","interrupted"):f.exitCode===0?this.finalizeOperation(m,n,"run_complete","idle"):this.finalizeOperation(m,n,"run_failed","error"),r.trim()){let g=p(r);if(this.sessionLogger?.writeEventParsed(r,g),n?.onStdout?.(r+`
|
|
210
|
-
`)
|
|
211
|
-
`).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,r=[],p=`${i}/`;for(let f of o){let[h,g]=f.split("|");if(!h||!g)continue;let y=parseInt(g,10);l>0&&y<l||r.push(h);}let t={},u=await Promise.all(r.map(async f=>{try{let h=await n.files.read(f);return {relativePath:f.startsWith(p)?f.slice(p.length):f.split("/").pop()||f,content:h}}catch{return null}}));for(let f of u)f&&(t[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:t,data:null};let d=t["result.json"];if(!d)return {files:t,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 h=this.zodSchema.safeParse(f);return h.success?{files:t,data:h.data}:{files:t,data:null,error:`Schema validation failed: ${h.error.message}`,rawData:m}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:t,data:f};{let g=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:t,data:null,error:`Schema validation failed: ${g}`,rawData:m}}}return {files:t,data:null}}catch(f){return {files:t,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:m}}}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;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,i=this.activeOperationKind,a=false;try{this.activeCommand?a=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(a=await this.sandbox.commands.kill(this.activeProcessId));}catch{a=false;}if(!a)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let s=i==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,s),a}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.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 H=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e),this}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,n){return this.config.schema=e,n&&(R(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}static composio=Fe;async initializeAgent(){let e=Te(this.config.agent),n=this.config.sandbox??await Re(),i=e.isDirectMode?{}:Ke(e.apiKey),a={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...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};this.agent=new G(e,a);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,i=this.listenerCount("content")>0,a=this.listenerCount("lifecycle")>0;return {onStdout:e?s=>this.emit("stdout",s):void 0,onStderr:n?s=>this.emit("stderr",s):void 0,onContent:i?s=>this.emit("content",s):void 0,onLifecycle:a?s=>this.emit("lifecycle",s):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let n=this.status();this.emit("lifecycle",{sandboxId:n.sandboxId,sandbox:n.sandbox,agent:n.agent,timestamp:new Date().toISOString(),reason:e});}async run({prompt:e,timeoutMs:n,background:i}){this.agent||await this.initializeAgent();let a=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:i},a)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let i=this.createStreamCallbacks();return this.agent.executeCommand(e,n,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)}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 N=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 A=Symbol.for("evolve.SwarmResult"),j=class c extends Array{get success(){return this.filter(e=>e.status==="success")}get filtered(){return this.filter(e=>e.status==="filtered")}get error(){return this.filter(e=>e.status==="error")}static from(e){let n=new c;return n.push(...e),n}};var $e=class c{config;semaphore;constructor(e={}){let n=e.concurrency??Je;if(n>ke)throw new Error(`concurrency=${n} exceeds max ${ke}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:n,timeoutMs:e.timeoutMs??W,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new N(this.config.concurrency);}async map(e){let{items:n,prompt:i,bestOf:a,verify:s}=e,o=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs;if(a&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let p=await Promise.all(n.map((t,u)=>a?this.executeMapItemWithBestOf(t,i,u,l,e,r,o):s?this.executeMapItemWithVerify(t,i,u,l,e,r,o):o?_(d=>this.executeMapItem(t,i,u,l,e,r,d),o,u):this.executeMapItem(t,i,u,l,e,r)));return j.from(p)}async filter(e){let{items:n,prompt:i,condition:a,verify:s}=e,o=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,p=await Promise.all(n.map((u,d)=>s?this.executeFilterItemWithVerify(u,i,d,l,e,r,o):o?_(m=>this.executeFilterItem(u,i,d,l,e,r,m),o,d):this.executeFilterItem(u,i,d,l,e,r))),t=[];for(let u of p)if(u.status==="error")t.push(u);else if(u.data!==null)try{a(u.data)?t.push(u):t.push({...u,status:"filtered"});}catch(d){t.push({...u,status:"error",data:null,error:`Condition function threw: ${d.message}`});}return j.from(t)}async reduce(e){let{items:n,prompt:i,verify:a}=e,s=e.retry??this.config.retry,o=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,r=[],p=[];n.forEach((b,C)=>{r.push(this.getFiles(b)),p.push(this.getIndex(b,C));});let t={};r.forEach((b,C)=>{Object.entries(b).forEach(([S,w])=>{t[`item_${p[C]}/${S}`]=w;});});let u=ue(t),d=E(ft,{fileTree:u}),m=e.systemPrompt?`${d}
|
|
212
|
-
|
|
213
|
-
${e.systemPrompt}`:d,f=(b,C,S)=>({operationId:o,operation:"reduce",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:p,errorRetry:C,verifyRetry:S,...this.pipelineContextToMeta(e._pipelineContext)}),h=e.mcpServers??this.config.mcpServers,g=e.skills??this.config.skills,y=e.composio??this.config.composio,v=async(b,C,S,w)=>{let k=await this.semaphore.use(()=>this.execute(t,b,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:h,skills:g,composio:y,tagPrefix:C,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:e.name,operationId:o,operation:"reduce",role:"worker",errorRetry:S,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),F=f(k,S,w&&w>1?w-1:void 0);return k.error?{status:"error",data:null,files:k.files,meta:F,error:k.error,rawData:k.rawData}:{status:"success",data:k.data,files:k.files,meta:F}},x=`${this.config.tag}-reduce`;return a?this.runWithVerification((b,C,S)=>v(b,C,void 0,S),{originalPrompt:i,inputFiles:t,verifyConfig:a,timeoutMs:l,systemPrompt:m,schema:e.schema,mcpServers:h,skills:g,composio:y,operationId:o,baseTag:x,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?_(b=>{let C=b>1?b-1:void 0,S=C?`${x}-er${C}`:x;return v(i,S,C)},s):v(i,x)}async bestOf(e){let{item:n,prompt:i,config:a}=e,s=e.retry??this.config.retry,o=a.n??a.taskAgents?.length;if(o===void 0)throw new Error("bestOf requires n or taskAgents");if(o<2)throw new Error("bestOf requires n >= 2");let l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,p=this.getFiles(n),t=a.mcpServers??this.config.mcpServers,u=a.judgeMcpServers??a.mcpServers??this.config.mcpServers,d=a.skills??this.config.skills,m=a.judgeSkills??a.skills??this.config.skills,f=a.composio??this.config.composio,h=a.judgeComposio??a.composio??this.config.composio,g=await Promise.all(Array.from({length:o},async(C,S)=>{let w=s?await _(k=>this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:S,operationId:l,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:t,skills:d,composio:f,timeoutMs:r,attempt:k}),s,S):await this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:S,operationId:l,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:t,skills:d,composio:f,timeoutMs:r});return a.onCandidateComplete?.(0,S,w.status==="success"?"success":"error"),w})),y=s?await _(C=>this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:g,config:a,timeoutMs:r,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:h,attempt:C}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:g,config:a,timeoutMs:r,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:h}),v=g.findIndex(C=>C.status==="success"),x=y.decision?.winner??(v>=0?v:0);a.onJudgeComplete?.(0,x,y.decision?.reasoning??"Judge failed to provide reasoning");let b={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:o};return {winner:g[x]??g[0],winnerIndex:x,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:b,candidates:g}}async execute(e,n,i){let a=null,s="",o=i.tagPrefix,l={},r=null,p,t,u={...this.config.agent,...i.agent};try{a=new H().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&a.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&a.withSystemPrompt(i.systemPrompt),i.mcpServers&&a.withMcpServers(i.mcpServers),i.skills?.length&&a.withSkills(i.skills),i.composio&&a.withComposio(i.composio.userId,i.composio.config),i.observability&&a.withObservability(i.observability),Object.keys(e).length>0&&a.withContext(e);let d=await a.run({prompt:n,timeoutMs:i.timeoutMs});s=d.sandboxId,o=a.getSessionTag()??i.tagPrefix;let m=null;try{m=await a.getOutputFiles(!0),l=m.files;}catch{}d.exitCode!==0?p=`Agent exited with code ${d.exitCode}`:i.schema?m?(r=m.data,m.error&&(p=m.error),m.rawData&&(t=m.rawData)):p="Failed to read output files from sandbox":r=l;}catch(d){if(p=d.message,a){o=a.getSessionTag()??i.tagPrefix;try{l=(await a.getOutputFiles(!0)).files;}catch{}}}finally{a&&await a.kill().catch(()=>{});}return {files:l,data:r,tag:o,sandboxId:s,error:p,rawData:t}}async executeMapItem(e,n,i,a,s,o,l=1){let r=this.getFiles(e),p=l>1?`${this.config.tag}-map-${i}-er${l-1}`:`${this.config.tag}-map-${i}`,t=this.evaluatePrompt(n,r,i);if(t instanceof Error)return this.buildErrorResult(`Prompt function threw: ${t.message}`,{operationId:a,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(r,t,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:p,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:s.name,operationId:a,operation:"map",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),h={operationId:a,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,h)}async executeMapItemWithVerify(e,n,i,a,s,o,l){let r=this.getFiles(e),p=`${this.config.tag}-map-${i}`,t=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=this.evaluatePrompt(n,r,i);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:a,operation:"map",tag:p,sandboxId:"",itemIndex:i});let h=async(g,y,v)=>{let x=await this.semaphore.use(()=>this.execute(r,g,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:y,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:s.name,operationId:a,operation:"map",itemIndex:i,role:"worker",verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),b={operationId:a,operation:"map",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(x,b)};return this.runWithVerification(h,{originalPrompt:f,inputFiles:r,verifyConfig:t,timeoutMs:o,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:a,baseTag:p,retry:l,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,n,i,a,s,o,l){let r=this.getFiles(e),p=`${this.config.tag}-map-${i}`,t=this.evaluatePrompt(n,r,i);if(t instanceof Error)return this.buildErrorResult(`Prompt function threw: ${t.message}`,{operationId:a,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:a,operation:"map",tag:p,sandboxId:"",itemIndex:i});let m=s.mcpServers??this.config.mcpServers,f=u.mcpServers??m,h=u.judgeMcpServers??u.mcpServers??m,g=s.skills??this.config.skills,y=u.skills??g,v=u.judgeSkills??u.skills??g,x=s.composio??this.config.composio,b=u.composio??x,C=u.judgeComposio??u.composio??x,S=await Promise.all(Array.from({length:d},async(q,Z)=>{let Le=l?await _(wt=>this.executeBestOfCandidate({inputFiles:r,prompt:t,candidateIndex:Z,operationId:a,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:y,composio:b,timeoutMs:o,parentIndex:i,attempt:wt,_pipelineContext:s._pipelineContext}),l,Z):await this.executeBestOfCandidate({inputFiles:r,prompt:t,candidateIndex:Z,operationId:a,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:y,composio:b,timeoutMs:o,parentIndex:i,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(i,Z,Le.status==="success"?"success":"error"),Le})),w=l?await _(q=>this.executeBestOfJudge({inputFiles:r,taskPrompt:t,candidates:S,config:u,timeoutMs:o,operationId:a,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:h,skills:v,composio:C,parentIndex:i,attempt:q,_pipelineContext:s._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:r,taskPrompt:t,candidates:S,config:u,timeoutMs:o,operationId:a,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:h,skills:v,composio:C,parentIndex:i,_pipelineContext:s._pipelineContext}),k=S.findIndex(q=>q.status==="success"),F=w.decision?.winner??(k>=0?k:0),Ue=S[F]??S[0];u.onJudgeComplete?.(i,F,w.decision?.reasoning??"Judge failed to provide reasoning");let Ct={operationId:a,operation:"bestof-judge",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...Ue,meta:{...Ue.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:F,judgeReasoning:w.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Ct,candidates:S}}}async executeFilterItem(e,n,i,a,s,o,l=1){let r=this.getFiles(e),p=l>1?`${this.config.tag}-filter-${i}-er${l-1}`:`${this.config.tag}-filter-${i}`,t=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,d=s.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(r,n,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:t,skills:u,composio:d,tagPrefix:p,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:s.name,operationId:a,operation:"filter",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:a,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,r)}async executeFilterItemWithVerify(e,n,i,a,s,o,l){let r=this.getFiles(e),p=`${this.config.tag}-filter-${i}`,t=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=async(h,g,y)=>{let v=await this.semaphore.use(()=>this.execute(r,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:g,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:s.name,operationId:a,operation:"filter",itemIndex:i,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),x={operationId:a,operation:"filter",tag:v.tag,sandboxId:v.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(v,x,r)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:r,verifyConfig:t,timeoutMs:o,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:a,baseTag:p,retry:l,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:i,candidateIndex:a,operationId:s,config:o,timeoutMs:l,parentIndex:r,attempt:p=1,_pipelineContext:t}=e,u=r!==void 0?`${this.config.tag}-map-${r}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,d=p>1?`${u}-er${p-1}`:u,m=await this.semaphore.use(()=>this.execute(n,i,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:o.taskAgents?.[a],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"candidate",candidateIndex:a,errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(t)}})),f={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:p>1?p-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(t)};return this.buildResult(m,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((i,a)=>{i.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
|
|
214
|
-
|
|
215
|
-
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,o])=>{n[`candidate_${a}/${s}`]=o;});}),n}async executeBestOfJudge(e){let{candidates:n,config:i,timeoutMs:a,operationId:s,parentIndex:o,attempt:l=1,_pipelineContext:r}=e,p=o!==void 0?`${this.config.tag}-map-${o}-bestof-judge`:`${this.config.tag}-bestof-judge`,t=l>1?`${p}-er${l-1}`:p,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),d=ue(u),m=E(Pe,{candidateCount:String(n.length),criteria:i.judgeCriteria,fileTree:d}),f=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),h=await this.semaphore.use(()=>this.execute(u,dt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:t,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:o,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(r)}})),g=null;if(h.data&&!h.error)g=h.data;else if(h.rawData)try{let y=JSON.parse(h.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),g={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${h.error}`);}return {status:g?"success":"error",decision:g,tag:h.tag,sandboxId:h.sandboxId,error:g?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,a])=>{n[`worker_output/${i}`]=a;}),n}async executeVerify(e){let{config:n,timeoutMs:i,operationId:a,workerTag:s,retryAttempt:o=1,operation:l,itemIndex:r,attemptIndex:p,_pipelineContext:t}=e,u=o>1?`${s}-verifier-er${o-1}`:`${s}-verifier`,d=n.verifierMcpServers??e.mcpServers,m=n.verifierSkills??e.skills,f=n.verifierComposio??e.composio,h=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),g=ue(h),y=E(Ee,{criteria:n.criteria,fileTree:g}),v=await this.semaphore.use(()=>this.execute(h,mt,{systemPrompt:y,schema:c.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:a,operation:l,itemIndex:r,role:"verifier",verifyRetry:p&&p>1?p-1:void 0,errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(t)}})),x=null;if(v.data&&!v.error)x=v.data;else if(v.rawData)try{let b=JSON.parse(v.rawData);x={passed:!!b.passed,reasoning:b.reasoning??"Verification completed",feedback:b.feedback};}catch{console.warn(`Verify validation failed: ${v.error}`);}return {status:x?"success":"error",decision:x,tag:v.tag,sandboxId:v.sandboxId,error:x?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return E(Oe,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:i,inputFiles:a,verifyConfig:s,timeoutMs:o,operationId:l,baseTag:r,retry:p,itemIndex:t=0,operation:u,_pipelineContext:d}=n,m=s.maxAttempts??c.DEFAULT_VERIFY_MAX_ATTEMPTS,f=i,h=null,g=0;for(;g<m;){g++;let v=g>1?`${r}-vr${g-1}`:r,x=p?await _(S=>e(f,S>1?`${v}-er${S-1}`:v,g),p,t):await e(f,v,g);if(s.onWorkerComplete?.(t,g,x.status==="error"?"error":"success"),x.status==="error")return x;h=x;let b=p?await _(S=>this.executeVerify({inputFiles:a,outputFiles:x.files,taskPrompt:f,config:s,timeoutMs:o,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:l,workerTag:v,retryAttempt:S,operation:u,itemIndex:t,attemptIndex:g,_pipelineContext:d}),{...p,retryOn:void 0}):await this.executeVerify({inputFiles:a,outputFiles:x.files,taskPrompt:f,config:s,timeoutMs:o,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:l,workerTag:v,operation:u,itemIndex:t,attemptIndex:g,_pipelineContext:d}),C={operationId:l,operation:"verify",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,attempts:g,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(t,g,b.decision?.passed??false,b.decision?.feedback),b.decision?.passed)return {...x,verify:{passed:true,reasoning:b.decision.reasoning,verifyMeta:C,attempts:g}};if(g<m){let S=b.decision?.feedback??b.decision?.reasoning??"Output did not meet criteria";f=c.buildRetryPromptWithFeedback(i,S);}}let y=g>1?`${r}-vr${g-1}`:r;return {...h,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:l,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:g,...this.pipelineContextToMeta(d)},attempts:g}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,i){if(typeof e=="string")return e;try{return e(n,i)}catch(a){return a}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=R(e.schema)?L(e.schema):B(e.schema)),Object.entries(e.inputFiles).forEach(([i,a])=>{n[`worker_task/input/${i}`]=a;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&A in e&&e[A]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,i){let a=i??e.files;return e.error?{[A]:true,status:"error",data:null,files:a,meta:n,error:e.error,rawData:e.rawData}:{[A]:true,status:"success",data:e.data,files:a,meta:n}}buildErrorResult(e,n){return {[A]:true,status:"error",data:null,files:{},meta:n,error:e}}};var fe=class c{swarm;steps;events;constructor(e,n=[],i={}){this.swarm=e,this.steps=n,this.events=i;}map(e){return new c(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new c(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new ge(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new c(this.swarm,this.steps,{...this.events,[i]:n})}return new c(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),i=[],a=e,s=Date.now();for(let l=0;l<this.steps.length;l++){let r=this.steps[l],p=r.config.name,t=Date.now();this.events.onStepStart?.({type:r.type,index:l,name:p,itemCount:a.length});let u={pipelineRunId:n,pipelineStepIndex:l};try{let d=await this.executeStep(r,a,l,p,u),m=Date.now()-t;if(i.push({type:r.type,index:l,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:r.type,index:l,name:p,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),r.type==="reduce")return {pipelineRunId:n,steps:i,output:d.output,totalDurationMs:Date.now()-s};a=d.nextItems;}catch(d){throw this.events.onStepError?.({type:r.type,index:l,name:p,error:d instanceof Error?d:new Error(String(d))}),d}}let o=i[i.length-1];return {pipelineRunId:n,steps:i,output:o?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,i,a,s){if(e.type==="map"){let r=e.config,p=await this.swarm.map({items:n,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,a),verify:this.wrapVerify(r.verify,i,a),bestOf:this.wrapBestOf(r.bestOf,i,a)});return {output:[...p],nextItems:p.success,successCount:p.success.length,errorCount:p.error.length,filteredCount:0}}if(e.type==="filter"){let r=e.config,p=await this.swarm.filter({items:n,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,a),verify:this.wrapVerify(r.verify,i,a)}),t=r.emit??"success",u=t==="success"?p.success:t==="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 o=e.config,l=await this.swarm.reduce({items:n,...o,_pipelineContext:s,retry:this.wrapRetry(o.retry,i,a),verify:this.wrapVerify(o.verify,i,a)});return {output:l,nextItems:[],successCount:l.status==="success"?1:0,errorCount:l.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,i){if(e)return {...e,onItemRetry:(a,s,o)=>{e.onItemRetry?.(a,s,o),this.events.onItemRetry?.({stepIndex:n,stepName:i,itemIndex:a,attempt:s,error:o});}}}wrapVerify(e,n,i){if(e)return {...e,onWorkerComplete:(a,s,o)=>{e.onWorkerComplete?.(a,s,o),this.events.onWorkerComplete?.({stepIndex:n,stepName:i,itemIndex:a,attempt:s,status:o});},onVerifierComplete:(a,s,o,l)=>{e.onVerifierComplete?.(a,s,o,l),this.events.onVerifierComplete?.({stepIndex:n,stepName:i,itemIndex:a,attempt:s,passed:o,feedback:l});}}}wrapBestOf(e,n,i){if(e)return {...e,onCandidateComplete:(a,s,o)=>{e.onCandidateComplete?.(a,s,o),this.events.onCandidateComplete?.({stepIndex:n,stepName:i,itemIndex:a,candidateIndex:s,status:o});},onJudgeComplete:(a,s,o)=>{e.onJudgeComplete?.(a,s,o),this.events.onJudgeComplete?.({stepIndex:n,stepName:i,itemIndex:a,winnerIndex:s,reasoning:o});}}}},ge=class c extends fe{constructor(e,n,i){super(e,n,i);}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new c(this.swarm,this.steps,{...this.events,[i]:n})}return new c(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,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});exports.AGENT_REGISTRY=ye;exports.AGENT_TYPES=kt;exports.Agent=G;exports.Evolve=H;exports.JUDGE_PROMPT=Pe;exports.Pipeline=fe;exports.RETRY_FEEDBACK_PROMPT=Oe;exports.SCHEMA_PROMPT=ut;exports.SWARM_RESULT_BRAND=A;exports.SYSTEM_PROMPT=pt;exports.Semaphore=N;exports.Swarm=$e;exports.SwarmResultList=j;exports.TerminalPipeline=ge;exports.VALIDATION_PRESETS=he;exports.VERIFY_PROMPT=Ee;exports.WORKSPACE_PROMPT=ct;exports.WORKSPACE_SWE_PROMPT=lt;exports.applyTemplate=E;exports.buildWorkerSystemPrompt=Ie;exports.createAgentParser=I;exports.createClaudeParser=ne;exports.createCodexParser=ie;exports.createGeminiParser=se;exports.executeWithRetry=_;exports.expandPath=ve;exports.getAgentConfig=O;exports.getMcpSettingsDir=U;exports.getMcpSettingsPath=$;exports.isValidAgentType=_t;exports.isZodSchema=R;exports.jsonSchemaToString=B;exports.parseNdjsonLine=It;exports.parseNdjsonOutput=Mt;exports.parseQwenOutput=Ne;exports.readLocalDir=qe;exports.saveLocalDir=Ze;exports.writeClaudeMcpConfig=Q;exports.writeCodexMcpConfig=te;exports.writeGeminiMcpConfig=X;exports.writeMcpConfig=Ce;exports.writeQwenMcpConfig=ee;exports.zodSchemaToJson=L;
|
|
209
|
+
`;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)+`
|
|
210
|
+
`;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)+`
|
|
211
|
+
`;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>=st){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},rt));}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 s=1;s<=me;s++)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(s===me){console.debug(`[SessionLogger] Dashboard ${r.status} after ${s} retries, requeueing`),this.requeueEvents(e);return}await this.delay($e*s);continue}console.debug(`[SessionLogger] Dashboard ${r.status}, dropping events`);return}catch(r){s===me?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",r),this.requeueEvents(e)):await this.delay($e*s);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!I.startsWith("https://")&&!I.includes("localhost")&&!I.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 he="COMPOSIO_API_KEY";function Rt(o){return new core.Composio({apiKey:process.env[he]})}function Ke(o){if(!o?.trim())throw new Error("userId is required and cannot be empty")}async function ye(o,e,t){Ke(o);let s=Rt(),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 s.create(o,Object.keys(r).length>0?r:void 0)}async function Pt(o,e,t,s){Ke(o);let r=Rt(),p=(await r.toolkits.get(e)).authConfigDetails?.find(c=>c.mode==="API_KEY");if(!p)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await r.connectedAccounts.initiate(o,p.name,{config:core.AuthScheme.APIKey({api_key:t})});}async function je(o,e){if(Ke(o),e?.keys)for(let[s,r]of Object.entries(e.keys))try{await Pt(o,s,r);}catch(n){throw new Error(`Failed to create API key connection for "${s}": ${n.message}`)}let t=await ye(o,{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 It(o){if(!o?.trim())throw new Error("userId is required and cannot be empty")}function En(){return new core.Composio({apiKey:process.env[he]})}async function Ot(o,e){It(o);let s=await(await ye(o,{manageConnections:false})).authorize(e);return {url:s.redirectUrl,connectionId:s.id}}async function Mt(o,e){let t=await Ve(o),s={};for(let r of t)s[r.toolkit]=r.connected;return e?s[e]??false:s}async function Ve(o){return It(o),(await En().connectedAccounts.list({userIds:[o],statuses:["ACTIVE"]})).items.map(s=>({toolkit:s.toolkit.slug,connected:s.status==="ACTIVE",accountId:s.id}))}var We={auth:Ot,status:Mt,connections:Ve};var At=Symbol.for("evolve:awsSdkCache"),$t=Symbol.for("evolve:s3ClientCache");var Rn=3600,Pn=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function In(o){if(o.startsWith("s3://")){let r=o.slice(5),n=r.indexOf("/");return n===-1?{bucket:r,prefix:""}:{bucket:r.slice(0,n),prefix:r.slice(n+1).replace(/\/+$/,"")}}let e=new URL(o),t=e.hostname,s=e.pathname.split("/").filter(Boolean);if(t.includes(".s3.")&&t.endsWith(".amazonaws.com"))return {bucket:t.split(".s3.")[0],prefix:s.join("/")};if(s.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${o}`);return {bucket:s[0],prefix:s.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function be(o,e,t,s){if(!o?.url&&!o?.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:o?.region||"us-east-1",mode:"gateway",gatewayUrl:t,gatewayApiKey:s}}let r=o?.bucket||"",n=o?.prefix||"",a=o?.endpoint;if(o?.url){let p=In(o.url);r=r||p.bucket,n=n||p.prefix,a=a||p.endpoint;}if(!r)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:r,prefix:n,region:o?.region||process.env.AWS_REGION||"us-east-1",endpoint:a,credentials:o?.credentials,mode:"byok"}}function Dt(o){if(o.includes(".."))throw new Error(`settingsDir must not contain '..': ${o}`);let e;if(o.startsWith("~/"))e=o.slice(2);else if(o.startsWith("/home/user/"))e=o.slice(11);else if(o.startsWith("."))e=o;else throw new Error(`Unexpected settingsDir: ${o}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${o}`);return e}function On(o){if(o.includes(".."))throw new Error(`workingDir must not contain '..': ${o}`);if(!o.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${o}. Must start with /home/user/.`);let e=o.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${o}`);return e}function ve(o){return "'"+o.replace(/'/g,"'\\''")+"'"}function Mn(o,e){let t=P(o),s=On(e),r=t.checkpointDirs?.length?t.checkpointDirs.map(p=>Dt(p)):[Dt(t.mcpConfig.settingsDir)],n=[...Pn.map(p=>`--exclude=${ve(p)}`),`--exclude=${ve(s+"/temp")}`].join(" "),a=[ve(s+"/"),...r.map(p=>ve(p+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${n} ${a}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function j(){let o=globalThis[At];if(o)return o;let e="@aws-sdk/client-s3",t="@aws-sdk/s3-request-presigner";try{let[s,r]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(t)]);return globalThis[At]={s3:s,presigner:r},{s3:s,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 H(o){let e=o.credentials?`${o.credentials.accessKeyId}:${o.credentials.secretAccessKey.slice(-4)}`:"env",t=`${o.bucket}:${o.region}:${o.endpoint||""}:${e}`,s=globalThis[$t];if(s?.key===t)return s.client;let{s3:r}=await j(),n=new r.S3Client({region:o.region,...o.endpoint&&{endpoint:o.endpoint,forcePathStyle:true},...o.credentials&&{credentials:o.credentials}});return globalThis[$t]={client:n,key:t},n}async function Ft(o,e,t){let{s3:s,presigner:r}=await j(),n=await H(o),a=t==="put"?new s.PutObjectCommand({Bucket:o.bucket,Key:e,ContentType:"application/gzip"}):new s.GetObjectCommand({Bucket:o.bucket,Key:e});return r.getSignedUrl(n,a,{expiresIn:Rn})}async function Ut(o,e){let{s3:t}=await j(),s=await H(o);try{return await s.send(new t.HeadObjectCommand({Bucket:o.bucket,Key:e})),!0}catch(r){let n=r?.name||r?.message||"";if(r?.$metadata?.httpStatusCode===404||n==="NotFound"||n==="NoSuchKey")return false;throw r}}async function Lt(o,e){let{s3:t}=await j(),n=await(await(await H(o)).send(new t.GetObjectCommand({Bucket:o.bucket,Key:e}))).Body?.transformToString();if(!n)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(n)}async function An(o,e,t){let{s3:s}=await j();await(await H(o)).send(new s.PutObjectCommand({Bucket:o.bucket,Key:e,Body:JSON.stringify(t,null,2),ContentType:"application/json"}));}function Nt(o,e){return `${o.prefix?`${o.prefix}/`:""}data/${e}/archive.tar.gz`}function Bt(o,e){return `${o.prefix?`${o.prefix}/`:""}checkpoints/${e}.json`}function $n(){let o=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${o}_${e}`}async function Kt(o,e,t,s){let r=await fetch(`${o.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:t,action:s})});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`Gateway presign failed (${r.status}): ${n}`)}return r.json()}async function Dn(o,e){let t=await fetch(`${o.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o.gatewayApiKey}`},body:JSON.stringify(e)});if(!t.ok){let s=await t.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${t.status}): ${s}`)}return t.json()}async function Un(o,e){let t=await fetch(`${o.gatewayUrl}/api/checkpoints/${e}`,{method:"GET",headers:{Authorization:`Bearer ${o.gatewayApiKey}`}});if(!t.ok){if(t.status===404)throw new Error(`Checkpoint ${e} not found`);let s=await t.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${t.status}): ${s}`)}return t.json()}async function Je(o,e,t,s,r){let n=new Date().toISOString(),a=Mn(t,s),p=await o.commands.run(a,{timeoutMs:12e4});if(p.exitCode!==0)throw new Error(`Checkpoint tar failed: ${p.stderr}`);let c=p.stdout.trim().split(`
|
|
212
|
+
`).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);let l=await o.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),i=parseInt(l.stdout.trim(),10),d=Number.isNaN(i)?void 0:i,u;try{if(e.mode==="byok"){let m=Nt(e,c);if(!await Ut(e,m)){let h=await Ft(e,m,"put"),b=await o.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(b.exitCode!==0)throw new Error(`Checkpoint upload failed: ${b.stderr}`);if(!await Ut(e,m))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=$n();let g={id:u,hash:c,tag:r.tag,timestamp:n,sizeBytes:d,agentType:t,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment,sandboxId:o.sandboxId};await An(e,Bt(e,u),g);}else {let m=await Kt(e,r.tag,c,"put");if(!m.alreadyExists){let g=await o.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}`)}u=(await Dn(e,{tag:r.tag,hash:c,sizeBytes:d??0,agentType:t,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment})).id;}}finally{await o.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:u,hash:c,tag:r.tag,timestamp:n,sizeBytes:d,agentType:t,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment}}async function jt(o,e,t){let s,r,n={};if(e.mode==="byok"){let l=Bt(e,t),i;try{i=await Lt(e,l);}catch(d){let u=d.name;throw u==="AccessDenied"||u==="InvalidAccessKeyId"||u==="SignatureDoesNotMatch"||u==="ExpiredToken"||u==="NetworkingError"||u==="TimeoutError"?d:new Error(`Checkpoint ${t} not found`)}s=i.hash,n={agentType:i.agentType,workspaceMode:i.workspaceMode},r=await Ft(e,Nt(e,s),"get");}else {let l=await Un(e,t);s=l.hash,n={agentType:l.agentType,workspaceMode:l.workspaceMode},r=(await Kt(e,l.tag,s,"get")).url;}let a=await o.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${r}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(a.exitCode!==0)throw new Error(`Checkpoint download failed: ${a.stderr}`);let p=a.stdout.trim().split(`
|
|
213
|
+
`).pop()?.trim();if(p!==s)throw await o.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${p})`);let c=await o.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(c.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${c.stderr}`);return n}function Fn(o){let e=process.env.EVOLVE_API_KEY,t=!o.url&&!o.bucket&&!!e;return be(o,t,I,e)}async function Vt(o,e){let{s3:t}=await j(),s=await H(o),n=`${o.prefix?`${o.prefix}/`:""}checkpoints/`,a=[],p;do{let u={Bucket:o.bucket,Prefix:n,...p&&{ContinuationToken:p}},m=await s.send(new t.ListObjectsV2Command(u));if(m.Contents)for(let f of m.Contents)f.Key?.endsWith(".json")&&f.LastModified&&a.push({key:f.Key,lastModified:f.LastModified});p=m.IsTruncated?m.NextContinuationToken:void 0;}while(p);if(a.length===0)return [];a.sort((u,m)=>{let f=m.lastModified.getTime()-u.lastModified.getTime();return f!==0?f:m.key<u.key?-1:m.key>u.key?1:0});let l=!!e?.tag?a:e?.limit?a.slice(0,e.limit):a,d=(await Promise.all(l.map(async u=>{try{return await Lt(o,u.key)}catch{return null}}))).filter(u=>u!==null);return e?.tag&&(d=d.filter(u=>u.tag===e.tag)),e?.limit&&d.length>e.limit&&(d=d.slice(0,e.limit)),d}async function Wt(o,e){let t=new URLSearchParams;e?.limit&&t.set("limit",String(e.limit)),e?.tag&&t.set("tag",e.tag);let s=`${o.gatewayUrl}/api/checkpoints${t.toString()?`?${t}`:""}`,r=await fetch(s,{method:"GET",headers:{Authorization:`Bearer ${o.gatewayApiKey}`}});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${r.status}): ${n}`)}return r.json()}async function ze(o,e){let t=Fn(o),s=e?.limit&&e.limit>0?Math.min(e.limit,500):100;return t.mode==="byok"?Vt(t,{limit:s,tag:e?.tag}):Wt(t,{limit:s,tag:e?.tag})}async function Jt(o){return o.mode==="byok"?(await Vt(o,{limit:1}))[0]??null:(await Wt(o,{limit:1}))[0]??null}function Nn(o){return o.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||it,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 s=this.createAjvValidator();this.compiledValidator=s.compile(this.jsonSchema);}catch(s){throw new Error(`Invalid JSON Schema: ${s.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,s,r){let n=++this.nextOperationId;return this.activeOperationId=n,this.activeOperationKind=e,this.activeCommand=t,this.activeProcessId=t.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(s,r),n}finalizeOperation(e,t,s,r="idle",n="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=n,this.agentState=r,this.emitLifecycle(t,s),true)}watchBackgroundOperation(e,t,s,r){let n=t==="run"?"run_background_complete":"command_background_complete",a=t==="run"?"run_background_failed":"command_background_failed",p=t==="run"?"run_interrupted":"command_interrupted";s.wait().then(c=>{if(this.interruptedOperations.delete(e)||c.exitCode===130){this.finalizeOperation(e,r,p,"interrupted");return}let i=c.exitCode===0?n:a,d=c.exitCode===0?"idle":"error";this.finalizeOperation(e,r,i,d);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,r,a,"error");});}createAjvValidator(){let t={...ke[this.schemaOptions?.mode||"loose"],...this.schemaOptions?.coerceTypes!==void 0&&{coerceTypes:this.schemaOptions.coerceTypes},...this.schemaOptions?.removeAdditional!==void 0&&{removeAdditional:this.schemaOptions.removeAdditional},...this.schemaOptions?.useDefaults!==void 0&&{useDefaults:this.schemaOptions.useDefaults},...this.schemaOptions?.allErrors!==void 0&&{allErrors:this.schemaOptions.allErrors}};return new Ln__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 s=this.buildEnvironmentVariables();this.sandbox=await t.create({envs:s,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(s){throw this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}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],s=t?this.registry.providerEnvMap?.[t]:void 0,r=s?s.keyEnv:this.registry.apiKeyEnv,n=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:r;e[n]=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?Qe():J();if(this.registry.gatewayConfigEnv&&this.registry.providerEnvMap){let s={};for(let r of Object.keys(this.registry.providerEnvMap))s[r]={options:{baseURL:`${t}/v1`}};e[this.registry.gatewayConfigEnv]=JSON.stringify({provider:s});}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 s=this.options.workspaceMode||"knowledge",r=s==="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=Be({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:s}),p=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(p,a);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let n={...this.options.mcpServers};if(this.options.composio){let a=await je(this.options.composio.userId,this.options.composio.config);n={...n,composio:{type:"http",url:a.url,headers:a.headers}};}Object.keys(n).length>0&&await Pe(this.agentConfig.type,e,this.workingDir,n),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:t}=this.registry,{sourceDir:s,targetDir:r}=t;await e.files.makeDir(r);for(let n of this.skills){let a=`cp -r ${s}/${n} ${r}/ 2>/dev/null || true`;await e.commands.run(a,{timeoutMs:3e4});}}async uploadContextFiles(e,t){let s=Object.entries(t).map(([n,a])=>({path:`${this.workingDir}/context/${n}`,data:a}));if(s.length===0)return;let r=new Set(s.map(n=>n.path.substring(0,n.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}async uploadWorkspaceFiles(e,t){let s=Object.entries(t).map(([n,a])=>({path:n.startsWith("/")?n:`${this.workingDir}/${n}`,data:a}));if(s.length===0)return;let r=new Set(s.map(n=>n.path.substring(0,n.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}buildCommand(e){return this.registry.buildCommand({prompt:Nn(e),model:this.agentConfig.model||this.registry.defaultModel,isResume:this.hasRun,reasoningEffort:this.agentConfig.reasoningEffort,betas:this.agentConfig.betas,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,t){let{prompt:s,timeoutMs:r=z,background:n=false,checkpointComment:a}=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 Jt(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 jt(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 w=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!w}),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 c=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:c.sandboxId,tagPrefix:this.options.sessionTagPrefix,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(s);let l=this.buildCommand(s),i="",d=M(this.agentConfig.type),u=y=>{i+=y;let v=i.split(`
|
|
214
|
+
`);i=v.pop()??"";for(let k of v){if(!k.trim())continue;let w=d(k);if(this.sessionLogger?.writeEventParsed(k,w),t?.onStdout?.(k+`
|
|
215
|
+
`),w&&t?.onContent)for(let C of w)t.onContent(C);}},m=y=>{t?.onStderr?.(y);},f=await c.commands.spawn(l,{cwd:this.workingDir,timeoutMs:r,onStdout:u,onStderr:m}),g=this.beginOperation("run",f,t,"run_start");if(this.hasRun=true,n)return this.watchBackgroundOperation(g,"run",f,t),{sandboxId:c.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"),i.trim()){let y=d(i);if(this.sessionLogger?.writeEventParsed(i,y),t?.onStdout?.(i+`
|
|
216
|
+
`),y&&t?.onContent)for(let v of y)t.onContent(v);}let x;if(this.storage&&!n&&h.exitCode===0)try{x=await Je(c,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:a,parentId:this.lastCheckpointId}),this.lastCheckpointId=x.id;}catch(y){console.warn(`[Evolve] Auto-checkpoint failed: ${y.message}`);}return {sandboxId:c.sandboxId,exitCode:h.exitCode,stdout:h.stdout,stderr:h.stderr,checkpoint:x}}async executeCommand(e,t={},s){let{timeoutMs:r=z,background:n=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(s);this.lastRunTimestamp=Date.now();let p="",c="",l=g=>{p+=g,s?.onStdout?.(g);},i=g=>{c+=g,s?.onStderr?.(g);},d=await a.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,onStdout:l,onStderr:i}),u=this.beginOperation("command",d,s,"command_start");if(n)return this.watchBackgroundOperation(u,"command",d,s),{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with ID ${d.processId}`,stderr:""};let m;try{m=await d.wait();}catch(g){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,s,"command_failed","error"),g}return this.interruptedOperations.delete(u)||m.exitCode===130?this.finalizeOperation(u,s,"command_interrupted","interrupted"):m.exitCode===0?this.finalizeOperation(u,s,"command_complete","idle"):this.finalizeOperation(u,s,"command_failed","error"),{sandboxId:a.sandboxId,exitCode:m.exitCode,stdout:p||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(),s=`${this.workingDir}/output`,r=e?"":"-maxdepth 1",a=(await t.commands.run(`find ${s} ${r} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
217
|
+
`).filter(Boolean),p=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],l=`${s}/`;for(let f of a){let[g,h]=f.split("|");if(!g||!h)continue;let b=parseInt(h,10);p>0&&b<p||c.push(g);}let i={},d=await Promise.all(c.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 d)f&&(i[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:i,data:null};let u=i["result.json"];if(!u)return {files:i,data:null,error:"Schema provided but agent did not create output/result.json"};let m=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(m);if(this.zodSchema){let g=this.zodSchema.safeParse(f);return g.success?{files:i,data:g.data}:{files:i,data:null,error:`Schema validation failed: ${g.error.message}`,rawData:m}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:i,data:f};{let h=this.compiledValidator.errors?.map(b=>`${b.instancePath} ${b.message}`).join(", ")||"Unknown validation error";return {files:i,data:null,error:`Schema validation failed: ${h}`,rawData:m}}}return {files:i,data:null}}catch(f){return {files:i,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 Je(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,s=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 n=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,n),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){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=We;async initializeAgent(){let e=De(this.config.agent),t=this.config.sandbox??await Ue(),s=e.isDirectMode?{}:et(e.apiKey),r=this.config.storage!==void 0?be(this.config.storage,!e.isDirectMode,I,e.isDirectMode?void 0:e.apiKey):void 0,n={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:{...s,...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 q(e,n);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,r=this.listenerCount("lifecycle")>0;return {onStdout:e?n=>this.emit("stdout",n):void 0,onStderr:t?n=>this.emit("stderr",n):void 0,onContent:s?n=>this.emit("content",n):void 0,onLifecycle:r?n=>this.emit("lifecycle",n):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:s,from:r,checkpointComment:n}){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:s,from:r,checkpointComment:n},a)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,t,s)}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 ze(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 o 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 o;return t.push(...e),t}};var Ge=class o{config;semaphore;constructor(e={}){let t=e.concurrency??nt;if(t>Ae)throw new Error(`concurrency=${t} exceeds max ${Ae}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:t,timeoutMs:e.timeoutMs??z,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new V(this.config.concurrency);}async map(e){let{items:t,prompt:s,bestOf:r,verify:n}=e,a=e.retry??this.config.retry,p=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(r&&n)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(t.map((i,d)=>r?this.executeMapItemWithBestOf(i,s,d,p,e,c,a):n?this.executeMapItemWithVerify(i,s,d,p,e,c,a):a?_(u=>this.executeMapItem(i,s,d,p,e,c,u),a,d):this.executeMapItem(i,s,d,p,e,c)));return W.from(l)}async filter(e){let{items:t,prompt:s,condition:r,verify:n}=e,a=e.retry??this.config.retry,p=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,l=await Promise.all(t.map((d,u)=>n?this.executeFilterItemWithVerify(d,s,u,p,e,c,a):a?_(m=>this.executeFilterItem(d,s,u,p,e,c,m),a,u):this.executeFilterItem(d,s,u,p,e,c))),i=[];for(let d of l)if(d.status==="error")i.push(d);else if(d.data!==null)try{r(d.data)?i.push(d):i.push({...d,status:"filtered"});}catch(u){i.push({...d,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return W.from(i)}async reduce(e){let{items:t,prompt:s,verify:r}=e,n=e.retry??this.config.retry,a=this.generateOperationId(),p=e.timeoutMs??this.config.timeoutMs,c=[],l=[];t.forEach((v,k)=>{c.push(this.getFiles(v)),l.push(this.getIndex(v,k));});let i={};c.forEach((v,k)=>{Object.entries(v).forEach(([w,C])=>{i[`item_${l[k]}/${w}`]=C;});});let d=ge(i),u=O(_t,{fileTree:d}),m=e.systemPrompt?`${u}
|
|
218
|
+
|
|
219
|
+
${e.systemPrompt}`:u,f=(v,k,w)=>({operationId:a,operation:"reduce",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:t.length,inputIndices:l,errorRetry:k,verifyRetry:w,...this.pipelineContextToMeta(e._pipelineContext)}),g=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,b=e.composio??this.config.composio,x=async(v,k,w,C)=>{let S=await this.semaphore.use(()=>this.execute(i,v,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:g,skills:h,composio:b,tagPrefix:k,timeoutMs:p,observability:{swarmName:this.config.tag,operationName:e.name,operationId:a,operation:"reduce",role:"worker",errorRetry:w,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),U=f(S,w,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 r?this.runWithVerification((v,k,w)=>x(v,k,void 0,w),{originalPrompt:s,inputFiles:i,verifyConfig:r,timeoutMs:p,systemPrompt:m,schema:e.schema,mcpServers:g,skills:h,composio:b,operationId:a,baseTag:y,retry:n,operation:"reduce",_pipelineContext:e._pipelineContext}):n?_(v=>{let k=v>1?v-1:void 0,w=k?`${y}-er${k}`:y;return x(s,w,k)},n):x(s,y)}async bestOf(e){let{item:t,prompt:s,config:r}=e,n=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 p=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,l=this.getFiles(t),i=r.mcpServers??this.config.mcpServers,d=r.judgeMcpServers??r.mcpServers??this.config.mcpServers,u=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(k,w)=>{let C=n?await _(S=>this.executeBestOfCandidate({inputFiles:l,prompt:s,candidateIndex:w,operationId:p,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,composio:f,timeoutMs:c,attempt:S}),n,w):await this.executeBestOfCandidate({inputFiles:l,prompt:s,candidateIndex:w,operationId:p,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,composio:f,timeoutMs:c});return r.onCandidateComplete?.(0,w,C.status==="success"?"success":"error"),C})),b=n?await _(k=>this.executeBestOfJudge({inputFiles:l,taskPrompt:s,candidates:h,config:r,timeoutMs:c,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:d,skills:m,composio:g,attempt:k}),{...n,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:s,candidates:h,config:r,timeoutMs:c,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:d,skills:m,composio:g}),x=h.findIndex(k=>k.status==="success"),y=b.decision?.winner??(x>=0?x:0);r.onJudgeComplete?.(0,y,b.decision?.reasoning??"Judge failed to provide reasoning");let v={operationId:p,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:a};return {winner:h[y]??h[0],winnerIndex:y,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:v,candidates:h}}async execute(e,t,s){let r=null,n="",a=s.tagPrefix,p={},c=null,l,i,d={...this.config.agent,...s.agent};try{r=new Z().withAgent(d).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(s.tagPrefix),s.schema&&r.withSchema(s.schema,s.schemaOptions),s.systemPrompt&&r.withSystemPrompt(s.systemPrompt),s.mcpServers&&r.withMcpServers(s.mcpServers),s.skills?.length&&r.withSkills(s.skills),s.composio&&r.withComposio(s.composio.userId,s.composio.config),s.observability&&r.withObservability(s.observability),Object.keys(e).length>0&&r.withContext(e);let u=await r.run({prompt:t,timeoutMs:s.timeoutMs});n=u.sandboxId,a=r.getSessionTag()??s.tagPrefix;let m=null;try{m=await r.getOutputFiles(!0),p=m.files;}catch{}u.exitCode!==0?l=`Agent exited with code ${u.exitCode}`:s.schema?m?(c=m.data,m.error&&(l=m.error),m.rawData&&(i=m.rawData)):l="Failed to read output files from sandbox":c=p;}catch(u){if(l=u.message,r){a=r.getSessionTag()??s.tagPrefix;try{p=(await r.getOutputFiles(!0)).files;}catch{}}}finally{r&&await r.kill().catch(()=>{});}return {files:p,data:c,tag:a,sandboxId:n,error:l,rawData:i}}async executeMapItem(e,t,s,r,n,a,p=1){let c=this.getFiles(e),l=p>1?`${this.config.tag}-map-${s}-er${p-1}`:`${this.config.tag}-map-${s}`,i=this.evaluatePrompt(t,c,s);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:r,operation:"map",tag:l,sandboxId:"",itemIndex:s});let d=n.mcpServers??this.config.mcpServers,u=n.skills??this.config.skills,m=n.composio??this.config.composio,f=await this.semaphore.use(()=>this.execute(c,i,{systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,agent:n.agent,mcpServers:d,skills:u,composio:m,tagPrefix:l,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:n.name,operationId:r,operation:"map",itemIndex:s,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(n._pipelineContext)}})),g={operationId:r,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:n.name,itemIndex:s,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(n._pipelineContext)};return this.buildResult(f,g)}async executeMapItemWithVerify(e,t,s,r,n,a,p){let c=this.getFiles(e),l=`${this.config.tag}-map-${s}`,i=n.verify,d=n.mcpServers??this.config.mcpServers,u=n.skills??this.config.skills,m=n.composio??this.config.composio,f=this.evaluatePrompt(t,c,s);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:r,operation:"map",tag:l,sandboxId:"",itemIndex:s});let g=async(h,b,x)=>{let y=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,agent:n.agent,mcpServers:d,skills:u,composio:m,tagPrefix:b,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:n.name,operationId:r,operation:"map",itemIndex:s,role:"worker",verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToObservability(n._pipelineContext)}})),v={operationId:r,operation:"map",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:n.name,itemIndex:s,verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToMeta(n._pipelineContext)};return this.buildResult(y,v)};return this.runWithVerification(g,{originalPrompt:f,inputFiles:c,verifyConfig:i,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:d,skills:u,composio:m,operationId:r,baseTag:l,retry:p,itemIndex:s,operation:"map",_pipelineContext:n._pipelineContext})}async executeMapItemWithBestOf(e,t,s,r,n,a,p){let c=this.getFiles(e),l=`${this.config.tag}-map-${s}`,i=this.evaluatePrompt(t,c,s);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:r,operation:"map",tag:l,sandboxId:"",itemIndex:s});let d=n.bestOf,u=d.n??d.taskAgents?.length;if(u===void 0||u<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:r,operation:"map",tag:l,sandboxId:"",itemIndex:s});let m=n.mcpServers??this.config.mcpServers,f=d.mcpServers??m,g=d.judgeMcpServers??d.mcpServers??m,h=n.skills??this.config.skills,b=d.skills??h,x=d.judgeSkills??d.skills??h,y=n.composio??this.config.composio,v=d.composio??y,k=d.judgeComposio??d.composio??y,w=await Promise.all(Array.from({length:u},async(Q,X)=>{let He=p?await _(Gt=>this.executeBestOfCandidate({inputFiles:c,prompt:i,candidateIndex:X,operationId:r,config:d,systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,mcpServers:f,skills:b,composio:v,timeoutMs:a,parentIndex:s,attempt:Gt,_pipelineContext:n._pipelineContext}),p,X):await this.executeBestOfCandidate({inputFiles:c,prompt:i,candidateIndex:X,operationId:r,config:d,systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,mcpServers:f,skills:b,composio:v,timeoutMs:a,parentIndex:s,_pipelineContext:n._pipelineContext});return d.onCandidateComplete?.(s,X,He.status==="success"?"success":"error"),He})),C=p?await _(Q=>this.executeBestOfJudge({inputFiles:c,taskPrompt:i,candidates:w,config:d,timeoutMs:a,operationId:r,systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,mcpServers:g,skills:x,composio:k,parentIndex:s,attempt:Q,_pipelineContext:n._pipelineContext}),{...p,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:i,candidates:w,config:d,timeoutMs:a,operationId:r,systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,mcpServers:g,skills:x,composio:k,parentIndex:s,_pipelineContext:n._pipelineContext}),S=w.findIndex(Q=>Q.status==="success"),U=C.decision?.winner??(S>=0?S:0),Ye=w[U]??w[0];d.onJudgeComplete?.(s,U,C.decision?.reasoning??"Judge failed to provide reasoning");let zt={operationId:r,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:n.name,candidateCount:u,...this.pipelineContextToMeta(n._pipelineContext)};return {...Ye,meta:{...Ye.meta,operation:"map",swarmName:this.config.tag,operationName:n.name,itemIndex:s,...this.pipelineContextToMeta(n._pipelineContext)},bestOf:{winnerIndex:U,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:zt,candidates:w}}}async executeFilterItem(e,t,s,r,n,a,p=1){let c=this.getFiles(e),l=p>1?`${this.config.tag}-filter-${s}-er${p-1}`:`${this.config.tag}-filter-${s}`,i=n.mcpServers??this.config.mcpServers,d=n.skills??this.config.skills,u=n.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(c,t,{systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,agent:n.agent,mcpServers:i,skills:d,composio:u,tagPrefix:l,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:n.name,operationId:r,operation:"filter",itemIndex:s,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(n._pipelineContext)}})),f={operationId:r,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:n.name,itemIndex:s,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(n._pipelineContext)};return this.buildResult(m,f,c)}async executeFilterItemWithVerify(e,t,s,r,n,a,p){let c=this.getFiles(e),l=`${this.config.tag}-filter-${s}`,i=n.verify,d=n.mcpServers??this.config.mcpServers,u=n.skills??this.config.skills,m=n.composio??this.config.composio,f=async(g,h,b)=>{let x=await this.semaphore.use(()=>this.execute(c,g,{systemPrompt:n.systemPrompt,schema:n.schema,schemaOptions:n.schemaOptions,agent:n.agent,mcpServers:d,skills:u,composio:m,tagPrefix:h,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:n.name,operationId:r,operation:"filter",itemIndex:s,role:"worker",verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(n._pipelineContext)}})),y={operationId:r,operation:"filter",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:n.name,itemIndex:s,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToMeta(n._pipelineContext)};return this.buildResult(x,y,c)};return this.runWithVerification(f,{originalPrompt:t,inputFiles:c,verifyConfig:i,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:d,skills:u,composio:m,operationId:r,baseTag:l,retry:p,itemIndex:s,operation:"filter",_pipelineContext:n._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:t,prompt:s,candidateIndex:r,operationId:n,config:a,timeoutMs:p,parentIndex:c,attempt:l=1,_pipelineContext:i}=e,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${r}`:`${this.config.tag}-bestof-cand-${r}`,u=l>1?`${d}-er${l-1}`:d,m=await this.semaphore.use(()=>this.execute(t,s,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:a.taskAgents?.[r],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:u,timeoutMs:p,observability:{swarmName:this.config.tag,operationId:n,operation:"map",itemIndex:c,role:"candidate",candidateIndex:r,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(i)}})),f={operationId:n,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:r,errorRetry:l>1?l-1:void 0,candidateIndex:r,...this.pipelineContextToMeta(i)};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((s,r)=>{s.status==="error"&&(t[`candidate_${r}/_failed.txt`]=`STATUS: FAILED
|
|
220
|
+
|
|
221
|
+
Error: ${s.error??"Unknown error"}`),Object.entries(s.files).forEach(([n,a])=>{t[`candidate_${r}/${n}`]=a;});}),t}async executeBestOfJudge(e){let{candidates:t,config:s,timeoutMs:r,operationId:n,parentIndex:a,attempt:p=1,_pipelineContext:c}=e,l=a!==void 0?`${this.config.tag}-map-${a}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=p>1?`${l}-er${p-1}`:l,d=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:t,systemPrompt:e.systemPrompt,schema:e.schema}),u=ge(d),m=O(Fe,{candidateCount:String(t.length),criteria:s.judgeCriteria,fileTree:u}),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(d,Ct,{systemPrompt:m,schema:f,agent:s.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:i,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:n,operation:"map",itemIndex:a,role:"judge",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(c)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let b=JSON.parse(g.rawData);console.warn(`Judge returned invalid winner ${b.winner}, defaulting to candidate 0`),h={winner:0,reasoning:b.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(([s,r])=>{t[`worker_output/${s}`]=r;}),t}async executeVerify(e){let{config:t,timeoutMs:s,operationId:r,workerTag:n,retryAttempt:a=1,operation:p,itemIndex:c,attemptIndex:l,_pipelineContext:i}=e,d=a>1?`${n}-verifier-er${a-1}`:`${n}-verifier`,u=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),b=O(Le,{criteria:t.criteria,fileTree:h}),x=await this.semaphore.use(()=>this.execute(g,St,{systemPrompt:b,schema:o.VerifyDecisionSchema,agent:t.verifierAgent,mcpServers:u,skills:m,composio:f,tagPrefix:d,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:r,operation:p,itemIndex:c,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(i)}})),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 O(Ne,{originalPrompt:e,feedback:t})}async runWithVerification(e,t){let{originalPrompt:s,inputFiles:r,verifyConfig:n,timeoutMs:a,operationId:p,baseTag:c,retry:l,itemIndex:i=0,operation:d,_pipelineContext:u}=t,m=n.maxAttempts??o.DEFAULT_VERIFY_MAX_ATTEMPTS,f=s,g=null,h=0;for(;h<m;){h++;let x=h>1?`${c}-vr${h-1}`:c,y=l?await _(w=>e(f,w>1?`${x}-er${w-1}`:x,h),l,i):await e(f,x,h);if(n.onWorkerComplete?.(i,h,y.status==="error"?"error":"success"),y.status==="error")return y;g=y;let v=l?await _(w=>this.executeVerify({inputFiles:r,outputFiles:y.files,taskPrompt:f,config:n,timeoutMs:a,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:p,workerTag:x,retryAttempt:w,operation:d,itemIndex:i,attemptIndex:h,_pipelineContext:u}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:r,outputFiles:y.files,taskPrompt:f,config:n,timeoutMs:a,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:p,workerTag:x,operation:d,itemIndex:i,attemptIndex:h,_pipelineContext:u}),k={operationId:p,operation:"verify",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(n.onVerifierComplete?.(i,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 w=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=o.buildRetryPromptWithFeedback(s,w);}}let b=h>1?`${c}-vr${h-1}`:c;return {...g,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:p,operation:"verify",tag:`${b}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,t,s){if(typeof e=="string")return e;try{return e(t,s)}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"]=E(e.schema)?B(e.schema):K(e.schema)),Object.entries(e.inputFiles).forEach(([s,r])=>{t[`worker_task/input/${s}`]=r;}),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,s){let r=s??e.files;return e.error?{[$]:true,status:"error",data:null,files:r,meta:t,error:e.error,rawData:e.rawData}:{[$]:true,status:"success",data:e.data,files:r,meta:t}}buildErrorResult(e,t){return {[$]:true,status:"error",data:null,files:{},meta:t,error:e}}};var xe=class o{swarm;steps;events;constructor(e,t=[],s={}){this.swarm=e,this.steps=t,this.events=s;}map(e){return new o(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new o(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new we(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,t){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new o(this.swarm,this.steps,{...this.events,[s]:t})}return new o(this.swarm,this.steps,{...this.events,...e})}async run(e){let t=crypto.randomBytes(8).toString("hex"),s=[],r=e,n=Date.now();for(let p=0;p<this.steps.length;p++){let c=this.steps[p],l=c.config.name,i=Date.now();this.events.onStepStart?.({type:c.type,index:p,name:l,itemCount:r.length});let d={pipelineRunId:t,pipelineStepIndex:p};try{let u=await this.executeStep(c,r,p,l,d),m=Date.now()-i;if(s.push({type:c.type,index:p,durationMs:m,results:u.output}),this.events.onStepComplete?.({type:c.type,index:p,name:l,durationMs:m,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),c.type==="reduce")return {pipelineRunId:t,steps:s,output:u.output,totalDurationMs:Date.now()-n};r=u.nextItems;}catch(u){throw this.events.onStepError?.({type:c.type,index:p,name:l,error:u instanceof Error?u:new Error(String(u))}),u}}let a=s[s.length-1];return {pipelineRunId:t,steps:s,output:a?.results??[],totalDurationMs:Date.now()-n}}async executeStep(e,t,s,r,n){if(e.type==="map"){let c=e.config,l=await this.swarm.map({items:t,...c,_pipelineContext:n,retry:this.wrapRetry(c.retry,s,r),verify:this.wrapVerify(c.verify,s,r),bestOf:this.wrapBestOf(c.bestOf,s,r)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,l=await this.swarm.filter({items:t,...c,_pipelineContext:n,retry:this.wrapRetry(c.retry,s,r),verify:this.wrapVerify(c.verify,s,r)}),i=c.emit??"success",d=i==="success"?l.success:i==="filtered"?l.filtered:[...l.success,...l.filtered];return {output:[...l],nextItems:d,successCount:l.success.length,errorCount:l.error.length,filteredCount:l.filtered.length}}let a=e.config,p=await this.swarm.reduce({items:t,...a,_pipelineContext:n,retry:this.wrapRetry(a.retry,s,r),verify:this.wrapVerify(a.verify,s,r)});return {output:p,nextItems:[],successCount:p.status==="success"?1:0,errorCount:p.status==="error"?1:0,filteredCount:0}}wrapRetry(e,t,s){if(e)return {...e,onItemRetry:(r,n,a)=>{e.onItemRetry?.(r,n,a),this.events.onItemRetry?.({stepIndex:t,stepName:s,itemIndex:r,attempt:n,error:a});}}}wrapVerify(e,t,s){if(e)return {...e,onWorkerComplete:(r,n,a)=>{e.onWorkerComplete?.(r,n,a),this.events.onWorkerComplete?.({stepIndex:t,stepName:s,itemIndex:r,attempt:n,status:a});},onVerifierComplete:(r,n,a,p)=>{e.onVerifierComplete?.(r,n,a,p),this.events.onVerifierComplete?.({stepIndex:t,stepName:s,itemIndex:r,attempt:n,passed:a,feedback:p});}}}wrapBestOf(e,t,s){if(e)return {...e,onCandidateComplete:(r,n,a)=>{e.onCandidateComplete?.(r,n,a),this.events.onCandidateComplete?.({stepIndex:t,stepName:s,itemIndex:r,candidateIndex:n,status:a});},onJudgeComplete:(r,n,a)=>{e.onJudgeComplete?.(r,n,a),this.events.onJudgeComplete?.({stepIndex:t,stepName:s,itemIndex:r,winnerIndex:n,reasoning:a});}}}},we=class o extends xe{constructor(e,t,s){super(e,t,s);}on(e,t){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new o(this.swarm,this.steps,{...this.events,[s]:t})}return new o(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=Yt;exports.Agent=q;exports.Evolve=Z;exports.JUDGE_PROMPT=Fe;exports.Pipeline=xe;exports.RETRY_FEEDBACK_PROMPT=Ne;exports.SCHEMA_PROMPT=kt;exports.SWARM_RESULT_BRAND=$;exports.SYSTEM_PROMPT=wt;exports.Semaphore=V;exports.Swarm=Ge;exports.SwarmResultList=W;exports.TerminalPipeline=we;exports.VALIDATION_PRESETS=ke;exports.VERIFY_PROMPT=Le;exports.WORKSPACE_PROMPT=bt;exports.WORKSPACE_SWE_PROMPT=xt;exports.applyTemplate=O;exports.buildWorkerSystemPrompt=Be;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=Ht;exports.isZodSchema=E;exports.jsonSchemaToString=K;exports.listCheckpoints=ze;exports.parseNdjsonLine=on;exports.parseNdjsonOutput=sn;exports.parseQwenOutput=Ze;exports.readLocalDir=at;exports.resolveStorageConfig=be;exports.saveLocalDir=ct;exports.writeClaudeMcpConfig=ne;exports.writeCodexMcpConfig=se;exports.writeGeminiMcpConfig=ie;exports.writeMcpConfig=Pe;exports.writeQwenMcpConfig=oe;exports.zodSchemaToJson=B;
|