@evolvingmachines/sdk 0.0.22 → 0.0.24

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