@evolvingmachines/sdk 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,197 @@
1
+ import {EventEmitter}from'events';import Ht from'ajv';import Et from'zod-to-json-schema';import*as P 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';var bt={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen"},me={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var fe={claude:{templateId:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-5-20251101",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-5-20250929",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},availableBetas:{CONTEXT_1M:"context-1m-2025-08-07"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.claude/skills"},buildCommand:({prompt:c,model:e,isResume:n,betas:s})=>{let r=n?"--continue ":"",o=s?.length?`--betas ${s.join(",")} `:"";return `echo "${c}" | claude -p ${r}${o}--model ${e} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{templateId:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.2",models:[{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Base model"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Code-optimized"},{alias:"gpt-5.1-codex-max",modelId:"gpt-5.1-codex-max",description:"Best reasoning (xhigh effort)"},{alias:"gpt-5.1-mini",modelId:"gpt-5.1-mini",description:"Smaller/faster"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.codex/skills"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:c,model:e,isResume:n,reasoningEffort:s})=>{let r=s?` -c model_reasoning_effort="${s}"`:"";return `printf '%s' "${c}" | codex exec --model ${e}${r} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{templateId:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3-flash-preview",models:[{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Latest pro preview"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Latest flash preview"},{alias:"gemini-2.5-pro",modelId:"gemini-2.5-pro",description:"Complex tasks, deep reasoning"},{alias:"gemini-2.5-flash",modelId:"gemini-2.5-flash",description:"Balance speed/reasoning"},{alias:"gemini-2.5-flash-lite",modelId:"gemini-2.5-flash-lite",description:"Simple tasks, fastest"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.gemini/skills"},usePassthroughGateway:true,buildCommand:({prompt:c,model:e,isResume:n})=>`gemini "${c}" ${n?"--resume latest ":""}--model ${e} --yolo --output-format stream-json`},qwen:{templateId:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"qwen3-coder-plus",models:[{alias:"qwen3-coder-plus",modelId:"qwen3-coder-plus",description:"Code generation, debugging"},{alias:"qwen3-vl-plus",modelId:"qwen3-vl-plus",description:"Vision + language, multimodal"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.qwen/skills",enableFlag:"--experimental-skills"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:c,model:e,isResume:n,isDirectMode:s,skills:r})=>{let o=n?"--continue ":"",a=r?.length?"--experimental-skills ":"",l=s||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${c}" ${o}${a}--model ${l} --yolo --output-format stream-json`}}};function M(c){let e=fe[c];if(!e)throw new Error(`Unknown agent type: ${c}`);return e}function wt(c){return c in fe}function ge(c){return c.replace(/^~/,"/home/user")}function $(c){let e=M(c);return `${ge(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function U(c){let e=M(c);return ge(e.mcpConfig.settingsDir)}function V(c){if(c instanceof Error){let e=c.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function he(c,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${c}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${c}" cannot specify both command and url`)}function ye(c){for(let[e,n]of Object.entries(c))he(e,n);}function ve(c){return c.type?c.type:c.command?"stdio":"sse"}function Ct(c){let e=ve(c);return {...c,type:e}}function St(c){let{type:e,url:n,...s}=c;return ve(c)==="http"&&n?{httpUrl:n,...s}:n?{url:n,...s}:s}function kt(c){return {type:ve(c),...c}}async function Fe(c,e,n,s){ye(n);let r=U(e),o=$(e);await c.files.makeDir(r);let a={};try{let i=await c.files.read(o);typeof i=="string"&&(a=JSON.parse(i));}catch(i){if(!V(i))throw i}let l=Object.fromEntries(Object.entries(n).map(([i,p])=>[i,s(p)]));await c.files.write(o,JSON.stringify({...a,mcpServers:l},null,2));}async function Q(c,e,n){ye(n);let s=U("claude"),r=$("claude"),o=Object.fromEntries(Object.entries(n).map(([l,i])=>[l,kt(i)]));await c.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:o},null,2)),await c.files.makeDir(s);let a={};try{let l=await c.files.read(r);typeof l=="string"&&(a=JSON.parse(l));}catch(l){if(!V(l))throw l}a.enableAllProjectMcpServers=true,await c.files.write(r,JSON.stringify(a,null,2));}async function X(c,e){await Fe(c,"gemini",e,Ct);}async function ee(c,e){await Fe(c,"qwen",e,St);}function _(c){return typeof c=="string"?`"${c.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(c)?`[${c.map(e=>_(e)).join(", ")}]`:typeof c=="object"&&c!==null?`{ ${Object.entries(c).map(([n,s])=>`${n} = ${_(s)}`).join(", ")} }`:typeof c=="boolean"?c?"true":"false":String(c)}async function te(c,e){for(let[i,p]of Object.entries(e))he(i,p);let n=U("codex"),s=$("codex");await c.files.makeDir(n);let r="";try{let i=await c.files.read(s);typeof i=="string"&&(r=i);}catch(i){if(!V(i))throw i}let o=[],a=[];r.includes("experimental_use_rmcp_client")||(o.push("# Enable improved RMCP client (recommended)"),o.push("experimental_use_rmcp_client = true")),r.includes("[mcp_servers]")||a.push("[mcp_servers]","");for(let[i,p]of Object.entries(e)){if(r.includes(`[mcp_servers.${i}]`))continue;a.push(`[mcp_servers.${i}]`);let t=p.type??(p.command?"stdio":"http");if(t==="http"||t==="sse"||!!p.url){if(!p.url)throw new Error(`MCP server "${i}" is missing url for ${t} transport`);a.push(`url = ${_(p.url)}`),p.bearerTokenEnvVar&&a.push(`bearer_token_env_var = ${_(p.bearerTokenEnvVar)}`);let d=p.httpHeaders??p.headers;d&&Object.keys(d).length>0&&a.push(`http_headers = ${_(d)}`),p.envHttpHeaders&&Object.keys(p.envHttpHeaders).length>0&&a.push(`env_http_headers = ${_(p.envHttpHeaders)}`);}else a.push(`command = ${_(p.command)}`),p.args&&p.args.length>0&&a.push(`args = ${_(p.args)}`),p.cwd&&a.push(`cwd = ${_(p.cwd)}`);p.env&&Object.keys(p.env).length>0&&a.push(`env = ${_(p.env)}`),p.envVars&&p.envVars.length>0&&a.push(`env_vars = ${_(p.envVars)}`),a.push("");}let l=[r.trim(),o.join(`
2
+ `),a.join(`
3
+ `)].filter(i=>i.length>0);await c.files.write(s,l.join(`
4
+
5
+ `)+`
6
+ `);}async function xe(c,e,n,s){if(!(!s||Object.keys(s).length===0))switch(c){case "claude":await Q(e,n,s);break;case "codex":await te(e,s);break;case "gemini":await X(e,s);break;case "qwen":await ee(e,s);break;default:throw new Error(`Unknown agent type for MCP config: ${c}`)}}function ne(){let c={};return function(p){let t;try{t=JSON.parse(p);}catch{return null}if(t._meta||t._prompt)return null;let u=t.session_id;switch(t.type){case "system":return null;case "assistant":return e(t.message?.content,"assistant",u);case "user":{let d=t.message?.content;return typeof d=="string"||Array.isArray(d)&&d.length===1&&d[0].type==="text"?null:e(d,"user",u)}case "result":return null;default:return null}};function e(i,p,t){if(typeof i=="string")return p==="user"?null:[{sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}}}];if(!i||!Array.isArray(i))return null;let u=[];for(let d of i){let m=null;switch(d.type){case "text":case "text_delta":if(p==="user")break;m={sessionUpdate:"agent_message_chunk",content:{type:"text",text:d.text}};break;case "image":if(p==="user")break;m={sessionUpdate:"agent_message_chunk",content:{type:"image",data:d.source?.type==="base64"?d.source.data:"",mimeType:d.source?.type==="base64"?d.source.media_type:"",uri:d.source?.type==="url"?d.source.url:void 0}};break;case "thinking":case "thinking_delta":m={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:d.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(c[d.id]=d,d.name==="TodoWrite")Array.isArray(d.input?.todos)&&(m={sessionUpdate:"plan",entries:a(d.input)});else {let f=n(d);m={sessionUpdate:"tool_call",toolCallId:d.id,status:"pending",...f};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let f=c[d.tool_use_id];if(!f||(delete c[d.tool_use_id],f.name==="TodoWrite"))break;m={sessionUpdate:"tool_call_update",toolCallId:d.tool_use_id,status:"is_error"in d&&d.is_error?"failed":"completed",...s(d,f)};break}}m&&u.push({sessionId:t,update:m});}return u.length>0?u:null}function n(i){let p=i.name,t=i.input||{};switch(p){case "Task":return {title:t.description||"Task",kind:"think",content:t.prompt?[{type:"content",content:{type:"text",text:t.prompt}}]:[],rawInput:t};case "NotebookRead":return {title:t.notebook_path?`Read Notebook ${t.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:t.notebook_path?[{path:t.notebook_path}]:[],rawInput:t};case "NotebookEdit":return {title:t.notebook_path?`Edit Notebook ${t.notebook_path}`:"Edit Notebook",kind:"edit",content:t.new_source?[{type:"content",content:{type:"text",text:t.new_source}}]:[],locations:t.notebook_path?[{path:t.notebook_path}]:[],rawInput:t};case "Bash":return {title:t.command?"`"+t.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:t.description?[{type:"content",content:{type:"text",text:t.description}}]:[],rawInput:t};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:t};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:t};case "Read":{let u="";return t.limit?u=" ("+((t.offset??0)+1)+" - "+((t.offset??0)+t.limit)+")":t.offset&&(u=" (from line "+(t.offset+1)+")"),{title:"Read "+(t.file_path??"File")+u,kind:"read",content:[],locations:t.file_path?[{path:t.file_path,line:t.offset??0}]:[],rawInput:t}}case "LS":return {title:t.path?`List \`${t.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:t};case "Edit":{let u=t.file_path;return {title:u?`Edit \`${u}\``:"Edit",kind:"edit",content:u?[{type:"diff",path:u,oldText:t.old_string??null,newText:t.new_string??""}]:[],locations:u?[{path:u}]:[],rawInput:t}}case "Write":return {title:t.file_path?`Write ${t.file_path}`:"Write",kind:"edit",content:t.file_path?[{type:"diff",path:t.file_path,oldText:null,newText:t.content??""}]:[],locations:t.file_path?[{path:t.file_path}]:[],rawInput:t};case "Glob":{let u="Find";return t.path&&(u+=` \`${t.path}\``),t.pattern&&(u+=` \`${t.pattern}\``),{title:u,kind:"search",content:[],locations:t.path?[{path:t.path}]:[],rawInput:t}}case "Grep":{let u="grep";return t["-i"]&&(u+=" -i"),t["-n"]&&(u+=" -n"),t["-A"]!==void 0&&(u+=` -A ${t["-A"]}`),t["-B"]!==void 0&&(u+=` -B ${t["-B"]}`),t["-C"]!==void 0&&(u+=` -C ${t["-C"]}`),t.output_mode==="files_with_matches"?u+=" -l":t.output_mode==="count"&&(u+=" -c"),t.head_limit!==void 0&&(u+=` | head -${t.head_limit}`),t.glob&&(u+=` --include="${t.glob}"`),t.type&&(u+=` --type=${t.type}`),t.multiline&&(u+=" -P"),u+=` "${t.pattern??""}"`,t.path&&(u+=` ${t.path}`),{title:u,kind:"search",content:[],rawInput:t}}case "WebFetch":return {title:t.url?`Fetch ${t.url}`:"Fetch",kind:"fetch",content:t.prompt?[{type:"content",content:{type:"text",text:t.prompt}}]:[],rawInput:t};case "WebSearch":{let u=`"${t.query??""}"`;return t.allowed_domains?.length>0&&(u+=` (allowed: ${t.allowed_domains.join(", ")})`),t.blocked_domains?.length>0&&(u+=` (blocked: ${t.blocked_domains.join(", ")})`),{title:u,kind:"fetch",content:[],rawInput:t}}case "TodoWrite":return {title:Array.isArray(t.todos)?`Update TODOs: ${t.todos.map(u=>u.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:t};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:t.plan?[{type:"content",content:{type:"text",text:t.plan}}]:[],rawInput:t};default:if(p?.startsWith("mcp__")){let u=p.split("__"),d=u[1]||"mcp",m=u.slice(2).join("__")||p;return {title:`${d}: ${m}`,kind:"other",content:[],rawInput:t}}return {title:p||"Unknown Tool",kind:"other",content:[],rawInput:t}}}function s(i,p){let t=i.content;switch(p?.name){case "Read":return Array.isArray(t)&&t.length>0?{content:t.map(u=>({type:"content",content:u.type==="text"?{type:"text",text:l(u.text)}:o(u,false)}))}:typeof t=="string"&&t.length>0?{content:[{type:"content",content:{type:"text",text:l(t)}}]}:{};case "Edit":case "Write":case "Bash":return i.is_error&&t?r(t,true):{};case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return r(t,"is_error"in i?i.is_error:false)}}function r(i,p=false){return Array.isArray(i)&&i.length>0?{content:i.map(t=>({type:"content",content:o(t,p)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:p?"```\n"+i+"\n```":i}}]}:{}}function o(i,p){if(i.type==="text")return p?{type:"text",text:"```\n"+i.text+"\n```"}:{type:"text",text:i.text};if(i.type==="image"){if(i.data&&i.mimeType)return {type:"image",data:i.data,mimeType:i.mimeType};if(i.source?.type==="base64")return {type:"image",data:i.source.data||"",mimeType:i.source.media_type||""};if(i.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:i.source.url}}return i}function a(i){return i.todos.map(p=>({content:p.content,status:p.status||"pending",priority:"medium"}))}function l(i){let p="```",t=Array.from(i.matchAll(/^```+/gm));for(let[u]of t)for(;u.length>=p.length;)p+="`";return p+`
7
+ `+i+(i.endsWith(`
8
+ `)?"":`
9
+ `)+p}}function se(){return function(i){let p;try{p=JSON.parse(i);}catch{return null}if(p._meta||p._prompt)return null;let t=[];switch(p.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let u=p.item;if(!u)return null;let d=e(u);d&&t.push({update:d});break}case "item.updated":{let u=p.item;if(!u)return null;let d=n(u);d&&t.push({update:d});break}case "item.completed":{let u=p.item;if(!u)return null;let d=s(u);d&&t.push({update:d});break}default:return null}return t.length>0?t:null};function e(l){let i=l.id;switch(l.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${l.server}:${l.tool}`},{sessionUpdate:"tool_call",toolCallId:i,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:i,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:i,title:`Search: ${l.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(l.items)};default:return null}}function n(l){return l.type==="todo_list"?{sessionUpdate:"plan",entries:a(l.items)}:null}function s(l){let i=l.id;switch(l.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.text??l.summary?.join(`
10
+ `)??l.content?.join(`
11
+ `)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text??""}};case "mcp_tool_call":{let t=r(l.result),u=l.status==="failed"||l.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:i,status:u,content:t}}case "command_execution":{let t=l.aggregated_output?[{type:"content",content:{type:"text",text:l.aggregated_output}}]:[],u=l.status==="completed"||l.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:i,status:u,content:t}}case "file_change":{let t=l.changes??[],u=t.map(m=>({path:m.path})),d=t.length===1?`${t[0].kind==="add"?"Create":"Edit"} ${t[0].path}`:`Edit ${t.length} files`;return {sessionUpdate:"tool_call",toolCallId:i,title:d,kind:"edit",status:l.status==="completed"?"completed":"failed",content:t.map(m=>({type:"diff",path:m.path,oldText:m.kind==="add"?null:"",newText:""})),locations:u}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:i,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(i=>({type:"content",content:o(i)})):typeof l.content=="string"?[{type:"content",content:{type:"text",text:l.content}}]:[]:[]}function o(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 i=false;return l.map(p=>{let t;return p.completed?t="completed":i?t="pending":(t="in_progress",i=true),{content:p.text??"",status:t,priority:"medium"}})}}var Tt={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 ie(){return function(a){let l;try{l=JSON.parse(a);}catch{return null}if(l._meta||l._prompt)return null;let i=l.session_id,p=[];switch(l.type){case "init":case "result":return null;case "message":{let t=c(l);t&&p.push({sessionId:i,update:t});break}case "tool_use":{let t=e(l);t&&p.push({sessionId:i,update:t});break}case "tool_result":{let t=n(l);t&&p.push({sessionId:i,update:t});break}case "error":{let t=s(l);t&&p.push({sessionId:i,update:t});break}default:return null}return p.length>0?p:null};function c(o){let a=o.role,l=o.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(o){let a=o.tool_id,l=o.tool_name,i=o.parameters||{},{title:p,kind:t,content:u,locations:d}=r(l,i);return {sessionUpdate:"tool_call",toolCallId:a,title:p,kind:t,status:"pending",rawInput:i,content:u,locations:d}}function n(o){let a=o.tool_id,l=o.status,i=o.output,p=o.error,t=[];return i&&typeof i=="string"&&i.length>0&&t.push({type:"content",content:{type:"text",text:l==="error"?`\`\`\`
12
+ ${i}
13
+ \`\`\``:i}}),p?.message&&!i&&t.push({type:"content",content:{type:"text",text:`\`\`\`
14
+ ${p.message}
15
+ \`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:a,status:l==="success"?"completed":"failed",content:t}}function s(o){let a=o.severity,l=o.message;return l?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${l}`}}:null}function r(o,a){let l=Tt[o]||"other",i=[],p=[],t=o;switch(o){case "read_file":t=`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":t=`Write ${a.file_path||"file"}`,a.file_path&&(p.push({path:a.file_path}),i.push({type:"diff",path:a.file_path,oldText:null,newText:a.content||""}));break;case "edit_file":t=`Edit ${a.file_path||"file"}`,a.file_path&&p.push({path:a.file_path});break;case "replace":t=`Edit ${a.file_path||"file"}`,a.file_path&&(p.push({path:a.file_path}),(a.old_string!==void 0||a.new_string!==void 0)&&i.push({type:"diff",path:a.file_path,oldText:a.old_string||"",newText:a.new_string||""}));break;case "run_shell_command":case "shell":t=a.command?`\`${a.command}\``:"Run command",a.description&&i.push({type:"content",content:{type:"text",text:a.description}});break;case "brave_web_search":case "web_search":case "google_web_search":t=a.query?`"${a.query}"`:"Web search";break;case "web_fetch":t=a.prompt?`Fetch: ${a.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":t=`Find ${a.pattern||"files"}`,a.dir_path&&p.push({path:a.dir_path});break;case "grep":case "search_file_content":t=`grep "${a.pattern||a.query||""}"`;break;case "list_directory":t=`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":t=`Read ${a.include?.length||"multiple"} files`,Array.isArray(a.include)&&a.include.forEach(u=>p.push({path:u}));break;case "delegate_to_agent":t=a.agent_name?`Agent: ${a.agent_name}`:"Delegate to agent";break;case "write_todos":t="Update todos";break;case "save_memory":t=a.fact?`Remember: "${a.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":t=a.name?`Activate skill: ${a.name}`:"Activate skill";break;default:t=o;}return {title:t,kind:l,content:i,locations:p}}}var _t={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 oe(){let c=new Map,e=new Map;return function(t){let u;try{u=JSON.parse(t);}catch{return null}if(!u||typeof u!="object")return null;let d=u;if("_meta"in d||"_prompt"in d)return null;let m=d.session_id||void 0,f=[];switch(d.type){case "assistant":{let h=n(d);for(let g of h)f.push({sessionId:m,update:g});break}case "stream_event":{let h=s(d);for(let g of h)f.push({sessionId:m,update:g});break}case "user":{let h=r(d);for(let g of h)f.push({sessionId:m,update:g});break}case "system":case "result":return null;default:return null}return f.length>0?f:null};function n(p){let t=[],u=p.message?.content;if(!Array.isArray(u))return t;for(let d of u){let m=o(d);t.push(...m);}return t}function s(p){let t=[],u=p.event;if(!u)return t;switch(u.type){case "content_block_start":{let d=u.index??0,m=u.content_block;m&&(c.set(d,m),m.type==="tool_use"&&e.set(d,""));break}case "content_block_delta":{let d=u.index??0,m=u.delta,f=c.get(d);if(m?.type==="text_delta"&&m.text)t.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:m.text}});else if(m?.type==="thinking_delta"&&m.thinking)t.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 h=e.get(d)||"";e.set(d,h+m.partial_json);}break}case "content_block_stop":{let d=u.index??0,m=c.get(d);if(m&&!(m.type==="text"&&m.text)){if(!(m.type==="thinking"&&m.thinking)){if(m.type==="tool_use"){let f=m,h=e.get(d)||"";e.delete(d);let g=f.input;if(h)try{g=JSON.parse(h);}catch{}let y={...f,input:g},v=a(y);v&&t.push(v);}else if(m.type==="tool_result"){let f=l(m);f&&t.push(f);}}}c.delete(d);break}}return t}function r(p){let t=p.message?.content,u=[];if(typeof t=="string")return u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:t}}),u;if(Array.isArray(t)){for(let d of t)if(d.type==="text")u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:d.text}});else if(d.type==="tool_result"){let m=l(d);m&&u.push(m);}}return u}function o(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 t=a(p);return t?[t]:[]}case "tool_result":{let t=l(p);return t?[t]:[]}}}function a(p){let t=p.id,u=p.name,d=p.input;if(u==="TodoWrite"&&Array.isArray(d?.todos))return {sessionUpdate:"plan",entries:d.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:m,kind:f,content:h,locations:g}=i(u,d||{});return {sessionUpdate:"tool_call",toolCallId:t,title:m,kind:f,status:"pending",rawInput:d,content:h,locations:g}}function l(p){let t=p.tool_use_id,u=p.is_error??false,d=p.content,m=[];if(typeof d=="string"&&d.length>0)m.push({type:"content",content:{type:"text",text:u?`\`\`\`
16
+ ${d}
17
+ \`\`\``:d}});else if(Array.isArray(d)){for(let f of d)if(f.type==="text"){let h=f.text;m.push({type:"content",content:{type:"text",text:u?`\`\`\`
18
+ ${h}
19
+ \`\`\``:h}});}}return {sessionUpdate:"tool_call_update",toolCallId:t,status:u?"failed":"completed",content:m}}function i(p,t){let u=_t[p]||"other",d=[],m=[],f=p;switch(p){case "Read":case "read_file":f=`Read ${t.file_path||t.absolute_path||"file"}`,(t.file_path||t.absolute_path)&&m.push({path:t.file_path||t.absolute_path});break;case "Write":case "write_file":f=`Write ${t.file_path||"file"}`,t.file_path&&(m.push({path:t.file_path}),d.push({type:"diff",path:t.file_path,oldText:null,newText:t.content||""}));break;case "Edit":case "edit_file":f=`Edit ${t.file_path||"file"}`,t.file_path&&m.push({path:t.file_path});break;case "Bash":case "shell":case "run_shell_command":f=t.command?`\`${t.command}\``:"Run command",t.description&&d.push({type:"content",content:{type:"text",text:t.description}});break;case "WebFetch":f=t.url?`Fetch ${t.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=t.query?`"${t.query}"`:"Web search";break;case "Glob":f=`Find ${t.pattern||"files"}`,t.path&&m.push({path:t.path});break;case "Grep":f=`grep "${t.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${t.path||"directory"}`,t.path&&m.push({path:t.path});break;case "Task":f=t.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=p;}return {title:f,kind:u,content:d,locations:m}}}function $e(c){return oe()(c)}function I(c){switch(c){case "claude":return ne();case "codex":return se();case "gemini":return ie();case "qwen":return oe();default:return ()=>null}}function Rt(c,e){let n=e.trim();return n?I(c)(n):null}function Pt(c,e){let n=[],s=e.split(`
20
+ `),r=I(c);for(let o of s){let a=o.trim();if(!a)continue;let l=r(a);l&&n.push(...l);}return n}function K(){return process.env.EVOLVE_GATEWAY_URL||"https://evolve-gateway-692833842999.us-central1.run.app"}function Ue(){return `${K()}`}function Be(){return `${K()}/e2b`}function Ne(c){return {"browser-use":{type:"http",url:`${K()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${c}`}}}}var O="EVOLVE_API_KEY",re="E2B_API_KEY",je="claude",W=36e5,Le=4,be=100,Ve="/home/user/workspace",J="https://dashboard.evolvingmachines.ai",Ke=".evolve-sdk/observability/sessions",We=100,Je=5e3,ae=3,we=1e3;function R(c){return c!==null&&typeof c=="object"&&"safeParse"in c&&typeof c.safeParse=="function"}function B(c){return JSON.stringify(Et(c,{target:"jsonSchema7"}),null,2)}function N(c){return JSON.stringify(c,null,2)}function Ye(c,e=false){let n={};function s(r,o){for(let a of P.readdirSync(r)){let l=Y.join(r,a),i=o?`${o}/${a}`:a;P.statSync(l).isDirectory()?e&&s(l,i):n[i]=P.readFileSync(l);}}return s(c,""),n}function Ge(c,e){for(let[n,s]of Object.entries(e)){let r=Y.join(c,n),o=Y.dirname(r);P.mkdirSync(o,{recursive:true});let a;s instanceof ArrayBuffer||s instanceof Uint8Array?a=Buffer.from(s):a=s,P.writeFileSync(r,a);}}function Ce(c){let e=c?.type??je,n=M(e);if(c?.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:c.oauthToken,isDirectMode:true,isOAuth:true,model:c.model,reasoningEffort:c.reasoningEffort,betas:c.betas}}if(c?.providerApiKey){let a=c.providerBaseUrl??process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:c.providerApiKey,baseUrl:a,isDirectMode:true,model:c.model,reasoningEffort:c.reasoningEffort,betas:c.betas}}if(c?.apiKey)return {type:e,apiKey:c.apiKey,isDirectMode:false,model:c.model,reasoningEffort:c.reasoningEffort,betas:c.betas};let s=process.env[O];if(s)return {type:e,apiKey:s,isDirectMode:false,model:c?.model,reasoningEffort:c?.reasoningEffort,betas:c?.betas};let r=process.env[n.apiKeyEnv];if(r){let a=process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:r,baseUrl:a,isDirectMode:true,model:c?.model,reasoningEffort:c?.reasoningEffort,betas:c?.betas}}if(n.oauthEnv){let a=process.env[n.oauthEnv];if(a)return {type:e,apiKey:a,isDirectMode:true,isOAuth:true,model:c?.model,reasoningEffort:c?.reasoningEffort,betas:c?.betas}}let o=n.oauthEnv?`, oauthToken (Claude Max), or ${n.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${o}, or ${O} / ${n.apiKeyEnv} env var.`)}async function Se(){let c=process.env[O];if(c)try{let{createE2BProvider:n}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=Be(),n({apiKey:c})}catch(n){let s=n;throw s.message?.includes("Cannot find module")||s.message?.includes("MODULE_NOT_FOUND")?new Error(`${O} is set but @evolvingmachines/e2b failed to load.
21
+ Try reinstalling: npm install @evolvingmachines/sdk`):s}let e=process.env[re];if(e)try{let{createE2BProvider:n}=await import('@evolvingmachines/e2b');return n({apiKey:e})}catch(n){let s=n;throw s.message?.includes("Cannot find module")||s.message?.includes("MODULE_NOT_FOUND")?new Error(`${re} is set but @evolvingmachines/e2b failed to load.
22
+ Try reinstalling: npm install @evolvingmachines/sdk`):s}throw new Error(`No sandbox provider configured. Either:
23
+ 1. Set ${O} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
24
+ 2. Set ${re} environment variable (direct E2B access, get key at https://e2b.dev)
25
+ 3. Pass sandbox explicitly: .withSandbox(provider)`)}function Mt(c){return new Promise(e=>setTimeout(e,c))}async function T(c,e,n=0){let s=It(e),r=e?.onItemRetry,o=null,a=0,l=s.backoffMs;for(;a<s.maxAttempts;){if(a++,o=await c(a),!s.retryOn(o))return o;if(a>=s.maxAttempts)break;if(r){let i=o.error??"Unknown error";r(n,a,i);}await Mt(l),l*=s.backoffMultiplier;}return o}function It(c){return {maxAttempts:c?.maxAttempts??3,backoffMs:c?.backoffMs??1e3,backoffMultiplier:c?.backoffMultiplier??2,retryOn:c?.retryOn??(e=>e.status==="error")}}var ze=`## FILESYSTEM INSTRUCTIONS:
26
+
27
+ You are running in a sandbox environment.
28
+
29
+ The file system is mounted at \`{{workingDir}}/\`
30
+
31
+ Your present working directory: \`{{workingDir}}/\`
32
+
33
+ IMPORTANT - Directory structure:
34
+ \`\`\`
35
+ {{workingDir}}/
36
+ \u251C\u2500\u2500 context/ # Input files (read-only) provided by the user
37
+ \u251C\u2500\u2500 scripts/ # Your code goes here
38
+ \u251C\u2500\u2500 temp/ # Scratch space
39
+ \u2514\u2500\u2500 output/ # Where you can save final deliverables
40
+ \`\`\`
41
+
42
+ ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/\` as files.
43
+ ### Never just state results as text.
44
+
45
+ - The file system is being used as the main communication channel between the agent (you) and the user.
46
+ - Hence, all outputs results must be saved to the \`output/\` folder as files. The user will only be able to view the files in the \`output/\` folder.
47
+ - There are several reasons why we need to save the results to the \`output/\` folder:
48
+ - The user might be building a long-running agent which could be interrupted and resumed later.
49
+ - The user might pass the outputs to another agent for verification or further processing.
50
+ - etc.
51
+ `;var qe=`## FILESYSTEM INSTRUCTIONS:
52
+
53
+ You are running in a sandbox environment.
54
+
55
+ The file system is mounted at \`{{workingDir}}/\`
56
+
57
+ Your present working directory: \`{{workingDir}}/\`
58
+
59
+ IMPORTANT - Directory structure:
60
+ \`\`\`
61
+ {{workingDir}}/
62
+ \u251C\u2500\u2500 repo/ # Code repository
63
+ \u251C\u2500\u2500 context/ # Input files (read-only) provided by the user
64
+ \u251C\u2500\u2500 scripts/ # Your code goes here
65
+ \u251C\u2500\u2500 temp/ # Scratch space
66
+ \u2514\u2500\u2500 output/ # Final deliverables
67
+ \`\`\`
68
+
69
+ ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/\` as files.
70
+ ### Never just state results as text.
71
+
72
+ - The file system is being used as the main communication channel between the agent (you) and the user.
73
+ - Hence, all outputs results must be saved to the \`output/\` folder as files. The user will only be able to view the files in the \`output/\` folder.
74
+ - There are several reasons why we need to save the results to the \`output/\` folder:
75
+ - The user might be building a long-running agent which could be interrupted and resumed later.
76
+ - The user might pass the outputs to another agent for verification or further processing.
77
+ - etc.
78
+ `;var He=`## SYSTEM PROMPT
79
+
80
+ {{systemPrompt}}`;var Ze=`## STRUCTURED OUTPUT
81
+
82
+ Your final result MUST be saved to \`output/result.json\` following this schema:
83
+
84
+ \`\`\`json
85
+ {{schema}}
86
+ \`\`\`
87
+
88
+ You are free to:
89
+ - Reason through the problem step by step
90
+ - Read and analyze context files
91
+ - Use any available tools
92
+ - Process incrementally
93
+ - Create intermediate files in \`temp/\` or \`scripts/\`
94
+
95
+ But your final \`output/result.json\` MUST conform to the schema above.
96
+
97
+ ### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
98
+ ### Never just state results as text.`;var Qe=`### 1. YOUR ROLE: BEST OF N JUDGE
99
+
100
+ 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.
101
+
102
+ ### 2. CONTEXT STRUCTURE
103
+
104
+ \`\`\`
105
+ {{fileTree}}
106
+ \`\`\`
107
+
108
+ ### 3. YOUR EVALUATION CRITERIA
109
+
110
+ You must judge their work based on:
111
+
112
+ \`\`\`
113
+ {{criteria}}
114
+ \`\`\`
115
+
116
+ ### 4. YOUR PROCESS
117
+
118
+ 1. Read \`worker_task/\` to understand the task:
119
+ - Review the worker system prompt and task prompt
120
+ - Check the expected output schema (if present)
121
+ - Examine the worker input files in \`input/\`
122
+ 2. Carefully review EACH solution attempt in \`candidate_i/\`
123
+ 3. Compare outputs against the evaluation criteria
124
+ 4. Reason through your findings \u2014 perform all necessary evidence-based analyses and verifications before deciding
125
+ 5. Pick the best candidate (0-indexed)
126
+
127
+ **IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
128
+ `;var Xe=`### 1. YOUR ROLE: OUTPUT VERIFIER
129
+
130
+ 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.
131
+
132
+ ### 2. CONTEXT STRUCTURE
133
+
134
+ \`\`\`
135
+ {{fileTree}}
136
+ \`\`\`
137
+
138
+ ### 3. VERIFICATION CRITERIA
139
+
140
+ The output must satisfy:
141
+
142
+ \`\`\`
143
+ {{criteria}}
144
+ \`\`\`
145
+
146
+ ### 4. YOUR PROCESS
147
+
148
+ 1. Read \`worker_task/\` to understand what was asked:
149
+ - Review the worker system prompt (if present)
150
+ - Review the task prompt
151
+ - Check the expected output schema (if present)
152
+ - Examine any input files in \`input/\`
153
+ 2. Carefully review the worker's output in \`worker_output/\`
154
+ 3. Evaluate against the verification criteria
155
+ 4. Reason through your findings
156
+ 5. Make your decision
157
+
158
+ **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.
159
+
160
+ If failing, provide specific, actionable feedback explaining what needs to be fixed.
161
+ `;var et=`### CONTEXT STRUCTURE
162
+
163
+ \`\`\`
164
+ {{fileTree}}
165
+ \`\`\`
166
+
167
+ Examine all files within each item folder before producing your output.
168
+ `;var tt="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var nt="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var st=`{{originalPrompt}}
169
+
170
+ ## IMPORTANT: Previous Attempt Failed Verification
171
+
172
+ Your previous attempt did not pass quality verification. Please address this feedback:
173
+
174
+ {{feedback}}
175
+
176
+ Make sure your output addresses all the feedback points above.
177
+ `;var it=ze,ot=qe,rt=He,at=Ze,ke=Qe,ct=tt,Te=Xe,lt=nt,pt=et,_e=st;function E(c,e){let n=c;for(let[s,r]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${s}\\}\\}`,"g"),r);return n}function Re(c){let e=c.mode==="swe"?ot:it,n=E(e,{workingDir:c.workingDir}).trim();if(c.systemPrompt&&(n+=`
178
+
179
+
180
+ ${E(rt,{systemPrompt:c.systemPrompt}).trim()}`),c.schema){let s=R(c.schema)?B(c.schema):N(c.schema);n+=`
181
+
182
+
183
+ ${E(at,{schema:s}).trim()}`;}return n}function ce(c){let e=[...new Set(Object.keys(c).map(i=>i.split("/")[0]))].sort((i,p)=>i==="worker_task"?-1:p==="worker_task"?1:i.localeCompare(p));if(!e.length)return `context/
184
+ (empty)`;let n="worker_task/system_prompt.txt"in c,s="worker_task/schema.json"in c,r=Object.keys(c).some(i=>i.startsWith("worker_task/input/")),o=[];e.forEach((i,p)=>{let t=p===e.length-1,u=t?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=t?" ":"\u2502 ";if(i==="worker_task"){o.push({line:`${u}${i}/`,comment:"task given to worker"});let m=[];n&&m.push({name:"system_prompt.txt",comment:"worker system prompt"}),m.push({name:"user_prompt.txt",comment:"worker task prompt"}),s&&m.push({name:"schema.json",comment:"expected output schema"}),r&&m.push({name:"input/",comment:"worker input files"}),m.forEach((f,h)=>{let y=h===m.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";o.push({line:`${d}${y}${f.name}`,comment:f.comment});});}else if(i.startsWith("candidate_")){let m=i.replace("candidate_","");o.push({line:`${u}${i}/`,comment:`worker ${m} solution`});}else if(i==="worker_output")o.push({line:`${u}${i}/`,comment:"output to verify"});else if(i.startsWith("item_")){let m=i.replace("item_","");o.push({line:`${u}${i}/`,comment:`input ${m}`});}else o.push({line:`${u}${i}/`,comment:""});});let a=Math.max(...o.map(i=>i.line.length)),l=["context/"];for(let i of o)if(i.comment){let p=" ".repeat(a-i.line.length+3);l.push(`${i.line}${p}# ${i.comment}`);}else l.push(i.line);return l.join(`
185
+ `)}var ut=join(homedir(),Ke),G=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=mkdir(ut,{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=J,this.observability=e.observability;let n=e.tagPrefix||"evolve";this.tag=`${n}-${randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let s=this.timestamp.replace(/[:.]/g,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${s}.jsonl`;this.localFilePath=join(ut,r),this.parser=I(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let s of n)this.bufferForDashboard(s);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let s of n)this.bufferForDashboard(s);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.isClosed=true,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
186
+ `)?e:e+`
187
+ `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let n=JSON.stringify(e)+`
188
+ `;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&(this.eventBuffer.push(e),this.scheduleFlush());}writeMeta(){let e={_meta:{tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandbox_id:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability)}},n=JSON.stringify(e)+`
189
+ `;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>=We){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Je));}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 s=1;s<=ae;s++)try{let r=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(r.ok)return;if(r.status===429||r.status===401||r.status>=500){if(s===ae){console.debug(`[SessionLogger] Dashboard ${r.status} after ${s} retries, requeueing`),this.requeueEvents(e);return}await this.delay(we*s);continue}console.debug(`[SessionLogger] Dashboard ${r.status}, dropping events`);return}catch(r){s===ae?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",r),this.requeueEvents(e)):await this.delay(we*s);}}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 le="COMPOSIO_API_KEY";function mt(c){return new Composio({apiKey:process.env[le]})}function Pe(c){if(!c?.trim())throw new Error("userId is required and cannot be empty")}async function pe(c,e,n){Pe(c);let s=mt(),r={};return e?.toolkits&&(r.toolkits=e.toolkits),e?.tools&&(r.tools=e.tools),e?.authConfigs&&(r.authConfigs=e.authConfigs),e?.connectedAccounts&&(r.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(r.manageConnections=e.manageConnections),await s.create(c,Object.keys(r).length>0?r:void 0)}async function ft(c,e,n,s){Pe(c);let r=mt(),l=(await r.toolkits.get(e)).authConfigDetails?.find(i=>i.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(c,l.name,{config:AuthScheme.APIKey({api_key:n})});}async function Ee(c,e){if(Pe(c),e?.keys)for(let[s,r]of Object.entries(e.keys))try{await ft(c,s,r);}catch(o){throw new Error(`Failed to create API key connection for "${s}": ${o.message}`)}let n=await pe(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 gt(c){if(!c?.trim())throw new Error("userId is required and cannot be empty")}function qt(){return new Composio({apiKey:process.env[le]})}async function ht(c,e){gt(c);let s=await(await pe(c,{manageConnections:false})).authorize(e);return {url:s.redirectUrl,connectionId:s.id}}async function yt(c,e){let n=await Me(c),s={};for(let r of n)s[r.toolkit]=r.connected;return e?s[e]??false:s}async function Me(c){return gt(c),(await qt().connectedAccounts.list({userIds:[c],statuses:["ACTIVE"]})).items.map(s=>({toolkit:s.toolkit.slug,connected:s.status==="ACTIVE",accountId:s.id}))}var Ie={auth:ht,status:yt,connections:Me};function Zt(c){return c.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}var z=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionLogger;skills;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||Ve,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 s=this.createAjvValidator();this.compiledValidator=s.compile(this.jsonSchema);}catch(s){throw new Error(`Invalid JSON Schema: ${s.message}`)}}this.registry=M(e.type);}createAjvValidator(){let n={...me[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 Ht({...n,strict:false})}async getSandbox(){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let e=this.options.sandboxProvider;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 e.connect(this.options.sandboxId),this.hasRun=true;else {let n=this.buildEnvironmentVariables();this.sandbox=await e.create({templateId:this.registry.templateId,envs:n,workingDirectory:this.workingDir}),await this.setupAgentAuth(this.sandbox),await this.setupWorkspace(this.sandbox);}return this.sandbox}buildEnvironmentVariables(){let e={},n=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:this.registry.apiKeyEnv;return e[n]=this.agentConfig.apiKey,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?Ue():K(),e.EVOLVE_API_KEY=this.agentConfig.apiKey),this.options.secrets&&Object.assign(e,this.options.secrets),e}async setupAgentAuth(e){this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e){let n=this.options.workspaceMode||"knowledge",s=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 ${s}`,{timeoutMs:3e4});let r=Re({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:n}),o=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(o,r),this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let a={...this.options.mcpServers};if(this.options.composio){let l=await Ee(this.options.composio.userId,this.options.composio.config);a={...a,composio:{type:"http",url:l.url,headers:l.headers}};}Object.keys(a).length>0&&await xe(this.agentConfig.type,e,this.workingDir,a),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:s,targetDir:r}=n;for(let o of this.skills){let a=`cp -r ${s}/${o} ${r}/ 2>/dev/null || true`;await e.commands.run(a,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let s=Object.entries(n).map(([o,a])=>({path:`${this.workingDir}/context/${o}`,data:a}));if(s.length===0)return;let r=new Set(s.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}async uploadWorkspaceFiles(e,n){let s=Object.entries(n).map(([o,a])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:a}));if(s.length===0)return;let r=new Set(s.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(s);}buildCommand(e){return this.registry.buildCommand({prompt:Zt(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:s,timeoutMs:r=W,background:o=false}=e,a=await this.getSandbox();if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let m=this.options.sandboxProvider;this.sessionLogger=new G({provider:m?.name||m?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:a.sandboxId,tagPrefix:this.options.sessionTagPrefix,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(s);let l=this.buildCommand(s),i="",p=I(this.agentConfig.type),t=m=>{i+=m;let f=i.split(`
190
+ `);i=f.pop()??"";for(let h of f){if(!h.trim())continue;let g=p(h);if(this.sessionLogger?.writeEventParsed(h,g),n?.onStdout?.(h+`
191
+ `),g&&n?.onContent)for(let y of g)n.onContent(y);}},u=m=>{n?.onStderr?.(m);};if(o){let m=await a.commands.spawn(l,{cwd:this.workingDir,timeoutMs:r,onStdout:t,onStderr:u});return this.hasRun=true,{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with PID ${m.pid}`,stderr:""}}let d=await a.commands.run(l,{cwd:this.workingDir,timeoutMs:r,onStdout:t,onStderr:u});if(i.trim()){let m=p(i);if(this.sessionLogger?.writeEventParsed(i,m),n?.onStdout?.(i+`
192
+ `),m&&n?.onContent)for(let f of m)n.onContent(f);}return this.hasRun=true,{sandboxId:a.sandboxId,exitCode:d.exitCode,stdout:d.stdout,stderr:d.stderr}}async executeCommand(e,n={},s){let{timeoutMs:r=W,background:o=false}=n,a=await this.getSandbox();this.lastRunTimestamp=Date.now();let l="",i="",p=d=>{l+=d,s?.onStdout?.(d);},t=d=>{i+=d,s?.onStderr?.(d);};if(o){let d=await a.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,onStdout:p,onStderr:t});return {sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with PID ${d.pid}`,stderr:""}}let u=await a.commands.run(e,{cwd:this.workingDir,timeoutMs:r,onStdout:p,onStderr:t});return {sandboxId:a.sandboxId,exitCode:u.exitCode,stdout:l,stderr:i}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),s=`${this.workingDir}/output`,r=e?"":"-maxdepth 1",a=(await n.commands.run(`find ${s} ${r} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
193
+ `).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,i=[],p=`${s}/`;for(let f of a){let[h,g]=f.split("|");if(!h||!g)continue;let y=parseInt(g,10);l>0&&y<l||i.push(h);}let t={},u=await Promise.all(i.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){this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),this.options.sandboxId=e,this.sandbox=void 0,this.hasRun=true;}async pause(){this.sandbox&&await this.sandbox.pause();}async resume(){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId));}async kill(){this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0,this.hasRun=false);}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 q=class extends EventEmitter{config={};agent;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}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=Ie;async initializeAgent(){let e=Ce(this.config.agent),n=this.config.sandbox??await Se(),s=e.isDirectMode?{}:Ne(e.apiKey),r={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:{...s,...this.config.mcpServers},skills:this.config.skills,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio};this.agent=new z(e,r);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0;return {onStdout:e?r=>this.emit("stdout",r):void 0,onStderr:n?r=>this.emit("stderr",r):void 0,onContent:s?r=>this.emit("content",r):void 0}}async run({prompt:e,timeoutMs:n,background:s}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s},r)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}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.config.sandboxId=e;}async pause(){if(this.agent)return this.agent.pause();this.config.sandboxId&&this.config.sandbox&&await(await this.config.sandbox.connect(this.config.sandboxId)).pause();}async resume(){if(this.agent)return this.agent.resume();this.config.sandboxId&&this.config.sandbox&&await this.config.sandbox.connect(this.config.sandboxId);}async kill(){if(this.agent)return this.agent.kill();this.config.sandboxId&&this.config.sandbox&&await(await this.config.sandbox.connect(this.config.sandboxId)).kill();}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 j=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"),L=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 Oe=class c{config;semaphore;constructor(e={}){let n=e.concurrency??Le;if(n>be)throw new Error(`concurrency=${n} exceeds max ${be}. 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 j(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:r,verify:o}=e,a=e.retry??this.config.retry,l=this.generateOperationId(),i=e.timeoutMs??this.config.timeoutMs;if(r&&o)throw new Error("map() cannot use both bestOf and verify options simultaneously");let p=await Promise.all(n.map((t,u)=>r?this.executeMapItemWithBestOf(t,s,u,l,e,i,a):o?this.executeMapItemWithVerify(t,s,u,l,e,i,a):a?T(d=>this.executeMapItem(t,s,u,l,e,i,d),a,u):this.executeMapItem(t,s,u,l,e,i)));return L.from(p)}async filter(e){let{items:n,prompt:s,condition:r,verify:o}=e,a=e.retry??this.config.retry,l=this.generateOperationId(),i=e.timeoutMs??this.config.timeoutMs,p=await Promise.all(n.map((u,d)=>o?this.executeFilterItemWithVerify(u,s,d,l,e,i,a):a?T(m=>this.executeFilterItem(u,s,d,l,e,i,m),a,d):this.executeFilterItem(u,s,d,l,e,i))),t=[];for(let u of p)if(u.status==="error")t.push(u);else if(u.data!==null)try{r(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 L.from(t)}async reduce(e){let{items:n,prompt:s,verify:r}=e,o=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,i=[],p=[];n.forEach((x,C)=>{i.push(this.getFiles(x)),p.push(this.getIndex(x,C));});let t={};i.forEach((x,C)=>{Object.entries(x).forEach(([w,S])=>{t[`item_${p[C]}/${w}`]=S;});});let u=ce(t),d=E(pt,{fileTree:u}),m=e.systemPrompt?`${d}
194
+
195
+ ${e.systemPrompt}`:d,f=(x,C,w)=>({operationId:a,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:p,errorRetry:C,verifyRetry:w,...this.pipelineContextToMeta(e._pipelineContext)}),h=e.mcpServers??this.config.mcpServers,g=e.skills??this.config.skills,y=e.composio??this.config.composio,v=async(x,C,w,S)=>{let k=await this.semaphore.use(()=>this.execute(t,x,{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:a,operation:"reduce",role:"worker",errorRetry:w,verifyRetry:S&&S>1?S-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),F=f(k,w,S&&S>1?S-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}},b=`${this.config.tag}-reduce`;return r?this.runWithVerification((x,C,w)=>v(x,C,void 0,w),{originalPrompt:s,inputFiles:t,verifyConfig:r,timeoutMs:l,systemPrompt:m,schema:e.schema,mcpServers:h,skills:g,composio:y,operationId:a,baseTag:b,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?T(x=>{let C=x>1?x-1:void 0,w=C?`${b}-er${C}`:b;return v(s,w,C)},o):v(s,b)}async bestOf(e){let{item:n,prompt:s,config:r}=e,o=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(),i=e.timeoutMs??this.config.timeoutMs,p=this.getFiles(n),t=r.mcpServers??this.config.mcpServers,u=r.judgeMcpServers??r.mcpServers??this.config.mcpServers,d=r.skills??this.config.skills,m=r.judgeSkills??r.skills??this.config.skills,f=r.composio??this.config.composio,h=r.judgeComposio??r.composio??this.config.composio,g=await Promise.all(Array.from({length:a},async(C,w)=>{let S=o?await T(k=>this.executeBestOfCandidate({inputFiles:p,prompt:s,candidateIndex:w,operationId:l,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:t,skills:d,composio:f,timeoutMs:i,attempt:k}),o,w):await this.executeBestOfCandidate({inputFiles:p,prompt:s,candidateIndex:w,operationId:l,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:t,skills:d,composio:f,timeoutMs:i});return r.onCandidateComplete?.(0,w,S.status==="success"?"success":"error"),S})),y=o?await T(C=>this.executeBestOfJudge({inputFiles:p,taskPrompt:s,candidates:g,config:r,timeoutMs:i,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:h,attempt:C}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:p,taskPrompt:s,candidates:g,config:r,timeoutMs:i,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:h}),v=g.findIndex(C=>C.status==="success"),b=y.decision?.winner??(v>=0?v:0);r.onJudgeComplete?.(0,b,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:a};return {winner:g[b]??g[0],winnerIndex:b,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:g}}async execute(e,n,s){let r=null,o="",a=s.tagPrefix,l={},i=null,p,t,u={...this.config.agent,...s.agent};try{r=new q().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(s.tagPrefix),s.schema&&r.withSchema(s.schema,s.schemaOptions),s.systemPrompt&&r.withSystemPrompt(s.systemPrompt),s.mcpServers&&r.withMcpServers(s.mcpServers),s.skills?.length&&r.withSkills(s.skills),s.composio&&r.withComposio(s.composio.userId,s.composio.config),s.observability&&r.withObservability(s.observability),Object.keys(e).length>0&&r.withContext(e);let d=await r.run({prompt:n,timeoutMs:s.timeoutMs});o=d.sandboxId,a=r.getSessionTag()??s.tagPrefix;let m=null;try{m=await r.getOutputFiles(!0),l=m.files;}catch{}d.exitCode!==0?p=`Agent exited with code ${d.exitCode}`:s.schema?m?(i=m.data,m.error&&(p=m.error),m.rawData&&(t=m.rawData)):p="Failed to read output files from sandbox":i=l;}catch(d){if(p=d.message,r){a=r.getSessionTag()??s.tagPrefix;try{l=(await r.getOutputFiles(!0)).files;}catch{}}}finally{r&&await r.kill().catch(()=>{});}return {files:l,data:i,tag:a,sandboxId:o,error:p,rawData:t}}async executeMapItem(e,n,s,r,o,a,l=1){let i=this.getFiles(e),p=l>1?`${this.config.tag}-map-${s}-er${l-1}`:`${this.config.tag}-map-${s}`,t=this.evaluatePrompt(n,i,s);if(t instanceof Error)return this.buildErrorResult(`Prompt function threw: ${t.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:s});let u=o.mcpServers??this.config.mcpServers,d=o.skills??this.config.skills,m=o.composio??this.config.composio,f=await this.semaphore.use(()=>this.execute(i,t,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:u,skills:d,composio:m,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:r,operation:"map",itemIndex:s,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),h={operationId:r,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:s,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(f,h)}async executeMapItemWithVerify(e,n,s,r,o,a,l){let i=this.getFiles(e),p=`${this.config.tag}-map-${s}`,t=o.verify,u=o.mcpServers??this.config.mcpServers,d=o.skills??this.config.skills,m=o.composio??this.config.composio,f=this.evaluatePrompt(n,i,s);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:s});let h=async(g,y,v)=>{let b=await this.semaphore.use(()=>this.execute(i,g,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:u,skills:d,composio:m,tagPrefix:y,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:r,operation:"map",itemIndex:s,role:"worker",verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),x={operationId:r,operation:"map",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:s,verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(b,x)};return this.runWithVerification(h,{originalPrompt:f,inputFiles:i,verifyConfig:t,timeoutMs:a,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:u,skills:d,composio:m,operationId:r,baseTag:p,retry:l,itemIndex:s,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,s,r,o,a,l){let i=this.getFiles(e),p=`${this.config.tag}-map-${s}`,t=this.evaluatePrompt(n,i,s);if(t instanceof Error)return this.buildErrorResult(`Prompt function threw: ${t.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:s});let u=o.bestOf,d=u.n??u.taskAgents?.length;if(d===void 0||d<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:s});let m=o.mcpServers??this.config.mcpServers,f=u.mcpServers??m,h=u.judgeMcpServers??u.mcpServers??m,g=o.skills??this.config.skills,y=u.skills??g,v=u.judgeSkills??u.skills??g,b=o.composio??this.config.composio,x=u.composio??b,C=u.judgeComposio??u.composio??b,w=await Promise.all(Array.from({length:d},async(H,Z)=>{let De=l?await T(xt=>this.executeBestOfCandidate({inputFiles:i,prompt:t,candidateIndex:Z,operationId:r,config:u,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,composio:x,timeoutMs:a,parentIndex:s,attempt:xt,_pipelineContext:o._pipelineContext}),l,Z):await this.executeBestOfCandidate({inputFiles:i,prompt:t,candidateIndex:Z,operationId:r,config:u,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,composio:x,timeoutMs:a,parentIndex:s,_pipelineContext:o._pipelineContext});return u.onCandidateComplete?.(s,Z,De.status==="success"?"success":"error"),De})),S=l?await T(H=>this.executeBestOfJudge({inputFiles:i,taskPrompt:t,candidates:w,config:u,timeoutMs:a,operationId:r,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:h,skills:v,composio:C,parentIndex:s,attempt:H,_pipelineContext:o._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:i,taskPrompt:t,candidates:w,config:u,timeoutMs:a,operationId:r,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:h,skills:v,composio:C,parentIndex:s,_pipelineContext:o._pipelineContext}),k=w.findIndex(H=>H.status==="success"),F=S.decision?.winner??(k>=0?k:0),Ae=w[F]??w[0];u.onJudgeComplete?.(s,F,S.decision?.reasoning??"Judge failed to provide reasoning");let vt={operationId:r,operation:"bestof-judge",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:d,...this.pipelineContextToMeta(o._pipelineContext)};return {...Ae,meta:{...Ae.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:s,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:F,judgeReasoning:S.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:vt,candidates:w}}}async executeFilterItem(e,n,s,r,o,a,l=1){let i=this.getFiles(e),p=l>1?`${this.config.tag}-filter-${s}-er${l-1}`:`${this.config.tag}-filter-${s}`,t=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,d=o.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(i,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:t,skills:u,composio:d,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:r,operation:"filter",itemIndex:s,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:r,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:s,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(m,f,i)}async executeFilterItemWithVerify(e,n,s,r,o,a,l){let i=this.getFiles(e),p=`${this.config.tag}-filter-${s}`,t=o.verify,u=o.mcpServers??this.config.mcpServers,d=o.skills??this.config.skills,m=o.composio??this.config.composio,f=async(h,g,y)=>{let v=await this.semaphore.use(()=>this.execute(i,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:u,skills:d,composio:m,tagPrefix:g,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:o.name,operationId:r,operation:"filter",itemIndex:s,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),b={operationId:r,operation:"filter",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:s,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(v,b,i)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:i,verifyConfig:t,timeoutMs:a,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:u,skills:d,composio:m,operationId:r,baseTag:p,retry:l,itemIndex:s,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:s,candidateIndex:r,operationId:o,config:a,timeoutMs:l,parentIndex:i,attempt:p=1,_pipelineContext:t}=e,u=i!==void 0?`${this.config.tag}-map-${i}-bestof-cand-${r}`:`${this.config.tag}-bestof-cand-${r}`,d=p>1?`${u}-er${p-1}`:u,m=await this.semaphore.use(()=>this.execute(n,s,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:a.taskAgents?.[r],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:i,role:"candidate",candidateIndex:r,errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(t)}})),f={operationId:o,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(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((s,r)=>{s.status==="error"&&(n[`candidate_${r}/_failed.txt`]=`STATUS: FAILED
196
+
197
+ Error: ${s.error??"Unknown error"}`),Object.entries(s.files).forEach(([o,a])=>{n[`candidate_${r}/${o}`]=a;});}),n}async executeBestOfJudge(e){let{candidates:n,config:s,timeoutMs:r,operationId:o,parentIndex:a,attempt:l=1,_pipelineContext:i}=e,p=a!==void 0?`${this.config.tag}-map-${a}-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=ce(u),m=E(ke,{candidateCount:String(n.length),criteria:s.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,ct,{systemPrompt:m,schema:f,agent:s.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:t,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:a,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(i)}})),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(([s,r])=>{n[`worker_output/${s}`]=r;}),n}async executeVerify(e){let{config:n,timeoutMs:s,operationId:r,workerTag:o,retryAttempt:a=1,operation:l,itemIndex:i,attemptIndex:p,_pipelineContext:t}=e,u=a>1?`${o}-verifier-er${a-1}`:`${o}-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=ce(h),y=E(Te,{criteria:n.criteria,fileTree:g}),v=await this.semaphore.use(()=>this.execute(h,lt,{systemPrompt:y,schema:c.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:r,operation:l,itemIndex:i,role:"verifier",verifyRetry:p&&p>1?p-1:void 0,errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(t)}})),b=null;if(v.data&&!v.error)b=v.data;else if(v.rawData)try{let x=JSON.parse(v.rawData);b={passed:!!x.passed,reasoning:x.reasoning??"Verification completed",feedback:x.feedback};}catch{console.warn(`Verify validation failed: ${v.error}`);}return {status:b?"success":"error",decision:b,tag:v.tag,sandboxId:v.sandboxId,error:b?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return E(_e,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:s,inputFiles:r,verifyConfig:o,timeoutMs:a,operationId:l,baseTag:i,retry:p,itemIndex:t=0,operation:u,_pipelineContext:d}=n,m=o.maxAttempts??c.DEFAULT_VERIFY_MAX_ATTEMPTS,f=s,h=null,g=0;for(;g<m;){g++;let v=g>1?`${i}-vr${g-1}`:i,b=p?await T(w=>e(f,w>1?`${v}-er${w-1}`:v,g),p,t):await e(f,v,g);if(o.onWorkerComplete?.(t,g,b.status==="error"?"error":"success"),b.status==="error")return b;h=b;let x=p?await T(w=>this.executeVerify({inputFiles:r,outputFiles:b.files,taskPrompt:f,config:o,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:l,workerTag:v,retryAttempt:w,operation:u,itemIndex:t,attemptIndex:g,_pipelineContext:d}),{...p,retryOn:void 0}):await this.executeVerify({inputFiles:r,outputFiles:b.files,taskPrompt:f,config:o,timeoutMs:a,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:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,attempts:g,...this.pipelineContextToMeta(d)};if(o.onVerifierComplete?.(t,g,x.decision?.passed??false,x.decision?.feedback),x.decision?.passed)return {...b,verify:{passed:true,reasoning:x.decision.reasoning,verifyMeta:C,attempts:g}};if(g<m){let w=x.decision?.feedback??x.decision?.reasoning??"Output did not meet criteria";f=c.buildRetryPromptWithFeedback(s,w);}}let y=g>1?`${i}-vr${g-1}`:i;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,s){if(typeof e=="string")return e;try{return e(n,s)}catch(r){return r}}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)?B(e.schema):N(e.schema)),Object.entries(e.inputFiles).forEach(([s,r])=>{n[`worker_task/input/${s}`]=r;}),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,s){let r=s??e.files;return e.error?{[A]:true,status:"error",data:null,files:r,meta:n,error:e.error,rawData:e.rawData}:{[A]:true,status:"success",data:e.data,files:r,meta:n}}buildErrorResult(e,n){return {[A]:true,status:"error",data:null,files:{},meta:n,error:e}}};var ue=class c{swarm;steps;events;constructor(e,n=[],s={}){this.swarm=e,this.steps=n,this.events=s;}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 de(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new c(this.swarm,this.steps,{...this.events,[s]:n})}return new c(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=randomBytes(8).toString("hex"),s=[],r=e,o=Date.now();for(let l=0;l<this.steps.length;l++){let i=this.steps[l],p=i.config.name,t=Date.now();this.events.onStepStart?.({type:i.type,index:l,name:p,itemCount:r.length});let u={pipelineRunId:n,pipelineStepIndex:l};try{let d=await this.executeStep(i,r,l,p,u),m=Date.now()-t;if(s.push({type:i.type,index:l,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:i.type,index:l,name:p,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),i.type==="reduce")return {pipelineRunId:n,steps:s,output:d.output,totalDurationMs:Date.now()-o};r=d.nextItems;}catch(d){throw this.events.onStepError?.({type:i.type,index:l,name:p,error:d instanceof Error?d:new Error(String(d))}),d}}let a=s[s.length-1];return {pipelineRunId:n,steps:s,output:a?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,s,r,o){if(e.type==="map"){let i=e.config,p=await this.swarm.map({items:n,...i,_pipelineContext:o,retry:this.wrapRetry(i.retry,s,r),verify:this.wrapVerify(i.verify,s,r),bestOf:this.wrapBestOf(i.bestOf,s,r)});return {output:[...p],nextItems:p.success,successCount:p.success.length,errorCount:p.error.length,filteredCount:0}}if(e.type==="filter"){let i=e.config,p=await this.swarm.filter({items:n,...i,_pipelineContext:o,retry:this.wrapRetry(i.retry,s,r),verify:this.wrapVerify(i.verify,s,r)}),t=i.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 a=e.config,l=await this.swarm.reduce({items:n,...a,_pipelineContext:o,retry:this.wrapRetry(a.retry,s,r),verify:this.wrapVerify(a.verify,s,r)});return {output:l,nextItems:[],successCount:l.status==="success"?1:0,errorCount:l.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,s){if(e)return {...e,onItemRetry:(r,o,a)=>{e.onItemRetry?.(r,o,a),this.events.onItemRetry?.({stepIndex:n,stepName:s,itemIndex:r,attempt:o,error:a});}}}wrapVerify(e,n,s){if(e)return {...e,onWorkerComplete:(r,o,a)=>{e.onWorkerComplete?.(r,o,a),this.events.onWorkerComplete?.({stepIndex:n,stepName:s,itemIndex:r,attempt:o,status:a});},onVerifierComplete:(r,o,a,l)=>{e.onVerifierComplete?.(r,o,a,l),this.events.onVerifierComplete?.({stepIndex:n,stepName:s,itemIndex:r,attempt:o,passed:a,feedback:l});}}}wrapBestOf(e,n,s){if(e)return {...e,onCandidateComplete:(r,o,a)=>{e.onCandidateComplete?.(r,o,a),this.events.onCandidateComplete?.({stepIndex:n,stepName:s,itemIndex:r,candidateIndex:o,status:a});},onJudgeComplete:(r,o,a)=>{e.onJudgeComplete?.(r,o,a),this.events.onJudgeComplete?.({stepIndex:n,stepName:s,itemIndex:r,winnerIndex:o,reasoning:a});}}}},de=class c extends ue{constructor(e,n,s){super(e,n,s);}on(e,n){if(typeof e=="string"){let s=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new c(this.swarm,this.steps,{...this.events,[s]: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{fe as AGENT_REGISTRY,bt as AGENT_TYPES,z as Agent,q as Evolve,ke as JUDGE_PROMPT,ue as Pipeline,_e as RETRY_FEEDBACK_PROMPT,at as SCHEMA_PROMPT,A as SWARM_RESULT_BRAND,rt as SYSTEM_PROMPT,j as Semaphore,Oe as Swarm,L as SwarmResultList,de as TerminalPipeline,me as VALIDATION_PRESETS,Te as VERIFY_PROMPT,it as WORKSPACE_PROMPT,ot as WORKSPACE_SWE_PROMPT,E as applyTemplate,Re as buildWorkerSystemPrompt,I as createAgentParser,ne as createClaudeParser,se as createCodexParser,ie as createGeminiParser,T as executeWithRetry,ge as expandPath,M as getAgentConfig,U as getMcpSettingsDir,$ as getMcpSettingsPath,wt as isValidAgentType,R as isZodSchema,N as jsonSchemaToString,Rt as parseNdjsonLine,Pt as parseNdjsonOutput,$e as parseQwenOutput,Ye as readLocalDir,Ge as saveLocalDir,Q as writeClaudeMcpConfig,te as writeCodexMcpConfig,X as writeGeminiMcpConfig,xe as writeMcpConfig,ee as writeQwenMcpConfig,B as zodSchemaToJson};
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@evolvingmachines/sdk",
3
+ "version": "0.0.2",
4
+ "keywords": [
5
+ "ai",
6
+ "agents",
7
+ "orchestration",
8
+ "sandbox",
9
+ "e2b",
10
+ "claude code",
11
+ "codex",
12
+ "gemini cli",
13
+ "qwen code",
14
+ "automation",
15
+ "evolve-sdk"
16
+ ],
17
+ "homepage": "https://github.com/evolving-machines-lab/evolve",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/evolving-machines-lab/evolve.git"
21
+ },
22
+ "type": "module",
23
+ "main": "dist/index.cjs",
24
+ "types": "dist/index.d.ts",
25
+ "license": "Proprietary Beta Evaluation License - See LICENSE",
26
+ "files": [
27
+ "dist",
28
+ "LICENSE"
29
+ ],
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "require": "./dist/index.cjs"
35
+ }
36
+ },
37
+ "scripts": {
38
+ "build": "tsup --minify",
39
+ "dev": "tsup src/index.ts --watch",
40
+ "type-check": "tsc --noEmit",
41
+ "test": "npm run test:unit && npm run test:integration",
42
+ "pretest:unit": "npm run build",
43
+ "test:unit": "tsx tests/unit/semaphore.test.ts && tsx tests/unit/swarm-concurrency.test.ts && tsx tests/unit/swarm-verify.test.ts && tsx tests/unit/swarm-retry-verify.test.ts && tsx tests/unit/prompt-construction.test.ts && tsx tests/unit/observability-metadata.test.ts && tsx tests/unit/skills-integration.test.ts && tsx tests/unit/auth-config.test.ts",
44
+ "test:unit:semaphore": "tsx tests/unit/semaphore.test.ts",
45
+ "test:unit:swarm": "tsx tests/unit/swarm-concurrency.test.ts",
46
+ "test:unit:verify": "tsx tests/unit/swarm-verify.test.ts",
47
+ "test:unit:retry": "tsx tests/unit/swarm-retry-verify.test.ts",
48
+ "test:unit:prompts": "tsx tests/unit/prompt-construction.test.ts",
49
+ "test:unit:observability": "tsx tests/unit/observability-metadata.test.ts",
50
+ "test:unit:skills": "tsx tests/unit/skills-integration.test.ts",
51
+ "test:unit:auth": "tsx tests/unit/auth-config.test.ts",
52
+ "pretest:integration": "npm run build",
53
+ "test:integration": "npm run test:01",
54
+ "test:integration:all": "npm run test:01 && npm run test:02 && npm run test:03 && npm run test:04 && npm run test:05 && npm run test:06 && npm run test:07 && npm run test:08 && npm run test:09 && npm run test:10 && npm run test:11 && npm run test:12 && npm run test:13 && npm run test:14 && npm run test:15",
55
+ "test:01": "tsx tests/integration/01-all-agents-parallel.ts",
56
+ "test:02": "tsx tests/integration/02-execute-command-streaming.ts",
57
+ "test:03": "tsx tests/integration/03-file-operations.ts",
58
+ "test:04": "tsx tests/integration/04-session-lifecycle.ts",
59
+ "test:05": "tsx tests/integration/05-workspace-config.ts",
60
+ "test:06": "tsx tests/integration/06-observability.ts",
61
+ "test:07": "tsx tests/integration/07-background-timeouts.ts",
62
+ "test:08": "tsx tests/integration/08-network.ts",
63
+ "test:09": "tsx tests/integration/09-advanced-features.ts",
64
+ "test:10": "tsx tests/integration/10-swarm-abstractions.ts",
65
+ "test:11": "tsx tests/integration/11-schema-validation.ts",
66
+ "test:12": "tsx tests/integration/12-swarm-verify.ts",
67
+ "test:13": "tsx tests/integration/13-pipeline-abstractions.ts",
68
+ "test:14": "tsx tests/integration/14-byok-direct-mode.ts",
69
+ "test:15": "tsx tests/integration/15-oauth-mode.ts",
70
+ "test:claude": "tsx tests/integration/01-all-agents-parallel.ts claude",
71
+ "test:codex": "tsx tests/integration/01-all-agents-parallel.ts codex",
72
+ "test:gemini": "tsx tests/integration/01-all-agents-parallel.ts gemini",
73
+ "test:qwen": "tsx tests/integration/01-all-agents-parallel.ts qwen"
74
+ },
75
+ "dependencies": {
76
+ "@agentclientprotocol/sdk": "^0.5.1",
77
+ "@composio/core": "^0.5.1",
78
+ "@evolvingmachines/e2b": "file:../e2b",
79
+ "ajv": "^8.17.1",
80
+ "p-map": "^7.0.2",
81
+ "zod": "^3.24.0",
82
+ "zod-to-json-schema": "^3.25.0"
83
+ },
84
+ "devDependencies": {
85
+ "@types/node": "^22.15.18",
86
+ "tsup": "^8.4.0",
87
+ "typescript": "^5.8.3"
88
+ }
89
+ }