@evolvingmachines/sdk 0.0.31 → 0.0.34
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/LICENSE +2 -2
- package/dist/index.cjs +64 -63
- package/dist/index.d.cts +127 -11
- package/dist/index.d.ts +127 -11
- package/dist/index.js +64 -63
- package/package.json +4 -2
package/dist/index.cjs
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
|
-
'use strict';var events=require('events'),Wi=require('ajv'),crypto=require('crypto'),Xn=require('zod-to-json-schema'),I=require('fs'),Q=require('path'),promises=require('fs/promises'),os=require('os'),core=require('@composio/core'),child_process=require('child_process'),util=require('util'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal'),stream=require('stream'),promises$1=require('stream/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Wi__default=/*#__PURE__*/_interopDefault(Wi);var Xn__default=/*#__PURE__*/_interopDefault(Xn);var I__namespace=/*#__PURE__*/_interopNamespace(I);var Q__namespace=/*#__PURE__*/_interopNamespace(Q);var In={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode"},Ie={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Me={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",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"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:n,model:e,isResume:t,reasoningEffort:o})=>{let c=o?` -c model_reasoning_effort="${o}"`:"";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"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",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"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:n,model:e,isResume:t,isDirectMode:o,skills:c})=>{let s=t?"--continue ":"",r=c?.length?"--experimental-skills ":"",l=o||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${n}" ${s}${r}--auth-type openai --model ${l} --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",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},buildCommand:({prompt:n,model:e,isResume:t,isDirectMode:o})=>`printf '%s' "${n}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${o?"":"--config-file /home/user/.kimi/evolve-config.toml "}${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:o})=>{let c=t?"--continue ":"",s=e.startsWith("openrouter/")?e:`openrouter/${e}`;return o?`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 M(n){let e=Me[n];if(!e)throw new Error(`Unknown agent type: ${n}`);return e}function Mn(n){return n in Me}function q(n){return n.replace(/^~/,"/home/user")}function D(n){let e=M(n);return `${q(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function U(n){let e=M(n);return q(e.mcpConfig.settingsDir)}function F(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 Ae(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 re(n){for(let[e,t]of Object.entries(n))Ae(e,t);}function ae(n){return n.type?n.type:n.command?"stdio":"sse"}function An(n){let e=ae(n);return {...n,type:e}}function $n(n){let{type:e,url:t,...o}=n;return ae(n)==="http"&&t?{httpUrl:t,...o}:t?{url:t,...o}:o}function Dn(n){return {type:ae(n),...n}}function Un(n){let{type:e,...t}=n;return t.command?{...t,transport:"stdio"}:t.url&&(e==="http"||e==="sse")?{...t,transport:e}:t}async function $e(n,e,t,o){re(t);let c=U(e),s=D(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(!F(a))throw a}let l=Object.fromEntries(Object.entries(t).map(([a,p])=>[a,o(p)]));await n.files.write(s,JSON.stringify({...r,mcpServers:l},null,2));}async function ce(n,e,t){re(t);let o=U("claude"),c=D("claude"),s=Object.fromEntries(Object.entries(t).map(([l,a])=>[l,Dn(a)]));await n.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await n.files.makeDir(o);let r={};try{let l=await n.files.read(c);typeof l=="string"&&(r=JSON.parse(l));}catch(l){if(!F(l))throw l}r.enableAllProjectMcpServers=true,await n.files.write(c,JSON.stringify(r,null,2));}async function le(n,e){await $e(n,"gemini",e,An);}async function pe(n,e){await $e(n,"qwen",e,$n);}async function ue(n,e,t,o){let c=U(e),s=D(e);await n.files.makeDir(c);let r={};try{let u=await n.files.read(s);typeof u=="string"&&(r=JSON.parse(u));}catch(u){if(!F(u))throw u}let l=t.split("."),a=r;for(let u=0;u<l.length-1;u++){let d=l[u];(typeof a[d]!="object"||a[d]===null)&&(a[d]={}),a=a[d];}let p=l[l.length-1],i=typeof a[p]=="object"&&a[p]!==null?a[p]:{};a[p]={...i,...o},await n.files.write(s,JSON.stringify(r,null,2));}async function De(n,e){await $e(n,"kimi",e,Un);}async function Ue(n,e,t){re(t);let o=`${e}/opencode.json`,c={};try{let r=await n.files.read(o);typeof r=="string"&&(c=JSON.parse(r));}catch(r){if(!F(r))throw r}let s=Object.fromEntries(Object.entries(t).map(([r,l])=>[r,Fn(l)]));await n.files.write(o,JSON.stringify({...c,mcp:s},null,2));}function Fn(n){let e=ae(n);if(e==="stdio"&&n.command){let o={type:"local",command:n.args?[n.command,...n.args]:[n.command]};return n.env&&Object.keys(n.env).length>0&&(o.environment=n.env),o}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 N(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function Fe(){return `${N()}`}function ft(){return `${N()}/e2b`}function ht(n){return {"browser-use":{type:"http",url:`${N()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${n}`}}}}var R="EVOLVE_API_KEY",de="E2B_API_KEY",me="DAYTONA_API_KEY",ge="MODAL_TOKEN_ID",Le="MODAL_TOKEN_SECRET",yt="claude",Z=36e5,wt=4,Ne=100,vt="/home/user/workspace",E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",P="x-litellm-customer-id",L="x-litellm-tags",V="run:",Ct=".evolve-sdk/observability/sessions",xt=100,kt=5e3,fe=3,Ke=1e3;function _(n){return typeof n=="string"?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(n)?`[${n.map(e=>_(e)).join(", ")}]`:typeof n=="object"&&n!==null?`{ ${Object.entries(n).map(([t,o])=>`${t} = ${_(o)}`).join(", ")} }`:typeof n=="boolean"?n?"true":"false":String(n)}async function he(n,e){for(let[a,p]of Object.entries(e))Ae(a,p);let t=U("codex"),o=D("codex");await n.files.makeDir(t);let c="";try{let a=await n.files.read(o);typeof a=="string"&&(c=a);}catch(a){if(!F(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,p]of Object.entries(e)){if(c.includes(`[mcp_servers.${a}]`))continue;r.push(`[mcp_servers.${a}]`);let i=p.type??(p.command?"stdio":"http");if(i==="http"||i==="sse"||!!p.url){if(!p.url)throw new Error(`MCP server "${a}" is missing url for ${i} transport`);r.push(`url = ${_(p.url)}`),p.bearerTokenEnvVar&&r.push(`bearer_token_env_var = ${_(p.bearerTokenEnvVar)}`);let d=p.httpHeaders??p.headers;d&&Object.keys(d).length>0&&r.push(`http_headers = ${_(d)}`),p.envHttpHeaders&&Object.keys(p.envHttpHeaders).length>0&&r.push(`env_http_headers = ${_(p.envHttpHeaders)}`);}else r.push(`command = ${_(p.command)}`),p.args&&p.args.length>0&&r.push(`args = ${_(p.args)}`),p.cwd&&r.push(`cwd = ${_(p.cwd)}`);p.env&&Object.keys(p.env).length>0&&r.push(`env = ${_(p.env)}`),p.envVars&&p.envVars.length>0&&r.push(`env_vars = ${_(p.envVars)}`),r.push("");}let l=[c.trim(),s.join(`
|
|
2
|
-
`),
|
|
3
|
-
`)].filter(
|
|
1
|
+
'use strict';var events=require('events'),Ss=require('ajv'),crypto=require('crypto'),Ii=require('zod-to-json-schema'),A=require('fs'),re=require('path'),promises=require('fs/promises'),os=require('os'),core=require('@composio/core'),child_process=require('child_process'),util=require('util'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal'),stream=require('stream'),promises$1=require('stream/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ss__default=/*#__PURE__*/_interopDefault(Ss);var Ii__default=/*#__PURE__*/_interopDefault(Ii);var A__namespace=/*#__PURE__*/_interopNamespace(A);var re__namespace=/*#__PURE__*/_interopNamespace(re);var Yn={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},je={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var Ve={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",models:[{alias:"opus",modelId:"claude-opus-4-7",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-4-6",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:t,model:e,isResume:n})=>`echo "${t}" | claude -p ${n?"--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.4",models:[{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Newest frontier model"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Flagship for professional work"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Fast, efficient mini model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Previous general-purpose model"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:i})=>{let r=i?` -c model_reasoning_effort="${i}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${r} --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.1-pro-preview",models:[{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"},{alias:"gemini-3.1-flash-lite-preview",modelId:"gemini-3.1-flash-lite-preview",description:"Cost-efficient, low latency"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Frontier flash performance"},{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"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",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.6-plus",models:[{alias:"qwen3.6-plus",modelId:"qwen3.6-plus",description:"Latest flagship (Apr 2026)"},{alias:"qwen3.5-plus",modelId:"qwen3.5-plus",description:"Previous flagship, thinking-enabled"},{alias:"qwen3-max-2026-01-23",modelId:"qwen3-max-2026-01-23",description:"Max model with thinking"},{alias:"qwen3-coder-next",modelId:"qwen3-coder-next",description:"Recommended coder: balances quality/speed/cost"},{alias:"qwen3-coder-plus",modelId:"qwen3-coder-plus",description:"Max-quality coder for complex tasks"},{alias:"qwen3-coder-flash",modelId:"qwen3-coder-flash",description:"Fast coder with context cache"},{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"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.6-plus":"dashscope/qwen3.6-plus","qwen3.5-plus":"dashscope/qwen3.5-plus","qwen3-max-2026-01-23":"dashscope/qwen3-max-2026-01-23","qwen3-coder-next":"dashscope/qwen3-coder-next","qwen3-coder-plus":"dashscope/qwen3-coder-plus","qwen3-coder-flash":"dashscope/qwen3-coder-flash","qwen3-vl-plus":"dashscope/qwen3-vl-plus"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:i})=>{let r=n?"--continue ":"",s=i||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${r}--auth-type openai --model ${s} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k2.6",models:[{alias:"kimi-k2.6",modelId:"moonshot/kimi-k2.6",description:"Latest: long-horizon coding, swarm orchestration"},{alias:"kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Previous multimodal flagship"}],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",spendTrackingTomlProvider:{configPath:"~/.kimi/evolve-config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:i})=>`printf '%s' "${t}" | KIMI_MODEL_NAME=${e} kimi --print --output-format stream-json --yolo ${i?"":"--config-file /home/user/.kimi/evolve-config.toml "}${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.7",modelId:"openrouter/anthropic/claude-opus-4.7",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.5",modelId:"openrouter/openai/gpt-5.5",description:"OpenAI GPT-5.5 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4",modelId:"openrouter/openai/gpt-5.4",description:"OpenAI GPT-5.4 via OpenRouter"},{alias:"openrouter/openai/gpt-5.4-mini",modelId:"openrouter/openai/gpt-5.4-mini",description:"OpenAI GPT-5.4 Mini via OpenRouter"},{alias:"openrouter/openai/gpt-5.3-codex",modelId:"openrouter/openai/gpt-5.3-codex",description:"OpenAI Codex via OpenRouter"},{alias:"openrouter/openai/gpt-5.2",modelId:"openrouter/openai/gpt-5.2",description:"OpenAI GPT-5.2 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-flash-preview",modelId:"openrouter/google/gemini-3-flash-preview",description:"Gemini 3 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-next",modelId:"openrouter/qwen/qwen3-coder-next",description:"Qwen Coder Next via OpenRouter"},{alias:"openrouter/qwen/qwen3-coder-plus",modelId:"openrouter/qwen/qwen3-coder-plus",description:"Qwen Coder via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k2.6",modelId:"openrouter/moonshotai/kimi-k2.6",description:"Kimi K2.6 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 r=n?"--continue ":"",s=e.startsWith("openrouter/")?e:`openrouter/${e}`;return i?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${r}--model ${s} --format json "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${r}--model litellm/${s} --format json "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",defaultModel:"gpt-5.5",models:[{alias:"claude-opus-4-7",modelId:"claude-opus-4-7",description:"Factory-managed Claude Opus 4.7"},{alias:"claude-opus-4-7-fast",modelId:"claude-opus-4-7-fast",description:"Factory-managed Claude Opus 4.7 Fast Mode"},{alias:"claude-sonnet-4-6",modelId:"claude-sonnet-4-6",description:"Factory-managed Claude Sonnet 4.6"},{alias:"claude-opus-4-6",modelId:"claude-opus-4-6",description:"Factory-managed Claude Opus 4.6"},{alias:"claude-opus-4-6-fast",modelId:"claude-opus-4-6-fast",description:"Factory-managed Claude Opus 4.6 Fast Mode"},{alias:"claude-opus-4-5",modelId:"claude-opus-4-5-20251101",description:"Factory-managed Claude Opus 4.5"},{alias:"claude-sonnet-4-5",modelId:"claude-sonnet-4-5-20250929",description:"Factory-managed Claude Sonnet 4.5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Factory-managed GPT-5.5"},{alias:"gpt-5.5-fast",modelId:"gpt-5.5-fast",description:"Factory-managed GPT-5.5 Fast Mode"},{alias:"gpt-5.5-pro",modelId:"gpt-5.5-pro",description:"Factory-managed GPT-5.5 Pro"},{alias:"gpt-5.4",modelId:"gpt-5.4",description:"Factory-managed GPT-5.4"},{alias:"gpt-5.4-fast",modelId:"gpt-5.4-fast",description:"Factory-managed GPT-5.4 Fast Mode"},{alias:"gpt-5.4-mini",modelId:"gpt-5.4-mini",description:"Factory-managed GPT-5.4 Mini"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Factory-managed GPT-5.3-Codex"},{alias:"gpt-5.3-codex-fast",modelId:"gpt-5.3-codex-fast",description:"Factory-managed GPT-5.3-Codex Fast"},{alias:"gpt-5.2",modelId:"gpt-5.2",description:"Factory-managed GPT-5.2"},{alias:"gpt-5.2-codex",modelId:"gpt-5.2-codex",description:"Factory-managed GPT-5.2-Codex"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Factory-managed Gemini 3.1 Pro"},{alias:"gemini-3-pro-preview",modelId:"gemini-3-pro-preview",description:"Factory-managed Gemini 3 Pro"},{alias:"gemini-3-flash-preview",modelId:"gemini-3-flash-preview",description:"Factory-managed Gemini 3 Flash"},{alias:"kimi-k2.6",modelId:"kimi-k2.6",description:"Factory-managed Droid Core Kimi K2.6"},{alias:"kimi-k2.5",modelId:"kimi-k2.5",description:"Factory-managed Droid Core Kimi K2.5"},{alias:"deepseek-v4-pro",modelId:"deepseek-v4-pro",description:"Factory-managed Droid Core DeepSeek V4 Pro"},{alias:"minimax-m2.7",modelId:"minimax-m2.7",description:"Factory-managed Droid Core MiniMax M2.7"},{alias:"minimax-m2.5",modelId:"minimax-m2.5",description:"Factory-managed Droid Core MiniMax M2.5"},{alias:"glm-5.1",modelId:"glm-5.1",description:"Factory-managed Droid Core GLM-5.1"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.5":"moonshot/kimi-k2.5","deepseek-v4-pro":"deepseek/deepseek-v4-pro","minimax-m2.7":"minimax/minimax-m2.7","minimax-m2.5":"minimax/minimax-m2.5","glm-5.1":"openrouter/z-ai/glm-5.1"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:t,model:e,isResume:n,sessionId:i,reasoningEffort:r,isDirectMode:s})=>{let a=s?"":"--settings /home/user/.factory/evolve-settings.json ",l=s?e:"custom:Evolve-Gateway-0",c=r&&s?` --reasoning-effort ${r}`:"",p=n&&i?`--session-id ${Be(i)} `:"";return `printf '%s' ${Be(t)} | droid ${a}exec ${p}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${Be(l)}${c}`}}};function $(t){let e=Ve[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function Zn(t){return t in Ve}function G(t){return t.replace(/^~/,"/home/user")}function Be(t){return `'${t.replace(/'/g,"'\\''")}'`}function K(t){let e=$(t);return `${G(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function j(t){let e=$(t);return G(e.mcpConfig.settingsDir)}function D(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 Ge(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 ne(t){for(let[e,n]of Object.entries(t))Ge(e,n);}function ie(t){return t.type?t.type:t.command?"stdio":"sse"}function Qn(t){let e=ie(t);return {...t,type:e}}function Xn(t){let{type:e,url:n,...i}=t;return ie(t)==="http"&&n?{httpUrl:n,...i}:n?{url:n,...i}:i}function ei(t){return {type:ie(t),...t}}function ti(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function ni(t){let e=ie(t),{type:n,httpHeaders:i,envHttpHeaders:r,bearerTokenEnvVar:s,envVars:a,...l}=t;if(e==="stdio"&&t.command)return {type:"stdio",...l};if(t.url){let c={...l,type:e==="sse"?"sse":"http",url:t.url},p=t.headers??i;return p&&Object.keys(p).length>0&&(c.headers=p),c}return {type:e==="stdio"?"stdio":"http",...l}}async function ze(t,e,n,i){ne(n);let r=j(e),s=K(e);await t.files.makeDir(r);let a={};try{let c=await t.files.read(s);typeof c=="string"&&(a=JSON.parse(c));}catch(c){if(!D(c))throw c}let l=Object.fromEntries(Object.entries(n).map(([c,p])=>[c,i(p)]));await t.files.write(s,JSON.stringify({...a,mcpServers:l},null,2));}async function me(t,e,n){ne(n);let i=j("claude"),r=K("claude"),s=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,ei(c)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await t.files.makeDir(i);let a={};try{let l=await t.files.read(r);typeof l=="string"&&(a=JSON.parse(l));}catch(l){if(!D(l))throw l}a.enableAllProjectMcpServers=true,await t.files.write(r,JSON.stringify(a,null,2));}async function fe(t,e){await ze(t,"gemini",e,Qn);}async function he(t,e){await ze(t,"qwen",e,Xn);}async function ye(t,e,n,i){let r=j(e),s=K(e);await t.files.makeDir(r);let a={};try{let d=await t.files.read(s);typeof d=="string"&&(a=JSON.parse(d));}catch(d){if(!D(d))throw d}let l=n.split("."),c=a;for(let d=0;d<l.length-1;d++){let u=l[d];(typeof c[u]!="object"||c[u]===null)&&(c[u]={}),c=c[u];}let p=l[l.length-1],o=typeof c[p]=="object"&&c[p]!==null?c[p]:{};c[p]={...o,...i},await t.files.write(s,JSON.stringify(a,null,2));}async function We(t,e){await ze(t,"kimi",e,ti);}async function we(t,e,n){ne(n);let i=`${e}/.factory`,r=`${i}/mcp.json`;await t.files.makeDir(i);let s={};try{let l=await t.files.read(r);typeof l=="string"&&(s=JSON.parse(l));}catch(l){if(!D(l))throw l}let a=Object.fromEntries(Object.entries(n).map(([l,c])=>[l,ni(c)]));await t.files.write(r,JSON.stringify({...s,mcpServers:a},null,2));}async function ve(t,e,n){let i=G(e.settingsPath),r=i.slice(0,i.lastIndexOf("/"));await t.files.makeDir(r);let s={cloudSessionSync:false,customModels:[{model:e.model,displayName:e.displayName,baseUrl:e.baseUrl,apiKey:`\${${e.apiKeyEnv}}`,provider:e.provider,...e.maxOutputTokens!==void 0&&{maxOutputTokens:e.maxOutputTokens},extraHeaders:n}]};await t.files.write(i,JSON.stringify(s,null,2));}async function Je(t,e,n){ne(n);let i=`${e}/opencode.json`,r={};try{let a=await t.files.read(i);typeof a=="string"&&(r=JSON.parse(a));}catch(a){if(!D(a))throw a}let s=Object.fromEntries(Object.entries(n).map(([a,l])=>[a,ii(l)]));await t.files.write(i,JSON.stringify({...r,mcp:s},null,2));}function ii(t){let e=ie(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 B(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function qe(){return `${B()}`}function Pt(){return `${B()}/e2b`}function Rt(t){return {"browser-use":{type:"http",url:`${B()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var O="EVOLVE_API_KEY",xe="E2B_API_KEY",ke="DAYTONA_API_KEY",Ce="MODAL_TOKEN_ID",He="MODAL_TOKEN_SECRET",It="claude",se=36e5,Ot=4,Ye=100,Mt="/home/user/workspace",P=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",I="x-litellm-customer-id",U="x-litellm-tags",z="run:",At=".evolve-sdk/observability/sessions",$t=100,Dt=5e3,Se=3,Ze=1e3;function E(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>E(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,i])=>`${n} = ${E(i)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function be(t,e){for(let[c,p]of Object.entries(e))Ge(c,p);let n=j("codex"),i=K("codex");await t.files.makeDir(n);let r="";try{let c=await t.files.read(i);typeof c=="string"&&(r=c);}catch(c){if(!D(c))throw c}let s=[],a=[];r.includes("experimental_use_rmcp_client")||(s.push("# Enable improved RMCP client (recommended)"),s.push("experimental_use_rmcp_client = true")),r.includes("[mcp_servers]")||a.push("[mcp_servers]","");for(let[c,p]of Object.entries(e)){if(r.includes(`[mcp_servers.${c}]`))continue;a.push(`[mcp_servers.${c}]`);let o=p.type??(p.command?"stdio":"http");if(o==="http"||o==="sse"||!!p.url){if(!p.url)throw new Error(`MCP server "${c}" is missing url for ${o} transport`);a.push(`url = ${E(p.url)}`),p.bearerTokenEnvVar&&a.push(`bearer_token_env_var = ${E(p.bearerTokenEnvVar)}`);let u=p.httpHeaders??p.headers;u&&Object.keys(u).length>0&&a.push(`http_headers = ${E(u)}`),p.envHttpHeaders&&Object.keys(p.envHttpHeaders).length>0&&a.push(`env_http_headers = ${E(p.envHttpHeaders)}`);}else a.push(`command = ${E(p.command)}`),p.args&&p.args.length>0&&a.push(`args = ${E(p.args)}`),p.cwd&&a.push(`cwd = ${E(p.cwd)}`);p.env&&Object.keys(p.env).length>0&&a.push(`env = ${E(p.env)}`),p.envVars&&p.envVars.length>0&&a.push(`env_vars = ${E(p.envVars)}`),a.push("");}let l=[r.trim(),s.join(`
|
|
2
|
+
`),a.join(`
|
|
3
|
+
`)].filter(c=>c.length>0);await t.files.write(i,l.join(`
|
|
4
4
|
|
|
5
5
|
`)+`
|
|
6
|
-
`);}async function
|
|
6
|
+
`);}async function Qe(t,e,n){let i=j("codex"),r=K("codex");await t.files.makeDir(i);let s="";try{let f=await t.files.read(r);typeof f=="string"&&(s=f);}catch(f){if(!D(f))throw f}let a=s.search(/^\[/m),l=a>=0?s.slice(0,a):s,c=a>=0?s.slice(a):"",p=s.includes("[model_providers.evolve-gateway]"),o=/^model_provider\s*=\s*"evolve-gateway"/m.test(l);if(p&&o)return;s=(l.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
|
|
7
7
|
|
|
8
|
-
`)+
|
|
9
|
-
`),
|
|
8
|
+
`)+c).replace(/^\n+/,"");let u='model_provider = "evolve-gateway"',g=p?"":["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${E(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${E({[I]:n.sessionTagEnv,[U]:n.runTagEnv})}`].join(`
|
|
9
|
+
`),m;if(!s.trim())m=g?`${u}
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
`:`${
|
|
13
|
-
`;else {let f=s.search(/^\[/m);f>0?
|
|
11
|
+
${g}
|
|
12
|
+
`:`${u}
|
|
13
|
+
`;else {let f=s.search(/^\[/m);f>0?m=s.slice(0,f)+u+`
|
|
14
14
|
|
|
15
|
-
`+s.slice(f).trimEnd():f===0?
|
|
15
|
+
`+s.slice(f).trimEnd():f===0?m=u+`
|
|
16
16
|
|
|
17
|
-
`+s.trimEnd():
|
|
17
|
+
`+s.trimEnd():m=s.trimEnd()+`
|
|
18
18
|
|
|
19
|
-
`+
|
|
19
|
+
`+u,g&&(m=m.trimEnd()+`
|
|
20
20
|
|
|
21
|
-
`+
|
|
22
|
-
`;}await
|
|
21
|
+
`+g),m+=`
|
|
22
|
+
`;}await t.files.write(r,m);}async function Xe(t,e,n){let i=G(e.configPath),r=i.slice(0,i.lastIndexOf("/"));await t.files.makeDir(r);let s=[`default_model = ${E(e.modelName)}`,"",`[providers.${e.providerName}]`,'type = "kimi"','base_url = ""','api_key = ""',`custom_headers = ${E(n)}`,"",`[models.${e.modelName}]`,`provider = ${E(e.providerName)}`,'model = ""',`max_context_size = ${e.maxContextSize}`].join(`
|
|
23
23
|
`)+`
|
|
24
|
-
`;await
|
|
25
|
-
`+
|
|
24
|
+
`;await t.files.write(i,s);}async function et(t,e,n,i){if(!(!i||Object.keys(i).length===0))switch(t){case "claude":await me(e,n,i);break;case "codex":await be(e,i);break;case "gemini":await fe(e,i);break;case "qwen":await he(e,i);break;case "kimi":await We(e,i);break;case "opencode":await Je(e,n,i);break;case "droid":await we(e,n,i);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function _e(){let t={};return function(p){let o;try{o=JSON.parse(p);}catch{return null}if(o._meta||o._prompt)return null;let d=o.session_id;switch(o.type){case "system":return null;case "assistant":return e(o.message?.content,"assistant",d);case "user":{let u=o.message?.content;return typeof u=="string"||Array.isArray(u)&&u.length===1&&u[0].type==="text"?null:e(u,"user",d)}case "result":return null;default:return null}};function e(c,p,o){if(typeof c=="string")return p==="user"?null:[{sessionId:o,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}];if(!c||!Array.isArray(c))return null;let d=[];for(let u of c){let g=null;switch(u.type){case "text":case "text_delta":if(p==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(p==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:u.source?.type==="base64"?u.source.data:"",mimeType:u.source?.type==="base64"?u.source.media_type:"",uri:u.source?.type==="url"?u.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[u.id]=u,u.name==="TodoWrite")Array.isArray(u.input?.todos)&&(g={sessionUpdate:"plan",entries:a(u.input)});else {let m=n(u);g={sessionUpdate:"tool_call",toolCallId:u.id,status:"pending",...m};}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 m=t[u.tool_use_id];if(!m||(delete t[u.tool_use_id],m.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:u.tool_use_id,status:"is_error"in u&&u.is_error?"failed":"completed",...i(u,m)};break}}g&&d.push({sessionId:o,update:g});}return d.length>0?d:null}function n(c){let p=c.name,o=c.input||{};switch(p){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 d="";return o.limit?d=" ("+((o.offset??0)+1)+" - "+((o.offset??0)+o.limit)+")":o.offset&&(d=" (from line "+(o.offset+1)+")"),{title:"Read "+(o.file_path??"File")+d,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 d=o.file_path;return {title:d?`Edit \`${d}\``:"Edit",kind:"edit",content:d?[{type:"diff",path:d,oldText:o.old_string??null,newText:o.new_string??""}]:[],locations:d?[{path:d}]:[],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 d="Find";return o.path&&(d+=` \`${o.path}\``),o.pattern&&(d+=` \`${o.pattern}\``),{title:d,kind:"search",content:[],locations:o.path?[{path:o.path}]:[],rawInput:o}}case "Grep":{let d="grep";return o["-i"]&&(d+=" -i"),o["-n"]&&(d+=" -n"),o["-A"]!==void 0&&(d+=` -A ${o["-A"]}`),o["-B"]!==void 0&&(d+=` -B ${o["-B"]}`),o["-C"]!==void 0&&(d+=` -C ${o["-C"]}`),o.output_mode==="files_with_matches"?d+=" -l":o.output_mode==="count"&&(d+=" -c"),o.head_limit!==void 0&&(d+=` | head -${o.head_limit}`),o.glob&&(d+=` --include="${o.glob}"`),o.type&&(d+=` --type=${o.type}`),o.multiline&&(d+=" -P"),d+=` "${o.pattern??""}"`,o.path&&(d+=` ${o.path}`),{title:d,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 d=`"${o.query??""}"`;return o.allowed_domains?.length>0&&(d+=` (allowed: ${o.allowed_domains.join(", ")})`),o.blocked_domains?.length>0&&(d+=` (blocked: ${o.blocked_domains.join(", ")})`),{title:d,kind:"fetch",content:[],rawInput:o}}case "TodoWrite":return {title:Array.isArray(o.todos)?`Update TODOs: ${o.todos.map(d=>d.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(p?.startsWith("mcp__")){let d=p.split("__"),u=d[1]||"mcp",g=d.slice(2).join("__")||p;return {title:`${u}: ${g}`,kind:"other",content:[],rawInput:o}}return {title:p||"Unknown Tool",kind:"other",content:[],rawInput:o}}}function i(c,p){let o=c.content;switch(p?.name){case "Read":return Array.isArray(o)&&o.length>0?{content:o.map(d=>({type:"content",content:d.type==="text"?{type:"text",text:l(d.text)}:s(d,false)}))}:typeof o=="string"&&o.length>0?{content:[{type:"content",content:{type:"text",text:l(o)}}]}:{};case "Edit":case "Write":case "Bash":return r(o,c.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return r(o,"is_error"in c?c.is_error:false)}}function r(c,p=false){return Array.isArray(c)&&c.length>0?{content:c.map(o=>({type:"content",content:s(o,p)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:p?"```\n"+c+"\n```":c}}]}:{}}function s(c,p){if(c.type==="text")return p?{type:"text",text:"```\n"+c.text+"\n```"}:{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return {type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return {type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function a(c){return c.todos.map(p=>({content:p.content,status:p.status||"pending",priority:"medium"}))}function l(c){let p="```",o=Array.from(c.matchAll(/^```+/gm));for(let[d]of o)for(;d.length>=p.length;)p+="`";return p+`
|
|
25
|
+
`+c+(c.endsWith(`
|
|
26
26
|
`)?"":`
|
|
27
|
-
`)+p}}function
|
|
27
|
+
`)+p}}function Ee(){return function(c){let p;try{p=JSON.parse(c);}catch{return null}if(p._meta||p._prompt)return null;let o=[];switch(p.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "item.started":{let d=p.item;if(!d)return null;let u=e(d);u&&o.push({update:u});break}case "item.updated":{let d=p.item;if(!d)return null;let u=n(d);u&&o.push({update:u});break}case "item.completed":{let d=p.item;if(!d)return null;let u=i(d);u&&o.push({update:u});break}default:return null}return o.length>0?o:null};function e(l){let c=l.id;switch(l.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${l.server}:${l.tool}`},{sessionUpdate:"tool_call",toolCallId:c,title:`${l.server}: ${l.tool}`,kind:"other",status:"in_progress",rawInput:l.arguments,content:[]};case "command_execution":return {type:"command_execution",name:l.command},{sessionUpdate:"tool_call",toolCallId:c,title:l.command?`\`${l.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:l.command},content:[]};case "web_search":return {type:"web_search",name:l.query},{sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${l.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(l.items)};default:return null}}function n(l){return l.type==="todo_list"?{sessionUpdate:"plan",entries:a(l.items)}:null}function i(l){let c=l.id;switch(l.type){case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l.text??l.summary?.join(`
|
|
28
28
|
`)??l.content?.join(`
|
|
29
|
-
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text??""}};case "mcp_tool_call":{let
|
|
30
|
-
${
|
|
31
|
-
\`\`\``:
|
|
29
|
+
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:l.text??""}};case "mcp_tool_call":{let o=r(l.result),d=l.status==="failed"||l.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:d,content:o}}case "command_execution":{let o=l.aggregated_output?[{type:"content",content:{type:"text",text:l.aggregated_output}}]:[],d=l.status==="completed"||l.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:c,status:d,content:o}}case "file_change":{let o=l.changes??[],d=o.map(g=>({path:g.path})),u=o.length===1?`${o[0].kind==="add"?"Create":"Edit"} ${o[0].path}`:`Edit ${o.length} files`;return {sessionUpdate:"tool_call",toolCallId:c,title:u,kind:"edit",status:l.status==="completed"?"completed":"failed",content:o.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:d}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:c,title:`Search: ${l.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:a(l.items)};default:return null}}function r(l){return l?.content?Array.isArray(l.content)?l.content.map(c=>({type:"content",content:s(c)})):typeof l.content=="string"?[{type:"content",content:{type:"text",text:l.content}}]:[]:[]}function s(l){return l.type==="text"?{type:"text",text:l.text??""}:l.type==="image"?{type:"image",data:l.data??"",mimeType:l.mime_type??l.mimeType??"",uri:l.uri}:l}function a(l){if(!Array.isArray(l))return [];let c=false;return l.map(p=>{let o;return p.completed?o="completed":c?o="pending":(o="in_progress",c=true),{content:p.text??"",status:o,priority:"medium"}})}}var si={applypatch:"edit",apply_patch:"edit",create:"edit",edit:"edit",grep:"search",glob:"search",ls:"search",read:"read",write:"edit",execute:"execute",execute_cli:"execute",fetchurl:"fetch",fetch_url:"fetch",webfetch:"fetch",web_fetch:"fetch",websearch:"fetch",web_search:"fetch",skill:"execute",task:"think",todowrite:"other",todo_write:"other"},oi=new Set(["assistant_text_complete","thinking_text_complete","droid_working_state_changed","permission_resolved","settings_updated","session_title_updated","mcp_status_changed","session_token_usage_changed","mission_state_changed","mission_features_changed","mission_progress_entry","mission_heartbeat","mission_worker_started","mission_worker_completed","mcp_auth_required","mcp_auth_completed","structured_output"]);function Te(){let t=new Map,e,n=false,i="";return function(s){let a;try{a=JSON.parse(s);}catch{return null}if(!Lt(a))return null;let l=ri(a);if(l.sessionId&&(e=l.sessionId),l.errorText)return [V(e,l.errorText)];if(l.resultText)return i=l.resultText,n=true,[V(e,l.resultText)];if(l.handled)return null;let p=ai(a)??a,o=Ft(p);o&&(e=o);let d=[],u=S(p,"type");switch(u){case "system":return null;case "message":{let g=S(p,"role"),m=S(p,"text")||tt(p.content);if(!m)break;g==="assistant"&&(n=true,i=m,d.push(V(e,m)));break}case "completion":{let g=S(p,"finalText")||S(p,"result");g&&(!n||g!==i)&&(n=true,i=g,d.push(V(e,g)));break}case "assistant_text_delta":{let g=S(p,"textDelta")||S(p,"text");g&&(n=true,i+=g,d.push(V(e,g)));break}case "thinking_text_delta":{let g=S(p,"textDelta")||S(p,"text");g&&d.push({sessionId:e,update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g}}});break}case "assistant":{let g=S(p,"text")||tt(T(p.message)?.content);g&&(n=true,i=g,d.push(V(e,g)));break}case "tool_call":case "tool_call_delta":{let g=T(p.toolUse)??T(p.tool_use)??p,m=Ut(g,t);m&&d.push({sessionId:e,update:m});break}case "tool_result":{let g=li(p,t);g&&d.push({sessionId:e,update:g});break}case "tool_progress_update":case "tool_progress":{let g=pi(p);g&&d.push({sessionId:e,update:g});break}case "create_message":{for(let g of ci(p,t)){if(g.sessionUpdate==="agent_message_chunk"){let m=g.content.type==="text"?g.content.text:"";if(n&&m===i)continue;n=true,i=m;}d.push({sessionId:e,update:g});}break}case "result":{let g=oe(p.result??p.text??p.error);g&&(n=true,i=g,d.push(V(e,g)));break}case "error":{let g=oe(p.message??p.error??p);g&&d.push(V(e,g));break}default:if(u&&!oi.has(u))return null}return d.length>0?d:null}}function ri(t){if(t.type!=="response")return {handled:false};let e=T(t.result),n=T(t.error),i=Ft(e??t);if(n)return {handled:true,sessionId:i,errorText:oe(n.message??n)};let r=e?S(e,"finalText")||S(e,"result"):"";return {handled:true,sessionId:i,resultText:r}}function ai(t){return t.method!=="droid.session_notification"?null:T(T(t.params)?.notification)}function ci(t,e){let n=T(t.message);if(!n)return [];let i=[],r=n.content;if(Array.isArray(r))for(let s of r){let a=T(s);if(a&&a.type==="tool_use"){let l=Ut(a,e);l&&i.push(l);}}if(n.role==="assistant"){let s=tt(r);s&&i.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}});}return i}function Ut(t,e){let n=S(t,"id")||S(t,"toolUseId")||S(t,"tool_use_id"),i=S(t,"name")||S(t,"toolName")||S(t,"tool_name")||"Tool";if(!n)return null;e.set(n,i);let r=T(t.input)??T(t.toolInput)??T(t.arguments)??{};if(Nt(i)==="todowrite"){let p=di(r);if(p)return p}let{title:s,kind:a,content:l,locations:c}=ui(i,r);return {sessionUpdate:"tool_call",toolCallId:n,title:s,kind:a,status:"pending",rawInput:r,content:l,locations:c}}function li(t,e){let n=S(t,"toolUseId")||S(t,"tool_use_id")||S(t,"tool_id");if(!n)return null;let i=S(t,"toolName")||S(t,"tool_name")||e.get(n);return e.delete(n),{sessionUpdate:"tool_call_update",toolCallId:n,status:t.isError===true||t.is_error===true?"failed":"completed",title:i,content:nt(t.content??t.result??t.error)}}function pi(t){let e=S(t,"toolUseId")||S(t,"tool_use_id")||S(t,"tool_id");if(!e)return null;let n=T(t.update),i=oe(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:i?nt(i):void 0}}function di(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(i=>{let r=T(i);if(!r)return [];let s=S(r,"content"),a=gi(S(r,"status")),l=mi(S(r,"priority"));return s?[{content:s,status:a,priority:l}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function ui(t,e){let n=si[Nt(t)]||"other",i=S(e,"path")||S(e,"filePath")||S(e,"file_path")||S(e,"absolute_path"),r=S(e,"command"),s=S(e,"url"),a=i||r||s;return {title:a?`${t} ${a}`:t,kind:n,content:Object.keys(e).length>0?nt(e):[],locations:i?[{path:i}]:[]}}function Ft(t){if(t)return S(t,"session_id")||S(t,"sessionId")}function V(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function tt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=T(e);return n?S(n,"text")||S(n,"content"):""}).filter(Boolean).join(""):""}function nt(t){let e=oe(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function oe(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function Lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function T(t){return Lt(t)?t:null}function S(t,e){let n=t[e];return typeof n=="string"?n:""}function Nt(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function gi(t){return t==="in_progress"||t==="completed"?t:"pending"}function mi(t){return t==="high"||t==="low"?t:"medium"}var fi={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 Pe(){return function(a){let l;try{l=JSON.parse(a);}catch{return null}if(l._meta||l._prompt)return null;let c=l.session_id,p=[];switch(l.type){case "init":case "result":return null;case "message":{let o=t(l);o&&p.push({sessionId:c,update:o});break}case "tool_use":{let o=e(l);o&&p.push({sessionId:c,update:o});break}case "tool_result":{let o=n(l);o&&p.push({sessionId:c,update:o});break}case "error":{let o=i(l);o&&p.push({sessionId:c,update:o});break}default:return null}return p.length>0?p:null};function t(s){let a=s.role,l=s.content;return l?a==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}:a==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:l}}:null:null}function e(s){let a=s.tool_id,l=s.tool_name,c=s.parameters||{},{title:p,kind:o,content:d,locations:u}=r(l,c);return {sessionUpdate:"tool_call",toolCallId:a,title:p,kind:o,status:"pending",rawInput:c,content:d,locations:u}}function n(s){let a=s.tool_id,l=s.status,c=s.output,p=s.error,o=[];return c&&typeof c=="string"&&c.length>0&&o.push({type:"content",content:{type:"text",text:l==="error"?`\`\`\`
|
|
30
|
+
${c}
|
|
31
|
+
\`\`\``:c}}),p?.message&&!c&&o.push({type:"content",content:{type:"text",text:`\`\`\`
|
|
32
32
|
${p.message}
|
|
33
|
-
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:r,status:l==="success"?"completed":"failed",content:i}}function o(s){let r=s.severity,l=s.message;return l?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${r==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${l}`}}:null}function c(s,r){let l=Ln[s]||"other",a=[],p=[],i=s;switch(s){case "read_file":i=`Read ${r.absolute_path||r.file_path||"file"}`,(r.absolute_path||r.file_path)&&p.push({path:r.absolute_path||r.file_path});break;case "write_file":i=`Write ${r.file_path||"file"}`,r.file_path&&(p.push({path:r.file_path}),a.push({type:"diff",path:r.file_path,oldText:null,newText:r.content||""}));break;case "edit_file":i=`Edit ${r.file_path||"file"}`,r.file_path&&p.push({path:r.file_path});break;case "replace":i=`Edit ${r.file_path||"file"}`,r.file_path&&(p.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":i=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":i=r.query?`"${r.query}"`:"Web search";break;case "web_fetch":i=r.prompt?`Fetch: ${r.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${r.pattern||"files"}`,r.dir_path&&p.push({path:r.dir_path});break;case "grep":case "search_file_content":i=`grep "${r.pattern||r.query||""}"`;break;case "list_directory":i=`List ${r.dir_path||r.path||"directory"}`,(r.dir_path||r.path)&&p.push({path:r.dir_path||r.path});break;case "read_many_files":i=`Read ${r.include?.length||"multiple"} files`,Array.isArray(r.include)&&r.include.forEach(u=>p.push({path:u}));break;case "delegate_to_agent":i=r.agent_name?`Agent: ${r.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=r.fact?`Remember: "${r.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=r.name?`Activate skill: ${r.name}`:"Activate skill";break;default:i=s;}return {title:i,kind:l,content:a,locations:p}}}var Nn={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 ze(n){return /<system>\s*ERROR:/i.test(n)||n.includes("<error>")||n.includes("ToolError")}function bt(n){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(n);if(!e)return null;let t=e[1]||"",o=e[2]||"",c=e[3]||"";return /;base64/i.test(o)?{mimeType:t,data:c}:null}function Je(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=bt(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 We(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 o=Je(t);o&&e.push(o);}return e}if(n&&typeof n=="object"){let t=Je(n);t&&e.push(t);}return e}function Kn(n){return n.some(e=>e.type==="content"&&e.content.type==="text"&&ze(e.content.text))}function Bn(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=bt(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 jn(n){return n==="in_progress"?"in_progress":n==="done"||n==="completed"?"completed":"pending"}function St(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 o=t.title;if(typeof o!="string"||o.length===0)return null;let c=t.status;return {content:o,status:jn(c),priority:"medium"}}).filter(t=>t!==null):[]}function Ge(){let n=new Set,e=0;function t(l,a){return typeof l=="string"&&l.length>0?l:(e+=1,`kimi_${a.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(a){let p;try{p=JSON.parse(a);}catch{return null}if(!p||typeof p!="object"||"_meta"in p||"_prompt"in p)return null;let i=p.role;return i==="assistant"?o(p):i==="tool"?c(p):typeof p.type=="string"&&"payload"in p?s(p):null};function o(l){let a=[],p=l.content,i=l.tool_calls;if(typeof p=="string"&&p.length>0)a.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});else if(Array.isArray(p))for(let u of p){let d=Bn(u);d&&a.push(d);}if(Array.isArray(i))for(let u of i){if(!u||typeof u!="object")continue;let d=u.function;if(!d)continue;let m=d.name??"",g=t(u.id,m),f;try{f=d.arguments?JSON.parse(d.arguments):{};}catch{f=d.arguments;}if(m==="SetTodoList"){let x=St(f);x.length>0&&a.push({update:{sessionUpdate:"plan",entries:x}}),n.add(g);continue}let{title:h,kind:y,toolContent:w,locations:k}=r(m,typeof f=="object"&&f!==null?f:{});a.push({update:{sessionUpdate:"tool_call",toolCallId:g,title:h,kind:y,status:"pending",rawInput:f,content:w,locations:k}});}return a.length>0?a:null}function c(l){let a=l.tool_call_id;if(typeof a!="string"||a.length===0)return null;if(n.has(a))return n.delete(a),null;let p=l.content,i=[],u=false;if(typeof p=="string")u=ze(p),p.length>0&&i.push({type:"content",content:{type:"text",text:p}});else if(Array.isArray(p))for(let d of p){let m=Je(d);m&&(m.type==="content"&&m.content.type==="text"&&ze(m.content.text)&&(u=true),i.push(m));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:a,status:u?"failed":"completed",content:i}}]}function s(l){let a=l.type,p=l.payload??{},i=[];switch(a){case "TextPart":{let u=p.text;typeof u=="string"&&u.length>0&&i.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u}}});break}case "ThinkPart":{let u=p.think;typeof u=="string"&&u.length>0&&i.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u}}});break}case "ToolCall":{let u=p.function?.name??"",d=t(p.id,u),m=p.function;if(!m)break;let g;try{g=m.arguments?JSON.parse(m.arguments):{};}catch{g=m.arguments;}if(u==="SetTodoList"){let k=St(g);k.length>0&&i.push({update:{sessionUpdate:"plan",entries:k}}),n.add(d);break}let{title:f,kind:h,toolContent:y,locations:w}=r(u,typeof g=="object"&&g!==null?g:{});i.push({update:{sessionUpdate:"tool_call",toolCallId:d,title:f,kind:h,status:"pending",rawInput:g,content:y,locations:w}});break}case "ToolResult":{let u=p.tool_call_id;if(typeof u!="string"||u.length===0)break;if(n.has(u)){n.delete(u);break}let d=p.return_value??p.content,m=[],g=p.is_error===true;if(d&&typeof d=="object"&&!Array.isArray(d)){let f=d;g=g||f.type==="ToolError"||f.is_error===true,m.push(...We(f.output)),m.length===0&&typeof f.message=="string"&&f.message.length>0&&m.push({type:"content",content:{type:"text",text:f.message}}),m.length===0&&m.push(...We(d));}else m.push(...We(d));g=g||Kn(m),i.push({update:{sessionUpdate:"tool_call_update",toolCallId:u,status:g?"failed":"completed",content:m}});break}default:return null}return i.length>0?i:null}function r(l,a){let p=Nn[l]||"other",i=[],u=[],d=l;switch(l){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"&&i.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=l;}return {title:d,kind:p,toolContent:i,locations:u}}}var Vn={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 Wn(n){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(n);if(!e)return null;let t=e[1]||"",o=e[2]||"",c=e[3]||"";return /;base64/i.test(o)?{mimeType:t,data:c}:null}function zn(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 Jn(n){return n==="high"||n==="medium"||n==="low"?n:"medium"}function _t(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:zn(e.status),priority:Jn(e.priority)}}).filter(e=>e!==null):[]}function Gn(n){if(!n||typeof n!="object")return null;let e=n,t=typeof e.mime=="string"?e.mime:"",o=typeof e.url=="string"?e.url:"";if(t.startsWith("image/")){if(o.length>0){let l=Wn(o);return l?{type:"content",content:{type:"image",data:l.data,mimeType:l.mimeType||t}}:{type:"content",content:{type:"image",data:"",mimeType:t,uri:o}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${t||"file"})`}}}function Hn(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 Yn(n,e){return n==="error"?"failed":n==="running"?"in_progress":n==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function He(){return function(r){let l;try{l=JSON.parse(r);}catch{return null}if(!l||typeof l!="object")return null;let a=l.sessionID,p=[];switch(l.type){case "step_start":case "step_finish":return null;case "text":{let i=n(l);i&&p.push({sessionId:a,update:i});break}case "reasoning":{let i=e(l);i&&p.push({sessionId:a,update:i});break}case "tool_use":{let i=t(l);for(let u of i)p.push({sessionId:a,update:u});break}case "error":{let i=o(l);i&&p.push({sessionId:a,update:i});break}default:return null}return p.length>0?p: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 l=typeof r.callID=="string"?r.callID:"";if(l.length===0)return [];let a=typeof r.tool=="string"?r.tool.toLowerCase():"",p=typeof r.state=="object"&&r.state?r.state:{},i=typeof p.input=="object"&&p.input?p.input:{},u=p.status,d=p.title??p.metadata?.description??a,m=p.metadata?.exit,{kind:g,content:f,locations:h}=c(a,i),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:l,title:d,kind:g,status:"pending",rawInput:i,content:f,locations:h}),a==="todowrite"){let v=_t(i.todos);if(v.length===0&&typeof p.output=="string")try{v=_t(JSON.parse(p.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=Yn(u,m);if(w==="pending")return y;let k=Hn(u,p),x=[];if(typeof k=="string"&&k.length>0&&x.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
|
|
34
|
-
${
|
|
35
|
-
\`\`\``:
|
|
36
|
-
${
|
|
37
|
-
\`\`\``:
|
|
33
|
+
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:a,status:l==="success"?"completed":"failed",content:o}}function i(s){let a=s.severity,l=s.message;return l?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${a==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${l}`}}:null}function r(s,a){let l=fi[s]||"other",c=[],p=[],o=s;switch(s){case "read_file":o=`Read ${a.absolute_path||a.file_path||"file"}`,(a.absolute_path||a.file_path)&&p.push({path:a.absolute_path||a.file_path});break;case "write_file":o=`Write ${a.file_path||"file"}`,a.file_path&&(p.push({path:a.file_path}),c.push({type:"diff",path:a.file_path,oldText:null,newText:a.content||""}));break;case "edit_file":o=`Edit ${a.file_path||"file"}`,a.file_path&&p.push({path:a.file_path});break;case "replace":o=`Edit ${a.file_path||"file"}`,a.file_path&&(p.push({path:a.file_path}),(a.old_string!==void 0||a.new_string!==void 0)&&c.push({type:"diff",path:a.file_path,oldText:a.old_string||"",newText:a.new_string||""}));break;case "run_shell_command":case "shell":o=a.command?`\`${a.command}\``:"Run command",a.description&&c.push({type:"content",content:{type:"text",text:a.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=a.query?`"${a.query}"`:"Web search";break;case "web_fetch":o=a.prompt?`Fetch: ${a.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${a.pattern||"files"}`,a.dir_path&&p.push({path:a.dir_path});break;case "grep":case "search_file_content":o=`grep "${a.pattern||a.query||""}"`;break;case "list_directory":o=`List ${a.dir_path||a.path||"directory"}`,(a.dir_path||a.path)&&p.push({path:a.dir_path||a.path});break;case "read_many_files":o=`Read ${a.include?.length||"multiple"} files`,Array.isArray(a.include)&&a.include.forEach(d=>p.push({path:d}));break;case "delegate_to_agent":o=a.agent_name?`Agent: ${a.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=a.fact?`Remember: "${a.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=a.name?`Activate skill: ${a.name}`:"Activate skill";break;default:o=s;}return {title:o,kind:l,content:c,locations:p}}}var hi={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 st(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function jt(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",i=e[2]||"",r=e[3]||"";return /;base64/i.test(i)?{mimeType:n,data:r}:null}function ot(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=jt(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 it(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=ot(n);i&&e.push(i);}return e}if(t&&typeof t=="object"){let n=ot(t);n&&e.push(n);}return e}function yi(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&st(e.content.text))}function wi(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=jt(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 vi(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function Kt(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 r=n.status;return {content:i,status:vi(r),priority:"medium"}}).filter(n=>n!==null):[]}function rt(){let t=new Set,e=0;function n(l,c){return typeof l=="string"&&l.length>0?l:(e+=1,`kimi_${c.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(c){let p;try{p=JSON.parse(c);}catch{return null}if(!p||typeof p!="object"||"_meta"in p||"_prompt"in p)return null;let o=p.role;return o==="assistant"?i(p):o==="tool"?r(p):typeof p.type=="string"&&"payload"in p?s(p):null};function i(l){let c=[],p=l.content,o=l.tool_calls;if(typeof p=="string"&&p.length>0)c.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});else if(Array.isArray(p))for(let d of p){let u=wi(d);u&&c.push(u);}if(Array.isArray(o))for(let d of o){if(!d||typeof d!="object")continue;let u=d.function;if(!u)continue;let g=u.name??"",m=n(d.id,g),f;try{f=u.arguments?JSON.parse(u.arguments):{};}catch{f=u.arguments;}if(g==="SetTodoList"){let k=Kt(f);k.length>0&&c.push({update:{sessionUpdate:"plan",entries:k}}),t.add(m);continue}let{title:h,kind:y,toolContent:w,locations:C}=a(g,typeof f=="object"&&f!==null?f:{});c.push({update:{sessionUpdate:"tool_call",toolCallId:m,title:h,kind:y,status:"pending",rawInput:f,content:w,locations:C}});}return c.length>0?c:null}function r(l){let c=l.tool_call_id;if(typeof c!="string"||c.length===0)return null;if(t.has(c))return t.delete(c),null;let p=l.content,o=[],d=false;if(typeof p=="string")d=st(p),p.length>0&&o.push({type:"content",content:{type:"text",text:p}});else if(Array.isArray(p))for(let u of p){let g=ot(u);g&&(g.type==="content"&&g.content.type==="text"&&st(g.content.text)&&(d=true),o.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:c,status:d?"failed":"completed",content:o}}]}function s(l){let c=l.type,p=l.payload??{},o=[];switch(c){case "TextPart":{let d=p.text;typeof d=="string"&&d.length>0&&o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});break}case "ThinkPart":{let d=p.think;typeof d=="string"&&d.length>0&&o.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:d}}});break}case "ToolCall":{let d=p.function?.name??"",u=n(p.id,d),g=p.function;if(!g)break;let m;try{m=g.arguments?JSON.parse(g.arguments):{};}catch{m=g.arguments;}if(d==="SetTodoList"){let C=Kt(m);C.length>0&&o.push({update:{sessionUpdate:"plan",entries:C}}),t.add(u);break}let{title:f,kind:h,toolContent:y,locations:w}=a(d,typeof m=="object"&&m!==null?m:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:u,title:f,kind:h,status:"pending",rawInput:m,content:y,locations:w}});break}case "ToolResult":{let d=p.tool_call_id;if(typeof d!="string"||d.length===0)break;if(t.has(d)){t.delete(d);break}let u=p.return_value??p.content,g=[],m=p.is_error===true;if(u&&typeof u=="object"&&!Array.isArray(u)){let f=u;m=m||f.type==="ToolError"||f.is_error===true,g.push(...it(f.output)),g.length===0&&typeof f.message=="string"&&f.message.length>0&&g.push({type:"content",content:{type:"text",text:f.message}}),g.length===0&&g.push(...it(u));}else g.push(...it(u));m=m||yi(g),o.push({update:{sessionUpdate:"tool_call_update",toolCallId:d,status:m?"failed":"completed",content:g}});break}default:return null}return o.length>0?o:null}function a(l,c){let p=hi[l]||"other",o=[],d=[],u=l;switch(l){case "ReadFile":{let g=c.path??c.file_path;u=`Read ${g||"file"}`,g&&d.push({path:g});break}case "ReadMediaFile":{let g=c.path??c.file_path;u=`Read media ${g||"file"}`,g&&d.push({path:g});break}case "WriteFile":{let g=c.path??c.file_path;u=`Write ${g||"file"}`,g&&(d.push({path:g}),typeof c.content=="string"&&o.push({type:"diff",path:g,oldText:null,newText:c.content}));break}case "StrReplaceFile":{let g=c.path??c.file_path;u=`Edit ${g||"file"}`,g&&d.push({path:g});break}case "Shell":u=c.command?`\`${c.command}\``:"Run command";break;case "Glob":u=`Find ${c.pattern||"files"}`,c.path&&d.push({path:c.path});break;case "Grep":u=`grep "${c.pattern||""}"`,c.path&&d.push({path:c.path});break;case "SearchWeb":u=c.query?`"${c.query}"`:"Web search";break;case "FetchURL":u=c.url?`Fetch ${c.url}`:"Web fetch";break;case "Task":u=c.description||"Subagent task";break;case "Think":u=c.thought||"Thinking";break;case "CreateSubagent":u=c.name?`Subagent: ${c.name}`:"Create subagent";break;case "SetTodoList":u="Update todos";break;default:u=l;}return {title:u,kind:p,toolContent:o,locations:d}}}var xi={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 ki(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",i=e[2]||"",r=e[3]||"";return /;base64/i.test(i)?{mimeType:n,data:r}:null}function Ci(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 Si(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function Bt(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:Ci(e.status),priority:Si(e.priority)}}).filter(e=>e!==null):[]}function bi(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 l=ki(i);return l?{type:"content",content:{type:"image",data:l.data,mimeType:l.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 _i(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 Ei(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function at(){return function(a){let l;try{l=JSON.parse(a);}catch{return null}if(!l||typeof l!="object")return null;let c=l.sessionID,p=[];switch(l.type){case "step_start":case "step_finish":return null;case "text":{let o=t(l);o&&p.push({sessionId:c,update:o});break}case "reasoning":{let o=e(l);o&&p.push({sessionId:c,update:o});break}case "tool_use":{let o=n(l);for(let d of o)p.push({sessionId:c,update:d});break}case "error":{let o=i(l);o&&p.push({sessionId:c,update:o});break}default:return null}return p.length>0?p:null};function t(s){let a=s.part?.text;return typeof a!="string"||a.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}}function e(s){let a=s.part?.text;return typeof a!="string"||a.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a}}}function n(s){let a=s.part;if(!a)return [];let l=typeof a.callID=="string"?a.callID:"";if(l.length===0)return [];let c=typeof a.tool=="string"?a.tool.toLowerCase():"",p=typeof a.state=="object"&&a.state?a.state:{},o=typeof p.input=="object"&&p.input?p.input:{},d=p.status,u=p.title??p.metadata?.description??c,g=p.metadata?.exit,{kind:m,content:f,locations:h}=r(c,o),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:l,title:u,kind:m,status:"pending",rawInput:o,content:f,locations:h}),c==="todowrite"){let v=Bt(o.todos);if(v.length===0&&typeof p.output=="string")try{v=Bt(JSON.parse(p.output));}catch{}v.length>0&&y.push({sessionUpdate:"plan",entries:v});}let w=Ei(d,g);if(w==="pending")return y;let C=_i(d,p),k=[];if(typeof C=="string"&&C.length>0&&k.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
|
|
34
|
+
${C}
|
|
35
|
+
\`\`\``:C}}),Array.isArray(p.attachments))for(let v of p.attachments){let x=bi(v);x&&k.push(x);}return y.push({sessionUpdate:"tool_call_update",toolCallId:l,status:w,content:k}),y}function i(s){let a=s.error?.name??"Error",l=s.error?.data?.message??s.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${a}: ${l}`}}}function r(s,a){let l=xi[s]||"other",c=[],p=[];switch(s){case "read":{let o=a.filePath??a.path;if(o){let d=a.offset;p.push({path:o,line:typeof d=="number"&&Number.isFinite(d)?Math.max(0,d-1):void 0});}break}case "write":{let o=a.filePath??a.path;o&&(p.push({path:o}),typeof a.content=="string"&&c.push({type:"diff",path:o,oldText:null,newText:a.content}));break}case "edit":case "multiedit":{let o=a.filePath??a.path;o&&(p.push({path:o}),s==="edit"&&(a.oldString!==void 0||a.newString!==void 0)&&c.push({type:"diff",path:o,oldText:a.oldString??"",newText:a.newString??""}));break}case "apply_patch":break;case "bash":{let o=a.command;o&&a.description?c.push({type:"content",content:{type:"text",text:a.description}}):o&&c.push({type:"content",content:{type:"text",text:o}});break}case "glob":case "list":{let o=a.path;o&&p.push({path:o});break}case "grep":{let o=a.path;o&&p.push({path:o});break}case "codesearch":case "websearch":{let o=a.query;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "webfetch":{let o=a.url;o&&c.push({type:"content",content:{type:"text",text:o}});break}case "task":{let o=a.description;o&&c.push({type:"content",content:{type:"text",text:o}});break}}return {kind:l,content:c,locations:p}}}var Ti={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 Re(){let t=new Map,e=new Map;return function(o){let d;try{d=JSON.parse(o);}catch{return null}if(!d||typeof d!="object")return null;let u=d;if("_meta"in u||"_prompt"in u)return null;let g=u.session_id||void 0,m=[];switch(u.type){case "assistant":{let f=n(u);for(let h of f)m.push({sessionId:g,update:h});break}case "stream_event":{let f=i(u);for(let h of f)m.push({sessionId:g,update:h});break}case "user":{let f=r(u);for(let h of f)m.push({sessionId:g,update:h});break}case "system":case "result":return null;default:return null}return m.length>0?m:null};function n(p){let o=[],d=p.message?.content;if(!Array.isArray(d))return o;for(let u of d){let g=s(u);o.push(...g);}return o}function i(p){let o=[],d=p.event;if(!d)return o;switch(d.type){case "content_block_start":{let u=d.index??0,g=d.content_block;g&&(t.set(u,g),g.type==="tool_use"&&e.set(u,""));break}case "content_block_delta":{let u=d.index??0,g=d.delta,m=t.get(u);if(g?.type==="text_delta"&&g.text)o.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:g.text}});else if(g?.type==="thinking_delta"&&g.thinking)o.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:g.thinking}});else if(g?.type==="input_json_delta"&&g.partial_json&&m?.type==="tool_use"){let f=e.get(u)||"";e.set(u,f+g.partial_json);}break}case "content_block_stop":{let u=d.index??0,g=t.get(u);if(g&&!(g.type==="text"&&g.text)){if(!(g.type==="thinking"&&g.thinking)){if(g.type==="tool_use"){let m=g,f=e.get(u)||"";e.delete(u);let h=m.input;if(f)try{h=JSON.parse(f);}catch{}let y={...m,input:h},w=a(y);w&&o.push(w);}else if(g.type==="tool_result"){let m=l(g);m&&o.push(m);}}}t.delete(u);break}}return o}function r(p){let o=p.message?.content,d=[];if(typeof o=="string")return d.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:o}}),d;if(Array.isArray(o)){for(let u of o)if(u.type==="text")d.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:u.text}});else if(u.type==="tool_result"){let g=l(u);g&&d.push(g);}}return d}function s(p){switch(p.type){case "text":return p.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}}]:[];case "thinking":return p.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.thinking}}]:[];case "tool_use":{let o=a(p);return o?[o]:[]}case "tool_result":{let o=l(p);return o?[o]:[]}}}function a(p){let o=p.id,d=p.name,u=p.input;if(d==="TodoWrite"&&Array.isArray(u?.todos))return {sessionUpdate:"plan",entries:u.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:g,kind:m,content:f,locations:h}=c(d,u||{});return {sessionUpdate:"tool_call",toolCallId:o,title:g,kind:m,status:"pending",rawInput:u,content:f,locations:h}}function l(p){let o=p.tool_use_id,d=p.is_error??false,u=p.content,g=[];if(typeof u=="string"&&u.length>0)g.push({type:"content",content:{type:"text",text:d?`\`\`\`
|
|
36
|
+
${u}
|
|
37
|
+
\`\`\``:u}});else if(Array.isArray(u)){for(let m of u)if(m.type==="text"){let f=m.text;g.push({type:"content",content:{type:"text",text:d?`\`\`\`
|
|
38
38
|
${f}
|
|
39
|
-
\`\`\``:f}});}}return {sessionUpdate:"tool_call_update",toolCallId:
|
|
40
|
-
`),
|
|
41
|
-
Try reinstalling: npm install @evolvingmachines/sdk`):
|
|
42
|
-
Try installing: npm install @evolvingmachines/daytona`):
|
|
43
|
-
Try installing: npm install @evolvingmachines/modal`):
|
|
44
|
-
Try reinstalling: npm install @evolvingmachines/sdk`):
|
|
45
|
-
1. Set ${
|
|
46
|
-
2. Set ${
|
|
47
|
-
3. Set ${
|
|
48
|
-
4. Set ${
|
|
49
|
-
5. Pass sandbox explicitly: .withSandbox(provider)`)}function
|
|
39
|
+
\`\`\``:f}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:d?"failed":"completed",content:g}}function c(p,o){let d=Ti[p]||"other",u=[],g=[],m=p;switch(p){case "Read":case "read_file":m=`Read ${o.file_path||o.absolute_path||"file"}`,(o.file_path||o.absolute_path)&&g.push({path:o.file_path||o.absolute_path});break;case "Write":case "write_file":m=`Write ${o.file_path||"file"}`,o.file_path&&(g.push({path:o.file_path}),u.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":m=`Edit ${o.file_path||"file"}`,o.file_path&&g.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":m=o.command?`\`${o.command}\``:"Run command",o.description&&u.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":m=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":m=o.query?`"${o.query}"`:"Web search";break;case "Glob":m=`Find ${o.pattern||"files"}`,o.path&&g.push({path:o.path});break;case "Grep":m=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":m=`List ${o.path||"directory"}`,o.path&&g.push({path:o.path});break;case "Task":m=o.description||"Subagent task";break;case "TodoWrite":m="Update todos";break;case "ExitPlanMode":m="Exit plan mode";break;default:m=p;}return {title:m,kind:d,content:u,locations:g}}}function Vt(t){return Re()(t)}function W(t){switch(t){case "claude":return _e();case "codex":return Ee();case "gemini":return Pe();case "qwen":return Re();case "kimi":return rt();case "opencode":return at();case "droid":return Te();default:return ()=>null}}function Pi(t,e){let n=e.trim();return n?W(t)(n):null}function Ri(t,e){let n=[],i=e.split(`
|
|
40
|
+
`),r=W(t);for(let s of i){let a=s.trim();if(!a)continue;let l=r(a);l&&n.push(...l);}return n}function M(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function H(t){return JSON.stringify(Ii__default.default(t,{target:"jsonSchema7"}),null,2)}function Y(t){return JSON.stringify(t,null,2)}function Gt(t,e=false){let n={};function i(r,s){for(let a of A__namespace.readdirSync(r)){let l=re__namespace.join(r,a),c=s?`${s}/${a}`:a;A__namespace.statSync(l).isDirectory()?e&&i(l,c):n[c]=A__namespace.readFileSync(l);}}return i(t,""),n}function zt(t,e){for(let[n,i]of Object.entries(e)){let r=re__namespace.join(t,n),s=re__namespace.dirname(r);A__namespace.mkdirSync(s,{recursive:true});let a;i instanceof ArrayBuffer||i instanceof Uint8Array?a=Buffer.from(i):a=i,A__namespace.writeFileSync(r,a);}}function Oi(t){let e=t.replace(/^~/,process.env.HOME||"");if(!A__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return A__namespace.readFileSync(e,"utf-8")}function Oe(t){let e=t?.type??It,n=$(e);if(t?.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:t.oauthToken,isDirectMode:true,isOAuth:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.providerApiKey){let a=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,l=t.providerBaseUrl??a??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:l,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort};let i=process.env[O];if(i)return {type:e,apiKey:i,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort};if(n.providerEnvMap){let l=(t?.model??n.defaultModel)?.split("/")[0],c=l?n.providerEnvMap[l]:void 0,p=c?process.env[c.keyEnv]:void 0;if(p){let d=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:p,baseUrl:d,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let r=process.env[n.apiKeyEnv];if(r){let l=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:r,baseUrl:l,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}if(n.oauthEnv){let a=process.env[n.oauthEnv];if(a){if(n.oauthFileName){let l=Oi(a);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:l,model:t?.model,reasoningEffort:t?.reasoningEffort}}return {type:e,apiKey:a,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort}}}let s=n.oauthEnv?n.oauthFileName?`, or ${n.oauthEnv}`:`, oauthToken, or ${n.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${s}, or ${O} / ${n.apiKeyEnv} env var.`)}async function ct(){let t=process.env[xe];if(t)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return s({apiKey:t})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${xe} is set but @evolvingmachines/e2b failed to load.
|
|
41
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):a}let e=process.env[ke];if(e)try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return s({apiKey:e})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${ke} is set but @evolvingmachines/daytona failed to load.
|
|
42
|
+
Try installing: npm install @evolvingmachines/daytona`):a}let n=process.env[Ce],i=process.env[He];if(n&&i)try{let{createModalProvider:s}=await import('@evolvingmachines/modal');return s({tokenId:n,tokenSecret:i})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ce} is set but @evolvingmachines/modal failed to load.
|
|
43
|
+
Try installing: npm install @evolvingmachines/modal`):a}let r=process.env[O];if(r)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=Pt(),s({apiKey:r})}catch(s){let a=s;throw a.message?.includes("Cannot find module")||a.message?.includes("MODULE_NOT_FOUND")?new Error(`${O} is set but @evolvingmachines/e2b failed to load.
|
|
44
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):a}throw new Error(`No sandbox provider configured. Either:
|
|
45
|
+
1. Set ${O} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
46
|
+
2. Set ${xe} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
47
|
+
3. Set ${ke} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
48
|
+
4. Set ${Ce} and ${He} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
49
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function Mi(t){return new Promise(e=>setTimeout(e,t))}async function R(t,e,n=0){let i=Ai(e),r=e?.onItemRetry,s=null,a=0,l=i.backoffMs;for(;a<i.maxAttempts;){if(a++,s=await t(a),!i.retryOn(s))return s;if(a>=i.maxAttempts)break;if(r){let c=s.error??"Unknown error";r(n,a,c);}await Mi(l),l*=i.backoffMultiplier;}return s}function Ai(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var Wt=`## FILESYSTEM INSTRUCTIONS:
|
|
50
50
|
|
|
51
51
|
You are running in a sandbox environment.
|
|
52
52
|
|
|
@@ -79,7 +79,7 @@ Examples:
|
|
|
79
79
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
80
80
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
81
81
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
82
|
-
`;var
|
|
82
|
+
`;var Jt=`## FILESYSTEM INSTRUCTIONS:
|
|
83
83
|
|
|
84
84
|
You are running in a sandbox environment.
|
|
85
85
|
|
|
@@ -113,9 +113,9 @@ Examples:
|
|
|
113
113
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
114
114
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
115
115
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
116
|
-
`;var
|
|
116
|
+
`;var qt=`## SYSTEM PROMPT
|
|
117
117
|
|
|
118
|
-
{{systemPrompt}}`;var
|
|
118
|
+
{{systemPrompt}}`;var Ht=`## STRUCTURED OUTPUT
|
|
119
119
|
|
|
120
120
|
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
121
121
|
|
|
@@ -133,7 +133,7 @@ You are free to:
|
|
|
133
133
|
But your final \`output/result.json\` MUST conform to the schema above.
|
|
134
134
|
|
|
135
135
|
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
136
|
-
### Never just state results as text.`;var
|
|
136
|
+
### Never just state results as text.`;var Yt=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
137
137
|
|
|
138
138
|
You are a judge. {{candidateCount}} AI workers attempted the same task independently. Your job is to analyze their solution attempts and pick the best one based on the evaluation criteria below.
|
|
139
139
|
|
|
@@ -163,7 +163,7 @@ You must judge their work based on:
|
|
|
163
163
|
5. Pick the best candidate (0-indexed)
|
|
164
164
|
|
|
165
165
|
**IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
|
|
166
|
-
`;var
|
|
166
|
+
`;var Zt=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
167
167
|
|
|
168
168
|
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.
|
|
169
169
|
|
|
@@ -196,14 +196,14 @@ The output must satisfy:
|
|
|
196
196
|
**IMPORTANT:** Be thorough and fair. Cite specific evidence. If the output generally achieves the goal with minor issues, consider passing. Only fail if there are significant problems that violate the criteria.
|
|
197
197
|
|
|
198
198
|
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
199
|
-
`;var
|
|
199
|
+
`;var Qt=`### CONTEXT STRUCTURE
|
|
200
200
|
|
|
201
201
|
\`\`\`
|
|
202
202
|
{{fileTree}}
|
|
203
203
|
\`\`\`
|
|
204
204
|
|
|
205
205
|
Examine all files within each item folder before producing your output.
|
|
206
|
-
`;var
|
|
206
|
+
`;var Xt="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var en="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var tn=`{{originalPrompt}}
|
|
207
207
|
|
|
208
208
|
## IMPORTANT: Previous Attempt Failed Verification
|
|
209
209
|
|
|
@@ -212,28 +212,29 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
212
212
|
{{feedback}}
|
|
213
213
|
|
|
214
214
|
Make sure your output addresses all the feedback points above.
|
|
215
|
-
`;var
|
|
215
|
+
`;var nn=Wt,sn=Jt,on=qt,rn=Ht,lt=Yt,an=Xt,pt=Zt,cn=en,ln=Qt,dt=tn;function F(t,e){let n=t;for(let[i,r]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${i}\\}\\}`,"g"),r);return n}function ut(t){let e=t.mode==="swe"?sn:nn,n=F(e,{workingDir:t.workingDir}).trim();if(t.systemPrompt&&(n+=`
|
|
216
216
|
|
|
217
217
|
|
|
218
|
-
${
|
|
218
|
+
${F(on,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let i=M(t.schema)?H(t.schema):Y(t.schema);n+=`
|
|
219
219
|
|
|
220
220
|
|
|
221
|
-
${
|
|
222
|
-
(empty)`;let
|
|
223
|
-
`)}var
|
|
221
|
+
${F(rn,{schema:i}).trim()}`;}return n}function Me(t){let e=[...new Set(Object.keys(t).map(c=>c.split("/")[0]))].sort((c,p)=>c==="worker_task"?-1:p==="worker_task"?1:c.localeCompare(p));if(!e.length)return `context/
|
|
222
|
+
(empty)`;let n="worker_task/system_prompt.txt"in t,i="worker_task/schema.json"in t,r=Object.keys(t).some(c=>c.startsWith("worker_task/input/")),s=[];e.forEach((c,p)=>{let o=p===e.length-1,d=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=o?" ":"\u2502 ";if(c==="worker_task"){s.push({line:`${d}${c}/`,comment:"task given to worker"});let g=[];n&&g.push({name:"system_prompt.txt",comment:"worker system prompt"}),g.push({name:"user_prompt.txt",comment:"worker task prompt"}),i&&g.push({name:"schema.json",comment:"expected output schema"}),r&&g.push({name:"input/",comment:"worker input files"}),g.forEach((m,f)=>{let y=f===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";s.push({line:`${u}${y}${m.name}`,comment:m.comment});});}else if(c.startsWith("candidate_")){let g=c.replace("candidate_","");s.push({line:`${d}${c}/`,comment:`worker ${g} solution`});}else if(c==="worker_output")s.push({line:`${d}${c}/`,comment:"output to verify"});else if(c.startsWith("item_")){let g=c.replace("item_","");s.push({line:`${d}${c}/`,comment:`input ${g}`});}else s.push({line:`${d}${c}/`,comment:""});});let a=Math.max(...s.map(c=>c.line.length)),l=["context/"];for(let c of s)if(c.comment){let p=" ".repeat(a-c.line.length+3);l.push(`${c.line}${p}# ${c.comment}`);}else l.push(c.line);return l.join(`
|
|
223
|
+
`)}var pn=re.join(os.homedir(),At),ae=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;localQueue=Promise.resolve();dirReady=promises.mkdir(pn,{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=P,this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),i=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=re.join(pn,i),this.parser=W(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let i of n)this.bufferForDashboard(i);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let i of n)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 n=e.endsWith(`
|
|
224
224
|
`)?e:e+`
|
|
225
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(
|
|
226
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(
|
|
227
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(
|
|
228
|
-
`).pop()?.trim();if(!
|
|
229
|
-
`).pop()?.trim();if(
|
|
230
|
-
`)){if(!s||s.startsWith("total "))continue;let
|
|
231
|
-
`)}var ne=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;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||vt,this.sandboxState=t.sandboxId?"ready":"stopped",this.skills=t.skills,this.storage=t.storage,t.schema)if(O(t.schema))this.zodSchema=t.schema,t.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=t.schema,this.schemaOptions=t.schemaOptions;try{let o=this.createAjvValidator();this.compiledValidator=o.compile(this.jsonSchema);}catch(o){throw new Error(`Invalid JSON Schema: ${o.message}`)}}this.registry=M(e.type),this.sessionTag=Tn(t.sessionTagPrefix||"evolve");}emitLifecycle(e,t){e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:t});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,t,o,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(o,c),s}finalizeOperation(e,t,o,c="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=c,this.emitLifecycle(t,o),true)}watchBackgroundOperation(e,t,o,c){let s=t==="run"?"run_background_complete":"command_background_complete",r=t==="run"?"run_background_failed":"command_background_failed",l=t==="run"?"run_interrupted":"command_interrupted";o.wait().then(a=>{if(this.interruptedOperations.delete(e)||a.exitCode===130){this.finalizeOperation(e,c,l,"interrupted");return}let i=a.exitCode===0?s:r,u=a.exitCode===0?"idle":"error";this.finalizeOperation(e,c,i,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,c,r,"error");});}createAjvValidator(){let t={...Ie[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 Wi__default.default({...t,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let t=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, context, files, and systemPrompt"),this.sandbox=await t.connect(this.options.sandboxId),this.hasRun=!0,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {let o=this.buildEnvironmentVariables();this.sandbox=await t.create({envs:o,workingDirectory:this.workingDir}),await this.setupAgentAuth(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(o){throw this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),o}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else 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],o=t?this.registry.providerEnvMap?.[t]:void 0,c=o?o.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?Fe():N();this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[P]:this.sessionTag}):e[this.registry.baseUrlEnv]=t,e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.options.secrets&&Object.assign(e,this.options.secrets),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let t=this.registry.customHeadersEnv,o=this.registry.customHeadersFormat||"newline";e[t]=Rn(e[t],{[P]:this.sessionTag},o);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildGatewayConfigJson(e){let t=this.registry.usePassthroughGateway?Fe():N(),o=this.agentConfig.model||this.registry.defaultModel,c={},s=this.options.secrets?.[this.registry.gatewayConfigEnv];if(s)try{c=JSON.parse(s);}catch{}let r=c.provider??{},l=r.litellm??{},a=l.options??{},p=l.models??{},i=p[o]??{},u=i.headers??{};return c.provider={...r,litellm:{...l,npm:"@ai-sdk/openai-compatible",options:{...a,baseURL:`${t}/v1`,apiKey:this.agentConfig.apiKey},models:{...p,[o]:{...i,name:o,headers:{...u,...e}}}}},JSON.stringify(c)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let t=this.registry.customHeadersEnv;if(t){let c=this.options.secrets?.[t],s=this.registry.customHeadersFormat||"newline";return {[t]:Rn(c,{[P]:this.sessionTag,[L]:`${V}${e}`},s)}}let o=this.registry.spendTrackingEnvs;if(o)return {[o.sessionTagEnv]:this.sessionTag,[o.runTagEnv]:`${V}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[P]:this.sessionTag,[L]:`${V}${e}`})}}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let t=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(t),await e.files.write(`${t}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e,t){let o=this.options.workspaceMode||"knowledge",c=o==="swe"?`${this.workingDir}/repo ${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`:`${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`;if(await e.commands.run(`mkdir -p ${c}`,{timeoutMs:3e4}),!t?.skipSystemPrompt){let r=Xe({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:o}),l=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(l,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 tt(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 Ve(this.agentConfig.type,e,this.workingDir,s),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await Be(e,this.agentConfig.baseUrl||N(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ue(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[P]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:t}=this.registry,{sourceDir:o,targetDir:c}=t;await e.files.makeDir(c);for(let s of this.skills){let r=`cp -r ${o}/${s} ${c}/ 2>/dev/null || true`;await e.commands.run(r,{timeoutMs:3e4});}}async uploadContextFiles(e,t){let o=Object.entries(t).map(([s,r])=>({path:`${this.workingDir}/context/${s}`,data:r}));if(o.length===0)return;let c=new Set(o.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(o);}async uploadWorkspaceFiles(e,t){let o=Object.entries(t).map(([s,r])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:r}));if(o.length===0)return;let c=new Set(o.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(o);}buildCommand(e){return this.registry.buildCommand({prompt:Gi(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:o,timeoutMs:c=Z,background:s=false,checkpointComment:r}=e,{from:l}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(l&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(l==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await lt(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');l=v.id;}if(l){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(t,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir});let C=await wn(this.sandbox,this.storage,l);if(C.agentType&&C.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${C.agentType}, current: ${this.agentConfig.type})`);let S=this.options.workspaceMode||"knowledge";if(C.workspaceMode&&C.workspaceMode!==S)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${C.workspaceMode}, current: ${S})`);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=l,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(t,"sandbox_ready");}catch(C){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(t,"sandbox_error"),C}}let a=await this.getSandbox(t);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new X({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:a.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(o);let p=this.buildCommand(o),i=crypto.randomUUID(),u=this.buildRunEnvs(i);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ue(a,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[P]:this.sessionTag,[L]:`${V}${i}`}),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await je(a,this.registry.spendTrackingTomlProvider,{[P]:this.sessionTag,[L]:`${V}${i}`});let d="",m=K(this.agentConfig.type),g=v=>{d+=v;let C=d.split(`
|
|
232
|
-
`);d=C.pop()??"";for(let S of C){if(!S.trim())continue;let b=m(S);if(this.sessionLogger?.writeEventParsed(S,b),t?.onStdout?.(S+`
|
|
233
|
-
`)
|
|
234
|
-
`),
|
|
235
|
-
`).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,a=[],p=`${o}/`;for(let g of r){let[f,h]=g.split("|");if(!f||!h)continue;let y=parseInt(h,10);l>0&&y<l||a.push(f);}let i={},u=await Promise.all(a.map(async g=>{try{let f=await t.files.read(g);return {relativePath:g.startsWith(p)?g.slice(p.length):g.split("/").pop()||g,content:f}}catch{return null}}));for(let g of u)g&&(i[g.relativePath]=g.content);if(!this.zodSchema&&!this.jsonSchema)return {files:i,data:null};let d=i["result.json"];if(!d)return {files:i,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 g=JSON.parse(m);if(this.zodSchema){let f=this.zodSchema.safeParse(g);return f.success?{files:i,data:f.data}:{files:i,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:m}}if(this.compiledValidator){if(this.compiledValidator(g))return {files:i,data:g};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:i,data:null,error:`Schema validation failed: ${h}`,rawData:m}}}return {files:i,data:null}}catch(g){return {files:i,data:null,error:`Failed to parse result.json: ${g.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 ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,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.");await this.rotateSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let t=this.activeOperationId,o=this.activeOperationKind,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=o==="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){await this.rotateSession(),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.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=Tn(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let t=this.agentConfig.apiKey;if(!t)throw new Error("Cost tracking requires an API key.");let o=process.env.EVOLVE_DASHBOARD_URL||E,c=await fetch(`${o}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Spend query failed (${c.status}): ${s}`)}return c}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,t){return {...e,asOf:e.asOf??t.asOf,isComplete:e.isComplete??t.isComplete,truncated:e.truncated??t.truncated}}normalizeSessionCost(e){let t={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(o=>this.normalizeRunCost(o,t))}}async getSessionCost(){let e=this.resolveSpendTag(),t=new URLSearchParams({tag:e}),c=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(c)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let r=new URLSearchParams({tag:t,runId:e.runId}),a=await(await this.fetchSpend(r)).json();return this.normalizeRunCost(a,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let o=await this.getSessionCost(),c=e.index>0?e.index-1:o.runs.length+e.index,s=o.runs[c];if(!s)throw new Error(`Run index ${e.index} out of range. Session has ${o.runs.length} run(s).`);return s}};var ie=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),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&&(O(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=it;async initializeAgent(){let e=ke(this.config.agent),t=this.config.sandbox??await Ye(),o=e.isDirectMode?{}:ht(e.apiKey),c=this.config.storage!==void 0?Re(this.config.storage,!e.isDirectMode,E,e.isDirectMode?void 0:e.apiKey):void 0,s={sandboxProvider:t,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...o,...this.config.mcpServers},skills:this.config.skills,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:c};this.agent=new ne(e,s);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,o=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:o?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:o,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:o,from:c,checkpointComment:s},r)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let o=this.createStreamCallbacks();return this.agent.executeCommand(e,t,o)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=ke(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:E,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return ut(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return ut(this.config.storage,this.resolveGatewayOverrides()||{})}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}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var H=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 B=Symbol.for("evolve.SwarmResult"),Y=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 dt=class n{config;semaphore;constructor(e={}){let t=e.concurrency??wt;if(t>Ne)throw new Error(`concurrency=${t} exceeds max ${Ne}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:t,timeoutMs:e.timeoutMs??Z,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new H(this.config.concurrency);}async map(e){let{items:t,prompt:o,bestOf:c,verify:s}=e,r=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs;if(c&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let p=await Promise.all(t.map((i,u)=>c?this.executeMapItemWithBestOf(i,o,u,l,e,a,r):s?this.executeMapItemWithVerify(i,o,u,l,e,a,r):r?T(d=>this.executeMapItem(i,o,u,l,e,a,d),r,u):this.executeMapItem(i,o,u,l,e,a)));return Y.from(p)}async filter(e){let{items:t,prompt:o,condition:c,verify:s}=e,r=e.retry??this.config.retry,l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,p=await Promise.all(t.map((u,d)=>s?this.executeFilterItemWithVerify(u,o,d,l,e,a,r):r?T(m=>this.executeFilterItem(u,o,d,l,e,a,m),r,d):this.executeFilterItem(u,o,d,l,e,a))),i=[];for(let u of p)if(u.status==="error")i.push(u);else if(u.data!==null)try{c(u.data)?i.push(u):i.push({...u,status:"filtered"});}catch(d){i.push({...u,status:"error",data:null,error:`Condition function threw: ${d.message}`});}return Y.from(i)}async reduce(e){let{items:t,prompt:o,verify:c}=e,s=e.retry??this.config.retry,r=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,a=[],p=[];t.forEach((x,v)=>{a.push(this.getFiles(x)),p.push(this.getIndex(x,v));});let i={};a.forEach((x,v)=>{Object.entries(x).forEach(([C,S])=>{i[`item_${p[v]}/${C}`]=S;});});let u=Se(i),d=A(zt,{fileTree:u}),m=e.systemPrompt?`${d}
|
|
236
|
-
|
|
237
|
-
${e.systemPrompt}`:d,g=(x,v,C)=>({operationId:r,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:t.length,inputIndices:p,errorRetry:v,verifyRetry:C,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(x,v,C,S)=>{let b=await this.semaphore.use(()=>this.execute(i,x,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:e.name,operationId:r,operation:"reduce",role:"worker",errorRetry:C,verifyRetry:S&&S>1?S-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),$=g(b,C,S&&S>1?S-1:void 0);return b.error?{status:"error",data:null,files:b.files,meta:$,error:b.error,rawData:b.rawData}:{status:"success",data:b.data,files:b.files,meta:$}},k=`${this.config.tag}-reduce`;return c?this.runWithVerification((x,v,C)=>w(x,v,void 0,C),{originalPrompt:o,inputFiles:i,verifyConfig:c,timeoutMs:l,systemPrompt:m,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:r,baseTag:k,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?T(x=>{let v=x>1?x-1:void 0,C=v?`${k}-er${v}`:k;return w(o,C,v)},s):w(o,k)}async bestOf(e){let{item:t,prompt:o,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 l=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,p=this.getFiles(t),i=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,g=c.composio??this.config.composio,f=c.judgeComposio??c.composio??this.config.composio,h=await Promise.all(Array.from({length:r},async(v,C)=>{let S=s?await T(b=>this.executeBestOfCandidate({inputFiles:p,prompt:o,candidateIndex:C,operationId:l,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:d,composio:g,timeoutMs:a,attempt:b}),s,C):await this.executeBestOfCandidate({inputFiles:p,prompt:o,candidateIndex:C,operationId:l,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:d,composio:g,timeoutMs:a});return c.onCandidateComplete?.(0,C,S.status==="success"?"success":"error"),S})),y=s?await T(v=>this.executeBestOfJudge({inputFiles:p,taskPrompt:o,candidates:h,config:c,timeoutMs:a,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:f,attempt:v}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:p,taskPrompt:o,candidates:h,config:c,timeoutMs:a,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:f}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);c.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:r};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:h}}async execute(e,t,o){let c=null,s="",r=o.tagPrefix,l={},a=null,p,i,u={...this.config.agent,...o.agent};try{c=new ie().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(o.tagPrefix),o.schema&&c.withSchema(o.schema,o.schemaOptions),o.systemPrompt&&c.withSystemPrompt(o.systemPrompt),o.mcpServers&&c.withMcpServers(o.mcpServers),o.skills?.length&&c.withSkills(o.skills),o.composio&&c.withComposio(o.composio.userId,o.composio.config),o.observability&&c.withObservability(o.observability),Object.keys(e).length>0&&c.withContext(e);let d=await c.run({prompt:t,timeoutMs:o.timeoutMs});s=d.sandboxId,r=c.getSessionTag()??o.tagPrefix;let m=null;try{m=await c.getOutputFiles(!0),l=m.files;}catch{}d.exitCode!==0?p=`Agent exited with code ${d.exitCode}`:o.schema?m?(a=m.data,m.error&&(p=m.error),m.rawData&&(i=m.rawData)):p="Failed to read output files from sandbox":a=l;}catch(d){if(p=d.message,c){r=c.getSessionTag()??o.tagPrefix;try{l=(await c.getOutputFiles(!0)).files;}catch{}}}finally{c&&await c.kill().catch(()=>{});}return {files:l,data:a,tag:r,sandboxId:s,error:p,rawData:i}}async executeMapItem(e,t,o,c,s,r,l=1){let a=this.getFiles(e),p=l>1?`${this.config.tag}-map-${o}-er${l-1}`:`${this.config.tag}-map-${o}`,i=this.evaluatePrompt(t,a,o);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:o});let u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(a,i,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:p,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:o,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:c,operation:"map",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:o,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(g,f)}async executeMapItemWithVerify(e,t,o,c,s,r,l){let a=this.getFiles(e),p=`${this.config.tag}-map-${o}`,i=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,g=this.evaluatePrompt(t,a,o);if(g instanceof Error)return this.buildErrorResult(`Prompt function threw: ${g.message}`,{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:o});let f=async(h,y,w)=>{let k=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:y,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:o,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),x={operationId:c,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:o,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(k,x)};return this.runWithVerification(f,{originalPrompt:g,inputFiles:a,verifyConfig:i,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:p,retry:l,itemIndex:o,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,t,o,c,s,r,l){let a=this.getFiles(e),p=`${this.config.tag}-map-${o}`,i=this.evaluatePrompt(t,a,o);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:c,operation:"map",tag:p,sandboxId:"",itemIndex:o});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:p,sandboxId:"",itemIndex:o});let m=s.mcpServers??this.config.mcpServers,g=u.mcpServers??m,f=u.judgeMcpServers??u.mcpServers??m,h=s.skills??this.config.skills,y=u.skills??h,w=u.judgeSkills??u.skills??h,k=s.composio??this.config.composio,x=u.composio??k,v=u.judgeComposio??u.composio??k,C=await Promise.all(Array.from({length:d},async(oe,se)=>{let gt=l?await T(On=>this.executeBestOfCandidate({inputFiles:a,prompt:i,candidateIndex:se,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:y,composio:x,timeoutMs:r,parentIndex:o,attempt:On,_pipelineContext:s._pipelineContext}),l,se):await this.executeBestOfCandidate({inputFiles:a,prompt:i,candidateIndex:se,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:y,composio:x,timeoutMs:r,parentIndex:o,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(o,se,gt.status==="success"?"success":"error"),gt})),S=l?await T(oe=>this.executeBestOfJudge({inputFiles:a,taskPrompt:i,candidates:C,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:o,attempt:oe,_pipelineContext:s._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:a,taskPrompt:i,candidates:C,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:o,_pipelineContext:s._pipelineContext}),b=C.findIndex(oe=>oe.status==="success"),$=S.decision?.winner??(b>=0?b:0),mt=C[$]??C[0];u.onJudgeComplete?.(o,$,S.decision?.reasoning??"Judge failed to provide reasoning");let Pn={operationId:c,operation:"bestof-judge",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...mt,meta:{...mt.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:o,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:$,judgeReasoning:S.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Pn,candidates:C}}}async executeFilterItem(e,t,o,c,s,r,l=1){let a=this.getFiles(e),p=l>1?`${this.config.tag}-filter-${o}-er${l-1}`:`${this.config.tag}-filter-${o}`,i=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:i,skills:u,composio:d,tagPrefix:p,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:o,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),g={operationId:c,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:o,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(m,g,a)}async executeFilterItemWithVerify(e,t,o,c,s,r,l){let a=this.getFiles(e),p=`${this.config.tag}-filter-${o}`,i=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,g=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(a,f,{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:o,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),k={operationId:c,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:o,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(w,k,a)};return this.runWithVerification(g,{originalPrompt:t,inputFiles:a,verifyConfig:i,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:p,retry:l,itemIndex:o,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:t,prompt:o,candidateIndex:c,operationId:s,config:r,timeoutMs:l,parentIndex:a,attempt:p=1,_pipelineContext:i}=e,u=a!==void 0?`${this.config.tag}-map-${a}-bestof-cand-${c}`:`${this.config.tag}-bestof-cand-${c}`,d=p>1?`${u}-er${p-1}`:u,m=await this.semaphore.use(()=>this.execute(t,o,{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:l,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"candidate",candidateIndex:c,errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(i)}})),g={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:c,errorRetry:p>1?p-1:void 0,candidateIndex:c,...this.pipelineContextToMeta(i)};return this.buildResult(m,g)}buildJudgeContext(e){let t=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((o,c)=>{o.status==="error"&&(t[`candidate_${c}/_failed.txt`]=`STATUS: FAILED
|
|
238
|
-
|
|
239
|
-
Error: ${o.error??"Unknown error"}`),Object.entries(o.files).forEach(([s,r])=>{t[`candidate_${c}/${s}`]=r;});}),t}async executeBestOfJudge(e){let{candidates:t,config:o,timeoutMs:c,operationId:s,parentIndex:r,attempt:l=1,_pipelineContext:a}=e,p=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=l>1?`${p}-er${l-1}`:p,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:t,systemPrompt:e.systemPrompt,schema:e.schema}),d=Se(u),m=A(qe,{candidateCount:String(t.length),criteria:o.judgeCriteria,fileTree:d}),g=zod.z.object({winner:zod.z.number().min(0).max(t.length-1),reasoning:zod.z.string()}),f=await this.semaphore.use(()=>this.execute(u,Vt,{systemPrompt:m,schema:g,agent:o.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:i,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(f.data&&!f.error)h=f.data;else if(f.rawData)try{let y=JSON.parse(f.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${f.error}`);}return {status:h?"success":"error",decision:h,tag:f.tag,sandboxId:f.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let t=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([o,c])=>{t[`worker_output/${o}`]=c;}),t}async executeVerify(e){let{config:t,timeoutMs:o,operationId:c,workerTag:s,retryAttempt:r=1,operation:l,itemIndex:a,attemptIndex:p,_pipelineContext:i}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=t.verifierMcpServers??e.mcpServers,m=t.verifierSkills??e.skills,g=t.verifierComposio??e.composio,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=Se(f),y=A(Ze,{criteria:t.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(f,Wt,{systemPrompt:y,schema:n.VerifyDecisionSchema,agent:t.verifierAgent,mcpServers:d,skills:m,composio:g,tagPrefix:u,timeoutMs:o,observability:{swarmName:this.config.tag,operationId:c,operation:l,itemIndex:a,role:"verifier",verifyRetry:p&&p>1?p-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let x=JSON.parse(w.rawData);k={passed:!!x.passed,reasoning:x.reasoning??"Verification completed",feedback:x.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:k?"success":"error",decision:k,tag:w.tag,sandboxId:w.sandboxId,error:k?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,t){return A(Qe,{originalPrompt:e,feedback:t})}async runWithVerification(e,t){let{originalPrompt:o,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:l,baseTag:a,retry:p,itemIndex:i=0,operation:u,_pipelineContext:d}=t,m=s.maxAttempts??n.DEFAULT_VERIFY_MAX_ATTEMPTS,g=o,f=null,h=0;for(;h<m;){h++;let w=h>1?`${a}-vr${h-1}`:a,k=p?await T(C=>e(g,C>1?`${w}-er${C-1}`:w,h),p,i):await e(g,w,h);if(s.onWorkerComplete?.(i,h,k.status==="error"?"error":"success"),k.status==="error")return k;f=k;let x=p?await T(C=>this.executeVerify({inputFiles:c,outputFiles:k.files,taskPrompt:g,config:s,timeoutMs:r,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:l,workerTag:w,retryAttempt:C,operation:u,itemIndex:i,attemptIndex:h,_pipelineContext:d}),{...p,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:k.files,taskPrompt:g,config:s,timeoutMs:r,systemPrompt:t.systemPrompt,schema:t.schema,mcpServers:t.mcpServers,skills:t.skills,composio:t.composio,operationId:l,workerTag:w,operation:u,itemIndex:i,attemptIndex:h,_pipelineContext:d}),v={operationId:l,operation:"verify",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(i,h,x.decision?.passed??false,x.decision?.feedback),x.decision?.passed)return {...k,verify:{passed:true,reasoning:x.decision.reasoning,verifyMeta:v,attempts:h}};if(h<m){let C=x.decision?.feedback??x.decision?.reasoning??"Output did not meet criteria";g=n.buildRetryPromptWithFeedback(o,C);}}let y=h>1?`${a}-vr${h-1}`:a;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:l,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,t,o){if(typeof e=="string")return e;try{return e(t,o)}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"]=O(e.schema)?W(e.schema):z(e.schema)),Object.entries(e.inputFiles).forEach(([o,c])=>{t[`worker_task/input/${o}`]=c;}),t}isSwarmResult(e){return typeof e=="object"&&e!==null&&B in e&&e[B]===true}getFiles(e){if(this.isSwarmResult(e)){let t={...e.files};return t["result.json"]&&(t["data.json"]=t["result.json"],delete t["result.json"]),t}return e}getIndex(e,t){return this.isSwarmResult(e)?e.meta.itemIndex:t}buildResult(e,t,o){let c=o??e.files;return e.error?{[B]:true,status:"error",data:null,files:c,meta:t,error:e.error,rawData:e.rawData}:{[B]:true,status:"success",data:e.data,files:c,meta:t}}buildErrorResult(e,t){return {[B]:true,status:"error",data:null,files:{},meta:t,error:e}}};var Pe=class n{swarm;steps;events;constructor(e,t=[],o={}){this.swarm=e,this.steps=t,this.events=o;}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 Oe(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,t){if(typeof e=="string"){let o=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new n(this.swarm,this.steps,{...this.events,[o]:t})}return new n(this.swarm,this.steps,{...this.events,...e})}async run(e){let t=crypto.randomBytes(8).toString("hex"),o=[],c=e,s=Date.now();for(let l=0;l<this.steps.length;l++){let a=this.steps[l],p=a.config.name,i=Date.now();this.events.onStepStart?.({type:a.type,index:l,name:p,itemCount:c.length});let u={pipelineRunId:t,pipelineStepIndex:l};try{let d=await this.executeStep(a,c,l,p,u),m=Date.now()-i;if(o.push({type:a.type,index:l,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:l,name:p,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:t,steps:o,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:l,name:p,error:d instanceof Error?d:new Error(String(d))}),d}}let r=o[o.length-1];return {pipelineRunId:t,steps:o,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,t,o,c,s){if(e.type==="map"){let a=e.config,p=await this.swarm.map({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,o,c),verify:this.wrapVerify(a.verify,o,c),bestOf:this.wrapBestOf(a.bestOf,o,c)});return {output:[...p],nextItems:p.success,successCount:p.success.length,errorCount:p.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,p=await this.swarm.filter({items:t,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,o,c),verify:this.wrapVerify(a.verify,o,c)}),i=a.emit??"success",u=i==="success"?p.success:i==="filtered"?p.filtered:[...p.success,...p.filtered];return {output:[...p],nextItems:u,successCount:p.success.length,errorCount:p.error.length,filteredCount:p.filtered.length}}let r=e.config,l=await this.swarm.reduce({items:t,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,o,c),verify:this.wrapVerify(r.verify,o,c)});return {output:l,nextItems:[],successCount:l.status==="success"?1:0,errorCount:l.status==="error"?1:0,filteredCount:0}}wrapRetry(e,t,o){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:t,stepName:o,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,t,o){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:t,stepName:o,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,l)=>{e.onVerifierComplete?.(c,s,r,l),this.events.onVerifierComplete?.({stepIndex:t,stepName:o,itemIndex:c,attempt:s,passed:r,feedback:l});}}}wrapBestOf(e,t,o){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:t,stepName:o,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:t,stepName:o,itemIndex:c,winnerIndex:s,reasoning:r});}}}},Oe=class n extends Pe{constructor(e,t,o){super(e,t,o);}on(e,t){if(typeof e=="string"){let o=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new n(this.swarm,this.steps,{...this.events,[o]: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")}};function no(n){let e=n?.apiKey||process.env[R];if(!e)throw new Error(`sessions() requires an API key. Set ${R} or pass { apiKey } in config.`);let t=n?.dashboardUrl||E;async function o(s,r){let l=await fetch(`${t}${s}`,{...r,headers:{Authorization:`Bearer ${e}`,...r?.headers}});if(!l.ok){let a=await l.text().catch(()=>"");throw new Error(`Dashboard API error (${l.status}): ${a||l.statusText}`)}return l}function c(s){return {id:s.id,tag:s.tag,agent:s.agent,model:s.model||null,provider:s.provider,sandboxId:s.sandboxId||null,state:s.isEnded?"ended":"live",runtimeStatus:s.runtimeStatus||"unknown",cost:typeof s.cost=="number"?s.cost:null,createdAt:s.createdAt,endedAt:s.endedAt||null,stepCount:s.stepCount||0,toolStats:s.toolStats||null}}return {async list(s){let r=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(s?.limit??20,200)),paginated:"true"});if(s?.cursor&&r.set("cursor",s.cursor),s?.state&&s.state!=="all"&&r.set("state",s.state),s?.agent&&r.set("agent",s.agent),s?.tagPrefix&&r.set("tagPrefix",s.tagPrefix),s?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};r.set("sortDirection",p[s.sort]),s.sort==="cost"?r.set("sortField","cost"):r.set("sortField","timestamp");}let a=await(await o(`/api/sessions?${r}`)).json();return {items:(a.items||[]).map(c),nextCursor:a.nextCursor||null,hasMore:!!a.hasMore}},async get(s){let l=await(await o(`/api/sessions/${encodeURIComponent(s)}`)).json();return c(l)},async events(s,r){let l=new URLSearchParams;r?.since!=null&&l.set("since",String(r.since));let a=l.toString();return (await(await o(`/api/sessions/${encodeURIComponent(s)}/events${a?`?${a}`:""}`)).json()).events||[]},async download(s,r){let p=(await(await o(`/api/sessions/${encodeURIComponent(s)}`)).json()).tag||s,i=await fetch(`${t}/api/sessions/${encodeURIComponent(s)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!i.ok){let g=await i.text().catch(()=>"");throw new Error(`Download failed (${i.status}): ${g||i.statusText}`)}let u=r?.to||process.cwd();await promises.mkdir(u,{recursive:true});let d=Q.join(u,`${p}.jsonl`);if(!i.body)throw new Error("Download response has no body");let m=stream.Readable.fromWeb(i.body);return await promises$1.pipeline(m,I.createWriteStream(d)),d}}}Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Me;exports.AGENT_TYPES=In;exports.Agent=ne;exports.Evolve=ie;exports.JUDGE_PROMPT=qe;exports.Pipeline=Pe;exports.RETRY_FEEDBACK_PROMPT=Qe;exports.SCHEMA_PROMPT=jt;exports.SWARM_RESULT_BRAND=B;exports.SYSTEM_PROMPT=Bt;exports.Semaphore=H;exports.Swarm=dt;exports.SwarmResultList=Y;exports.TerminalPipeline=Oe;exports.VALIDATION_PRESETS=Ie;exports.VERIFY_PROMPT=Ze;exports.WORKSPACE_PROMPT=Nt;exports.WORKSPACE_SWE_PROMPT=Kt;exports.applyTemplate=A;exports.buildWorkerSystemPrompt=Xe;exports.createAgentParser=K;exports.createClaudeParser=ye;exports.createCodexParser=we;exports.createGeminiParser=ve;exports.executeWithRetry=T;exports.expandPath=q;exports.getAgentConfig=M;exports.getMcpSettingsDir=U;exports.getMcpSettingsPath=D;exports.isValidAgentType=Mn;exports.isZodSchema=O;exports.jsonSchemaToString=z;exports.parseNdjsonLine=Zn;exports.parseNdjsonOutput=Qn;exports.parseQwenOutput=Et;exports.readLocalDir=Tt;exports.resolveStorageConfig=Re;exports.saveLocalDir=Rt;exports.sessions=no;exports.storage=Vi;exports.writeClaudeMcpConfig=ce;exports.writeCodexMcpConfig=he;exports.writeGeminiMcpConfig=le;exports.writeMcpConfig=Ve;exports.writeQwenMcpConfig=pe;exports.zodSchemaToJson=W;
|
|
225
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let n=JSON.stringify(e)+`
|
|
226
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&(this.eventBuffer.push(e),this.scheduleFlush());}writeMeta(){let e={_meta:{tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandbox_id:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability)}},n=JSON.stringify(e)+`
|
|
227
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=$t){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Dt));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let i=1;i<=Se;i++)try{let r=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(r.ok)return;if(r.status===429||r.status===401||r.status>=500){if(i===Se){console.debug(`[SessionLogger] Dashboard ${r.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Ze*i);continue}console.debug(`[SessionLogger] Dashboard ${r.status}, dropping events`);return}catch(r){i===Se?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",r),this.requeueEvents(e)):await this.delay(Ze*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!P.startsWith("https://")&&!P.includes("localhost")&&!P.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var Ae="COMPOSIO_API_KEY";function un(t){return new core.Composio({apiKey:process.env[Ae]})}function gt(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function $e(t,e,n){gt(t);let i=un(),r={};return e?.toolkits&&(r.toolkits=e.toolkits),e?.tools&&(r.tools=e.tools),e?.authConfigs&&(r.authConfigs=e.authConfigs),e?.connectedAccounts&&(r.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(r.manageConnections=e.manageConnections),await i.create(t,Object.keys(r).length>0?r:void 0)}async function gn(t,e,n,i){gt(t);let r=un(),l=(await r.toolkits.get(e)).authConfigDetails?.find(c=>c.mode==="API_KEY");if(!l)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await r.connectedAccounts.initiate(t,l.name,{config:core.AuthScheme.APIKey({api_key:n})});}async function mt(t,e){if(gt(t),e?.keys)for(let[i,r]of Object.entries(e.keys))try{await gn(t,i,r);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let n=await $e(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function mn(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function Zi(){return new core.Composio({apiKey:process.env[Ae]})}async function fn(t,e){mn(t);let i=await(await $e(t,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function hn(t,e){let n=await ft(t),i={};for(let r of n)i[r.toolkit]=r.connected;return e?i[e]??false:i}async function ft(t){return mn(t),(await Zi().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var ht={auth:fn,status:hn,connections:ft};util.promisify(child_process.exec);var xt=util.promisify(child_process.execFile),vn=Symbol.for("evolve:awsSdkCache"),xn=Symbol.for("evolve:s3ClientCache");var cs=3600,ls=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function ps(t){if(t.startsWith("s3://")){let r=t.slice(5),s=r.indexOf("/");return s===-1?{bucket:r,prefix:""}:{bucket:r.slice(0,s),prefix:r.slice(s+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,i=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.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 ${t}`);return {bucket:i[0],prefix:i.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function Fe(t,e,n,i){if(!t?.url&&!t?.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:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:i}}let r=t?.bucket||"",s=t?.prefix||"",a=t?.endpoint;if(t?.url){let l=ps(t.url);r=r||l.bucket,s=s||l.prefix,a=a||l.endpoint;}if(!r)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:r,prefix:s,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:a,credentials:t?.credentials,mode:"byok"}}function kn(t){if(t.includes(".."))throw new Error(`settingsDir must not contain '..': ${t}`);let e;if(t.startsWith("~/"))e=t.slice(2);else if(t.startsWith("/home/user/"))e=t.slice(11);else if(t.startsWith("."))e=t;else throw new Error(`Unexpected settingsDir: ${t}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${t}`);return e}function ds(t){if(t.includes(".."))throw new Error(`workingDir must not contain '..': ${t}`);if(!t.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${t}. Must start with /home/user/.`);let e=t.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${t}`);return e}function De(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function us(t,e){let n=$(t),i=ds(e),r=n.checkpointDirs?.length?n.checkpointDirs.map(l=>kn(l)):[kn(n.mcpConfig.settingsDir)],s=[...ls.map(l=>`--exclude=${De(l)}`),`--exclude=${De(i+"/temp")}`].join(" "),a=[De(i+"/"),...r.map(l=>De(l+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${s} ${a}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Q(){let t=globalThis[vn];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[i,r]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[vn]={s3:i,presigner:r},{s3:i,presigner:r}}catch{throw new Error("Storage requires @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner. Install: npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner")}}async function le(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,i=globalThis[xn];if(i?.key===n)return i.client;let{s3:r}=await Q(),s=new r.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[xn]={client:s,key:n},s}async function In(t,e,n){let{s3:i,presigner:r}=await Q(),s=await le(t),a=n==="put"?new i.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new i.GetObjectCommand({Bucket:t.bucket,Key:e});return r.getSignedUrl(s,a,{expiresIn:cs})}async function Cn(t,e){let{s3:n}=await Q(),i=await le(t);try{return await i.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(r){let s=r?.name||r?.message||"";if(r?.$metadata?.httpStatusCode===404||s==="NotFound"||s==="NoSuchKey")return false;throw r}}async function On(t,e){let{s3:n}=await Q(),s=await(await(await le(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!s)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(s)}async function gs(t,e,n){let{s3:i}=await Q();await(await le(t)).send(new i.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Mn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function An(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function ms(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function $n(t,e,n,i){let r=await fetch(`${t.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:n,action:i})});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Gateway presign failed (${r.status}): ${s}`)}return r.json()}async function fs(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify(e)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${i}`)}return n.json()}async function hs(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let i=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${i}`)}return n.json()}async function kt(t,e,n,i,r){let s=new Date().toISOString(),a=us(n,i),l=await t.commands.run(a,{timeoutMs:12e4});if(l.exitCode!==0)throw new Error(`Checkpoint tar failed: ${l.stderr}`);let c=l.stdout.trim().split(`
|
|
228
|
+
`).pop()?.trim();if(!c||c.length!==64)throw new Error(`Invalid checkpoint hash: ${c}`);let p=await t.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(p.stdout.trim(),10),d=Number.isNaN(o)?void 0:o,u;try{if(e.mode==="byok"){let g=Mn(e,c);if(!await Cn(e,g)){let h=await In(e,g,"put"),y=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(y.exitCode!==0)throw new Error(`Checkpoint upload failed: ${y.stderr}`);if(!await Cn(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}u=ms();let f={id:u,hash:c,tag:r.tag,timestamp:s,sizeBytes:d,agentType:n,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment,sandboxId:t.sandboxId};await gs(e,An(e,u),f);}else {let g=await $n(e,r.tag,c,"put");if(!g.alreadyExists){let f=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${g.url}"`,{timeoutMs:3e5});if(f.exitCode!==0)throw new Error(`Checkpoint upload failed: ${f.stderr}`)}u=(await fs(e,{tag:r.tag,hash:c,sizeBytes:d??0,agentType:n,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:u,hash:c,tag:r.tag,timestamp:s,sizeBytes:d,agentType:n,model:r.model,workspaceMode:r.workspaceMode,parentId:r.parentId,comment:r.comment}}async function Dn(t,e,n){let i=await St(e,n),r=i.hash,s={agentType:i.agentType,workspaceMode:i.workspaceMode},a=await Nn(e,i),l=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${a}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(l.exitCode!==0)throw new Error(`Checkpoint download failed: ${l.stderr}`);let c=l.stdout.trim().split(`
|
|
229
|
+
`).pop()?.trim();if(c!==r)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${r}, got ${c})`);let p=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(p.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${p.stderr}`);return s}function Un(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,i=e?.gatewayUrl||P,r=!t.url&&!t.bucket&&!!n;return Fe(t,r,i,n)}async function Fn(t,e){let{s3:n}=await Q(),i=await le(t),s=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,a=[],l;do{let u={Bucket:t.bucket,Prefix:s,...l&&{ContinuationToken:l}},g=await i.send(new n.ListObjectsV2Command(u));if(g.Contents)for(let m of g.Contents)m.Key?.endsWith(".json")&&m.LastModified&&a.push({key:m.Key,lastModified:m.LastModified});l=g.IsTruncated?g.NextContinuationToken:void 0;}while(l);if(a.length===0)return [];a.sort((u,g)=>{let m=g.lastModified.getTime()-u.lastModified.getTime();return m!==0?m:g.key<u.key?-1:g.key>u.key?1:0});let p=!!e?.tag?a:e?.limit?a.slice(0,e.limit):a,d=(await Promise.all(p.map(async u=>{try{return await On(t,u.key)}catch{return null}}))).filter(u=>u!==null);return e?.tag&&(d=d.filter(u=>u.tag===e.tag)),e?.limit&&d.length>e.limit&&(d=d.slice(0,e.limit)),d}async function Ln(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}`:""}`,r=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${r.status}): ${s}`)}return r.json()}function ys(t){return t&&t>0?Math.min(t,500):100}async function Ct(t,e){return t.mode==="byok"?(await Fn(t,{limit:1,tag:e?.tag}))[0]??null:(await Ln(t,{limit:1,tag:e?.tag}))[0]??null}async function St(t,e){if(t.mode==="byok"){let n=An(t,e);try{return await On(t,n)}catch(i){throw ws(i)?new Error(`Checkpoint ${e} not found`):i}}else return await hs(t,e)}async function Sn(t,e,n){if(e==="latest"){let i=await Ct(t,{tag:n});if(!i)throw new Error("No checkpoints found");return i.id}return e}async function Nn(t,e){if(t.mode==="byok")return In(t,Mn(t,e.hash),"get");{let n=await $n(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function Kn(t){return !(!t||re.isAbsolute(t)||t.startsWith("-")||re.normalize(t).startsWith("..")||t.includes("\0"))}function bn(t,e){let n=re.resolve(t,e),i=re.resolve(t),r=re.relative(i,n);if(r.startsWith("..")||re.isAbsolute(r))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function ws(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function yt(t){let e=t.filter(n=>!Kn(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var jn=10*1024*1024,_n=false;async function Bn(){if(!_n)try{await xt("tar",["--version"]),_n=!0;}catch{throw new Error("The 'tar' command is not available on this system. Storage download/extract requires tar (available on macOS, Linux, and Windows with Git Bash or WSL).")}}async function En(t,e){let n=await St(t,e),i=await Nn(t,n),r=e.replace(/[^a-zA-Z0-9_-]/g,"_"),s=re.join(os.tmpdir(),`evolve-dl-${r}-${Date.now()}.tar.gz`),a=await fetch(i);if(!a.ok)throw new Error(`Checkpoint download failed (${a.status})`);if(!a.body)throw new Error("Checkpoint download returned empty body");let l=crypto.createHash("sha256"),c=A.createWriteStream(s);try{let o=a.body.getReader();await new Promise((d,u)=>{c.on("error",u),c.on("finish",d);async function g(){for(;;){let{done:m,value:f}=await o.read();if(m){c.end();break}l.update(f),c.write(f)||await new Promise(h=>c.once("drain",h));}}g().catch(u);});}catch(o){throw c.destroy(),await promises.unlink(s).catch(()=>{}),o}let p=l.digest("hex");if(p!==n.hash)throw await promises.unlink(s).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${p})`);return {tmpPath:s,metadata:n}}async function Tn(t){await Bn();let{stdout:e}=await xt("tar",["-tvzf",t],{maxBuffer:jn}),n=new Set,i=[],r=[];for(let s of e.trim().split(`
|
|
230
|
+
`)){if(!s||s.startsWith("total "))continue;let a=s[0];if(a!=="-"&&a!=="d"&&a!=="l")throw new Error(`Archive contains unsupported entry type: "${a}"`);let l=s.match(/\d{2}:\d{2}\s+(.+)/)??s.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!l)continue;let c=l[1];if(a==="l"){let p=c.indexOf(" -> ");p!==-1&&(c=c.slice(0,p)),n.add(c);}else a==="d"?i.push(c.replace(/\/$/,"")):r.push(c);}return yt(i),yt([...n]),yt(r)}async function wt(t,e,n){await Bn(),await promises.mkdir(e,{recursive:true});let i=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&i.push("--",...n),await xt("tar",i,{maxBuffer:jn});}function vs(t){let e="^",n=0;for(;n<t.length;){let i=t[n];i==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):i==="*"?(e+="[^/]*",n++):i==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(i)?(e+="\\"+i,n++):(e+=i,n++);}return e+="$",new RegExp(e)}function bt(t,e){let n=Un(t,e);return Vn(n)}function xs(t){let e=Un(t||{});return Vn(e)}function Vn(t){return {async listCheckpoints(e){let n=ys(e?.limit);return t.mode==="byok"?Fn(t,{limit:n,tag:e?.tag}):Ln(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return St(t,e)},async downloadCheckpoint(e,n){let i=n?.extract!==false,r=n?.to||process.cwd(),s=await Sn(t,e),{tmpPath:a,metadata:l}=await En(t,s);try{if(i)return await promises.mkdir(r,{recursive:!0}),await Tn(a),await wt(a,r),r;{await promises.mkdir(r,{recursive:!0});let c=re.join(r,`checkpoint-${l.id}.tar.gz`);return await promises.copyFile(a,c),c}}finally{await promises.unlink(a).catch(()=>{});}},async downloadFiles(e,n){let i=await Sn(t,e),{tmpPath:r}=await En(t,i),s;try{let a=await Tn(r),l;if(n?.files){let p=n.files.filter(d=>!Kn(d));if(p.length>0)throw new Error(`Unsafe file path requested: ${p[0]}`);let o=new Set(n.files);l=a.filter(d=>o.has(d));}else if(n?.glob){let p=n.glob.map(vs);l=a.filter(o=>p.some(d=>d.test(o)));}else l=a;if(l.length===0)return {};s=re.join(os.tmpdir(),`evolve-extract-${Date.now()}`);try{await wt(r,s,l);}catch(p){let o=p?.message??"";if(!o.includes("E2BIG")&&!o.includes("Argument list too long")&&!o.includes("ENAMETOOLONG"))throw p;await promises.rm(s,{recursive:!0,force:!0}).catch(()=>{}),s=re.join(os.tmpdir(),`evolve-extract-${Date.now()}`),await wt(r,s);}let c={};return await Promise.all(l.map(async p=>{bn(s,p),c[p]=await promises.readFile(re.join(s,p));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(c).map(async([p,o])=>{bn(n.to,p);let d=re.join(n.to,p);await promises.mkdir(re.dirname(d),{recursive:!0}),await promises.writeFile(d,o);}))),c}finally{s&&await promises.rm(s,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(r).catch(()=>{});}}}}function L(t){return `'${t.replace(/'/g,"'\\''")}'`}function Le(t){return typeof t=="string"&&t.length>0}function X(t,e,n){let i=t[e];if(!Le(i))throw new Error(`withPlugins() for ${n} requires ${e}`);return i}function ks(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
|
|
231
|
+
${n}`)}function Cs(t,e){switch(t){case "droid":{let n=X(e,"marketplace",t),i=X(e,"plugin",t);return [`droid plugin marketplace add ${L(n)}`,`droid plugin install ${L(i)} --scope user`]}case "claude":{let n=X(e,"marketplace",t),i=X(e,"plugin",t);return [`claude plugin marketplace add ${L(n)} --scope user`,`claude plugin install ${L(i)} --scope user`]}case "gemini":{let n=X(e,"source",t),i=e,r=[`gemini extensions install ${L(n)}`];return Le(i.ref)&&r.push(`--ref ${L(i.ref)}`),i.autoUpdate===true&&r.push("--auto-update"),i.preRelease===true&&r.push("--pre-release"),r.push("--consent"),i.skipSettings===true&&r.push("--skip-settings"),[r.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=X(e,"marketplace",t),i=e,r=[`codex plugin marketplace add ${L(n)}`];if(Le(i.ref)&&r.push(`--ref ${L(i.ref)}`),Array.isArray(i.sparse))for(let s of i.sparse){if(!Le(s))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");r.push(`--sparse ${L(s)}`);}return [r.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function Gn(t,e,n){if(n?.length)for(let i of n){let r=Cs(t,i);for(let s of r){let a=await e.commands.run(s,{timeoutMs:12e4});if(a.exitCode!==0)throw ks(s,a)}}}var zn="/home/user/.factory/evolve-session.json";function Es(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function Wn(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function Jn(t,e,n="newline"){let i=new Map;if(t){let r=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let s of r){let a=s.trim();if(!a)continue;let l=a.indexOf(":");if(l<=0)continue;let c=a.slice(0,l).trim(),p=a.slice(l+1).trim();i.set(c.toLowerCase(),`${c}: ${p}`);}}for(let[r,s]of Object.entries(e)){let a=r.toLowerCase();if(a===U&&i.has(a)&&n==="newline"){let l=i.get(a),c=l.slice(l.indexOf(":")+1).trim();i.set(a,`${r}: ${c},${s}`);}else i.set(a,`${r}: ${s}`);}return Array.from(i.values()).join(n==="comma"?", ":`
|
|
232
|
+
`)}var pe=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||Mt,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,this.storage=n.storage,n.schema)if(M(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=$(e.type),this.sessionTag=Wn(n.sessionTagPrefix||"evolve");}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,r){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,r),s}finalizeOperation(e,n,i,r="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=r,this.emitLifecycle(n,i),true)}watchBackgroundOperation(e,n,i,r,s){let a=n==="run"?"run_background_complete":"command_background_complete",l=n==="run"?"run_background_failed":"command_background_failed",c=n==="run"?"run_interrupted":"command_interrupted";i.wait().then(async p=>{if(this.interruptedOperations.delete(e)||p.exitCode===130){this.finalizeOperation(e,r,c,"interrupted");return}n==="run"&&s&&await this.writeDroidSessionState(s);let d=p.exitCode===0?a:l,u=p.exitCode===0?"idle":"error";this.finalizeOperation(e,r,d,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,r,l,"error");});}createAjvValidator(){let n={...je[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 Ss__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, plugins, context, files, and systemPrompt"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,await this.loadDroidSessionState(this.sandbox),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.setupAgentPlugins(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.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))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,r=i?i.keyEnv:this.registry.apiKeyEnv,s=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:r;e[s]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=this.registry.usePassthroughGateway?qe():B();this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[I]:this.sessionTag}):this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=n),e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.options.secrets&&Object.assign(e,this.options.secrets),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let n=this.registry.customHeadersEnv,i=this.registry.customHeadersFormat||"newline";e[n]=Jn(e[n],{[I]:this.sessionTag},i);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildGatewayConfigJson(e){let n=this.registry.usePassthroughGateway?qe():B(),i=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),r={},s=this.options.secrets?.[this.registry.gatewayConfigEnv];if(s)try{r=JSON.parse(s);}catch{}let a=r.provider??{},l=a.litellm??{},c=l.options??{},p=l.models??{},o=p[i]??{},d=o.headers??{};return r.provider={...a,litellm:{...l,npm:"@ai-sdk/openai-compatible",options:{...c,baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{...p,[i]:{...o,name:i,headers:{...d,...e}}}}},JSON.stringify(r)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.registry.customHeadersEnv;if(n){let r=this.options.secrets?.[n],s=this.registry.customHeadersFormat||"newline";return {[n]:Jn(r,{[I]:this.sessionTag,[U]:`${z}${e}`},s)}}let i=this.registry.spendTrackingEnvs;if(i)return {[i.sessionTagEnv]:this.sessionTag,[i.runTagEnv]:`${z}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[I]:this.sessionTag,[U]:`${z}${e}`})}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let i=n?.find(s=>typeof s.sessionId=="string"&&s.sessionId.length>0)?.sessionId;if(i){this.droidSessionId=i;return}let r=this.extractDroidSessionId(e);r&&(this.droidSessionId=r);}extractDroidSessionId(e){try{return this.findDroidSessionId(JSON.parse(e))}catch{return}}findDroidSessionId(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,i=n.sessionId??n.session_id;return typeof i=="string"&&i.length>0?i:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(zn);if(typeof n!="string")return;let i=JSON.parse(n);typeof i.sessionId=="string"&&i.sessionId.length>0&&(this.droidSessionId=i.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir("/home/user/.factory"),await e.files.write(zn,JSON.stringify({sessionId:this.droidSessionId},null,2)));}resolveGatewayModel(e){return this.agentConfig.isDirectMode?e:this.registry.gatewayModelAliases?.[e]??e}resolveCommandModel(e){return (this.agentConfig.isDirectMode?this.registry.directModelAliases:this.registry.gatewayModelAliases)?.[e]??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 setupAgentPlugins(e){await Gn(this.agentConfig.type,e,this.options.plugins);}async setupWorkspace(e,n){let i=this.options.workspaceMode||"knowledge",r=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 ${r}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let a=ut({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:i}),l=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(l,a);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let s={...this.options.mcpServers};if(this.options.composio){let a=await mt(this.options.composio.userId,this.options.composio.config);s={...s,composio:{type:"http",url:a.url,headers:a.headers}};}Object.keys(s).length>0&&await et(this.agentConfig.type,e,this.workingDir,s),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await Qe(e,this.agentConfig.baseUrl||B(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ye(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[I]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:i,targetDir:r}=n;await e.files.makeDir(r);for(let s of this.skills){let a=`cp -r ${i}/${s} ${r}/ 2>/dev/null || true`;await e.commands.run(a,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let i=Object.entries(n).map(([s,a])=>({path:`${this.workingDir}/context/${s}`,data:a}));if(i.length===0)return;let r=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,n){let i=Object.entries(n).map(([s,a])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:a}));if(i.length===0)return;let r=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));r.size>0&&await e.commands.run(`mkdir -p ${Array.from(r).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:Es(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.agentConfig.reasoningEffort,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,n){let{prompt:i,timeoutMs:r=se,background:s=false,checkpointComment:a}=e,{from:l}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(l&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(l==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await Ct(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');l=v.id;}if(l){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:v,workingDirectory:this.workingDir});let x=await Dn(this.sandbox,this.storage,l);if(x.agentType&&x.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${x.agentType}, current: ${this.agentConfig.type})`);let b=this.options.workspaceMode||"knowledge";if(x.workspaceMode&&x.workspaceMode!==b)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${x.workspaceMode}, current: ${b})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let _=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!_}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=l,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(x){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),x}}let c=await this.getSandbox(n);if(await this.loadDroidSessionState(c),this.lastRunTimestamp=Date.now(),!this.sessionLogger){let v=this.options.sandboxProvider;this.sessionLogger=new ae({provider:v?.name||v?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:c.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(i);let p=this.buildCommand(i),o=crypto.randomUUID(),d=this.buildRunEnvs(o);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await ye(c,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[I]:this.sessionTag,[U]:`${z}${o}`}),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await Xe(c,this.registry.spendTrackingTomlProvider,{[I]:this.sessionTag,[U]:`${z}${o}`}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await ve(c,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${B()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[I]:this.sessionTag,[U]:`${z}${o}`});let u="",g=W(this.agentConfig.type),m=v=>{u+=v;let x=u.split(`
|
|
233
|
+
`);u=x.pop()??"";for(let b of x){if(!b.trim())continue;let _=g(b);if(this.captureDroidSession(b,_),this.sessionLogger?.writeEventParsed(b,_),n?.onStdout?.(b+`
|
|
234
|
+
`),_&&n?.onContent)for(let N of _)n.onContent(N);}},f=v=>{n?.onStderr?.(v);},h=await c.commands.spawn(p,{cwd:this.workingDir,timeoutMs:r,envs:d,onStdout:m,onStderr:f}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.sandboxId,runId:o,exitCode:0,stdout:`Background process started with ID ${h.processId}`,stderr:""};let w;try{w=await h.wait();}catch(v){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n,"run_failed","error"),v}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,n,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,n,"run_complete","idle"):this.finalizeOperation(y,n,"run_failed","error"),u.trim()){let v=g(u);if(this.captureDroidSession(u,v),this.sessionLogger?.writeEventParsed(u,v),n?.onStdout?.(u+`
|
|
235
|
+
`),v&&n?.onContent)for(let x of v)n.onContent(x);}await this.writeDroidSessionState(c),this.sessionLogger&&!s&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let k;if(this.storage&&!s&&w.exitCode===0)try{k=await kt(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:a,parentId:this.lastCheckpointId}),this.lastCheckpointId=k.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.sandboxId,runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:k}}async executeCommand(e,n={},i){let{timeoutMs:r=se,background:s=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let a=await this.getSandbox(i);this.lastRunTimestamp=Date.now();let l="",c="",p=f=>{l+=f,i?.onStdout?.(f);},o=f=>{c+=f,i?.onStderr?.(f);},d=await a.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,onStdout:p,onStderr:o}),u=this.beginOperation("command",d,i,"command_start");if(s)return this.watchBackgroundOperation(u,"command",d,i),{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with ID ${d.processId}`,stderr:""};let g;try{g=await d.wait();}catch(f){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,i,"command_failed","error"),f}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,i,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,i,"command_complete","idle"):this.finalizeOperation(u,i,"command_failed","error"),{sandboxId:a.sandboxId,exitCode:g.exitCode,stdout:l||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),i=`${this.workingDir}/output`,r=e?"":"-maxdepth 1",a=(await n.commands.run(`find ${i} ${r} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
236
|
+
`).filter(Boolean),l=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],p=`${i}/`;for(let m of a){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);l>0&&y<l||c.push(f);}let o={},d=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(p)?m.slice(p.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of d)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}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 kt(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,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.");await this.rotateSession(),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,r=false;try{this.activeCommand?r=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(r=await this.sandbox.commands.kill(this.activeProcessId));}catch{r=false;}if(!r)return this.sandboxState="running",this.agentState="running",false;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),r}status(){return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString()}}async kill(e){await this.rotateSession(),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.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=Wn(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let n=this.agentConfig.apiKey;if(!n)throw new Error("Cost tracking requires an API key.");let i=process.env.EVOLVE_DASHBOARD_URL||P,r=await fetch(`${i}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Spend query failed (${r.status}): ${s}`)}return r}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,n){return {...e,asOf:e.asOf??n.asOf,isComplete:e.isComplete??n.isComplete,truncated:e.truncated??n.truncated}}normalizeSessionCost(e){let n={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(i=>this.normalizeRunCost(i,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),r=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(r)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let a=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(a)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let i=await this.getSessionCost(),r=e.index>0?e.index-1:i.runs.length+e.index,s=i.runs[r];if(!s)throw new Error(`Run index ${e.index} out of range. Session has ${i.runs.length} run(s).`);return s}};var de=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),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}withBrowser(e="browser-use"){return e===false?delete this.config.browser:this.config.browser=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(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=ht;async initializeAgent(){let e=Oe(this.config.agent),n=this.config.sandbox??await ct(),i={};if(this.config.browser==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');i=Rt(e.apiKey);}let r=this.config.storage!==void 0?Fe(this.config.storage,!e.isDirectMode,P,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},plugins:this.config.plugins,skills:this.config.skills,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:r};this.agent=new pe(e,s);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,i=this.listenerCount("content")>0,r=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:r?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:r,checkpointComment:s}){if(r&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let a=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:i,from:r,checkpointComment:s},a)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let i=this.createStreamCallbacks();return this.agent.executeCommand(e,n,i)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Oe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:P,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return bt(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return bt(this.config.storage,this.resolveGatewayOverrides()||{})}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}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var ee=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 J=Symbol.for("evolve.SwarmResult"),te=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 _t=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Ot;if(n>Ye)throw new Error(`concurrency=${n} exceeds max ${Ye}. 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??se,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:i,bestOf:r,verify:s}=e,a=e.retry??this.config.retry,l=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(r&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let p=await Promise.all(n.map((o,d)=>r?this.executeMapItemWithBestOf(o,i,d,l,e,c,a):s?this.executeMapItemWithVerify(o,i,d,l,e,c,a):a?R(u=>this.executeMapItem(o,i,d,l,e,c,u),a,d):this.executeMapItem(o,i,d,l,e,c)));return te.from(p)}async filter(e){let{items:n,prompt:i,condition:r,verify:s}=e,a=e.retry??this.config.retry,l=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,p=await Promise.all(n.map((d,u)=>s?this.executeFilterItemWithVerify(d,i,u,l,e,c,a):a?R(g=>this.executeFilterItem(d,i,u,l,e,c,g),a,u):this.executeFilterItem(d,i,u,l,e,c))),o=[];for(let d of p)if(d.status==="error")o.push(d);else if(d.data!==null)try{r(d.data)?o.push(d):o.push({...d,status:"filtered"});}catch(u){o.push({...d,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:i,verify:r}=e,s=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,c=[],p=[];n.forEach((k,v)=>{c.push(this.getFiles(k)),p.push(this.getIndex(k,v));});let o={};c.forEach((k,v)=>{Object.entries(k).forEach(([x,b])=>{o[`item_${p[v]}/${x}`]=b;});});let d=Me(o),u=F(ln,{fileTree:d}),g=e.systemPrompt?`${u}
|
|
237
|
+
|
|
238
|
+
${e.systemPrompt}`:u,m=(k,v,x)=>({operationId:a,operation:"reduce",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:p,errorRetry:v,verifyRetry:x,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(k,v,x,b)=>{let _=await this.semaphore.use(()=>this.execute(o,k,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:e.name,operationId:a,operation:"reduce",role:"worker",errorRetry:x,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),N=m(_,x,b&&b>1?b-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:N,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:N}},C=`${this.config.tag}-reduce`;return r?this.runWithVerification((k,v,x)=>w(k,v,void 0,x),{originalPrompt:i,inputFiles:o,verifyConfig:r,timeoutMs:l,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:a,baseTag:C,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?R(k=>{let v=k>1?k-1:void 0,x=v?`${C}-er${v}`:C;return w(i,x,v)},s):w(i,C)}async bestOf(e){let{item:n,prompt:i,config:r}=e,s=e.retry??this.config.retry,a=r.n??r.taskAgents?.length;if(a===void 0)throw new Error("bestOf requires n or taskAgents");if(a<2)throw new Error("bestOf requires n >= 2");let l=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,p=this.getFiles(n),o=r.mcpServers??this.config.mcpServers,d=r.judgeMcpServers??r.mcpServers??this.config.mcpServers,u=r.skills??this.config.skills,g=r.judgeSkills??r.skills??this.config.skills,m=r.composio??this.config.composio,f=r.judgeComposio??r.composio??this.config.composio,h=await Promise.all(Array.from({length:a},async(v,x)=>{let b=s?await R(_=>this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:x,operationId:l,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c,attempt:_}),s,x):await this.executeBestOfCandidate({inputFiles:p,prompt:i,candidateIndex:x,operationId:l,config:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c});return r.onCandidateComplete?.(0,x,b.status==="success"?"success":"error"),b})),y=s?await R(v=>this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:h,config:r,timeoutMs:c,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:d,skills:g,composio:f,attempt:v}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:p,taskPrompt:i,candidates:h,config:r,timeoutMs:c,operationId:l,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:d,skills:g,composio:f}),w=h.findIndex(v=>v.status==="success"),C=y.decision?.winner??(w>=0?w:0);r.onJudgeComplete?.(0,C,y.decision?.reasoning??"Judge failed to provide reasoning");let k={operationId:l,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:a};return {winner:h[C]??h[0],winnerIndex:C,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:k,candidates:h}}async execute(e,n,i){let r=null,s="",a=i.tagPrefix,l={},c=null,p,o,d={...this.config.agent,...i.agent};try{r=new de().withAgent(d).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&r.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&r.withSystemPrompt(i.systemPrompt),i.mcpServers&&r.withMcpServers(i.mcpServers),i.skills?.length&&r.withSkills(i.skills),i.composio&&r.withComposio(i.composio.userId,i.composio.config),i.observability&&r.withObservability(i.observability),Object.keys(e).length>0&&r.withContext(e);let u=await r.run({prompt:n,timeoutMs:i.timeoutMs});s=u.sandboxId,a=r.getSessionTag()??i.tagPrefix;let g=null;try{g=await r.getOutputFiles(!0),l=g.files;}catch{}u.exitCode!==0?p=`Agent exited with code ${u.exitCode}`:i.schema?g?(c=g.data,g.error&&(p=g.error),g.rawData&&(o=g.rawData)):p="Failed to read output files from sandbox":c=l;}catch(u){if(p=u.message,r){a=r.getSessionTag()??i.tagPrefix;try{l=(await r.getOutputFiles(!0)).files;}catch{}}}finally{r&&await r.kill().catch(()=>{});}return {files:l,data:c,tag:a,sandboxId:s,error:p,rawData:o}}async executeMapItem(e,n,i,r,s,a,l=1){let c=this.getFiles(e),p=l>1?`${this.config.tag}-map-${i}-er${l-1}`:`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(n,c,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:i});let d=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,g=s.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(c,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:d,skills:u,composio:g,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"map",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:r,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,i,r,s,a,l){let c=this.getFiles(e),p=`${this.config.tag}-map-${i}`,o=s.verify,d=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,g=s.composio??this.config.composio,m=this.evaluatePrompt(n,c,i);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:i});let f=async(h,y,w)=>{let C=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:d,skills:u,composio:g,tagPrefix:y,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"map",itemIndex:i,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),k={operationId:r,operation:"map",tag:C.tag,sandboxId:C.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(C,k)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:c,verifyConfig:o,timeoutMs:a,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:d,skills:u,composio:g,operationId:r,baseTag:p,retry:l,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,n,i,r,s,a,l){let c=this.getFiles(e),p=`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(n,c,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:i});let d=s.bestOf,u=d.n??d.taskAgents?.length;if(u===void 0||u<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:r,operation:"map",tag:p,sandboxId:"",itemIndex:i});let g=s.mcpServers??this.config.mcpServers,m=d.mcpServers??g,f=d.judgeMcpServers??d.mcpServers??g,h=s.skills??this.config.skills,y=d.skills??h,w=d.judgeSkills??d.skills??h,C=s.composio??this.config.composio,k=d.composio??C,v=d.judgeComposio??d.composio??C,x=await Promise.all(Array.from({length:u},async(ue,ge)=>{let Tt=l?await R(Hn=>this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:r,config:d,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:m,skills:y,composio:k,timeoutMs:a,parentIndex:i,attempt:Hn,_pipelineContext:s._pipelineContext}),l,ge):await this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:r,config:d,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:m,skills:y,composio:k,timeoutMs:a,parentIndex:i,_pipelineContext:s._pipelineContext});return d.onCandidateComplete?.(i,ge,Tt.status==="success"?"success":"error"),Tt})),b=l?await R(ue=>this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:x,config:d,timeoutMs:a,operationId:r,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:i,attempt:ue,_pipelineContext:s._pipelineContext}),{...l,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:x,config:d,timeoutMs:a,operationId:r,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:i,_pipelineContext:s._pipelineContext}),_=x.findIndex(ue=>ue.status==="success"),N=b.decision?.winner??(_>=0?_:0),Et=x[N]??x[0];d.onJudgeComplete?.(i,N,b.decision?.reasoning??"Judge failed to provide reasoning");let qn={operationId:r,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:u,...this.pipelineContextToMeta(s._pipelineContext)};return {...Et,meta:{...Et.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:N,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:qn,candidates:x}}}async executeFilterItem(e,n,i,r,s,a,l=1){let c=this.getFiles(e),p=l>1?`${this.config.tag}-filter-${i}-er${l-1}`:`${this.config.tag}-filter-${i}`,o=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,u=s.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:d,composio:u,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"filter",itemIndex:i,role:"worker",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),m={operationId:r,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:l>1?l-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(g,m,c)}async executeFilterItemWithVerify(e,n,i,r,s,a,l){let c=this.getFiles(e),p=`${this.config.tag}-filter-${i}`,o=s.verify,d=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,g=s.composio??this.config.composio,m=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,f,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:d,skills:u,composio:g,tagPrefix:h,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:s.name,operationId:r,operation:"filter",itemIndex:i,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),C={operationId:r,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(w,C,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:o,timeoutMs:a,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:d,skills:u,composio:g,operationId:r,baseTag:p,retry:l,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:i,candidateIndex:r,operationId:s,config:a,timeoutMs:l,parentIndex:c,attempt:p=1,_pipelineContext:o}=e,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${r}`:`${this.config.tag}-bestof-cand-${r}`,u=p>1?`${d}-er${p-1}`:d,g=await this.semaphore.use(()=>this.execute(n,i,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:a.taskAgents?.[r],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:u,timeoutMs:l,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:c,role:"candidate",candidateIndex:r,errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(o)}})),m={operationId:s,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:r,errorRetry:p>1?p-1:void 0,candidateIndex:r,...this.pipelineContextToMeta(o)};return this.buildResult(g,m)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((i,r)=>{i.status==="error"&&(n[`candidate_${r}/_failed.txt`]=`STATUS: FAILED
|
|
239
|
+
|
|
240
|
+
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,a])=>{n[`candidate_${r}/${s}`]=a;});}),n}async executeBestOfJudge(e){let{candidates:n,config:i,timeoutMs:r,operationId:s,parentIndex:a,attempt:l=1,_pipelineContext:c}=e,p=a!==void 0?`${this.config.tag}-map-${a}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=l>1?`${p}-er${l-1}`:p,d=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=Me(d),g=F(lt,{candidateCount:String(n.length),criteria:i.judgeCriteria,fileTree:u}),m=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),f=await this.semaphore.use(()=>this.execute(d,an,{systemPrompt:g,schema:m,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"judge",errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(c)}})),h=null;if(f.data&&!f.error)h=f.data;else if(f.rawData)try{let y=JSON.parse(f.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${f.error}`);}return {status:h?"success":"error",decision:h,tag:f.tag,sandboxId:f.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,r])=>{n[`worker_output/${i}`]=r;}),n}async executeVerify(e){let{config:n,timeoutMs:i,operationId:r,workerTag:s,retryAttempt:a=1,operation:l,itemIndex:c,attemptIndex:p,_pipelineContext:o}=e,d=a>1?`${s}-verifier-er${a-1}`:`${s}-verifier`,u=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,m=n.verifierComposio??e.composio,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=Me(f),y=F(pt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(f,cn,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:u,skills:g,composio:m,tagPrefix:d,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:r,operation:l,itemIndex:c,role:"verifier",verifyRetry:p&&p>1?p-1:void 0,errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o)}})),C=null;if(w.data&&!w.error)C=w.data;else if(w.rawData)try{let k=JSON.parse(w.rawData);C={passed:!!k.passed,reasoning:k.reasoning??"Verification completed",feedback:k.feedback};}catch{console.warn(`Verify validation failed: ${w.error}`);}return {status:C?"success":"error",decision:C,tag:w.tag,sandboxId:w.sandboxId,error:C?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return F(dt,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:i,inputFiles:r,verifyConfig:s,timeoutMs:a,operationId:l,baseTag:c,retry:p,itemIndex:o=0,operation:d,_pipelineContext:u}=n,g=s.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,m=i,f=null,h=0;for(;h<g;){h++;let w=h>1?`${c}-vr${h-1}`:c,C=p?await R(x=>e(m,x>1?`${w}-er${x-1}`:w,h),p,o):await e(m,w,h);if(s.onWorkerComplete?.(o,h,C.status==="error"?"error":"success"),C.status==="error")return C;f=C;let k=p?await R(x=>this.executeVerify({inputFiles:r,outputFiles:C.files,taskPrompt:m,config:s,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:l,workerTag:w,retryAttempt:x,operation:d,itemIndex:o,attemptIndex:h,_pipelineContext:u}),{...p,retryOn:void 0}):await this.executeVerify({inputFiles:r,outputFiles:C.files,taskPrompt:m,config:s,timeoutMs:a,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:l,workerTag:w,operation:d,itemIndex:o,attemptIndex:h,_pipelineContext:u}),v={operationId:l,operation:"verify",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(s.onVerifierComplete?.(o,h,k.decision?.passed??false,k.decision?.feedback),k.decision?.passed)return {...C,verify:{passed:true,reasoning:k.decision.reasoning,verifyMeta:v,attempts:h}};if(h<g){let x=k.decision?.feedback??k.decision?.reasoning??"Output did not meet criteria";m=t.buildRetryPromptWithFeedback(i,x);}}let y=h>1?`${c}-vr${h-1}`:c;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:l,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,i){if(typeof e=="string")return e;try{return e(n,i)}catch(r){return r}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=M(e.schema)?H(e.schema):Y(e.schema)),Object.entries(e.inputFiles).forEach(([i,r])=>{n[`worker_task/input/${i}`]=r;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&J in e&&e[J]===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 r=i??e.files;return e.error?{[J]:true,status:"error",data:null,files:r,meta:n,error:e.error,rawData:e.rawData}:{[J]:true,status:"success",data:e.data,files:r,meta:n}}buildErrorResult(e,n){return {[J]:true,status:"error",data:null,files:{},meta:n,error:e}}};var Ne=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 Ke(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=crypto.randomBytes(8).toString("hex"),i=[],r=e,s=Date.now();for(let l=0;l<this.steps.length;l++){let c=this.steps[l],p=c.config.name,o=Date.now();this.events.onStepStart?.({type:c.type,index:l,name:p,itemCount:r.length});let d={pipelineRunId:n,pipelineStepIndex:l};try{let u=await this.executeStep(c,r,l,p,d),g=Date.now()-o;if(i.push({type:c.type,index:l,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:c.type,index:l,name:p,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),c.type==="reduce")return {pipelineRunId:n,steps:i,output:u.output,totalDurationMs:Date.now()-s};r=u.nextItems;}catch(u){throw this.events.onStepError?.({type:c.type,index:l,name:p,error:u instanceof Error?u:new Error(String(u))}),u}}let a=i[i.length-1];return {pipelineRunId:n,steps:i,output:a?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,i,r,s){if(e.type==="map"){let c=e.config,p=await this.swarm.map({items:n,...c,_pipelineContext:s,retry:this.wrapRetry(c.retry,i,r),verify:this.wrapVerify(c.verify,i,r),bestOf:this.wrapBestOf(c.bestOf,i,r)});return {output:[...p],nextItems:p.success,successCount:p.success.length,errorCount:p.error.length,filteredCount:0}}if(e.type==="filter"){let c=e.config,p=await this.swarm.filter({items:n,...c,_pipelineContext:s,retry:this.wrapRetry(c.retry,i,r),verify:this.wrapVerify(c.verify,i,r)}),o=c.emit??"success",d=o==="success"?p.success:o==="filtered"?p.filtered:[...p.success,...p.filtered];return {output:[...p],nextItems:d,successCount:p.success.length,errorCount:p.error.length,filteredCount:p.filtered.length}}let a=e.config,l=await this.swarm.reduce({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,r),verify:this.wrapVerify(a.verify,i,r)});return {output:l,nextItems:[],successCount:l.status==="success"?1:0,errorCount:l.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,i){if(e)return {...e,onItemRetry:(r,s,a)=>{e.onItemRetry?.(r,s,a),this.events.onItemRetry?.({stepIndex:n,stepName:i,itemIndex:r,attempt:s,error:a});}}}wrapVerify(e,n,i){if(e)return {...e,onWorkerComplete:(r,s,a)=>{e.onWorkerComplete?.(r,s,a),this.events.onWorkerComplete?.({stepIndex:n,stepName:i,itemIndex:r,attempt:s,status:a});},onVerifierComplete:(r,s,a,l)=>{e.onVerifierComplete?.(r,s,a,l),this.events.onVerifierComplete?.({stepIndex:n,stepName:i,itemIndex:r,attempt:s,passed:a,feedback:l});}}}wrapBestOf(e,n,i){if(e)return {...e,onCandidateComplete:(r,s,a)=>{e.onCandidateComplete?.(r,s,a),this.events.onCandidateComplete?.({stepIndex:n,stepName:i,itemIndex:r,candidateIndex:s,status:a});},onJudgeComplete:(r,s,a)=>{e.onJudgeComplete?.(r,s,a),this.events.onJudgeComplete?.({stepIndex:n,stepName:i,itemIndex:r,winnerIndex:s,reasoning:a});}}}},Ke=class t extends Ne{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")}};function Ds(t){let e=t?.apiKey||process.env[O];if(!e)throw new Error(`sessions() requires an API key. Set ${O} or pass { apiKey } in config.`);let n=t?.dashboardUrl||P;async function i(s,a){let l=await fetch(`${n}${s}`,{...a,headers:{Authorization:`Bearer ${e}`,...a?.headers}});if(!l.ok){let c=await l.text().catch(()=>"");throw new Error(`Dashboard API error (${l.status}): ${c||l.statusText}`)}return l}function r(s){return {id:s.id,tag:s.tag,agent:s.agent,model:s.model||null,provider:s.provider,sandboxId:s.sandboxId||null,state:s.isEnded?"ended":"live",runtimeStatus:s.runtimeStatus||"unknown",cost:typeof s.cost=="number"?s.cost:null,createdAt:s.createdAt,endedAt:s.endedAt||null,stepCount:s.stepCount||0,toolStats:s.toolStats||null}}return {async list(s){let a=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(s?.limit??20,200)),paginated:"true"});if(s?.cursor&&a.set("cursor",s.cursor),s?.state&&s.state!=="all"&&a.set("state",s.state),s?.agent&&a.set("agent",s.agent),s?.tagPrefix&&a.set("tagPrefix",s.tagPrefix),s?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};a.set("sortDirection",p[s.sort]),s.sort==="cost"?a.set("sortField","cost"):a.set("sortField","timestamp");}let c=await(await i(`/api/sessions?${a}`)).json();return {items:(c.items||[]).map(r),nextCursor:c.nextCursor||null,hasMore:!!c.hasMore}},async get(s){let l=await(await i(`/api/sessions/${encodeURIComponent(s)}`)).json();return r(l)},async events(s,a){let l=new URLSearchParams;a?.since!=null&&l.set("since",String(a.since));let c=l.toString();return (await(await i(`/api/sessions/${encodeURIComponent(s)}/events${c?`?${c}`:""}`)).json()).events||[]},async download(s,a){let p=(await(await i(`/api/sessions/${encodeURIComponent(s)}`)).json()).tag||s,o=await fetch(`${n}/api/sessions/${encodeURIComponent(s)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!o.ok){let m=await o.text().catch(()=>"");throw new Error(`Download failed (${o.status}): ${m||o.statusText}`)}let d=a?.to||process.cwd();await promises.mkdir(d,{recursive:true});let u=re.join(d,`${p}.jsonl`);if(!o.body)throw new Error("Download response has no body");let g=stream.Readable.fromWeb(o.body);return await promises$1.pipeline(g,A.createWriteStream(u)),u}}}Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Ve;exports.AGENT_TYPES=Yn;exports.Agent=pe;exports.Evolve=de;exports.JUDGE_PROMPT=lt;exports.Pipeline=Ne;exports.RETRY_FEEDBACK_PROMPT=dt;exports.SCHEMA_PROMPT=rn;exports.SWARM_RESULT_BRAND=J;exports.SYSTEM_PROMPT=on;exports.Semaphore=ee;exports.Swarm=_t;exports.SwarmResultList=te;exports.TerminalPipeline=Ke;exports.VALIDATION_PRESETS=je;exports.VERIFY_PROMPT=pt;exports.WORKSPACE_PROMPT=nn;exports.WORKSPACE_SWE_PROMPT=sn;exports.applyTemplate=F;exports.buildWorkerSystemPrompt=ut;exports.createAgentParser=W;exports.createClaudeParser=_e;exports.createCodexParser=Ee;exports.createDroidParser=Te;exports.createGeminiParser=Pe;exports.executeWithRetry=R;exports.expandPath=G;exports.getAgentConfig=$;exports.getMcpSettingsDir=j;exports.getMcpSettingsPath=K;exports.isValidAgentType=Zn;exports.isZodSchema=M;exports.jsonSchemaToString=Y;exports.parseNdjsonLine=Pi;exports.parseNdjsonOutput=Ri;exports.parseQwenOutput=Vt;exports.readLocalDir=Gt;exports.resolveStorageConfig=Fe;exports.saveLocalDir=zt;exports.sessions=Ds;exports.storage=xs;exports.writeClaudeMcpConfig=me;exports.writeCodexMcpConfig=be;exports.writeDroidGatewaySettings=ve;exports.writeDroidMcpConfig=we;exports.writeGeminiMcpConfig=fe;exports.writeMcpConfig=et;exports.writeQwenMcpConfig=he;exports.zodSchemaToJson=H;
|