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