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