@evolvingmachines/sdk 0.0.50 → 0.0.52-launch-round-1.20260803.37a56fe
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-5HFUY44N.js +6 -0
- package/dist/hosted/cli.cjs +19 -0
- package/dist/hosted/cli.d.cts +105 -0
- package/dist/hosted/cli.d.ts +105 -0
- package/dist/hosted/cli.js +14 -0
- package/dist/index.cjs +440 -82
- package/dist/index.d.cts +1224 -478
- package/dist/index.d.ts +1224 -478
- package/dist/index.js +427 -77
- package/dist/managed-modal-CRZFDIRG.js +4 -0
- package/dist/tar-PPIAXEGM.js +1 -0
- package/dist/types-B6iGD_du.d.cts +1582 -0
- package/dist/types-B6iGD_du.d.ts +1582 -0
- package/harness-capabilities.json +345 -0
- package/hosted-error-codes.json +57 -0
- package/package.json +35 -10
- package/spec/openapi.yaml +4031 -0
package/dist/index.js
CHANGED
|
@@ -1,52 +1,30 @@
|
|
|
1
|
-
import {EventEmitter}from'events';import fs from'ajv';import {randomBytes,randomUUID,publicEncrypt,constants,createHash}from'crypto';import ii from'zod-to-json-schema';import*as $ from'fs';import {createWriteStream}from'fs';import*as ae from'path';import {join,dirname,isAbsolute,normalize,resolve,relative}from'path';import {mkdir,appendFile,rm,readFile,writeFile,unlink,copyFile}from'fs/promises';import {homedir,tmpdir}from'os';import {exec,execFile}from'child_process';import {promisify}from'util';import {z as z$1}from'zod';export{E2BProvider,createE2BProvider}from'@evolvingmachines/e2b';export{DaytonaProvider,createDaytonaProvider}from'@evolvingmachines/daytona';export{ModalProvider,createModalProvider}from'@evolvingmachines/modal';import {Readable}from'stream';import {pipeline}from'stream/promises';var xr={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},He={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};function ne(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function qe(t){if(!(t==="off"||t==="none"||t==="no-thinking"))return !t||t==="thinking"||t==="medium"?"medium":t==="low"||t==="minimal"?"minimal":t==="xhigh"?"max":t}function Cr(t){let e=qe(t);return e?` --variant ${e} --thinking`:""}var Ye={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:"fable",modelId:"claude-fable-5",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-4-8",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,reasoningEffort:r})=>{let s=n?"--continue ":"",o=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${s}--model ${e}${o} --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:r})=>{let s=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${s} --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.5-flash",modelId:"gemini-3.5-flash",description:"Latest Flash model"},{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",gatewayPath:"/gemini",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.7-max",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"},{alias:"qwen3.6-plus",modelId:"qwen3.6-plus",description:"Compatibility model used in Qwen Code examples"}],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.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash","qwen3.6-plus":"dashscope/qwen3.6-plus"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r})=>{let s=n?"--continue ":"",o=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${o} --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.6-turbo",modelId:"kimi-k2.6-turbo",description:"Evolve-managed Kimi K2.6 turbo route for latency-sensitive agent runs"},{alias:"kimi-k2.5",modelId:"moonshot/kimi-k2.5",description:"Previous multimodal flagship"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"/home/user/.evolve/skills",targetDir:"/home/user/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k2.6":"moonshot/kimi-k2.6","kimi-k2.6-turbo":"kimi-k2.6-turbo","kimi-k2.5":"moonshot/kimi-k2.5"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n})=>{let r=e?"--continue ":"",s=ve(t),o="--config-file /home/user/.kimi-code/config.toml",c="$(if [ -f /home/user/.kimi-code/mcp.json ]; then printf ' --mcp-config-file /home/user/.kimi-code/mcp.json'; fi)",a=ne(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${r}${o}${c}${a} -p ${s} --output-format stream-json; else kimi ${r}-p ${s} --output-format stream-json; fi`}},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-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{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.8",modelId:"openrouter/anthropic/claude-opus-4.8",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.5-flash",modelId:"openrouter/google/gemini-3.5-flash",description:"Gemini 3.5 Flash 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:r,reasoningEffort:s})=>{let o=n?"--continue ":"",c=e.startsWith("openrouter/")?e:`openrouter/${e}`,a=Cr(s);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model ${c} --format json${a} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${o}--model litellm/${c} --format json${a} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",defaultModel:"gpt-5.5",models:[{alias:"claude-opus-4-8",modelId:"claude-opus-4-8",description:"Factory-managed Claude Opus 4.8"},{alias:"claude-opus-4-8-fast",modelId:"claude-opus-4-8-fast",description:"Factory-managed Claude Opus 4.8 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:r,reasoningEffort:s,isDirectMode:o})=>{let c=o?"":"--settings /home/user/.factory/evolve-settings.json ",a=o?e:"custom:Evolve-Gateway-0",l=s?` --reasoning-effort ${s}`:"",d=n&&r?`--session-id ${ve(r)} `:"";return `printf '%s' ${ve(t)} | droid ${c}exec ${d}--skip-permissions-unsafe --cwd /home/user/workspace --output-format stream-json --model ${ve(a)}${l}`}}};function D(t){let e=Ye[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function _r(t){return t in Ye}function V(t){return t.replace(/^~/,"/home/user")}function ve(t){return `'${t.replace(/'/g,"'\\''")}'`}function B(t){let e=D(t);return `${V(e.mcpConfig.settingsDir)}/${e.mcpConfig.filename}`}function U(t){let e=D(t);return V(e.mcpConfig.settingsDir)}function A(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 Qe(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 re(t){for(let[e,n]of Object.entries(t))Qe(e,n);}function ie(t){return t.type?t.type:t.command?"stdio":"sse"}function Er(t){let e=ie(t);return {...t,type:e}}function Tr(t){let{type:e,url:n,...r}=t;return ie(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function Ir(t){return {type:ie(t),...t}}function Rr(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function Pr(t){let e=ie(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:o,envVars:c,...a}=t;if(e==="stdio"&&t.command)return {type:"stdio",...a};if(t.url){let l={...a,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??r;return d&&Object.keys(d).length>0&&(l.headers=d),l}return {type:e==="stdio"?"stdio":"http",...a}}async function Ze(t,e,n,r){re(n);let s=U(e),o=B(e);await t.files.makeDir(s);let c={};try{let l=await t.files.read(o);typeof l=="string"&&(c=JSON.parse(l));}catch(l){if(!A(l))throw l}let a=Object.fromEntries(Object.entries(n).map(([l,d])=>[l,r(d)]));await t.files.write(o,JSON.stringify({...c,mcpServers:a},null,2));}async function Se(t,e,n){re(n);let r=U("claude"),s=B("claude"),o=Object.fromEntries(Object.entries(n).map(([a,l])=>[a,Ir(l)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:o},null,2)),await t.files.makeDir(r);let c={};try{let a=await t.files.read(s);typeof a=="string"&&(c=JSON.parse(a));}catch(a){if(!A(a))throw a}c.enableAllProjectMcpServers=true,await t.files.write(s,JSON.stringify(c,null,2));}async function ke(t,e){await Ze(t,"gemini",e,Er);}async function xe(t,e){await Ze(t,"qwen",e,Tr);}async function Ce(t,e,n,r){let s=U(e),o=B(e);await t.files.makeDir(s);let c={};try{let p=await t.files.read(o);typeof p=="string"&&(c=JSON.parse(p));}catch(p){if(!A(p))throw p}let a=n.split("."),l=c;for(let p=0;p<a.length-1;p++){let u=a[p];(typeof l[u]!="object"||l[u]===null)&&(l[u]={}),l=l[u];}let d=a[a.length-1],i=typeof l[d]=="object"&&l[d]!==null?l[d]:{};l[d]={...i,...r},await t.files.write(o,JSON.stringify(c,null,2));}async function Xe(t,e){let n=U("qwen"),r=B("qwen");await t.files.makeDir(n);let s={};try{let l=await t.files.read(r);typeof l=="string"&&(s=JSON.parse(l));}catch(l){if(!A(l))throw l}let o=s.model??{},c=o.generationConfig??{},a=c.extra_body??{};s.model={...o,generationConfig:{...c,extra_body:{...a,enable_thinking:e}}},await t.files.write(r,JSON.stringify(s,null,2));}async function et(t,e){await Ze(t,"kimi",e,Rr);}async function _e(t,e,n){re(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let o={};try{let a=await t.files.read(s);typeof a=="string"&&(o=JSON.parse(a));}catch(a){if(!A(a))throw a}let c=Object.fromEntries(Object.entries(n).map(([a,l])=>[a,Pr(l)]));await t.files.write(s,JSON.stringify({...o,mcpServers:c},null,2));}async function Ee(t,e,n){let r=V(e.settingsPath),s=r.slice(0,r.lastIndexOf("/"));await t.files.makeDir(s);let o={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(r,JSON.stringify(o,null,2));}async function tt(t,e,n){re(n);let r=`${e}/opencode.json`,s={};try{let c=await t.files.read(r);typeof c=="string"&&(s=JSON.parse(c));}catch(c){if(!A(c))throw c}let o=Object.fromEntries(Object.entries(n).map(([c,a])=>[c,Or(a)]));await t.files.write(r,JSON.stringify({...s,mcp:o},null,2));}function Or(t){let e=ie(t);if(e==="stdio"&&t.command){let r={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(r.environment=t.env),r}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 G(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Te(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||E;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}function nt(){return Te("/api/managed/e2b")}function Nt(t){return {"browser-use":{type:"http",url:G("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var I="EVOLVE_API_KEY",Ie="E2B_API_KEY",Re="DAYTONA_API_KEY",Pe="MODAL_TOKEN_ID",rt="MODAL_TOKEN_SECRET",Kt="claude",se=36e5,jt=4,it=100,Vt="/home/user/workspace",E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",O="x-litellm-customer-id",L="x-litellm-tags",W="run:",Gt=".evolve-sdk/observability/sessions",Wt=100,zt=5e3,Oe=3,st=1e3;function _(t){return typeof t=="string"?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:Array.isArray(t)?`[${t.map(e=>_(e)).join(", ")}]`:typeof t=="object"&&t!==null?`{ ${Object.entries(t).map(([n,r])=>`${n} = ${_(r)}`).join(", ")} }`:typeof t=="boolean"?t?"true":"false":String(t)}async function Ae(t,e){for(let[l,d]of Object.entries(e))Qe(l,d);let n=U("codex"),r=B("codex");await t.files.makeDir(n);let s="";try{let l=await t.files.read(r);typeof l=="string"&&(s=l);}catch(l){if(!A(l))throw l}let o=[],c=[];s.includes("experimental_use_rmcp_client")||(o.push("# Enable improved RMCP client (recommended)"),o.push("experimental_use_rmcp_client = true")),s.includes("[mcp_servers]")||c.push("[mcp_servers]","");for(let[l,d]of Object.entries(e)){if(s.includes(`[mcp_servers.${l}]`))continue;c.push(`[mcp_servers.${l}]`);let i=d.type??(d.command?"stdio":"http");if(i==="http"||i==="sse"||!!d.url){if(!d.url)throw new Error(`MCP server "${l}" is missing url for ${i} transport`);c.push(`url = ${_(d.url)}`),d.bearerTokenEnvVar&&c.push(`bearer_token_env_var = ${_(d.bearerTokenEnvVar)}`);let u=d.httpHeaders??d.headers;u&&Object.keys(u).length>0&&c.push(`http_headers = ${_(u)}`),d.envHttpHeaders&&Object.keys(d.envHttpHeaders).length>0&&c.push(`env_http_headers = ${_(d.envHttpHeaders)}`);}else c.push(`command = ${_(d.command)}`),d.args&&d.args.length>0&&c.push(`args = ${_(d.args)}`),d.cwd&&c.push(`cwd = ${_(d.cwd)}`);d.env&&Object.keys(d.env).length>0&&c.push(`env = ${_(d.env)}`),d.envVars&&d.envVars.length>0&&c.push(`env_vars = ${_(d.envVars)}`),c.push("");}let a=[s.trim(),o.join(`
|
|
2
|
-
`),c.join(`
|
|
3
|
-
`)].filter(l=>l.length>0);await t.files.write(r,a.join(`
|
|
4
|
-
|
|
5
|
-
`)+`
|
|
6
|
-
`);}async function ot(t,e,n){let r=U("codex"),s=B("codex");await t.files.makeDir(r);let o="";try{let m=await t.files.read(s);typeof m=="string"&&(o=m);}catch(m){if(!A(m))throw m}let c=o.search(/^\[/m),a=c>=0?o.slice(0,c):o,l=c>=0?o.slice(c):"",d=o.includes("[model_providers.evolve-gateway]"),i=/^model_provider\s*=\s*"evolve-gateway"/m.test(a);if(d&&i)return;o=(a.replace(/^model_provider\s*=\s*.*$/m,"").replace(/\n{3,}/g,`
|
|
7
|
-
|
|
8
|
-
`)+l).replace(/^\n+/,"");let u='model_provider = "evolve-gateway"',g=d?"":["[model_providers.evolve-gateway]",'name = "Evolve Gateway"',`base_url = ${_(e)}`,'env_key = "OPENAI_API_KEY"',`env_http_headers = ${_({[O]:n.sessionTagEnv,[L]:n.runTagEnv})}`].join(`
|
|
9
|
-
`),f;if(!o.trim())f=g?`${u}
|
|
10
|
-
|
|
11
|
-
${g}
|
|
12
|
-
`:`${u}
|
|
13
|
-
`;else {let m=o.search(/^\[/m);m>0?f=o.slice(0,m)+u+`
|
|
14
|
-
|
|
15
|
-
`+o.slice(m).trimEnd():m===0?f=u+`
|
|
16
|
-
|
|
17
|
-
`+o.trimEnd():f=o.trimEnd()+`
|
|
18
|
-
|
|
19
|
-
`+u,g&&(f=f.trimEnd()+`
|
|
20
|
-
|
|
21
|
-
`+g),f+=`
|
|
22
|
-
`;}await t.files.write(s,f);}async function at(t,e,n,r){let s=V(e.configPath),o=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(o);let c=[`default_model = ${_(e.modelName)}`,`default_thinking = ${_(r.defaultThinking)}`,'default_permission_mode = "auto"',"","[thinking]",`mode = ${_(r.defaultThinking?"on":"off")}`];r.defaultThinking&&r.thinkingEffort&&c.push(`effort = ${_(r.thinkingEffort)}`),c.push("",`[providers.${e.providerName}]`,'type = "kimi"',`base_url = ${_(r.baseUrl)}`,`api_key = ${_(r.apiKey)}`,`custom_headers = ${_(n)}`,"",`[models.${e.modelName}]`,`provider = ${_(e.providerName)}`,`model = ${_(r.model)}`,`max_context_size = ${e.maxContextSize}`,`capabilities = ${_(["image_in","thinking"])}`);let a=c.join(`
|
|
23
|
-
`)+`
|
|
24
|
-
`;await t.files.write(s,a);}async function ct(t,e,n,r){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await Se(e,n,r);break;case "codex":await Ae(e,r);break;case "gemini":await ke(e,r);break;case "qwen":await xe(e,r);break;case "kimi":await et(e,r);break;case "opencode":await tt(e,n,r);break;case "droid":await _e(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Me(){let t={};return function(d){let i;try{i=JSON.parse(d);}catch{return null}if(i._meta||i._prompt)return null;let p=i.session_id;switch(i.type){case "system":return null;case "assistant":return e(i.message?.content,"assistant",p);case "user":{let u=i.message?.content;return typeof u=="string"||Array.isArray(u)&&u.length===1&&u[0].type==="text"?null:e(u,"user",p)}case "result":return null;default:return null}};function e(l,d,i){if(typeof l=="string")return d==="user"?null:[{sessionId:i,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}];if(!l||!Array.isArray(l))return null;let p=[];for(let u of l){let g=null;switch(u.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:u.text}};break;case "image":if(d==="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:c(u.input)});else {let f=n(u);g={sessionUpdate:"tool_call",toolCallId:u.id,status:"pending",...f};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let f=t[u.tool_use_id];if(!f||(delete t[u.tool_use_id],f.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:u.tool_use_id,status:"is_error"in u&&u.is_error?"failed":"completed",...r(u,f)};break}}g&&p.push({sessionId:i,update:g});}return p.length>0?p:null}function n(l){let d=l.name,i=l.input||{};switch(d){case "Task":return {title:i.description||"Task",kind:"think",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "NotebookRead":return {title:i.notebook_path?`Read Notebook ${i.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "NotebookEdit":return {title:i.notebook_path?`Edit Notebook ${i.notebook_path}`:"Edit Notebook",kind:"edit",content:i.new_source?[{type:"content",content:{type:"text",text:i.new_source}}]:[],locations:i.notebook_path?[{path:i.notebook_path}]:[],rawInput:i};case "Bash":return {title:i.command?"`"+i.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:i.description?[{type:"content",content:{type:"text",text:i.description}}]:[],rawInput:i};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:i};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:i};case "Read":{let p="";return i.limit?p=" ("+((i.offset??0)+1)+" - "+((i.offset??0)+i.limit)+")":i.offset&&(p=" (from line "+(i.offset+1)+")"),{title:"Read "+(i.file_path??"File")+p,kind:"read",content:[],locations:i.file_path?[{path:i.file_path,line:i.offset??0}]:[],rawInput:i}}case "LS":return {title:i.path?`List \`${i.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:i};case "Edit":{let p=i.file_path;return {title:p?`Edit \`${p}\``:"Edit",kind:"edit",content:p?[{type:"diff",path:p,oldText:i.old_string??null,newText:i.new_string??""}]:[],locations:p?[{path:p}]:[],rawInput:i}}case "Write":return {title:i.file_path?`Write ${i.file_path}`:"Write",kind:"edit",content:i.file_path?[{type:"diff",path:i.file_path,oldText:null,newText:i.content??""}]:[],locations:i.file_path?[{path:i.file_path}]:[],rawInput:i};case "Glob":{let p="Find";return i.path&&(p+=` \`${i.path}\``),i.pattern&&(p+=` \`${i.pattern}\``),{title:p,kind:"search",content:[],locations:i.path?[{path:i.path}]:[],rawInput:i}}case "Grep":{let p="grep";return i["-i"]&&(p+=" -i"),i["-n"]&&(p+=" -n"),i["-A"]!==void 0&&(p+=` -A ${i["-A"]}`),i["-B"]!==void 0&&(p+=` -B ${i["-B"]}`),i["-C"]!==void 0&&(p+=` -C ${i["-C"]}`),i.output_mode==="files_with_matches"?p+=" -l":i.output_mode==="count"&&(p+=" -c"),i.head_limit!==void 0&&(p+=` | head -${i.head_limit}`),i.glob&&(p+=` --include="${i.glob}"`),i.type&&(p+=` --type=${i.type}`),i.multiline&&(p+=" -P"),p+=` "${i.pattern??""}"`,i.path&&(p+=` ${i.path}`),{title:p,kind:"search",content:[],rawInput:i}}case "WebFetch":return {title:i.url?`Fetch ${i.url}`:"Fetch",kind:"fetch",content:i.prompt?[{type:"content",content:{type:"text",text:i.prompt}}]:[],rawInput:i};case "WebSearch":{let p=`"${i.query??""}"`;return i.allowed_domains?.length>0&&(p+=` (allowed: ${i.allowed_domains.join(", ")})`),i.blocked_domains?.length>0&&(p+=` (blocked: ${i.blocked_domains.join(", ")})`),{title:p,kind:"fetch",content:[],rawInput:i}}case "TodoWrite":return {title:Array.isArray(i.todos)?`Update TODOs: ${i.todos.map(p=>p.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:i};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:i.plan?[{type:"content",content:{type:"text",text:i.plan}}]:[],rawInput:i};default:if(d?.startsWith("mcp__")){let p=d.split("__"),u=p[1]||"mcp",g=p.slice(2).join("__")||d;return {title:`${u}: ${g}`,kind:"other",content:[],rawInput:i}}return {title:d||"Unknown Tool",kind:"other",content:[],rawInput:i}}}function r(l,d){let i=l.content;switch(d?.name){case "Read":return Array.isArray(i)&&i.length>0?{content:i.map(p=>({type:"content",content:p.type==="text"?{type:"text",text:a(p.text)}:o(p,false)}))}:typeof i=="string"&&i.length>0?{content:[{type:"content",content:{type:"text",text:a(i)}}]}:{};case "Edit":case "Write":case "Bash":return s(i,l.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return s(i,"is_error"in l?l.is_error:false)}}function s(l,d=false){return Array.isArray(l)&&l.length>0?{content:l.map(i=>({type:"content",content:o(i,d)}))}:typeof l=="string"&&l.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+l+"\n```":l}}]}:{}}function o(l,d){if(l.type==="text")return d?{type:"text",text:"```\n"+l.text+"\n```"}:{type:"text",text:l.text};if(l.type==="image"){if(l.data&&l.mimeType)return {type:"image",data:l.data,mimeType:l.mimeType};if(l.source?.type==="base64")return {type:"image",data:l.source.data||"",mimeType:l.source.media_type||""};if(l.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:l.source.url}}return l}function c(l){return l.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function a(l){let d="```",i=Array.from(l.matchAll(/^```+/gm));for(let[p]of i)for(;p.length>=d.length;)d+="`";return d+`
|
|
1
|
+
import {w,o,p,n,g,s,m,h,c,e,d,f,i,j as j$1,k,l,r,q,a,t,v,u,x as x$1,b,y,z as z$1,A as A$1,B}from'./chunk-5HFUY44N.js';export{D as EVAL_SANDBOX_PROVIDERS,H as EvolveApiError,J as EvolveDigestMismatchError,K as EvolveIncompleteDownloadError,F as HOSTED_ERROR_CODES,c as MANAGED_SANDBOX_PROVIDERS,I as NoActiveVersionError,E as TRIAL_ARTIFACT_STREAMS,C as TRIAL_STATUSES,M as agents,P as auth,L as datasets,Q as hosted,G as isHostedErrorCode,N as jobs,R as meta,O as trials}from'./chunk-5HFUY44N.js';import {EventEmitter}from'events';import ca from'ajv';import {randomBytes,randomUUID,publicEncrypt,constants,createHash}from'crypto';import {stringify,parse}from'smol-toml';import Ls from'zod-to-json-schema';import*as $ from'fs';import {createWriteStream}from'fs';import*as U from'path';import {join,posix,dirname,isAbsolute,normalize,resolve,relative}from'path';import {mkdir,appendFile,rm,readFile,writeFile,unlink,copyFile}from'fs/promises';import {homedir,tmpdir}from'os';import {exec,execFile}from'child_process';import {promisify}from'util';import {z}from'zod';export{E2BProvider,createE2BProvider}from'@evolvingmachines/e2b';export{DaytonaProvider,createDaytonaProvider}from'@evolvingmachines/daytona';export{ModalProvider,createModalProvider}from'@evolvingmachines/modal';import {Readable}from'stream';import {pipeline}from'stream/promises';var es={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},Ct={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}};var On=["off","minimal","low","medium","high","xhigh","max","thinking"],Mn=["off","minimal","medium","thinking"],Dn="medium";function ts(t){return t==="none"?{efforts:[],defaultEffort:null}:{efforts:t==="binary"?Mn:On,defaultEffort:Dn}}function Un(t,e){return e??Z[t]?.defaultReasoningEffort}function ge(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function Et(t){if(!(t==="off"||t==="none"||t==="no-thinking"))return !t||t==="thinking"||t==="medium"?"medium":t==="low"||t==="minimal"?"minimal":t==="xhigh"?"max":t}function ns(t){let e=Et(t);return e?` --variant ${e} --thinking`:""}var Z={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",effortSupport:"level",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",defaultReasoningEffort:"high",models:[{alias:"fable",modelId:"claude-fable-5",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-5",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-5",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:"~/.evolve/skills",targetDir:"~/.claude/skills"},buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:r})=>{let i=n?"--continue ":"",s=r?` --effort ${r}`:"";return `echo "${t}" | claude -p ${i}--model ${e}${s} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",effortSupport:"level",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.6-sol",defaultReasoningEffort:"high",models:[{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Newest frontier flagship"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Balances intelligence and cost"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"High-volume, cost-sensitive tier"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Previous frontier model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.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:r})=>{let i=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${i} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",effortSupport:"none",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.6-flash",models:[{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Newest stable workhorse: coding + agentic planning"},{alias:"gemini-3.5-flash-lite",modelId:"gemini-3.5-flash-lite",description:"Most cost-effective 3.5-class model"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${pe(t)} --model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",effortSupport:"binary",defaultModel:"qwen3.7-max",defaultReasoningEffort:"thinking",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r})=>{let i=n?"--continue ":"",s=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${i}--auth-type openai --model ${s} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",effortSupport:"level",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k3",defaultReasoningEffort:"max",models:[{alias:"kimi-k3",modelId:"moonshot/kimi-k3",description:"Latest flagship: 1M context, always-on thinking",maxContextSize:1048576},{alias:"kimi-k2.7-code",modelId:"moonshot/kimi-k2.7-code",description:"Latest coding-specialized standard model"},{alias:"kimi-k3-raptor",modelId:"kimi-k3-raptor",description:"Evolve-managed Kimi K3 Raptor route for latency-sensitive agent runs",maxContextSize:1048576},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","kimi-k2.7-code":"moonshot/kimi-k2.7-code","kimi-k3-raptor":"kimi-k3-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n,homeDir:r=q})=>{let i=e?"--continue ":"",s=pe(t),c=`--config-file ${r}/.kimi-code/config.toml`,a=`$(if [ -f ${r}/.kimi-code/mcp.json ]; then printf ' --mcp-config-file ${r}/.kimi-code/mcp.json'; fi)`,l=ge(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${i}${c}${a}${l} -p ${s} --output-format stream-json; else kimi ${i}-p ${s} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",effortSupport:"level",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-opus-5",defaultReasoningEffort:"high",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-5",modelId:"openrouter/anthropic/claude-opus-5",description:"Anthropic Opus 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-5",modelId:"openrouter/anthropic/claude-sonnet-5",description:"Anthropic Sonnet 5 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.6-sol",modelId:"openrouter/openai/gpt-5.6-sol",description:"OpenAI GPT-5.6 Sol via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-terra",modelId:"openrouter/openai/gpt-5.6-terra",description:"OpenAI GPT-5.6 Terra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-luna",modelId:"openrouter/openai/gpt-5.6-luna",description:"OpenAI GPT-5.6 Luna via OpenRouter"},{alias:"openrouter/google/gemini-3.6-flash",modelId:"openrouter/google/gemini-3.6-flash",description:"Gemini 3.6 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3.7-max",modelId:"openrouter/qwen/qwen3.7-max",description:"Qwen 3.7 Max via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k3",modelId:"openrouter/moonshotai/kimi-k3",description:"Kimi K3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.2",modelId:"openrouter/z-ai/glm-5.2",description:"Zhipu GLM-5.2 via OpenRouter"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,isExternalGateway:i,reasoningEffort:s})=>{let c=n?"--continue ":"",a=ns(s);if(i)return `OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model litellm/${e} --format json${a} "${t}" < /dev/null`;let l=e.startsWith("openrouter/")?e:`openrouter/${e}`;return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model ${l} --format json${a} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${c}--model litellm/${l} --format json${a} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",effortSupport:"level",defaultModel:"claude-opus-5",defaultReasoningEffort:"high",models:[{alias:"claude-fable-5",modelId:"claude-fable-5",description:"Factory-managed Claude Fable 5"},{alias:"claude-opus-5",modelId:"claude-opus-5",description:"Factory-managed Claude Opus 5"},{alias:"claude-sonnet-5",modelId:"claude-sonnet-5",description:"Factory-managed Claude Sonnet 5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Factory-managed GPT-5.6 Sol"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Factory-managed GPT-5.6 Terra"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"Factory-managed GPT-5.6 Luna"},{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Factory-managed Gemini 3.6 Flash"},{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Qwen 3.7 Max via the Evolve gateway"},{alias:"kimi-k3",modelId:"kimi-k3",description:"Factory-managed Droid Core Kimi K3"},{alias:"glm-5.2",modelId:"glm-5.2",description:"Factory-managed Droid Core GLM-5.2"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{sourceDir:"~/.evolve/skills",targetDir:"~/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","glm-5.2":"openrouter/z-ai/glm-5.2","qwen3.7-max":"dashscope/qwen3.7-max"},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:r,reasoningEffort:i,isDirectMode:s,isExternalGateway:c,homeDir:a=q})=>{let l=!s||c,d=l?`--settings ${a}/.factory/evolve-settings.json `:"",o=l?"custom:Evolve-Gateway-0":e,u=i?` --reasoning-effort ${i}`:"",p=n&&r?`--session-id ${pe(r)} `:"";return `printf '%s' ${pe(t)} | droid ${d}exec ${p}--skip-permissions-unsafe --cwd ${a}/workspace --output-format stream-json --model ${pe(o)}${u}`}}};function I(t){let e=Z[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function _t(t){return t in Z}function A(t,e=q){return t.replace(/^~/,e)}function pe(t){return `'${t.replace(/'/g,"'\\''")}'`}function N(t,e=q){let n=I(t);return `${A(n.mcpConfig.settingsDir,e)}/${n.mcpConfig.filename}`}function F(t,e=q){let n=I(t);return A(n.mcpConfig.settingsDir,e)}function K(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 Tt(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 fe(t){for(let[e,n]of Object.entries(t))Tt(e,n);}function me(t){return t.type?t.type:t.command?"stdio":"sse"}function rs(t){let e=me(t);return {...t,type:e}}function is(t){let{type:e,url:n,...r}=t;return me(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function ss(t){return {type:me(t),...t}}function os(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function as(t){let e=me(t),{type:n,httpHeaders:r,envHttpHeaders:i,bearerTokenEnvVar:s,envVars:c,...a}=t;if(e==="stdio"&&t.command)return {type:"stdio",...a};if(t.url){let l={...a,type:e==="sse"?"sse":"http",url:t.url},d=t.headers??r;return d&&Object.keys(d).length>0&&(l.headers=d),l}return {type:e==="stdio"?"stdio":"http",...a}}async function Rt(t,e,n,r,i){fe(n);let s=F(e,i),c=N(e,i);await t.files.makeDir(s);let a={};try{let d=await t.files.read(c);typeof d=="string"&&(a=JSON.parse(d));}catch(d){if(!K(d))throw d}let l=Object.fromEntries(Object.entries(n).map(([d,o])=>[d,r(o)]));await t.files.write(c,JSON.stringify({...a,mcpServers:l},null,2));}async function Ke(t,e,n,r){fe(n);let i=F("claude",r),s=N("claude",r),c=Object.fromEntries(Object.entries(n).map(([l,d])=>[l,ss(d)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:c},null,2)),await t.files.makeDir(i);let a={};try{let l=await t.files.read(s);typeof l=="string"&&(a=JSON.parse(l));}catch(l){if(!K(l))throw l}a.enableAllProjectMcpServers=true,await t.files.write(s,JSON.stringify(a,null,2));}async function je(t,e,n){await Rt(t,"gemini",e,rs,n);}async function Ge(t,e,n){await Rt(t,"qwen",e,is,n);}async function Ve(t,e,n,r,i){let s=F(e,i),c=N(e,i);await t.files.makeDir(s);let a={};try{let p=await t.files.read(c);typeof p=="string"&&(a=JSON.parse(p));}catch(p){if(!K(p))throw p}let l=n.split("."),d=a;for(let p=0;p<l.length-1;p++){let g=l[p];(typeof d[g]!="object"||d[g]===null)&&(d[g]={}),d=d[g];}let o=l[l.length-1],u=typeof d[o]=="object"&&d[o]!==null?d[o]:{};d[o]={...u,...r},await t.files.write(c,JSON.stringify(a,null,2));}async function Pt(t,e,n){let r=F("qwen",n),i=N("qwen",n);await t.files.makeDir(r);let s={};try{let d=await t.files.read(i);typeof d=="string"&&(s=JSON.parse(d));}catch(d){if(!K(d))throw d}let c=s.model??{},a=c.generationConfig??{},l=a.extra_body??{};s.model={...c,generationConfig:{...a,extra_body:{...l,enable_thinking:e}}},await t.files.write(i,JSON.stringify(s,null,2));}async function It(t,e,n){await Rt(t,"kimi",e,os,n);}async function ze(t,e,n){fe(n);let r=`${e}/.factory`,i=`${r}/mcp.json`;await t.files.makeDir(r);let s={};try{let a=await t.files.read(i);typeof a=="string"&&(s=JSON.parse(a));}catch(a){if(!K(a))throw a}let c=Object.fromEntries(Object.entries(n).map(([a,l])=>[a,as(l)]));await t.files.write(i,JSON.stringify({...s,mcpServers:c},null,2));}async function We(t,e,n,r){let i=A(e.settingsPath,r),s=i.slice(0,i.lastIndexOf("/"));await t.files.makeDir(s);let c={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(c,null,2));}async function At(t,e,n){fe(n);let r=`${e}/opencode.json`,i={};try{let c=await t.files.read(r);typeof c=="string"&&(i=JSON.parse(c));}catch(c){if(!K(c))throw c}let s=Object.fromEntries(Object.entries(n).map(([c,a])=>[c,cs(a)]));await t.files.write(r,JSON.stringify({...i,mcp:s},null,2));}function cs(t){let e=me(t);if(e==="stdio"&&t.command){let r={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(r.environment=t.env),r}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 Ot(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function $n(t,e,n){let r=t[e];if(r===void 0)return {};let i=Ot(r);if(!i){let s=Array.isArray(r)?"an array":`a ${typeof r}`;throw new Error(`Refusing to rewrite "${e}" in ${n}: expected a TOML table, found ${s}`)}return i}function Mt(t,e){if(t===e)return true;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((s,c)=>Mt(s,e[c]));let n=Ot(t),r=Ot(e);if(!n||!r)return false;let i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(s=>s in r&&Mt(n[s],r[s]))}async function Bn(t,e){let n="";try{let r=await t.files.read(e);typeof r=="string"&&(n=r);}catch(r){if(!K(r))throw r;return {}}if(!n.trim())return {};try{return parse(n)}catch(r){throw new Error(`Failed to parse TOML at ${e}: ${r.message}`)}}async function Dt(t,e,n){await t.files.write(e,stringify(n).trimEnd()+`
|
|
2
|
+
`);}function us(t,e){let n={},r=e.type??(e.command?"stdio":"http");if(r==="http"||r==="sse"||!!e.url){if(!e.url)throw new Error(`MCP server "${t}" is missing url for ${r} transport`);n.url=e.url,e.bearerTokenEnvVar&&(n.bearer_token_env_var=e.bearerTokenEnvVar);let s=e.httpHeaders??e.headers;s&&Object.keys(s).length>0&&(n.http_headers=s),e.envHttpHeaders&&Object.keys(e.envHttpHeaders).length>0&&(n.env_http_headers=e.envHttpHeaders);}else n.command=e.command,e.args&&e.args.length>0&&(n.args=e.args),e.cwd&&(n.cwd=e.cwd);return e.env&&Object.keys(e.env).length>0&&(n.env=e.env),e.envVars&&e.envVars.length>0&&(n.env_vars=e.envVars),n}async function He(t,e,n){for(let[a,l]of Object.entries(e))Tt(a,l);let r=F("codex",n),i=N("codex",n);await t.files.makeDir(r);let s=await Bn(t,i);s.experimental_use_rmcp_client===void 0&&(s.experimental_use_rmcp_client=true);let c=$n(s,"mcp_servers",i);s.mcp_servers=c;for(let[a,l]of Object.entries(e))c[a]===void 0&&(c[a]=us(a,l));await Dt(t,i,s);}async function qe(t$1,e,n,r={},i){let s=F("codex",i),c=N("codex",i);await t$1.files.makeDir(s);let a=await Bn(t$1,c),l={...n?{[t]:n.sessionTagEnv,[u]:n.runTagEnv}:{},...r},d={name:"Evolve Gateway",base_url:e,env_key:"OPENAI_API_KEY",wire_api:"responses",...Object.keys(l).length>0?{env_http_headers:l}:{}},o=$n(a,"model_providers",c);a.model_provider==="evolve-gateway"&&Mt(o["evolve-gateway"],d)||(a.model_provider="evolve-gateway",o["evolve-gateway"]=d,a.model_providers=o,await Dt(t$1,c,a));}async function Ut(t,e,n,r,i){let s=A(e.configPath,i),c=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(c);let a={default_model:e.modelName,default_thinking:r.defaultThinking,default_permission_mode:"auto",thinking:{mode:r.defaultThinking?"on":"off",...r.defaultThinking&&r.thinkingEffort?{effort:r.thinkingEffort}:{}},providers:{[e.providerName]:{type:"kimi",base_url:r.baseUrl,api_key:r.apiKey,custom_headers:n}},models:{[e.modelName]:{provider:e.providerName,model:r.model,max_context_size:e.maxContextSize,capabilities:["image_in","thinking"]}}};await Dt(t,s,a);}async function $t(t,e,n,r,i){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await Ke(e,n,r,i);break;case "codex":await He(e,r,i);break;case "gemini":await je(e,r,i);break;case "qwen":await Ge(e,r,i);break;case "kimi":await It(e,r,i);break;case "opencode":await At(e,n,r);break;case "droid":await ze(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function Je(){let t={};return function(d){let o;try{o=JSON.parse(d);}catch{return null}if(o._meta||o._prompt)return null;let u=o.session_id;switch(o.type){case "system":return null;case "assistant":return e(o.message?.content,"assistant",u);case "user":{let p=o.message?.content;return typeof p=="string"||Array.isArray(p)&&p.length===1&&p[0].type==="text"?null:e(p,"user",u)}case "result":return null;default:return null}};function e(l,d,o){if(typeof l=="string")return d==="user"?null:[{sessionId:o,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}];if(!l||!Array.isArray(l))return null;let u=[];for(let p of l){let g=null;switch(p.type){case "text":case "text_delta":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}};break;case "image":if(d==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:p.source?.type==="base64"?p.source.data:"",mimeType:p.source?.type==="base64"?p.source.media_type:"",uri:p.source?.type==="url"?p.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[p.id]=p,p.name==="TodoWrite")Array.isArray(p.input?.todos)&&(g={sessionUpdate:"plan",entries:c(p.input)});else {let f=n(p);g={sessionUpdate:"tool_call",toolCallId:p.id,status:"pending",...f};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let f=t[p.tool_use_id];if(!f||(delete t[p.tool_use_id],f.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:p.tool_use_id,status:"is_error"in p&&p.is_error?"failed":"completed",...r(p,f)};break}}g&&u.push({sessionId:o,update:g});}return u.length>0?u:null}function n(l){let d=l.name,o=l.input||{};switch(d){case "Task":return {title:o.description||"Task",kind:"think",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "NotebookRead":return {title:o.notebook_path?`Read Notebook ${o.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "NotebookEdit":return {title:o.notebook_path?`Edit Notebook ${o.notebook_path}`:"Edit Notebook",kind:"edit",content:o.new_source?[{type:"content",content:{type:"text",text:o.new_source}}]:[],locations:o.notebook_path?[{path:o.notebook_path}]:[],rawInput:o};case "Bash":return {title:o.command?"`"+o.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:o.description?[{type:"content",content:{type:"text",text:o.description}}]:[],rawInput:o};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:o};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:o};case "Read":{let u="";return o.limit?u=" ("+((o.offset??0)+1)+" - "+((o.offset??0)+o.limit)+")":o.offset&&(u=" (from line "+(o.offset+1)+")"),{title:"Read "+(o.file_path??"File")+u,kind:"read",content:[],locations:o.file_path?[{path:o.file_path,line:o.offset??0}]:[],rawInput:o}}case "LS":return {title:o.path?`List \`${o.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:o};case "Edit":{let u=o.file_path;return {title:u?`Edit \`${u}\``:"Edit",kind:"edit",content:u?[{type:"diff",path:u,oldText:o.old_string??null,newText:o.new_string??""}]:[],locations:u?[{path:u}]:[],rawInput:o}}case "Write":return {title:o.file_path?`Write ${o.file_path}`:"Write",kind:"edit",content:o.file_path?[{type:"diff",path:o.file_path,oldText:null,newText:o.content??""}]:[],locations:o.file_path?[{path:o.file_path}]:[],rawInput:o};case "Glob":{let u="Find";return o.path&&(u+=` \`${o.path}\``),o.pattern&&(u+=` \`${o.pattern}\``),{title:u,kind:"search",content:[],locations:o.path?[{path:o.path}]:[],rawInput:o}}case "Grep":{let u="grep";return o["-i"]&&(u+=" -i"),o["-n"]&&(u+=" -n"),o["-A"]!==void 0&&(u+=` -A ${o["-A"]}`),o["-B"]!==void 0&&(u+=` -B ${o["-B"]}`),o["-C"]!==void 0&&(u+=` -C ${o["-C"]}`),o.output_mode==="files_with_matches"?u+=" -l":o.output_mode==="count"&&(u+=" -c"),o.head_limit!==void 0&&(u+=` | head -${o.head_limit}`),o.glob&&(u+=` --include="${o.glob}"`),o.type&&(u+=` --type=${o.type}`),o.multiline&&(u+=" -P"),u+=` "${o.pattern??""}"`,o.path&&(u+=` ${o.path}`),{title:u,kind:"search",content:[],rawInput:o}}case "WebFetch":return {title:o.url?`Fetch ${o.url}`:"Fetch",kind:"fetch",content:o.prompt?[{type:"content",content:{type:"text",text:o.prompt}}]:[],rawInput:o};case "WebSearch":{let u=`"${o.query??""}"`;return o.allowed_domains?.length>0&&(u+=` (allowed: ${o.allowed_domains.join(", ")})`),o.blocked_domains?.length>0&&(u+=` (blocked: ${o.blocked_domains.join(", ")})`),{title:u,kind:"fetch",content:[],rawInput:o}}case "TodoWrite":return {title:Array.isArray(o.todos)?`Update TODOs: ${o.todos.map(u=>u.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:o};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:o.plan?[{type:"content",content:{type:"text",text:o.plan}}]:[],rawInput:o};default:if(d?.startsWith("mcp__")){let u=d.split("__"),p=u[1]||"mcp",g=u.slice(2).join("__")||d;return {title:`${p}: ${g}`,kind:"other",content:[],rawInput:o}}return {title:d||"Unknown Tool",kind:"other",content:[],rawInput:o}}}function r(l,d){let o=l.content;switch(d?.name){case "Read":return Array.isArray(o)&&o.length>0?{content:o.map(u=>({type:"content",content:u.type==="text"?{type:"text",text:a(u.text)}:s(u,false)}))}:typeof o=="string"&&o.length>0?{content:[{type:"content",content:{type:"text",text:a(o)}}]}:{};case "Edit":case "Write":case "Bash":return i(o,l.is_error||false);case "ExitPlanMode":return {title:"Exited Plan Mode"};default:return i(o,"is_error"in l?l.is_error:false)}}function i(l,d=false){return Array.isArray(l)&&l.length>0?{content:l.map(o=>({type:"content",content:s(o,d)}))}:typeof l=="string"&&l.length>0?{content:[{type:"content",content:{type:"text",text:d?"```\n"+l+"\n```":l}}]}:{}}function s(l,d){if(l.type==="text")return d?{type:"text",text:"```\n"+l.text+"\n```"}:{type:"text",text:l.text};if(l.type==="image"){if(l.data&&l.mimeType)return {type:"image",data:l.data,mimeType:l.mimeType};if(l.source?.type==="base64")return {type:"image",data:l.source.data||"",mimeType:l.source.media_type||""};if(l.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:l.source.url}}return l}function c(l){return l.todos.map(d=>({content:d.content,status:d.status||"pending",priority:"medium"}))}function a(l){let d="```",o=Array.from(l.matchAll(/^```+/gm));for(let[u]of o)for(;u.length>=d.length;)d+="`";return d+`
|
|
25
3
|
`+l+(l.endsWith(`
|
|
26
4
|
`)?"":`
|
|
27
|
-
`)+d}}function
|
|
5
|
+
`)+d}}function Ye(){return function(l){let d;try{d=JSON.parse(l);}catch{return null}if(d._meta||d._prompt)return null;let o=[];switch(d.type){case "thread.started":case "turn.started":case "turn.completed":return null;case "error":{let u=typeof d.message=="string"?d.message:JSON.stringify(d);o.push({update:{sessionUpdate:"error",message:u,fatal:false}});break}case "turn.failed":{let u=typeof d.error?.message=="string"?d.error.message:JSON.stringify(d.error??d);o.push({update:{sessionUpdate:"error",message:u,fatal:true}});break}case "item.started":{let u=d.item;if(!u)return null;let p=e(u);p&&o.push({update:p});break}case "item.updated":{let u=d.item;if(!u)return null;let p=n(u);p&&o.push({update:p});break}case "item.completed":{let u=d.item;if(!u)return null;let p=r(u);p&&o.push({update:p});break}default:return null}return o.length>0?o:null};function e(a){let l=a.id;switch(a.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${a.server}:${a.tool}`},{sessionUpdate:"tool_call",toolCallId:l,title:`${a.server}: ${a.tool}`,kind:"other",status:"in_progress",rawInput:a.arguments,content:[]};case "command_execution":return {type:"command_execution",name:a.command},{sessionUpdate:"tool_call",toolCallId:l,title:a.command?`\`${a.command}\``:"Execute Command",kind:"execute",status:"in_progress",rawInput:{command:a.command},content:[]};case "web_search":return {type:"web_search",name:a.query},{sessionUpdate:"tool_call",toolCallId:l,title:`Search: ${a.query??""}`,kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:c(a.items)};default:return null}}function n(a){return a.type==="todo_list"?{sessionUpdate:"plan",entries:c(a.items)}:null}function r(a){let l=a.id;switch(a.type){case "error":return {sessionUpdate:"error",message:typeof a.message=="string"?a.message:JSON.stringify(a),fatal:false};case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a.text??a.summary?.join(`
|
|
28
6
|
`)??a.content?.join(`
|
|
29
|
-
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:a.text??""}};case "mcp_tool_call":{let i
|
|
7
|
+
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:a.text??""}};case "mcp_tool_call":{let o=i(a.result),u=a.status==="failed"||a.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:l,status:u,content:o}}case "command_execution":{let o=a.aggregated_output?[{type:"content",content:{type:"text",text:a.aggregated_output}}]:[],u=a.status==="completed"||a.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:l,status:u,content:o}}case "file_change":{let o=a.changes??[],u=o.map(g=>({path:g.path})),p=o.length===1?`${o[0].kind==="add"?"Create":"Edit"} ${o[0].path}`:`Edit ${o.length} files`;return {sessionUpdate:"tool_call",toolCallId:l,title:p,kind:"edit",status:a.status==="completed"?"completed":"failed",content:o.map(g=>({type:"diff",path:g.path,oldText:g.kind==="add"?null:"",newText:""})),locations:u}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:l,title:`Search: ${a.query??""}`,kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:c(a.items)};default:return null}}function i(a){return a?.content?Array.isArray(a.content)?a.content.map(l=>({type:"content",content:s(l)})):typeof a.content=="string"?[{type:"content",content:{type:"text",text:a.content}}]:[]:[]}function s(a){return a.type==="text"?{type:"text",text:a.text??""}:a.type==="image"?{type:"image",data:a.data??"",mimeType:a.mime_type??a.mimeType??"",uri:a.uri}:a}function c(a){if(!Array.isArray(a))return [];let l=false;return a.map(d=>{let o;return d.completed?o="completed":l?o="pending":(o="in_progress",l=true),{content:d.text??"",status:o,priority:"medium"}})}}var ps={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"},gs=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 Xe(){let t=new Map,e,n=false,r="",i;return function(c){let a;try{a=JSON.parse(c);}catch{return null}if(!Kn(a))return null;let l=fs(a);if(l.sessionId&&(e=l.sessionId),l.errorText)return [W(e,l.errorText)];if(l.resultText)return r=l.resultText,n=true,[W(e,l.resultText)];if(l.handled)return null;let o=ms(a)??a,u=Fn(o);u&&(e=u);let p=[],g=x(o,"type");switch(g){case "system":return null;case "message":{let f=x(o,"role"),m=x(o,"text")||Lt(o.content);if(!m)break;f==="assistant"&&(n=true,r=m,p.push(W(e,m)));break}case "completion":{let f=x(o,"finalText")||x(o,"result");f&&(!n||f!==r)&&(n=true,r=f,p.push(W(e,f)));break}case "assistant_text_delta":{let f=x(o,"textDelta")||x(o,"text");f&&(n=true,r+=f,p.push(W(e,f)));break}case "thinking_text_delta":{let f=x(o,"textDelta")||x(o,"text");if(f){let m=Ln(o,f,i);m&&(i=m.signature,p.push({sessionId:e,update:m.event}));}break}case "reasoning":{let f=x(o,"text");if(f){let m=Ln(o,f,i);m&&(i=m.signature,p.push({sessionId:e,update:m.event}));}break}case "assistant":{let f=x(o,"text")||Lt(T(o.message)?.content);f&&(n=true,r=f,p.push(W(e,f)));break}case "tool_call":case "tool_call_delta":{let f=T(o.toolUse)??T(o.tool_use)??o,m=Nn(f,t);m&&p.push({sessionId:e,update:m});break}case "tool_result":{let f=ys(o,t);f&&p.push({sessionId:e,update:f});break}case "tool_progress_update":case "tool_progress":{let f=ws(o);f&&p.push({sessionId:e,update:f});break}case "create_message":{for(let f of hs(o,t)){if(f.sessionUpdate==="agent_message_chunk"){let m=f.content.type==="text"?f.content.text:"";if(n&&m===r)continue;n=true,r=m;}p.push({sessionId:e,update:f});}break}case "result":{let f=he(o.result??o.text??o.error);f&&(n=true,r=f,p.push(W(e,f)));break}case "error":{let f=he(o.message??o.error??o);f&&p.push(W(e,f));break}default:if(g&&!gs.has(g))return null}return p.length>0&&g!=="reasoning"&&g!=="thinking_text_delta"&&(i=void 0),p.length>0?p:null}}function Ln(t,e,n){let r=Bt(t,"id")||Bt(t,"messageId"),i=Bt(t,"blockIndex"),s=`${x(t,"type")}:${r}:${i}:${e}`;return s===n?null:{signature:s,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function fs(t){if(t.type!=="response")return {handled:false};let e=T(t.result),n=T(t.error),r=Fn(e??t);if(n)return {handled:true,sessionId:r,errorText:he(n.message??n)};let i=e?x(e,"finalText")||x(e,"result"):"";return {handled:true,sessionId:r,resultText:i}}function ms(t){return t.method!=="droid.session_notification"?null:T(T(t.params)?.notification)}function hs(t,e){let n=T(t.message);if(!n)return [];let r=[],i=n.content;if(Array.isArray(i))for(let s of i){let c=T(s);if(c&&c.type==="tool_use"){let a=Nn(c,e);a&&r.push(a);}}if(n.role==="assistant"){let s=Lt(i);s&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:s}});}return r}function Nn(t,e){let n=x(t,"id")||x(t,"toolUseId")||x(t,"tool_use_id"),r=x(t,"name")||x(t,"toolName")||x(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let i=T(t.input)??T(t.toolInput)??T(t.arguments)??T(t.parameters)??{};if(jn(r)==="todowrite"){let d=bs(i);if(d)return d}let{title:s,kind:c,content:a,locations:l}=vs(r,i);return {sessionUpdate:"tool_call",toolCallId:n,title:s,kind:c,status:"pending",rawInput:i,content:a,locations:l}}function ys(t,e){let n=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id")||x(t,"id")||x(t,"toolId");if(!n)return null;let r=x(t,"toolName")||x(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:r,content:Nt(t.content??t.result??t.value??t.error)}}function ws(t){let e=x(t,"toolUseId")||x(t,"tool_use_id")||x(t,"tool_id")||x(t,"id")||x(t,"toolId");if(!e)return null;let n=T(t.update),r=he(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?Nt(r):void 0}}function bs(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let i=T(r);if(!i)return [];let s=x(i,"content"),c=Ss(x(i,"status")),a=xs(x(i,"priority"));return s?[{content:s,status:c,priority:a}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function vs(t,e){let n=ps[jn(t)]||"other",r=x(e,"path")||x(e,"filePath")||x(e,"file_path")||x(e,"absolute_path"),i=x(e,"command"),s=x(e,"url"),c=r||i||s;return {title:c?`${t} ${c}`:t,kind:n,content:Object.keys(e).length>0?Nt(e):[],locations:r?[{path:r}]:[]}}function Fn(t){if(t)return x(t,"session_id")||x(t,"sessionId")}function W(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function Lt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=T(e);return n?x(n,"text")||x(n,"content"):""}).filter(Boolean).join(""):""}function Nt(t){let e=he(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function he(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function Kn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function T(t){return Kn(t)?t:null}function x(t,e){let n=t[e];return typeof n=="string"?n:""}function Bt(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function jn(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Ss(t){return t==="in_progress"||t==="completed"?t:"pending"}function xs(t){return t==="high"||t==="low"?t:"medium"}var ks={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 Qe(){return function(c){let a;try{a=JSON.parse(c);}catch{return null}if(a._meta||a._prompt)return null;let l=a.session_id,d=[];switch(a.type){case "init":case "result":return null;case "message":{let o=t(a);o&&d.push({sessionId:l,update:o});break}case "tool_use":{let o=e(a);o&&d.push({sessionId:l,update:o});break}case "tool_result":{let o=n(a);o&&d.push({sessionId:l,update:o});break}case "error":{let o=r(a);o&&d.push({sessionId:l,update:o});break}default:return null}return d.length>0?d:null};function t(s){let c=s.role,a=s.content;return a?c==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}:c==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:a}}:null:null}function e(s){let c=s.tool_id,a=s.tool_name,l=s.parameters||{},{title:d,kind:o,content:u,locations:p}=i(a,l);return {sessionUpdate:"tool_call",toolCallId:c,title:d,kind:o,status:"pending",rawInput:l,content:u,locations:p}}function n(s){let c=s.tool_id,a=s.status,l=s.output,d=s.error,o=[];return l&&typeof l=="string"&&l.length>0&&o.push({type:"content",content:{type:"text",text:a==="error"?`\`\`\`
|
|
30
8
|
${l}
|
|
31
|
-
\`\`\``:l}}),d?.message&&!l&&
|
|
9
|
+
\`\`\``:l}}),d?.message&&!l&&o.push({type:"content",content:{type:"text",text:`\`\`\`
|
|
32
10
|
${d.message}
|
|
33
|
-
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:c,status:a==="success"?"completed":"failed",content:i}}function r(o){let c=o.severity,a=o.message;return a?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${c==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${a}`}}:null}function s(o,c){let a=Vr[o]||"other",l=[],d=[],i=o;switch(o){case "read_file":i=`Read ${c.absolute_path||c.file_path||"file"}`,(c.absolute_path||c.file_path)&&d.push({path:c.absolute_path||c.file_path});break;case "write_file":i=`Write ${c.file_path||"file"}`,c.file_path&&(d.push({path:c.file_path}),l.push({type:"diff",path:c.file_path,oldText:null,newText:c.content||""}));break;case "edit_file":i=`Edit ${c.file_path||"file"}`,c.file_path&&d.push({path:c.file_path});break;case "replace":i=`Edit ${c.file_path||"file"}`,c.file_path&&(d.push({path:c.file_path}),(c.old_string!==void 0||c.new_string!==void 0)&&l.push({type:"diff",path:c.file_path,oldText:c.old_string||"",newText:c.new_string||""}));break;case "run_shell_command":case "shell":i=c.command?`\`${c.command}\``:"Run command",c.description&&l.push({type:"content",content:{type:"text",text:c.description}});break;case "brave_web_search":case "web_search":case "google_web_search":i=c.query?`"${c.query}"`:"Web search";break;case "web_fetch":i=c.prompt?`Fetch: ${c.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":i=`Find ${c.pattern||"files"}`,c.dir_path&&d.push({path:c.dir_path});break;case "grep":case "search_file_content":i=`grep "${c.pattern||c.query||""}"`;break;case "list_directory":i=`List ${c.dir_path||c.path||"directory"}`,(c.dir_path||c.path)&&d.push({path:c.dir_path||c.path});break;case "read_many_files":i=`Read ${c.include?.length||"multiple"} files`,Array.isArray(c.include)&&c.include.forEach(p=>d.push({path:p}));break;case "delegate_to_agent":i=c.agent_name?`Agent: ${c.agent_name}`:"Delegate to agent";break;case "write_todos":i="Update todos";break;case "save_memory":i=c.fact?`Remember: "${c.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":i=c.name?`Activate skill: ${c.name}`:"Activate skill";break;default:i=o;}return {title:i,kind:a,content:l,locations:d}}}var Gr={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function Zt(t){return t==="TodoList"||t==="SetTodoList"}function gt(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function en(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function ft(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=en(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 ut(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 r=ft(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=ft(t);n&&e.push(n);}return e}function Wr(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&>(e.content.text))}function zr(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=en(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 Jr(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function Xt(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 r=n.title;if(typeof r!="string"||r.length===0)return null;let s=n.status;return {content:r,status:Jr(s),priority:"medium"}}).filter(n=>n!==null):[]}function mt(){let t=new Set,e=0;function n(a,l){return typeof a=="string"&&a.length>0?a:(e+=1,`kimi_${l.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(l){let d;try{d=JSON.parse(l);}catch{return null}if(!d||typeof d!="object")return null;let i=d.role;return "_meta"in d||"_prompt"in d||i==="meta"?null:i==="assistant"?r(d):i==="tool"?s(d):typeof d.type=="string"&&"payload"in d?o(d):null};function r(a){let l=[],d=a.content,i=a.tool_calls;if(typeof d=="string"&&d.length>0)l.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let p of d){let u=zr(p);u&&l.push(u);}if(Array.isArray(i))for(let p of i){if(!p||typeof p!="object")continue;let u=p.function;if(!u)continue;let g=u.name??"",f=n(p.id,g),m;try{m=u.arguments?JSON.parse(u.arguments):{};}catch{m=u.arguments;}if(Zt(g)){let S=Xt(m);S.length>0&&l.push({update:{sessionUpdate:"plan",entries:S}}),t.add(f);continue}let{title:h,kind:y,toolContent:w,locations:k}=c(g,typeof m=="object"&&m!==null?m:{});l.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:m,content:w,locations:k}});}return l.length>0?l:null}function s(a){let l=a.tool_call_id;if(typeof l!="string"||l.length===0)return null;if(t.has(l))return t.delete(l),null;let d=a.content,i=[],p=false;if(typeof d=="string")p=gt(d),d.length>0&&i.push({type:"content",content:{type:"text",text:d}});else if(Array.isArray(d))for(let u of d){let g=ft(u);g&&(g.type==="content"&&g.content.type==="text"&>(g.content.text)&&(p=true),i.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:l,status:p?"failed":"completed",content:i}}]}function o(a){let l=a.type,d=a.payload??{},i=[];switch(l){case "TextPart":{let p=d.text;typeof p=="string"&&p.length>0&&i.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:p}}});break}case "ThinkPart":{let p=d.think;typeof p=="string"&&p.length>0&&i.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p}}});break}case "ToolCall":{let p=d.function?.name??"",u=n(d.id,p),g=d.function;if(!g)break;let f;try{f=g.arguments?JSON.parse(g.arguments):{};}catch{f=g.arguments;}if(Zt(p)){let k=Xt(f);k.length>0&&i.push({update:{sessionUpdate:"plan",entries:k}}),t.add(u);break}let{title:m,kind:h,toolContent:y,locations:w}=c(p,typeof f=="object"&&f!==null?f:{});i.push({update:{sessionUpdate:"tool_call",toolCallId:u,title:m,kind:h,status:"pending",rawInput:f,content:y,locations:w}});break}case "ToolResult":{let p=d.tool_call_id;if(typeof p!="string"||p.length===0)break;if(t.has(p)){t.delete(p);break}let u=d.return_value??d.content,g=[],f=d.is_error===true;if(u&&typeof u=="object"&&!Array.isArray(u)){let m=u;f=f||m.type==="ToolError"||m.is_error===true,g.push(...ut(m.output)),g.length===0&&typeof m.message=="string"&&m.message.length>0&&g.push({type:"content",content:{type:"text",text:m.message}}),g.length===0&&g.push(...ut(u));}else g.push(...ut(u));f=f||Wr(g),i.push({update:{sessionUpdate:"tool_call_update",toolCallId:p,status:f?"failed":"completed",content:g}});break}default:return null}return i.length>0?i:null}function c(a,l){let d=Gr[a]||"other",i=[],p=[],u=a;switch(a){case "Read":case "ReadFile":{let g=l.path??l.file_path;u=`Read ${g||"file"}`,g&&p.push({path:g});break}case "ReadMediaFile":{let g=l.path??l.file_path;u=`Read media ${g||"file"}`,g&&p.push({path:g});break}case "Write":case "WriteFile":{let g=l.path??l.file_path;u=`Write ${g||"file"}`,g&&(p.push({path:g}),typeof l.content=="string"&&i.push({type:"diff",path:g,oldText:null,newText:l.content}));break}case "Edit":case "StrReplaceFile":{let g=l.path??l.file_path;u=`Edit ${g||"file"}`,g&&p.push({path:g});break}case "Bash":case "Shell":u=l.command?`\`${l.command}\``:"Run command";break;case "Glob":u=`Find ${l.pattern||"files"}`,l.path&&p.push({path:l.path});break;case "Grep":u=`grep "${l.pattern||""}"`,l.path&&p.push({path:l.path});break;case "WebSearch":case "SearchWeb":u=l.query?`"${l.query}"`:"Web search";break;case "FetchURL":u=l.url?`Fetch ${l.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":u=l.description||"Subagent task";break;case "Think":u=l.thought||"Thinking";break;case "CreateSubagent":u=l.name?`Subagent: ${l.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":u="Update todos";break;default:u=a;}return {title:u,kind:d,toolContent:i,locations:p}}}var Hr={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 qr(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function Yr(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 Qr(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function tn(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:Yr(e.status),priority:Qr(e.priority)}}).filter(e=>e!==null):[]}function Zr(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let a=qr(r);return a?{type:"content",content:{type:"image",data:a.data,mimeType:a.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function Xr(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 ht(){return function(c){let a;try{a=JSON.parse(c);}catch{return null}if(!a||typeof a!="object")return null;let l=a.sessionID,d=[];switch(a.type){case "step_start":case "step_finish":return null;case "text":{let i=t(a);i&&d.push({sessionId:l,update:i});break}case "reasoning":{let i=e(a);i&&d.push({sessionId:l,update:i});break}case "tool_use":{let i=n(a);for(let p of i)d.push({sessionId:l,update:p});break}case "error":{let i=r(a);i&&d.push({sessionId:l,update:i});break}default:return null}return d.length>0?d:null};function t(o){let c=o.part?.text;return typeof c!="string"||c.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}function e(o){let c=o.part?.text;return typeof c!="string"||c.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c}}}function n(o){let c=o.part;if(!c)return [];let a=typeof c.callID=="string"?c.callID:"";if(a.length===0)return [];let l=typeof c.tool=="string"?c.tool.toLowerCase():"",d=typeof c.state=="object"&&c.state?c.state:{},i=typeof d.input=="object"&&d.input?d.input:{},p=d.status,u=d.title??d.metadata?.description??l,g=d.metadata?.exit,{kind:f,content:m,locations:h}=s(l,i),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:a,title:u,kind:f,status:"pending",rawInput:i,content:m,locations:h}),l==="todowrite"){let b=tn(i.todos);if(b.length===0&&typeof d.output=="string")try{b=tn(JSON.parse(d.output));}catch{}b.length>0&&y.push({sessionUpdate:"plan",entries:b});}let w=ei(p,g);if(w==="pending")return y;let k=Xr(p,d),S=[];if(typeof k=="string"&&k.length>0&&S.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
|
|
11
|
+
\`\`\``}}),{sessionUpdate:"tool_call_update",toolCallId:c,status:a==="success"?"completed":"failed",content:o}}function r(s){let c=s.severity,a=s.message;return a?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`${c==="warning"?"\u26A0\uFE0F Warning":"\u274C Error"}: ${a}`}}:null}function i(s,c){let a=ks[s]||"other",l=[],d=[],o=s;switch(s){case "read_file":o=`Read ${c.absolute_path||c.file_path||"file"}`,(c.absolute_path||c.file_path)&&d.push({path:c.absolute_path||c.file_path});break;case "write_file":o=`Write ${c.file_path||"file"}`,c.file_path&&(d.push({path:c.file_path}),l.push({type:"diff",path:c.file_path,oldText:null,newText:c.content||""}));break;case "edit_file":o=`Edit ${c.file_path||"file"}`,c.file_path&&d.push({path:c.file_path});break;case "replace":o=`Edit ${c.file_path||"file"}`,c.file_path&&(d.push({path:c.file_path}),(c.old_string!==void 0||c.new_string!==void 0)&&l.push({type:"diff",path:c.file_path,oldText:c.old_string||"",newText:c.new_string||""}));break;case "run_shell_command":case "shell":o=c.command?`\`${c.command}\``:"Run command",c.description&&l.push({type:"content",content:{type:"text",text:c.description}});break;case "brave_web_search":case "web_search":case "google_web_search":o=c.query?`"${c.query}"`:"Web search";break;case "web_fetch":o=c.prompt?`Fetch: ${c.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":o=`Find ${c.pattern||"files"}`,c.dir_path&&d.push({path:c.dir_path});break;case "grep":case "search_file_content":o=`grep "${c.pattern||c.query||""}"`;break;case "list_directory":o=`List ${c.dir_path||c.path||"directory"}`,(c.dir_path||c.path)&&d.push({path:c.dir_path||c.path});break;case "read_many_files":o=`Read ${c.include?.length||"multiple"} files`,Array.isArray(c.include)&&c.include.forEach(u=>d.push({path:u}));break;case "delegate_to_agent":o=c.agent_name?`Agent: ${c.agent_name}`:"Delegate to agent";break;case "write_todos":o="Update todos";break;case "save_memory":o=c.fact?`Remember: "${c.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":o=c.name?`Activate skill: ${c.name}`:"Activate skill";break;default:o=s;}return {title:o,kind:a,content:l,locations:d}}}var Cs={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function Gn(t){return t==="TodoList"||t==="SetTodoList"}function Kt(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function zn(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",i=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:i}:null}function jt(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=zn(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 Ft(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 r=jt(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=jt(t);n&&e.push(n);}return e}function Es(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&Kt(e.content.text))}function _s(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=zn(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 Ts(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function Vn(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 r=n.title;if(typeof r!="string"||r.length===0)return null;let i=n.status;return {content:r,status:Ts(i),priority:"medium"}}).filter(n=>n!==null):[]}function Gt(){let t=new Set,e=0;function n(a,l){return typeof a=="string"&&a.length>0?a:(e+=1,`kimi_${l.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(l){let d;try{d=JSON.parse(l);}catch{return null}if(!d||typeof d!="object")return null;let o=d.role;return "_meta"in d||"_prompt"in d||o==="meta"?null:o==="assistant"?r(d):o==="tool"?i(d):typeof d.type=="string"&&"payload"in d?s(d):null};function r(a){let l=[],d=a.content,o=a.tool_calls;if(typeof d=="string"&&d.length>0)l.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d}}});else if(Array.isArray(d))for(let u of d){let p=_s(u);p&&l.push(p);}if(Array.isArray(o))for(let u of o){if(!u||typeof u!="object")continue;let p=u.function;if(!p)continue;let g=p.name??"",f=n(u.id,g),m;try{m=p.arguments?JSON.parse(p.arguments):{};}catch{m=p.arguments;}if(Gn(g)){let S=Vn(m);S.length>0&&l.push({update:{sessionUpdate:"plan",entries:S}}),t.add(f);continue}let{title:h,kind:y,toolContent:w,locations:k}=c(g,typeof m=="object"&&m!==null?m:{});l.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,kind:y,status:"pending",rawInput:m,content:w,locations:k}});}return l.length>0?l:null}function i(a){let l=a.tool_call_id;if(typeof l!="string"||l.length===0)return null;if(t.has(l))return t.delete(l),null;let d=a.content,o=[],u=false;if(typeof d=="string")u=Kt(d),d.length>0&&o.push({type:"content",content:{type:"text",text:d}});else if(Array.isArray(d))for(let p of d){let g=jt(p);g&&(g.type==="content"&&g.content.type==="text"&&Kt(g.content.text)&&(u=true),o.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:l,status:u?"failed":"completed",content:o}}]}function s(a){let l=a.type,d=a.payload??{},o=[];switch(l){case "TextPart":{let u=d.text;typeof u=="string"&&u.length>0&&o.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:u}}});break}case "ThinkPart":{let u=d.think;typeof u=="string"&&u.length>0&&o.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:u}}});break}case "ToolCall":{let u=d.function?.name??"",p=n(d.id,u),g=d.function;if(!g)break;let f;try{f=g.arguments?JSON.parse(g.arguments):{};}catch{f=g.arguments;}if(Gn(u)){let k=Vn(f);k.length>0&&o.push({update:{sessionUpdate:"plan",entries:k}}),t.add(p);break}let{title:m,kind:h,toolContent:y,locations:w}=c(u,typeof f=="object"&&f!==null?f:{});o.push({update:{sessionUpdate:"tool_call",toolCallId:p,title:m,kind:h,status:"pending",rawInput:f,content:y,locations:w}});break}case "ToolResult":{let u=d.tool_call_id;if(typeof u!="string"||u.length===0)break;if(t.has(u)){t.delete(u);break}let p=d.return_value??d.content,g=[],f=d.is_error===true;if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p;f=f||m.type==="ToolError"||m.is_error===true,g.push(...Ft(m.output)),g.length===0&&typeof m.message=="string"&&m.message.length>0&&g.push({type:"content",content:{type:"text",text:m.message}}),g.length===0&&g.push(...Ft(p));}else g.push(...Ft(p));f=f||Es(g),o.push({update:{sessionUpdate:"tool_call_update",toolCallId:u,status:f?"failed":"completed",content:g}});break}default:return null}return o.length>0?o:null}function c(a,l){let d=Cs[a]||"other",o=[],u=[],p=a;switch(a){case "Read":case "ReadFile":{let g=l.path??l.file_path;p=`Read ${g||"file"}`,g&&u.push({path:g});break}case "ReadMediaFile":{let g=l.path??l.file_path;p=`Read media ${g||"file"}`,g&&u.push({path:g});break}case "Write":case "WriteFile":{let g=l.path??l.file_path;p=`Write ${g||"file"}`,g&&(u.push({path:g}),typeof l.content=="string"&&o.push({type:"diff",path:g,oldText:null,newText:l.content}));break}case "Edit":case "StrReplaceFile":{let g=l.path??l.file_path;p=`Edit ${g||"file"}`,g&&u.push({path:g});break}case "Bash":case "Shell":p=l.command?`\`${l.command}\``:"Run command";break;case "Glob":p=`Find ${l.pattern||"files"}`,l.path&&u.push({path:l.path});break;case "Grep":p=`grep "${l.pattern||""}"`,l.path&&u.push({path:l.path});break;case "WebSearch":case "SearchWeb":p=l.query?`"${l.query}"`:"Web search";break;case "FetchURL":p=l.url?`Fetch ${l.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":p=l.description||"Subagent task";break;case "Think":p=l.thought||"Thinking";break;case "CreateSubagent":p=l.name?`Subagent: ${l.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":p="Update todos";break;default:p=a;}return {title:p,kind:d,toolContent:o,locations:u}}}var Rs={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 Ps(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",i=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:i}:null}function Is(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 As(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function Wn(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:Is(e.status),priority:As(e.priority)}}).filter(e=>e!==null):[]}function Os(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let a=Ps(r);return a?{type:"content",content:{type:"image",data:a.data,mimeType:a.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function Ms(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 Ds(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function Vt(){return function(c){let a;try{a=JSON.parse(c);}catch{return null}if(!a||typeof a!="object")return null;let l=a.sessionID,d=[];switch(a.type){case "step_start":case "step_finish":return null;case "text":{let o=t(a);o&&d.push({sessionId:l,update:o});break}case "reasoning":{let o=e(a);o&&d.push({sessionId:l,update:o});break}case "tool_use":{let o=n(a);for(let u of o)d.push({sessionId:l,update:u});break}case "error":{let o=r(a);o&&d.push({sessionId:l,update:o});break}default:return null}return d.length>0?d:null};function t(s){let c=s.part?.text;return typeof c!="string"||c.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}}function e(s){let c=s.part?.text;return typeof c!="string"||c.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c}}}function n(s){let c=s.part;if(!c)return [];let a=typeof c.callID=="string"?c.callID:"";if(a.length===0)return [];let l=typeof c.tool=="string"?c.tool.toLowerCase():"",d=typeof c.state=="object"&&c.state?c.state:{},o=typeof d.input=="object"&&d.input?d.input:{},u=d.status,p=d.title??d.metadata?.description??l,g=d.metadata?.exit,{kind:f,content:m,locations:h}=i(l,o),y=[];if(y.push({sessionUpdate:"tool_call",toolCallId:a,title:p,kind:f,status:"pending",rawInput:o,content:m,locations:h}),l==="todowrite"){let b=Wn(o.todos);if(b.length===0&&typeof d.output=="string")try{b=Wn(JSON.parse(d.output));}catch{}b.length>0&&y.push({sessionUpdate:"plan",entries:b});}let w=Ds(u,g);if(w==="pending")return y;let k=Ms(u,d),S=[];if(typeof k=="string"&&k.length>0&&S.push({type:"content",content:{type:"text",text:w==="failed"?`\`\`\`
|
|
34
12
|
${k}
|
|
35
|
-
\`\`\``:k}}),Array.isArray(d.attachments))for(let b of d.attachments){let v=
|
|
36
|
-
${
|
|
37
|
-
\`\`\``:
|
|
13
|
+
\`\`\``:k}}),Array.isArray(d.attachments))for(let b of d.attachments){let v=Os(b);v&&S.push(v);}return y.push({sessionUpdate:"tool_call_update",toolCallId:a,status:w,content:S}),y}function r(s){let c=s.error?.name??"Error",a=s.error?.data?.message??s.error?.message??"Unknown error";return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:`\u274C ${c}: ${a}`}}}function i(s,c){let a=Rs[s]||"other",l=[],d=[];switch(s){case "read":{let o=c.filePath??c.path;if(o){let u=c.offset;d.push({path:o,line:typeof u=="number"&&Number.isFinite(u)?Math.max(0,u-1):void 0});}break}case "write":{let o=c.filePath??c.path;o&&(d.push({path:o}),typeof c.content=="string"&&l.push({type:"diff",path:o,oldText:null,newText:c.content}));break}case "edit":case "multiedit":{let o=c.filePath??c.path;o&&(d.push({path:o}),s==="edit"&&(c.oldString!==void 0||c.newString!==void 0)&&l.push({type:"diff",path:o,oldText:c.oldString??"",newText:c.newString??""}));break}case "apply_patch":break;case "bash":{let o=c.command;o&&c.description?l.push({type:"content",content:{type:"text",text:c.description}}):o&&l.push({type:"content",content:{type:"text",text:o}});break}case "glob":case "list":{let o=c.path;o&&d.push({path:o});break}case "grep":{let o=c.path;o&&d.push({path:o});break}case "codesearch":case "websearch":{let o=c.query;o&&l.push({type:"content",content:{type:"text",text:o}});break}case "webfetch":{let o=c.url;o&&l.push({type:"content",content:{type:"text",text:o}});break}case "task":{let o=c.description;o&&l.push({type:"content",content:{type:"text",text:o}});break}}return {kind:a,content:l,locations:d}}}var Us={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 Ze(){let t=new Map,e=new Map;return function(o){let u;try{u=JSON.parse(o);}catch{return null}if(!u||typeof u!="object")return null;let p=u;if("_meta"in p||"_prompt"in p)return null;let g=p.session_id||void 0,f=[];switch(p.type){case "assistant":{let m=n(p);for(let h of m)f.push({sessionId:g,update:h});break}case "stream_event":{let m=r(p);for(let h of m)f.push({sessionId:g,update:h});break}case "user":{let m=i(p);for(let h of m)f.push({sessionId:g,update:h});break}case "system":case "result":return null;default:return null}return f.length>0?f:null};function n(d){let o=[],u=d.message?.content;if(!Array.isArray(u))return o;for(let p of u){let g=s(p);o.push(...g);}return o}function r(d){let o=[],u=d.event;if(!u)return o;switch(u.type){case "content_block_start":{let p=u.index??0,g=u.content_block;g&&(t.set(p,g),g.type==="tool_use"&&e.set(p,""));break}case "content_block_delta":{let p=u.index??0,g=u.delta,f=t.get(p);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&&f?.type==="tool_use"){let m=e.get(p)||"";e.set(p,m+g.partial_json);}break}case "content_block_stop":{let p=u.index??0,g=t.get(p);if(g&&!(g.type==="text"&&g.text)){if(!(g.type==="thinking"&&g.thinking)){if(g.type==="tool_use"){let f=g,m=e.get(p)||"";e.delete(p);let h=f.input;if(m)try{h=JSON.parse(m);}catch{}let y={...f,input:h},w=c(y);w&&o.push(w);}else if(g.type==="tool_result"){let f=a(g);f&&o.push(f);}}}t.delete(p);break}}return o}function i(d){let o=d.message?.content,u=[];if(typeof o=="string")return u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:o}}),u;if(Array.isArray(o)){for(let p of o)if(p.type==="text")u.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:p.text}});else if(p.type==="tool_result"){let g=a(p);g&&u.push(g);}}return u}function s(d){switch(d.type){case "text":return d.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:d.text}}]:[];case "thinking":return d.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:d.thinking}}]:[];case "tool_use":{let o=c(d);return o?[o]:[]}case "tool_result":{let o=a(d);return o?[o]:[]}}}function c(d){let o=d.id,u=d.name,p=d.input;if(u==="TodoWrite"&&Array.isArray(p?.todos))return {sessionUpdate:"plan",entries:p.todos.map(y=>({content:y.content,status:y.status||"pending",priority:"medium"}))};let{title:g,kind:f,content:m,locations:h}=l(u,p||{});return {sessionUpdate:"tool_call",toolCallId:o,title:g,kind:f,status:"pending",rawInput:p,content:m,locations:h}}function a(d){let o=d.tool_use_id,u=d.is_error??false,p=d.content,g=[];if(typeof p=="string"&&p.length>0)g.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
14
|
+
${p}
|
|
15
|
+
\`\`\``:p}});else if(Array.isArray(p)){for(let f of p)if(f.type==="text"){let m=f.text;g.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
38
16
|
${m}
|
|
39
|
-
\`\`\``:m}});}}return {sessionUpdate:"tool_call_update",toolCallId:
|
|
40
|
-
`),
|
|
41
|
-
Try
|
|
42
|
-
Try
|
|
43
|
-
Try installing: npm install @evolvingmachines/
|
|
44
|
-
Try
|
|
45
|
-
1. Set ${
|
|
46
|
-
2. Set ${
|
|
47
|
-
3. Set ${
|
|
48
|
-
4. Set ${
|
|
49
|
-
5. Pass sandbox explicitly: .withSandbox(provider)`)}function
|
|
17
|
+
\`\`\``:m}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:g}}function l(d,o){let u=Us[d]||"other",p=[],g=[],f=d;switch(d){case "Read":case "read_file":f=`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":f=`Write ${o.file_path||"file"}`,o.file_path&&(g.push({path:o.file_path}),p.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":f=`Edit ${o.file_path||"file"}`,o.file_path&&g.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":f=o.command?`\`${o.command}\``:"Run command",o.description&&p.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":f=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=o.query?`"${o.query}"`:"Web search";break;case "Glob":f=`Find ${o.pattern||"files"}`,o.path&&g.push({path:o.path});break;case "Grep":f=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${o.path||"directory"}`,o.path&&g.push({path:o.path});break;case "Task":f=o.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=d;}return {title:f,kind:u,content:p,locations:g}}}function Hn(t){return Ze()(t)}function qn(t){return !!t&&t.sessionUpdate!=="error"}function J(t){switch(t){case "claude":return Je();case "codex":return Ye();case "gemini":return Qe();case "qwen":return Ze();case "kimi":return Gt();case "opencode":return Vt();case "droid":return Xe();default:return ()=>null}}function $s(t,e){let n=e.trim();return n?J(t)(n):null}function Bs(t,e){let n=[],r=e.split(`
|
|
18
|
+
`),i=J(t);for(let s of r){let c=s.trim();if(!c)continue;let a=i(c);a&&n.push(...a);}return n}function D(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function ee(t){return JSON.stringify(Ls(t,{target:"jsonSchema7"}),null,2)}function te(t){return JSON.stringify(t,null,2)}function Jn(t,e=false){let n={};function r(i,s){for(let c of $.readdirSync(i)){let a=U.join(i,c),l=s?`${s}/${c}`:c;$.statSync(a).isDirectory()?e&&r(a,l):n[l]=$.readFileSync(a);}}return r(t,""),n}function Yn(t,e){let n=U.resolve(t),r=n.endsWith(U.sep)?n:n+U.sep;for(let[i,s]of Object.entries(e)){let c=U.resolve(n,i);if(!c.startsWith(r))throw new Error(`Unsafe file path escapes target directory: ${i}`);let a=U.dirname(c);$.mkdirSync(a,{recursive:true});let l;s instanceof ArrayBuffer||s instanceof Uint8Array?l=Buffer.from(s):l=s,$.writeFileSync(c,l);}}var H=class extends Error{field;constructor(e,n){super(n),this.name="EvolveConfigError",this.field=e;}};function Xn(t){return typeof t=="string"&&t.trim()!==""}function zt(t){return t==null?String(t):JSON.stringify(t)}function ye(t){if(!t)return;if(t.type!==void 0&&!_t(t.type))throw new H("type",`Evolve agent config: unknown agent type ${zt(t.type)}. Valid types: ${Object.keys(Z).join(", ")}.`);let e=t.type??m;if(t.model!==void 0&&!Xn(t.model))throw new H("model",`Evolve agent config: "model" is empty (${zt(t.model)}). Pass a model id such as "${I(e).defaultModel}", or omit model entirely to use ${e}'s default.`)}function Wt(t){if(!t||!Xn(t.prompt))throw new H("prompt",`run() requires a non-empty "prompt" string, received ${zt(t?.prompt)}.`)}function Ht(t){if(t){for(let e of x$1)if(e in t)throw new H(`observability.${e}`,`Evolve observability metadata: "${e}" is reserved for session identity and would split this run across two dashboard sessions. Reserved keys: ${x$1.join(", ")}. Use a different key, or set the session tag with .withSessionTagPrefix().`)}}function tt(t){if(t.externalGateway){if(t.providerApiKey||t.providerBaseUrl||t.oauthToken)throw new Error("externalGateway cannot be combined with providerApiKey/providerBaseUrl/oauthToken (direct mode)");if(t.apiKey)throw new Error("externalGateway cannot be combined with apiKey (Evolve gateway mode)")}}function Ns(t){let e=t.replace(/^~/,process.env.HOME||"");if(!$.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return $.readFileSync(e,"utf-8")}function nt(t){let e=t?.type??m,n=I(e);if(t?.externalGateway){tt(t);let{apiKey:c,baseUrl:a,revoke:l}=t.externalGateway;if(!c||!a||typeof l!="function")throw new Error("externalGateway requires apiKey, baseUrl, and a revoke() function");return {type:e,apiKey:c,baseUrl:a,isDirectMode:true,externalGateway:{revoke:l},model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize}}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,maxContextSize:t.maxContextSize}}if(t?.providerApiKey){let c=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,a=t.providerBaseUrl??c??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:a,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize};let r=process.env[h];if(r)return {type:e,apiKey:r,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize};if(n.providerEnvMap){let a=(t?.model??n.defaultModel)?.split("/")[0],l=a?n.providerEnvMap[a]:void 0,d=l?process.env[l.keyEnv]:void 0;if(d){let u=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:u,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}}let i=process.env[n.apiKeyEnv];if(i){let a=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:i,baseUrl:a,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}if(n.oauthEnv){let c=process.env[n.oauthEnv];if(c){if(n.oauthFileName){let a=Ns(c);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:a,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}return {type:e,apiKey:c,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize}}}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 ${h} / ${n.apiKeyEnv} env var.`)}function Fs(t){return `e2b_${Buffer.from(t,"utf8").toString("hex")}`}var er=new WeakSet;function qt(t){return er.add(t),t}function we(t){return er.has(t)}function Qn(t,e){return new Error(`${h} is set but ${t} failed to load.
|
|
19
|
+
Try installing: ${e}`)}function Zn(t){return t.message?.includes("Cannot find module")||t.message?.includes("MODULE_NOT_FOUND")}function Jt(t,e){if(!e||e.timeoutMs===void 0&&e.resources===void 0)return t;let n=t.create.bind(t);return t.create=(r={})=>n({...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.resources!==void 0?{resources:e.resources}:{},...r}),t}async function be(t,e$1="e2b",n){let r=t||process.env[h];if(!r)throw new Error(`${h} is required for Evolve-managed sandbox features`);if(!c.includes(e$1))throw new Error(`Unknown managed sandbox provider "${e$1}". Supported: ${c.join(", ")}`);if(e$1==="daytona")try{let{createDaytonaProvider:i}=await import('@evolvingmachines/daytona');return Jt(qt(i({apiKey:r,apiUrl:d("daytona"),managedToolboxUrl:e()})),n)}catch(i){let s=i;throw Zn(s)?Qn("@evolvingmachines/daytona","npm install @evolvingmachines/daytona"):s}if(e$1==="modal"){let{ManagedModalProvider:i}=await import('./managed-modal-CRZFDIRG.js');return Jt(qt(new i({apiKey:r,baseUrl:d("modal")})),n)}try{let{createE2BProvider:i}=await import('@evolvingmachines/e2b');return Jt(qt(i({apiKey:Fs(r),apiUrl:f()})),n)}catch(i){let s=i;throw Zn(s)?Qn("@evolvingmachines/e2b","npm install @evolvingmachines/sdk"):s}}function Ks(t="e2b",e){let n=typeof e=="string"?{apiKey:e}:e??{},{apiKey:r,...i}=n;return be(r,t,i)}async function Yt(){let t=process.env[i];if(t)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===f()&&delete process.env.E2B_API_URL,s({apiKey:t})}catch(s){let c=s;throw c.message?.includes("Cannot find module")||c.message?.includes("MODULE_NOT_FOUND")?new Error(`${i} is set but @evolvingmachines/e2b failed to load.
|
|
20
|
+
Try reinstalling: npm install @evolvingmachines/sdk`):c}let e=process.env[j$1];if(e)try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return s({apiKey:e})}catch(s){let c=s;throw c.message?.includes("Cannot find module")||c.message?.includes("MODULE_NOT_FOUND")?new Error(`${j$1} is set but @evolvingmachines/daytona failed to load.
|
|
21
|
+
Try installing: npm install @evolvingmachines/daytona`):c}let n=process.env[k],r=process.env[l];if(n&&r)try{let{createModalProvider:s}=await import('@evolvingmachines/modal');return s({tokenId:n,tokenSecret:r})}catch(s){let c=s;throw c.message?.includes("Cannot find module")||c.message?.includes("MODULE_NOT_FOUND")?new Error(`${k} is set but @evolvingmachines/modal failed to load.
|
|
22
|
+
Try installing: npm install @evolvingmachines/modal`):c}let i$1=process.env[h];if(i$1)return be(i$1);throw new Error(`No sandbox provider configured. Either:
|
|
23
|
+
1. Set ${h} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
24
|
+
2. Set ${i} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
25
|
+
3. Set ${j$1} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
26
|
+
4. Set ${k} and ${l} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
27
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function js(t){return new Promise(e=>setTimeout(e,t))}async function O(t,e,n=0){let r=Gs(e),i=e?.onItemRetry,s=null,c=0,a=r.backoffMs;for(;c<r.maxAttempts;){if(c++,s=await t(c),!r.retryOn(s))return s;if(c>=r.maxAttempts)break;if(i){let l=s.error??"Unknown error";i(n,c,l);}await js(a),a*=r.backoffMultiplier;}return s}function Gs(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var tr=`## FILESYSTEM INSTRUCTIONS:
|
|
50
28
|
|
|
51
29
|
You are running in a sandbox environment.
|
|
52
30
|
|
|
@@ -79,7 +57,7 @@ Examples:
|
|
|
79
57
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
80
58
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
81
59
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
82
|
-
`;var
|
|
60
|
+
`;var nr=`## FILESYSTEM INSTRUCTIONS:
|
|
83
61
|
|
|
84
62
|
You are running in a sandbox environment.
|
|
85
63
|
|
|
@@ -113,9 +91,9 @@ Examples:
|
|
|
113
91
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
114
92
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
115
93
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
116
|
-
`;var
|
|
94
|
+
`;var rr=`## SYSTEM PROMPT
|
|
117
95
|
|
|
118
|
-
{{systemPrompt}}`;var
|
|
96
|
+
{{systemPrompt}}`;var ir=`## STRUCTURED OUTPUT
|
|
119
97
|
|
|
120
98
|
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
121
99
|
|
|
@@ -133,13 +111,13 @@ You are free to:
|
|
|
133
111
|
But your final \`output/result.json\` MUST conform to the schema above.
|
|
134
112
|
|
|
135
113
|
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
136
|
-
### Never just state results as text.`;var
|
|
114
|
+
### Never just state results as text.`;var sr=`## BROWSER AUTOMATION
|
|
137
115
|
|
|
138
116
|
Actionbook is preconfigured for remote browser automation in this environment. When browser automation is needed, start sessions with \`actionbook browser start --session s1\`, then use normal Actionbook browser commands. Do not override the configured browser mode or browser endpoint unless the user explicitly asks.
|
|
139
|
-
`;var
|
|
117
|
+
`;var or=`## Browser Automation
|
|
140
118
|
|
|
141
119
|
The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
|
|
142
|
-
`;var
|
|
120
|
+
`;var ar=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
143
121
|
|
|
144
122
|
You are a judge. {{candidateCount}} AI workers attempted the same task independently. Your job is to analyze their solution attempts and pick the best one based on the evaluation criteria below.
|
|
145
123
|
|
|
@@ -169,7 +147,7 @@ You must judge their work based on:
|
|
|
169
147
|
5. Pick the best candidate (0-indexed)
|
|
170
148
|
|
|
171
149
|
**IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
|
|
172
|
-
`;var
|
|
150
|
+
`;var cr=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
173
151
|
|
|
174
152
|
You are a quality verifier. An AI worker produced output for a task. Your job is to verify whether the output meets the specified quality criteria.
|
|
175
153
|
|
|
@@ -202,14 +180,14 @@ The output must satisfy:
|
|
|
202
180
|
**IMPORTANT:** Be thorough and fair. Cite specific evidence. If the output generally achieves the goal with minor issues, consider passing. Only fail if there are significant problems that violate the criteria.
|
|
203
181
|
|
|
204
182
|
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
205
|
-
`;var
|
|
183
|
+
`;var lr=`### CONTEXT STRUCTURE
|
|
206
184
|
|
|
207
185
|
\`\`\`
|
|
208
186
|
{{fileTree}}
|
|
209
187
|
\`\`\`
|
|
210
188
|
|
|
211
189
|
Examine all files within each item folder before producing your output.
|
|
212
|
-
`;var
|
|
190
|
+
`;var dr="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var ur="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var pr=`{{originalPrompt}}
|
|
213
191
|
|
|
214
192
|
## IMPORTANT: Previous Attempt Failed Verification
|
|
215
193
|
|
|
@@ -218,38 +196,410 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
218
196
|
{{feedback}}
|
|
219
197
|
|
|
220
198
|
Make sure your output addresses all the feedback points above.
|
|
221
|
-
`;var
|
|
199
|
+
`;var gr=tr,fr=nr,mr=rr,hr=ir,Xt=sr,yr=or,Qt=ar,wr=dr,Zt=cr,br=ur,vr=lr,en=pr;function j(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:n)}function tn(t){let e=t.mode==="swe"?fr:gr,n=j(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
|
|
222
200
|
|
|
223
201
|
|
|
224
202
|
${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
|
|
225
203
|
|
|
226
204
|
|
|
227
|
-
${
|
|
205
|
+
${j(mr,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=D(t.schema)?ee(t.schema):te(t.schema);n+=`
|
|
228
206
|
|
|
229
207
|
|
|
230
|
-
${
|
|
231
|
-
(empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,
|
|
232
|
-
`)}var
|
|
208
|
+
${j(hr,{schema:r}).trim()}`;}return n}function rt(t){let e=[...new Set(Object.keys(t).map(l=>l.split("/")[0]))].sort((l,d)=>l==="worker_task"?-1:d==="worker_task"?1:l.localeCompare(d));if(!e.length)return `context/
|
|
209
|
+
(empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,i=Object.keys(t).some(l=>l.startsWith("worker_task/input/")),s=[];e.forEach((l,d)=>{let o=d===e.length-1,u=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",p=o?" ":"\u2502 ";if(l==="worker_task"){s.push({line:`${u}${l}/`,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"}),r&&g.push({name:"schema.json",comment:"expected output schema"}),i&&g.push({name:"input/",comment:"worker input files"}),g.forEach((f,m)=>{let y=m===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";s.push({line:`${p}${y}${f.name}`,comment:f.comment});});}else if(l.startsWith("candidate_")){let g=l.replace("candidate_","");s.push({line:`${u}${l}/`,comment:`worker ${g} solution`});}else if(l==="worker_output")s.push({line:`${u}${l}/`,comment:"output to verify"});else if(l.startsWith("item_")){let g=l.replace("item_","");s.push({line:`${u}${l}/`,comment:`input ${g}`});}else s.push({line:`${u}${l}/`,comment:""});});let c=Math.max(...s.map(l=>l.line.length)),a=["context/"];for(let l of s)if(l.comment){let d=" ".repeat(c-l.line.length+3);a.push(`${l.line}${d}# ${l.comment}`);}else a.push(l.line);return a.join(`
|
|
210
|
+
`)}var Sr=join(homedir(),w),ve=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;warnedKeys=new Set;localQueue=Promise.resolve();dirReady=mkdir(Sr,{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=b(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=join(Sr,r),this.parser=J(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 r of n)this.bufferForDashboard(r);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let r of n)this.bufferForDashboard(r);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),this.isClosed=true,await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
|
|
233
211
|
`)?e:e+`
|
|
234
212
|
`;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)+`
|
|
235
|
-
`;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.
|
|
236
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=Wt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},zt));}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 r=1;r<=Oe;r++)try{let s=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(s.ok)return;if(s.status===429||s.status===401||s.status>=500){if(r===Oe){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(st*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===Oe?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(st*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Te();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.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)):{}}};function le(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function de(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed integrations");return e}async function pe(t){return await t.text().catch(()=>"")}function xt(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function _i(t){let e=Array.from(new Set((t??[]).map(n=>n.trim()).filter(Boolean)));if(e.length===0)throw new Error("withIntegrations() requires at least one app");return e}async function In(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:xt(t.userId),apps:_i(t.apps),tools:t.tools,accounts:t.accounts,keys:t.keys,authConfigs:t.authConfigs,sessionTag:t.sessionTag}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integrations session create failed (${e.status}): ${await pe(e)}`);let n=await e.json();if(!n.mcp?.url)throw new Error("Managed integrations response missing mcp.url");return {url:n.mcp.url,headers:n.mcp.headers??{}}}async function Ei(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:xt(t.userId),app:t.app,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration connect failed (${e.status}): ${await pe(e)}`);return await e.json()}async function Ti(t){let e=Array.from(new Set((t.userIds??[]).map(c=>xt(c))));if(e.length===0)throw new Error("Integration accounts.list() requires at least one userId");let n=new URLSearchParams({userIds:e.join(",")});t.app&&n.set("app",t.app),t.statuses?.length&&n.set("statuses",t.statuses.join(","));let r={Authorization:`Bearer ${de(t.apiKey)}`,accept:"application/json"},s=await fetch(`${le(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Managed integration status failed (${s.status}): ${await pe(s)}`);return ((await s.json()).accounts??[]).map(c=>({userId:String(c.userId??""),app:String(c.app??""),appName:typeof c.appName=="string"?c.appName:void 0,appIcon:typeof c.appIcon=="string"?c.appIcon:void 0,accountLabel:typeof c.accountLabel=="string"?c.accountLabel:void 0,status:String(c.status??""),accountId:typeof c.accountId=="string"?c.accountId:void 0,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:void 0}))}async function Ii(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account update failed (${e.status}): ${await pe(e)}`);return await e.json()}async function Ri(t){let e=await fetch(`${le(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${de(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account delete failed (${e.status}): ${await pe(e)}`);return await e.json()}var Rn={auth:Ei,accounts:{list:Ti,update:Ii,delete:Ri}};promisify(exec);var It=promisify(execFile),An=Symbol.for("evolve:awsSdkCache"),Mn=Symbol.for("evolve:s3ClientCache");var Ni=3600,Ki=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function ji(t){if(t.startsWith("s3://")){let s=t.slice(5),o=s.indexOf("/");return o===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,o),prefix:s.slice(o+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,r=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:r.join("/")};if(r.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:r[0],prefix:r.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function je(t,e,n,r){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:r}}let s=t?.bucket||"",o=t?.prefix||"",c=t?.endpoint;if(t?.url){let a=ji(t.url);s=s||a.bucket,o=o||a.prefix,c=c||a.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:o,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:c,credentials:t?.credentials,mode:"byok"}}function Ct(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 Vi(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 ue(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Gi(t,e){let n=D(t),r=Vi(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(a=>Ct(a)):[Ct(n.mcpConfig.settingsDir)],o=[...Ki.map(a=>`--exclude=${ue(a)}`),`--exclude=${ue(r+"/temp")}`,...(n.checkpointExcludes??[]).map(a=>`--exclude=${ue(Ct(a))}`)].join(" "),c=[ue(r+"/"),...s.map(a=>ue(a+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${o} ${c}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Z(){let t=globalThis[An];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,s]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[An]={s3:r,presigner:s},{s3:r,presigner:s}}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 fe(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[Mn];if(r?.key===n)return r.client;let{s3:s}=await Z(),o=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Mn]={client:o,key:n},o}async function jn(t,e,n){let{s3:r,presigner:s}=await Z(),o=await fe(t),c=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(o,c,{expiresIn:Ni})}async function $n(t,e){let{s3:n}=await Z(),r=await fe(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let o=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||o==="NotFound"||o==="NoSuchKey")return false;throw s}}async function Vn(t,e){let{s3:n}=await Z(),o=await(await(await fe(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!o)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(o)}async function Wi(t,e,n){let{s3:r}=await Z();await(await fe(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Gn(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function Wn(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function zi(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function zn(t,e,n,r){let s=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:r})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${o}`)}return s.json()}async function Ji(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${r}`)}return n.json()}async function Hi(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${r}`)}return n.json()}async function Rt(t,e,n,r,s){let o=new Date().toISOString(),c=Gi(n,r),a=await t.commands.run(c,{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint tar failed: ${a.stderr}`);let l=a.stdout.trim().split(`
|
|
237
|
-
`).pop()?.trim();if(!l||l.length!==64)throw new Error(`Invalid checkpoint hash: ${l}`);let d=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}),
|
|
238
|
-
`).pop()?.trim();if(l!==
|
|
239
|
-
`)){if(!
|
|
240
|
-
${n}`)}function
|
|
241
|
-
|
|
242
|
-
[browser]
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
`)}var ws=262144,bs=new Set(["low","medium","high","xhigh","max"]);function wr(t){if(t)return bs.has(t)?t:void 0}function vs(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var he=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;managedBrowserSession;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||Vt,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 r=this.createAjvValidator();this.compiledValidator=r.compile(this.jsonSchema);}catch(r){throw new Error(`Invalid JSON Schema: ${r.message}`)}}this.registry=D(e.type),this.sessionTag=hr(n.sessionTagPrefix||"evolve");}browserRuntimeInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl,sessionId:this.managedBrowserSession.sessionId,sessionTag:this.managedBrowserSession.sessionTag}}browserResponseInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl}}emitLifecycle(e,n){let r=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...r?{browser:r}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,r,s){let o=++this.nextOperationId;return this.activeOperationId=o,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),o}finalizeOperation(e,n,r,s="idle",o="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=o,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,o){let c=n==="run"?"run_background_complete":"command_background_complete",a=n==="run"?"run_background_failed":"command_background_failed",l=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,s,l,"interrupted");return}n==="run"&&o&&await this.writeDroidSessionState(o);let p=d.exitCode===0?c:a,u=d.exitCode===0?"idle":"error";this.finalizeOperation(e,s,p,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,a,"error");});}createAjvValidator(){let n={...He[this.schemaOptions?.mode||"loose"],...this.schemaOptions?.coerceTypes!==void 0&&{coerceTypes:this.schemaOptions.coerceTypes},...this.schemaOptions?.removeAdditional!==void 0&&{removeAdditional:this.schemaOptions.removeAdditional},...this.schemaOptions?.useDefaults!==void 0&&{useDefaults:this.schemaOptions.useDefaults},...this.schemaOptions?.allErrors!==void 0&&{allErrors:this.schemaOptions.allErrors}};return new fs({...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.integrations||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser||this.options.browserCredentials)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, integrations, plugins, context, files, systemPrompt, managed browser setup, and browser credentials"),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 {await this.ensureManagedBrowserSession(e);let r=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:r,workingDirectory:this.workingDir}),await this.setupManagedBrowser(this.sandbox),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(r){throw await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),r}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode){let n=ne(this.agentConfig.reasoningEffort),r=wr(this.agentConfig.reasoningEffort);e.KIMI_MODEL_NAME=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),e.KIMI_MODEL_API_KEY=this.agentConfig.apiKey,e.KIMI_MODEL_PROVIDER_TYPE="kimi",e.KIMI_MODEL_MAX_CONTEXT_SIZE=String(this.registry.spendTrackingTomlProvider?.maxContextSize??ws),e.KIMI_MODEL_DEFAULT_THINKING=n?"true":"false",e.KIMI_MODEL_THINKING_MODE=n?"on":"off",r&&(e.KIMI_MODEL_THINKING_EFFORT=r),this.agentConfig.baseUrl&&(e.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl);}else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){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],r=n?this.registry.providerEnvMap?.[n]:void 0,s=r?r.keyEnv:this.registry.apiKeyEnv,o=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:s;e[o]=this.agentConfig.apiKey;}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=G(this.registry.gatewayPath);this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[O]:this.sessionTag}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=n),e.EVOLVE_API_KEY=this.agentConfig.apiKey;}if(this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Mt(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.options.secrets){if(Object.prototype.hasOwnProperty.call(this.options.secrets,I))throw new Error(`${I} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);Object.assign(e,this.options.secrets);}if(!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let n=this.registry.customHeadersEnv,r=this.registry.customHeadersFormat||"newline";e[n]=yr(e[n],{[O]:this.sessionTag},r);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await ur(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Mt(this.options.managedBrowser.provider,this.managedBrowserSession);for(let r of n.directories)await e.files.makeDir(r);for(let r of n.files)await e.files.write(r.path,r.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await gr(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}buildGatewayConfigJson(e){let n=G(this.registry.gatewayPath),r=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),s={},o=this.options.secrets?.[this.registry.gatewayConfigEnv];if(o)try{s=JSON.parse(o);}catch{}let c=s.provider??{},a=c.litellm??{},l=a.options??{},d=a.models??{},i=d[r]??{},p=i.headers??{},u=this.agentConfig.type==="opencode"?qe(this.agentConfig.reasoningEffort):void 0,g=i.variants??{},f=u?g[u]??{}:void 0;return s.provider={...c,litellm:{...a,npm:"@ai-sdk/openai-compatible",options:{...l,baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{...d,[r]:{...i,name:r,headers:{...p,...e},...u?{variants:{...g,[u]:{...f,reasoningEffort:u}}}:{}}}}},JSON.stringify(s)}buildRunEnvs(e){if(this.agentConfig.isDirectMode)return;let n=this.registry.customHeadersEnv;if(n){let s=this.options.secrets?.[n],o=this.registry.customHeadersFormat||"newline";return {[n]:yr(s,{[O]:this.sessionTag,[L]:`${W}${e}`},o)}}let r=this.registry.spendTrackingEnvs;if(r)return {[r.sessionTagEnv]:this.sessionTag,[r.runTagEnv]:`${W}${e}`};if(this.registry.gatewayConfigEnv)return {[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[O]:this.sessionTag,[L]:`${W}${e}`})}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(o=>typeof o.sessionId=="string"&&o.sessionId.length>0)?.sessionId;if(r){this.droidSessionId=r;return}let s=this.extractDroidSessionId(e);s&&(this.droidSessionId=s);}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,r=n.sessionId??n.session_id;return typeof r=="string"&&r.length>0?r: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(mr);if(typeof n!="string")return;let r=JSON.parse(n);typeof r.sessionId=="string"&&r.sessionId.length>0&&(this.droidSessionId=r.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir("/home/user/.factory"),await e.files.write(mr,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 nr(this.agentConfig.type,e,this.options.plugins);}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge",s=r==="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 ${s}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let c=kt({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),a=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(a,c);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let o={...this.options.mcpServers};if(this.options.integrations){let c=await In({...this.options.integrations,sessionTag:this.sessionTag});o={...o,integrations:{type:"http",url:c.url,headers:c.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let c=await fr({apiKey:this.options.browserCredentials.apiKey,dashboardUrl:this.options.browserCredentials.dashboardUrl,browserSessionId:this.managedBrowserSession.id,sessionTag:this.managedBrowserSession.sessionTag,grantToken:this.managedBrowserSession.browserAuthGrantToken,config:this.options.browserCredentials.config});o={...o,[$t]:c};}Object.keys(o).length>0&&await ct(this.agentConfig.type,e,this.workingDir,o),!this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&this.agentConfig.type==="codex"&&await ot(e,this.agentConfig.baseUrl||G(),this.registry.spendTrackingEnvs),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Ce(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[O]:this.sessionTag}),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:r,targetDir:s}=n;await e.files.makeDir(s);for(let o of this.skills){let c=`cp -r ${r}/${o} ${s}/ 2>/dev/null || true`;await e.commands.run(c,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([o,c])=>({path:`${this.workingDir}/context/${o}`,data:c}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([o,c])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:c}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:ys(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:r,timeoutMs:s=se,background:o=false,checkpointComment:c}=e,{from:a}=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(a&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(a==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let b=await Pt(this.storage);if(!b)throw new Error('No checkpoints found for from: "latest".');a=b.id;}if(a){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");await this.ensureManagedBrowserSession(n);let b=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:b,workingDirectory:this.workingDir});let v=await Jn(this.sandbox,this.storage,a);if(await this.setupManagedBrowser(this.sandbox),v.agentType&&v.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${v.agentType}, current: ${this.agentConfig.type})`);let C=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==C)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${C})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let T=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!T}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=a,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(v){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),v}}let l=await this.getSandbox(n);if(await this.loadDroidSessionState(l),this.lastRunTimestamp=Date.now(),!this.sessionLogger){let b=this.options.sandboxProvider;this.sessionLogger=new ce({provider:b?.name||b?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:l.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}this.sessionLogger.writePrompt(r);let d=this.buildCommand(r),i=randomUUID(),p=this.buildRunEnvs(i);!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Ce(l,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[O]:this.sessionTag,[L]:`${W}${i}`}),this.agentConfig.type==="qwen"&&await Xe(l,ne(this.agentConfig.reasoningEffort)),!this.agentConfig.isDirectMode&&this.registry.spendTrackingTomlProvider&&await at(l,this.registry.spendTrackingTomlProvider,{[O]:this.sessionTag,[L]:`${W}${i}`},{baseUrl:vs(G(this.registry.gatewayPath)),apiKey:this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:ne(this.agentConfig.reasoningEffort),thinkingEffort:wr(this.agentConfig.reasoningEffort)}),!this.agentConfig.isDirectMode&&this.registry.droidGatewaySettings&&await Ee(l,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:`${G()}/v1`,apiKeyEnv:"EVOLVE_API_KEY"},{[O]:this.sessionTag,[L]:`${W}${i}`});let u="",g=z(this.agentConfig.type),f=b=>{u+=b;let v=u.split(`
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
`).filter(Boolean),a=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,l=[],d=`${r}/`;for(let f of c){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);a>0&&y<a||l.push(m);}let i={},p=await Promise.all(l.map(async f=>{try{let m=await n.files.read(f);return {relativePath:f.startsWith(d)?f.slice(d.length):f.split("/").pop()||f,content:m}}catch{return null}}));for(let f of p)f&&(i[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:i,data:null};let u=i["result.json"];if(!u)return {files:i,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(g);if(this.zodSchema){let m=this.zodSchema.safeParse(f);return m.success?{files:i,data:m.data}:{files:i,data:null,error:`Schema validation failed: ${m.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:i,data:f};{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:g}}}return {files:i,data:null}}catch(f){return {files:i,data:null,error:`Failed to parse result.json: ${f.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 Rt(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(),await this.closeManagedBrowserSession(),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,r=this.activeOperationKind,s=false;try{this.activeCommand?s=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(s=await this.sandbox.commands.kill(this.activeProcessId));}catch{s=false;}if(!s)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let o=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,o),s}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(r){n=r;}finally{await this.closeManagedBrowserSession();}if(n)throw n;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=hr(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 r=process.env.EVOLVE_DASHBOARD_URL||E,s=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${o}`)}return s}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(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),s=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(s)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let c=new URLSearchParams({tag:n,runId:e.runId}),l=await(await this.fetchSpend(c)).json();return this.normalizeRunCost(l,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,o=r.runs[s];if(!o)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return o}};function Ss(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function ks(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return e}async function xs(t){return await t.text().catch(()=>"")}async function br(t,e,n={}){let r=await fetch(`${Ss(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${ks(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await xs(r)}`);return r.status===204?{}:await r.json()}var We=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await br(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await br(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function Bt(t={}){return new We(t)}var ye=class extends EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._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){if(Object.prototype.hasOwnProperty.call(e,I))throw new Error(`${I} is reserved for Evolve-managed sandbox services and cannot be set with withSecrets()`);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={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=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}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=Rn;static browserCredentials=Dt;static browserProfiles=Bt;async initializeAgent(){let e=Fe(this.config.agent),n=this.config.sandbox??await yt();if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");let r={},s,o,c=this.config.skills,a;if(this.config.browser){let i=cr(this.config.browser);if(a=i,i.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');r=Nt(e.apiKey);}if((i.provider==="actionbook"||i.provider==="agent-browser")&&(c=lr(i.provider,c),i.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${i.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);s=i.provider==="actionbook"?wt:kn,o={provider:i.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,...i.profile?{profile:i.profile}:{}};}if(i.profile&&!i.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!a||a.provider!=="agent-browser"||!a.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let l=this.config.storage!==void 0?je(this.config.storage,!e.isDirectMode,E,e.isDirectMode?void 0:e.apiKey):void 0,d={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:{...r,...this.config.mcpServers},browserPrompt:s,managedBrowser:o,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:c,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E}:void 0,storage:l};this.agent=new he(e,d);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,s=this.listenerCount("lifecycle")>0;return {onStdout:e?o=>this.emit("stdout",o):void 0,onStderr:n?o=>this.emit("stderr",o):void 0,onContent:r?o=>this.emit("content",o):void 0,onLifecycle:s?o=>this.emit("lifecycle",o):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,...n.browser?{browser:n.browser}:{}});}async run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o}){if(s&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let c=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o},c)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.executeCommand(e,n,r)}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=Fe(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 At(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return At(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 Ut=class t{config;semaphore;constructor(e={}){let n=e.concurrency??jt;if(n>it)throw new Error(`concurrency=${n} exceeds max ${it}. 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,integrations:e.integrations},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:s,verify:o}=e,c=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs;if(s&&o)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((i,p)=>s?this.executeMapItemWithBestOf(i,r,p,a,e,l,c):o?this.executeMapItemWithVerify(i,r,p,a,e,l,c):c?P(u=>this.executeMapItem(i,r,p,a,e,l,u),c,p):this.executeMapItem(i,r,p,a,e,l)));return te.from(d)}async filter(e){let{items:n,prompt:r,condition:s,verify:o}=e,c=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>o?this.executeFilterItemWithVerify(p,r,u,a,e,l,c):c?P(g=>this.executeFilterItem(p,r,u,a,e,l,g),c,u):this.executeFilterItem(p,r,u,a,e,l))),i=[];for(let p of d)if(p.status==="error")i.push(p);else if(p.data!==null)try{s(p.data)?i.push(p):i.push({...p,status:"filtered"});}catch(u){i.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(i)}async reduce(e){let{items:n,prompt:r,verify:s}=e,o=e.retry??this.config.retry,c=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,l=[],d=[];n.forEach((S,b)=>{l.push(this.getFiles(S)),d.push(this.getIndex(S,b));});let i={};l.forEach((S,b)=>{Object.entries(S).forEach(([v,C])=>{i[`item_${d[b]}/${v}`]=C;});});let p=Ne(i),u=F(_n,{fileTree:p}),g=e.systemPrompt?`${u}
|
|
252
|
-
|
|
253
|
-
${e.systemPrompt}`:u,f=(S,b,v)=>({operationId:c,operation:"reduce",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:b,verifyRetry:v,...this.pipelineContextToMeta(e._pipelineContext)}),m=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,w=async(S,b,v,C)=>{let T=await this.semaphore.use(()=>this.execute(i,S,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:b,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:e.name,operationId:c,operation:"reduce",role:"worker",errorRetry:v,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),K=f(T,v,C&&C>1?C-1:void 0);return T.error?{status:"error",data:null,files:T.files,meta:K,error:T.error,rawData:T.rawData}:{status:"success",data:T.data,files:T.files,meta:K}},k=`${this.config.tag}-reduce`;return s?this.runWithVerification((S,b,v)=>w(S,b,void 0,v),{originalPrompt:r,inputFiles:i,verifyConfig:s,timeoutMs:a,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:c,baseTag:k,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?P(S=>{let b=S>1?S-1:void 0,v=b?`${k}-er${b}`:k;return w(r,v,b)},o):w(r,k)}async bestOf(e){let{item:n,prompt:r,config:s}=e,o=e.retry??this.config.retry,c=s.n??s.taskAgents?.length;if(c===void 0)throw new Error("bestOf requires n or taskAgents");if(c<2)throw new Error("bestOf requires n >= 2");let a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),i=s.mcpServers??this.config.mcpServers,p=s.judgeMcpServers??s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,g=s.judgeSkills??s.skills??this.config.skills,f=s.integrations??this.config.integrations,m=s.judgeIntegrations??s.integrations??this.config.integrations,h=await Promise.all(Array.from({length:c},async(b,v)=>{let C=o?await P(T=>this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:a,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:l,attempt:T}),o,v):await this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:a,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:i,skills:u,integrations:f,timeoutMs:l});return s.onCandidateComplete?.(0,v,C.status==="success"?"success":"error"),C})),y=o?await P(b=>this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m,attempt:b}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,integrations:m}),w=h.findIndex(b=>b.status==="success"),k=y.decision?.winner??(w>=0?w:0);s.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let S={operationId:a,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:c};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:S,candidates:h}}async execute(e,n,r){let s=null,o="",c=r.tagPrefix,a={},l=null,d,i,p={...this.config.agent,...r.agent};try{s=new ye().withAgent(p).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&s.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&s.withSystemPrompt(r.systemPrompt),r.mcpServers&&s.withMcpServers(r.mcpServers),r.skills?.length&&s.withSkills(r.skills),r.integrations&&s.withIntegrations(r.integrations),r.observability&&s.withObservability(r.observability),Object.keys(e).length>0&&s.withContext(e);let u=await s.run({prompt:n,timeoutMs:r.timeoutMs});o=u.sandboxId,c=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),a=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:r.schema?g?(l=g.data,g.error&&(d=g.error),g.rawData&&(i=g.rawData)):d="Failed to read output files from sandbox":l=a;}catch(u){if(d=u.message,s){c=s.getSessionTag()??r.tagPrefix;try{a=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:a,data:l,tag:c,sandboxId:o,error:d,rawData:i}}async executeMapItem(e,n,r,s,o,c,a=1){let l=this.getFiles(e),d=a>1?`${this.config.tag}-map-${r}-er${a-1}`:`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,l,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(l,i,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:d,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),m={operationId:s,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,s,o,c,a){let l=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=o.verify,p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=this.evaluatePrompt(n,l,r);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let m=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(l,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:y,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),S={operationId:s,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(k,S)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:l,verifyConfig:i,timeoutMs:c,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:a,itemIndex:r,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,o,c,a){let l=this.getFiles(e),d=`${this.config.tag}-map-${r}`,i=this.evaluatePrompt(n,l,r);if(i instanceof Error)return this.buildErrorResult(`Prompt function threw: ${i.message}`,{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let p=o.bestOf,u=p.n??p.taskAgents?.length;if(u===void 0||u<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:s,operation:"map",tag:d,sandboxId:"",itemIndex:r});let g=o.mcpServers??this.config.mcpServers,f=p.mcpServers??g,m=p.judgeMcpServers??p.mcpServers??g,h=o.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,k=o.integrations??this.config.integrations,S=p.integrations??k,b=p.judgeIntegrations??p.integrations??k,v=await Promise.all(Array.from({length:u},async(we,be)=>{let Ft=a?await P(kr=>this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:be,operationId:s,config:p,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:c,parentIndex:r,attempt:kr,_pipelineContext:o._pipelineContext}),a,be):await this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:be,operationId:s,config:p,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:c,parentIndex:r,_pipelineContext:o._pipelineContext});return p.onCandidateComplete?.(r,be,Ft.status==="success"?"success":"error"),Ft})),C=a?await P(we=>this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:v,config:p,timeoutMs:c,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:b,parentIndex:r,attempt:we,_pipelineContext:o._pipelineContext}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:v,config:p,timeoutMs:c,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:w,integrations:b,parentIndex:r,_pipelineContext:o._pipelineContext}),T=v.findIndex(we=>we.status==="success"),K=C.decision?.winner??(T>=0?T:0),Lt=v[K]??v[0];p.onJudgeComplete?.(r,K,C.decision?.reasoning??"Judge failed to provide reasoning");let Sr={operationId:s,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:u,...this.pipelineContextToMeta(o._pipelineContext)};return {...Lt,meta:{...Lt.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:r,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:K,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Sr,candidates:v}}}async executeFilterItem(e,n,r,s,o,c,a=1){let l=this.getFiles(e),d=a>1?`${this.config.tag}-filter-${r}-er${a-1}`:`${this.config.tag}-filter-${r}`,i=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,u=o.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(l,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:i,skills:p,integrations:u,tagPrefix:d,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(g,f,l)}async executeFilterItemWithVerify(e,n,r,s,o,c,a){let l=this.getFiles(e),d=`${this.config.tag}-filter-${r}`,i=o.verify,p=o.mcpServers??this.config.mcpServers,u=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=async(m,h,y)=>{let w=await this.semaphore.use(()=>this.execute(l,m,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:p,skills:u,integrations:g,tagPrefix:h,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),k={operationId:s,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(w,k,l)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:l,verifyConfig:i,timeoutMs:c,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:p,skills:u,integrations:g,operationId:s,baseTag:d,retry:a,itemIndex:r,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:o,config:c,timeoutMs:a,parentIndex:l,attempt:d=1,_pipelineContext:i}=e,p=l!==void 0?`${this.config.tag}-map-${l}-bestof-cand-${s}`:`${this.config.tag}-bestof-cand-${s}`,u=d>1?`${p}-er${d-1}`:p,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:c.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:u,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:l,role:"candidate",candidateIndex:s,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(i)}})),f={operationId:o,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:s,errorRetry:d>1?d-1:void 0,candidateIndex:s,...this.pipelineContextToMeta(i)};return this.buildResult(g,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((r,s)=>{r.status==="error"&&(n[`candidate_${s}/_failed.txt`]=`STATUS: FAILED
|
|
254
|
-
|
|
255
|
-
Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([o,c])=>{n[`candidate_${s}/${o}`]=c;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:o,parentIndex:c,attempt:a=1,_pipelineContext:l}=e,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-judge`:`${this.config.tag}-bestof-judge`,i=a>1?`${d}-er${a-1}`:d,p=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),u=Ne(p),g=F(bt,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:u}),f=z$1.object({winner:z$1.number().min(0).max(n.length-1),reasoning:z$1.string()}),m=await this.semaphore.use(()=>this.execute(p,xn,{systemPrompt:g,schema:f,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:i,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:c,role:"judge",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(l)}})),h=null;if(m.data&&!m.error)h=m.data;else if(m.rawData)try{let y=JSON.parse(m.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: ${m.error}`);}return {status:h?"success":"error",decision:h,tag:m.tag,sandboxId:m.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=z$1.object({passed:z$1.boolean(),reasoning:z$1.string(),feedback:z$1.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([r,s])=>{n[`worker_output/${r}`]=s;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:s,workerTag:o,retryAttempt:c=1,operation:a,itemIndex:l,attemptIndex:d,_pipelineContext:i}=e,p=c>1?`${o}-verifier-er${c-1}`:`${o}-verifier`,u=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,f=n.verifierIntegrations??e.integrations,m=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=Ne(m),y=F(vt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(m,Cn,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:u,skills:g,integrations:f,tagPrefix:p,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:a,itemIndex:l,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(i)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let S=JSON.parse(w.rawData);k={passed:!!S.passed,reasoning:S.reasoning??"Verification completed",feedback:S.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,n){return F(St,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:s,verifyConfig:o,timeoutMs:c,operationId:a,baseTag:l,retry:d,itemIndex:i=0,operation:p,_pipelineContext:u}=n,g=o.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let w=h>1?`${l}-vr${h-1}`:l,k=d?await P(v=>e(f,v>1?`${w}-er${v-1}`:w,h),d,i):await e(f,w,h);if(o.onWorkerComplete?.(i,h,k.status==="error"?"error":"success"),k.status==="error")return k;m=k;let S=d?await P(v=>this.executeVerify({inputFiles:s,outputFiles:k.files,taskPrompt:f,config:o,timeoutMs:c,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,retryAttempt:v,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:k.files,taskPrompt:f,config:o,timeoutMs:c,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,operation:p,itemIndex:i,attemptIndex:h,_pipelineContext:u}),b={operationId:a,operation:"verify",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)};if(o.onVerifierComplete?.(i,h,S.decision?.passed??false,S.decision?.feedback),S.decision?.passed)return {...k,verify:{passed:true,reasoning:S.decision.reasoning,verifyMeta:b,attempts:h}};if(h<g){let v=S.decision?.feedback??S.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(r,v);}}let y=h>1?`${l}-vr${h-1}`:l;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:a,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(u)},attempts:h}}}generateOperationId(){return randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,r){if(typeof e=="string")return e;try{return e(n,r)}catch(s){return s}}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)?q(e.schema):Y(e.schema)),Object.entries(e.inputFiles).forEach(([r,s])=>{n[`worker_task/input/${r}`]=s;}),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,r){let s=r??e.files;return e.error?{[J]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[J]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[J]:true,status:"error",data:null,files:{},meta:n,error:e}}};var ze=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}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 Je(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=randomBytes(8).toString("hex"),r=[],s=e,o=Date.now();for(let a=0;a<this.steps.length;a++){let l=this.steps[a],d=l.config.name,i=Date.now();this.events.onStepStart?.({type:l.type,index:a,name:d,itemCount:s.length});let p={pipelineRunId:n,pipelineStepIndex:a};try{let u=await this.executeStep(l,s,a,d,p),g=Date.now()-i;if(r.push({type:l.type,index:a,durationMs:g,results:u.output}),this.events.onStepComplete?.({type:l.type,index:a,name:d,durationMs:g,successCount:u.successCount,errorCount:u.errorCount,filteredCount:u.filteredCount}),l.type==="reduce")return {pipelineRunId:n,steps:r,output:u.output,totalDurationMs:Date.now()-o};s=u.nextItems;}catch(u){throw this.events.onStepError?.({type:l.type,index:a,name:d,error:u instanceof Error?u:new Error(String(u))}),u}}let c=r[r.length-1];return {pipelineRunId:n,steps:r,output:c?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,r,s,o){if(e.type==="map"){let l=e.config,d=await this.swarm.map({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s),bestOf:this.wrapBestOf(l.bestOf,r,s)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let l=e.config,d=await this.swarm.filter({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s)}),i=l.emit??"success",p=i==="success"?d.success:i==="filtered"?d.filtered:[...d.success,...d.filtered];return {output:[...d],nextItems:p,successCount:d.success.length,errorCount:d.error.length,filteredCount:d.filtered.length}}let c=e.config,a=await this.swarm.reduce({items:n,...c,_pipelineContext:o,retry:this.wrapRetry(c.retry,r,s),verify:this.wrapVerify(c.verify,r,s)});return {output:a,nextItems:[],successCount:a.status==="success"?1:0,errorCount:a.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,o,c)=>{e.onItemRetry?.(s,o,c),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,error:c});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,o,c)=>{e.onWorkerComplete?.(s,o,c),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,status:c});},onVerifierComplete:(s,o,c,a)=>{e.onVerifierComplete?.(s,o,c,a),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,passed:c,feedback:a});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,o,c)=>{e.onCandidateComplete?.(s,o,c),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:o,status:c});},onJudgeComplete:(s,o,c)=>{e.onJudgeComplete?.(s,o,c),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:o,reasoning:c});}}}},Je=class t extends ze{constructor(e,n,r){super(e,n,r);}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]: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")}};var As=6e5,Ms=5e3;function vr(t,e,n){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be a positive number`);return r}function $s(t){let e=t?.apiKey||process.env[I];if(!e)throw new Error(`sessions() requires an API key. Set ${I} or pass { apiKey } in config.`);let n=t?.dashboardUrl||E;async function r(a,l){let d=await fetch(`${n}${a}`,{...l,headers:{Authorization:`Bearer ${e}`,...l?.headers}});if(!d.ok){let i=await d.text().catch(()=>"");throw new Error(`Dashboard API error (${d.status}): ${i||d.statusText}`)}return d}function s(a){return {id:a.id,tag:a.tag,agent:a.agent,model:a.model||null,provider:a.provider,sandboxId:a.sandboxId||null,state:a.isEnded?"ended":"live",runtimeStatus:a.runtimeStatus||"unknown",cost:typeof a.cost=="number"?a.cost:null,createdAt:a.createdAt,endedAt:a.endedAt||null,stepCount:a.stepCount||0,toolStats:a.toolStats||null}}function o(a,l){if(a.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(a.status||"unknown")})`);if(typeof a.replayUrl!="string"||typeof a.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:a.sessionId||l,status:"ready",replayUrl:a.replayUrl,downloadUrl:a.downloadUrl,suggestedStartSeconds:typeof a.suggestedStartSeconds=="number"?a.suggestedStartSeconds:void 0,sizeBytes:typeof a.sizeBytes=="number"?a.sizeBytes:void 0,readyAt:typeof a.readyAt=="string"?a.readyAt:void 0}}let c=a=>new Promise(l=>setTimeout(l,a));return {async list(a){let l=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(a?.limit??20,200)),paginated:"true"});if(a?.cursor&&l.set("cursor",a.cursor),a?.state&&a.state!=="all"&&l.set("state",a.state),a?.agent&&l.set("agent",a.agent),a?.tagPrefix&&l.set("tagPrefix",a.tagPrefix),a?.sort){let p={newest:"desc",oldest:"asc",cost:"desc"};l.set("sortDirection",p[a.sort]),a.sort==="cost"?l.set("sortField","cost"):l.set("sortField","timestamp");}let i=await(await r(`/api/sessions?${l}`)).json();return {items:(i.items||[]).map(s),nextCursor:i.nextCursor||null,hasMore:!!i.hasMore}},async get(a){let d=await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json();return s(d)},async events(a,l){let d=new URLSearchParams;l?.since!=null&&d.set("since",String(l.since));let i=d.toString();return (await(await r(`/api/sessions/${encodeURIComponent(a)}/events${i?`?${i}`:""}`)).json()).events||[]},async download(a,l){let p=(await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json()).tag||a,u=await fetch(`${n}/api/sessions/${encodeURIComponent(a)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!u.ok){let h=await u.text().catch(()=>"");throw new Error(`Download failed (${u.status}): ${h||u.statusText}`)}let g=l?.to||process.cwd();await mkdir(g,{recursive:true});let f=join(g,`${p}.jsonl`);if(!u.body)throw new Error("Download response has no body");let m=Readable.fromWeb(u.body);return await pipeline(m,createWriteStream(f)),f},async browserReplay(a,l){let d=vr("timeoutMs",l?.timeoutMs,As),i=vr("intervalMs",l?.intervalMs,Ms),p=Date.now()+d,u=`/api/sessions/${encodeURIComponent(a)}/browser-replay`;for(;;){let g=p-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let f;try{f=await fetch(`${n}${u}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,g))});}catch(h){let y=h.name;throw y==="AbortError"||y==="TimeoutError"?new Error(`Browser replay timed out after ${d}ms`):h}let m={};if(f.ok)m=await f.json();else {let h=await f.text().catch(()=>"");throw new Error(`Dashboard API error (${f.status}): ${h||f.statusText}`)}if(m.status==="ready")return o(m,a);if(m.status==="failed"){let h=typeof m.error=="string"?m.error:"unknown error";throw new Error(`Browser replay failed: ${h}`)}if(Date.now()>=p)throw new Error(`Browser replay timed out after ${d}ms`);await c(Math.min(i,Math.max(0,p-Date.now())));}}}}export{Ye as AGENT_REGISTRY,xr as AGENT_TYPES,he as Agent,wt as BROWSER_ACTIONBOOK_PROMPT,$t as BROWSER_LOGIN_MCP_SERVER_NAME,Ge as BrowserCredentialsClient,We as BrowserProfilesClient,ye as Evolve,bt as JUDGE_PROMPT,ze as Pipeline,St as RETRY_FEEDBACK_PROMPT,Sn as SCHEMA_PROMPT,J as SWARM_RESULT_BRAND,vn as SYSTEM_PROMPT,ee as Semaphore,Ut as Swarm,te as SwarmResultList,Je as TerminalPipeline,He as VALIDATION_PRESETS,vt as VERIFY_PROMPT,wn as WORKSPACE_PROMPT,bn as WORKSPACE_SWE_PROMPT,F as applyTemplate,Dt as browserCredentials,Bt as browserProfiles,kt as buildWorkerSystemPrompt,z as createAgentParser,Me as createClaudeParser,$e as createCodexParser,De as createDroidParser,Be as createGeminiParser,P as executeWithRetry,V as expandPath,D as getAgentConfig,U as getMcpSettingsDir,B as getMcpSettingsPath,_r as isValidAgentType,M as isZodSchema,Y as jsonSchemaToString,ni as parseNdjsonLine,ri as parseNdjsonOutput,nn as parseQwenOutput,rn as readLocalDir,je as resolveStorageConfig,sn as saveLocalDir,$s as sessions,Zi as storage,Se as writeClaudeMcpConfig,Ae as writeCodexMcpConfig,Ee as writeDroidGatewaySettings,_e as writeDroidMcpConfig,ke as writeGeminiMcpConfig,ct as writeMcpConfig,xe as writeQwenMcpConfig,q as zodSchemaToJson};
|
|
213
|
+
`;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.annotations()}},n=JSON.stringify(e)+`
|
|
214
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=y){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},z$1));}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.annotations(),events:e};for(let r=1;r<=A$1;r++)try{let i=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(i.ok)return;if(i.status===429||i.status===401||i.status>=500){if(r===A$1){console.debug(`[SessionLogger] Dashboard ${i.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(B*r);continue}console.debug(`[SessionLogger] Dashboard ${i.status}, dropping events`);return}catch(i){r===A$1?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",i),this.requeueEvents(e)):await this.delay(B*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=b();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.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))}annotations(){if(!this.observability)return {};let e={};for(let[n,r]of Object.entries(this.observability))if(r!==void 0){if(x$1.includes(n)){this.warnedKeys.has(n)||(this.warnedKeys.add(n),console.warn(`[SessionLogger] observability key "${n}" is reserved for session identity \u2014 ignoring it.`));continue}e[n]=r;}return e}};function Se(t){return (t||process.env.EVOLVE_DASHBOARD_URL||s).replace(/\/$/,"")}function xe(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed integrations");return e}async function ke(t){return await t.text().catch(()=>"")}function nn(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function oo(t){let e=Array.from(new Set((t??[]).map(n=>n.trim()).filter(Boolean)));if(e.length===0)throw new Error("withIntegrations() requires at least one app");return e}async function kr(t){let e=await fetch(`${Se(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${xe(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:nn(t.userId),apps:oo(t.apps),tools:t.tools,accounts:t.accounts,keys:t.keys,authConfigs:t.authConfigs,sessionTag:t.sessionTag}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integrations session create failed (${e.status}): ${await ke(e)}`);let n=await e.json();if(!n.mcp?.url)throw new Error("Managed integrations response missing mcp.url");return {url:n.mcp.url,headers:n.mcp.headers??{}}}async function ao(t){let e=await fetch(`${Se(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${xe(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:nn(t.userId),app:t.app,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration connect failed (${e.status}): ${await ke(e)}`);return await e.json()}async function co(t){let e=Array.from(new Set((t.userIds??[]).map(c=>nn(c))));if(e.length===0)throw new Error("Integration accounts.list() requires at least one userId");let n=new URLSearchParams({userIds:e.join(",")});t.app&&n.set("app",t.app),t.statuses?.length&&n.set("statuses",t.statuses.join(","));let r={Authorization:`Bearer ${xe(t.apiKey)}`,accept:"application/json"},i=await fetch(`${Se(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!i.ok)throw new Error(`Managed integration status failed (${i.status}): ${await ke(i)}`);return ((await i.json()).accounts??[]).map(c=>({userId:String(c.userId??""),app:String(c.app??""),appName:typeof c.appName=="string"?c.appName:void 0,appIcon:typeof c.appIcon=="string"?c.appIcon:void 0,accountLabel:typeof c.accountLabel=="string"?c.accountLabel:void 0,status:String(c.status??""),accountId:typeof c.accountId=="string"?c.accountId:void 0,updatedAt:typeof c.updatedAt=="string"?c.updatedAt:void 0}))}async function lo(t){let e=await fetch(`${Se(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${xe(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account update failed (${e.status}): ${await ke(e)}`);return await e.json()}async function uo(t){let e=await fetch(`${Se(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${xe(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account delete failed (${e.status}): ${await ke(e)}`);return await e.json()}var Cr={auth:ao,accounts:{list:co,update:lo,delete:uo}};promisify(exec);var cn=promisify(execFile),Tr=Symbol.for("evolve:awsSdkCache"),Rr=Symbol.for("evolve:s3ClientCache");var xo=3600,ko=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Co(t){if(t.startsWith("s3://")){let i=t.slice(5),s=i.indexOf("/");return s===-1?{bucket:i,prefix:""}:{bucket:i.slice(0,s),prefix:i.slice(s+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,r=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:r.join("/")};if(r.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:r[0],prefix:r.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function st(t,e,n,r){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:r}}let i=t?.bucket||"",s=t?.prefix||"",c=t?.endpoint;if(t?.url){let a=Co(t.url);i=i||a.bucket,s=s||a.prefix,c=c||a.endpoint;}if(!i)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:i,prefix:s,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:c,credentials:t?.credentials,mode:"byok"}}function rn(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 Eo(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 Ce(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function _o(t,e){let n=I(t),r=Eo(e),i=n.checkpointDirs?.length?n.checkpointDirs.map(a=>rn(a)):[rn(n.mcpConfig.settingsDir)],s=[...ko.map(a=>`--exclude=${Ce(a)}`),`--exclude=${Ce(r+"/temp")}`,...(n.checkpointExcludes??[]).map(a=>`--exclude=${Ce(rn(a))}`)].join(" "),c=[Ce(r+"/"),...i.map(a=>Ce(a+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${s} ${c}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function re(){let t=globalThis[Tr];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,i]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[Tr]={s3:r,presigner:i},{s3:r,presigner:i}}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 _e(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[Rr];if(r?.key===n)return r.client;let{s3:i}=await re(),s=new i.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Rr]={client:s,key:n},s}async function Br(t,e,n){let{s3:r,presigner:i}=await re(),s=await _e(t),c=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return i.getSignedUrl(s,c,{expiresIn:xo})}async function Pr(t,e){let{s3:n}=await re(),r=await _e(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(i){let s=i?.name||i?.message||"";if(i?.$metadata?.httpStatusCode===404||s==="NotFound"||s==="NoSuchKey")return false;throw i}}async function Lr(t,e){let{s3:n}=await re(),s=await(await(await _e(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 To(t,e,n){let{s3:r}=await re();await(await _e(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Nr(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function Fr(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Ro(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Kr(t,e,n,r){let i=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:r})});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Gateway presign failed (${i.status}): ${s}`)}return i.json()}async function Po(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${r}`)}return n.json()}async function Io(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${r}`)}return n.json()}async function ln(t,e,n,r,i){let s=new Date().toISOString(),c=_o(n,r),a=await t.commands.run(c,{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint tar failed: ${a.stderr}`);let l=a.stdout.trim().split(`
|
|
215
|
+
`).pop()?.trim();if(!l||l.length!==64)throw new Error(`Invalid checkpoint hash: ${l}`);let d=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(d.stdout.trim(),10),u=Number.isNaN(o)?void 0:o,p;try{if(e.mode==="byok"){let g=Nr(e,l);if(!await Pr(e,g)){let h=await Br(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 Pr(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}p=Ro();let m={id:p,hash:l,tag:i.tag,timestamp:s,sizeBytes:u,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment,sandboxId:t.sandboxId};await To(e,Fr(e,p),m);}else {let g=await Kr(e,i.tag,l,"put");if(!g.alreadyExists){let m=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(m.exitCode!==0)throw new Error(`Checkpoint upload failed: ${m.stderr}`)}p=(await Po(e,{tag:i.tag,hash:l,sizeBytes:u??0,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:p,hash:l,tag:i.tag,timestamp:s,sizeBytes:u,agentType:n,model:i.model,workspaceMode:i.workspaceMode,parentId:i.parentId,comment:i.comment}}async function jr(t,e,n){let r=await un(e,n),i=r.hash,s={agentType:r.agentType,workspaceMode:r.workspaceMode},c=await Wr(e,r),a=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${c}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(a.exitCode!==0)throw new Error(`Checkpoint download failed: ${a.stderr}`);let l=a.stdout.trim().split(`
|
|
216
|
+
`).pop()?.trim();if(l!==i)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${i}, got ${l})`);let d=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(d.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${d.stderr}`);return s}function Gr(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||s,i=!t.url&&!t.bucket&&!!n;return st(t,i,r,n)}async function Vr(t,e){let{s3:n}=await re(),r=await _e(t),s=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,c=[],a;do{let p={Bucket:t.bucket,Prefix:s,...a&&{ContinuationToken:a}},g=await r.send(new n.ListObjectsV2Command(p));if(g.Contents)for(let f of g.Contents)f.Key?.endsWith(".json")&&f.LastModified&&c.push({key:f.Key,lastModified:f.LastModified});a=g.IsTruncated?g.NextContinuationToken:void 0;}while(a);if(c.length===0)return [];c.sort((p,g)=>{let f=g.lastModified.getTime()-p.lastModified.getTime();return f!==0?f:g.key<p.key?-1:g.key>p.key?1:0});let d=!!e?.tag?c:e?.limit?c.slice(0,e.limit):c,u=(await Promise.all(d.map(async p=>{try{return await Lr(t,p.key)}catch{return null}}))).filter(p=>p!==null);return e?.tag&&(u=u.filter(p=>p.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function zr(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let r=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,i=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${i.status}): ${s}`)}return i.json()}function Ao(t){return t&&t>0?Math.min(t,500):100}async function dn(t,e){return t.mode==="byok"?(await Vr(t,{limit:1,tag:e?.tag}))[0]??null:(await zr(t,{limit:1,tag:e?.tag}))[0]??null}async function un(t,e){if(t.mode==="byok"){let n=Fr(t,e);try{return await Lr(t,n)}catch(r){throw Oo(r)?new Error(`Checkpoint ${e} not found`):r}}else return await Io(t,e)}async function Ir(t,e,n){if(e==="latest"){let r=await dn(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function Wr(t,e){if(t.mode==="byok")return Br(t,Nr(t,e.hash),"get");{let n=await Kr(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function Hr(t){return !(!t||isAbsolute(t)||t.startsWith("-")||normalize(t).startsWith("..")||t.includes("\0"))}function Ar(t,e){let n=resolve(t,e),r=resolve(t),i=relative(r,n);if(i.startsWith("..")||isAbsolute(i))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function Oo(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function sn(t){let e=t.filter(n=>!Hr(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var qr=10*1024*1024,Or=false;async function Jr(){if(!Or)try{await cn("tar",["--version"]),Or=!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 Mr(t,e){let n=await un(t,e),r=await Wr(t,n),i=e.replace(/[^a-zA-Z0-9_-]/g,"_"),s=join(tmpdir(),`evolve-dl-${i}-${Date.now()}.tar.gz`),c=await fetch(r);if(!c.ok)throw new Error(`Checkpoint download failed (${c.status})`);if(!c.body)throw new Error("Checkpoint download returned empty body");let a=createHash("sha256"),l=createWriteStream(s);try{let o=c.body.getReader();await new Promise((u,p)=>{l.on("error",p),l.on("finish",u);async function g(){for(;;){let{done:f,value:m}=await o.read();if(f){l.end();break}a.update(m),l.write(m)||await new Promise(h=>l.once("drain",h));}}g().catch(p);});}catch(o){throw l.destroy(),await unlink(s).catch(()=>{}),o}let d=a.digest("hex");if(d!==n.hash)throw await unlink(s).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${d})`);return {tmpPath:s,metadata:n}}async function Dr(t){await Jr();let{stdout:e}=await cn("tar",["-tvzf",t],{maxBuffer:qr}),n=new Set,r=[],i=[];for(let s of e.trim().split(`
|
|
217
|
+
`)){if(!s||s.startsWith("total "))continue;let c=s[0];if(c!=="-"&&c!=="d"&&c!=="l")throw new Error(`Archive contains unsupported entry type: "${c}"`);let a=s.match(/\d{2}:\d{2}\s+(.+)/)??s.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!a)continue;let l=a[1];if(c==="l"){let d=l.indexOf(" -> ");d!==-1&&(l=l.slice(0,d)),n.add(l);}else c==="d"?r.push(l.replace(/\/$/,"")):i.push(l);}return sn(r),sn([...n]),sn(i)}async function on(t,e,n){await Jr(),await mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await cn("tar",r,{maxBuffer:qr});}function Mo(t){let e="^",n=0;for(;n<t.length;){let r=t[n];r==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):r==="*"?(e+="[^/]*",n++):r==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(r)?(e+="\\"+r,n++):(e+=r,n++);}return e+="$",new RegExp(e)}function pn(t,e){let n=Gr(t,e);return Yr(n)}function Do(t){let e=Gr(t||{});return Yr(e)}function Yr(t){return {async listCheckpoints(e){let n=Ao(e?.limit);return t.mode==="byok"?Vr(t,{limit:n,tag:e?.tag}):zr(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return un(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,i=n?.to||process.cwd(),s=await Ir(t,e),{tmpPath:c,metadata:a}=await Mr(t,s);try{if(r)return await mkdir(i,{recursive:!0}),await Dr(c),await on(c,i),i;{await mkdir(i,{recursive:!0});let l=join(i,`checkpoint-${a.id}.tar.gz`);return await copyFile(c,l),l}}finally{await unlink(c).catch(()=>{});}},async downloadFiles(e,n){let r=await Ir(t,e),{tmpPath:i}=await Mr(t,r),s;try{let c=await Dr(i),a;if(n?.files){let d=n.files.filter(u=>!Hr(u));if(d.length>0)throw new Error(`Unsafe file path requested: ${d[0]}`);let o=new Set(n.files);a=c.filter(u=>o.has(u));}else if(n?.glob){let d=n.glob.map(Mo);a=c.filter(o=>d.some(u=>u.test(o)));}else a=c;if(a.length===0)return {};s=join(tmpdir(),`evolve-extract-${Date.now()}`);try{await on(i,s,a);}catch(d){let o=d?.message??"";if(!o.includes("E2BIG")&&!o.includes("Argument list too long")&&!o.includes("ENAMETOOLONG"))throw d;await rm(s,{recursive:!0,force:!0}).catch(()=>{}),s=join(tmpdir(),`evolve-extract-${Date.now()}`),await on(i,s);}let l={};return await Promise.all(a.map(async d=>{Ar(s,d),l[d]=await readFile(join(s,d));})),n?.to&&(await mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(l).map(async([d,o])=>{Ar(n.to,d);let u=join(n.to,d);await mkdir(dirname(u),{recursive:!0}),await writeFile(u,o);}))),l}finally{s&&await rm(s,{recursive:true,force:true}).catch(()=>{}),await unlink(i).catch(()=>{});}}}}function G(t){return `'${t.replace(/'/g,"'\\''")}'`}function ot(t){return typeof t=="string"&&t.length>0}function ie(t,e,n){let r=t[e];if(!ot(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function Uo(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
|
|
218
|
+
${n}`)}function $o(t,e){switch(t){case "droid":{let n=ie(e,"marketplace",t),r=ie(e,"plugin",t);return [`droid plugin marketplace add ${G(n)}`,`droid plugin install ${G(r)} --scope user`]}case "claude":{let n=ie(e,"marketplace",t),r=ie(e,"plugin",t);return [`claude plugin marketplace add ${G(n)} --scope user`,`claude plugin install ${G(r)} --scope user`]}case "gemini":{let n=ie(e,"source",t),r=e,i=[`gemini extensions install ${G(n)}`];return ot(r.ref)&&i.push(`--ref ${G(r.ref)}`),r.autoUpdate===true&&i.push("--auto-update"),r.preRelease===true&&i.push("--pre-release"),i.push("--consent"),r.skipSettings===true&&i.push("--skip-settings"),[i.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=ie(e,"marketplace",t),r=e,i=[`codex plugin marketplace add ${G(n)}`];if(ot(r.ref)&&i.push(`--ref ${G(r.ref)}`),Array.isArray(r.sparse))for(let s of r.sparse){if(!ot(s))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");i.push(`--sparse ${G(s)}`);}return [i.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function Xr(t,e,n){if(n?.length)for(let r of n){let i=$o(t,r);for(let s of i){let c=await e.commands.run(s,{timeoutMs:12e4});if(c.exitCode!==0)throw Uo(s,c)}}}var Lo=["actionbook","active-research","extract"],No=["agent-browser"],Fo={actionbook:Lo,"agent-browser":No},ti="/home/user/.agent-browser",Qr=`${ti}/config.json`,ni="/home/user/.actionbook",Ko=`${ni}/config.toml`;function Zr(t){return t==="actionbook"||t==="agent-browser"}function jo(t){return t.remote===true}function ei(t){if(t==null)return;if(typeof t!="string")throw new Error("browser profile must be a string");let e=t.trim();if(!e)throw new Error("browser profile cannot be empty");return e}function ri(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(Zr(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(t.provider===void 0)return {provider:"agent-browser",managed:t.remote!==false,profile:ei(t.profile)};if(Zr(t.provider))return {provider:t.provider,managed:jo(t),profile:ei(t.profile)};throw new Error("Unsupported browser configuration")}function ii(t,e){return Array.from(new Set([...e??[],...Fo[t]]))}function gn(t,e){return t==="actionbook"?{envs:{},files:[{path:Ko,data:stringify({version:1,browser:{mode:"cloud",cdp_endpoint:e.cdpUrl}}).trimEnd()+`
|
|
219
|
+
`}],directories:[ni]}:{envs:{AGENT_BROWSER_CONFIG:Qr},files:[{path:Qr,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
|
|
220
|
+
`}],directories:[ti]}}function si(t){return (t?.dashboardUrl||s).replace(/\/$/,"")}async function oi(t){return await t.text().catch(()=>"")}async function ai(t,e,n={}){let r=await fetch(`${si(t)}/api/browser-sessions`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({sessionTag:e,options:{remote:true},browserAuth:n.browserCredentials===true,...t.profile?{profile:t.profile}:{}}),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`Managed browser session create failed (${r.status}): ${await oi(r)}`);let i=await r.json();if(!i.id||!i.sessionId||!i.cdpUrl||!i.liveUrl)throw new Error("Managed browser session response missing id, sessionId, cdpUrl, or liveUrl");return {id:i.id,sessionId:i.sessionId,sessionTag:i.sessionTag,cdpUrl:i.cdpUrl,liveUrl:i.liveUrl,browserAuthGrantToken:i.browserAuthGrantToken}}async function ci(t,e){let n=await fetch(`${si(t)}/api/browser-sessions/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!n.ok&&n.status!==404)throw new Error(`Managed browser session stop failed (${n.status}): ${await oi(n)}`)}var zo="RSA-OAEP-256",fn="browser-login";function Wo(t){return (t||process.env.EVOLVE_DASHBOARD_URL||s).replace(/\/$/,"")}function Ho(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser credentials require EVOLVE_API_KEY or an explicit apiKey");return e}async function qo(t){return await t.text().catch(()=>"")}async function Te(t,e,n={}){let r=await fetch(`${Wo(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${Ho(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser credentials request failed (${r.status}): ${await qo(r)}`);return await r.json()}async function Jo(t,e){let n=await Te(t,"/api/browser-credentials/public-key"),r=publicEncrypt({key:n.publicKey,padding:constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"utf8"));return {algorithm:zo,keyId:n.id,ciphertext:r.toString("base64url")}}var at=class{constructor(e={}){this.config=e;}toMetadata(e){let{account_label:n,...r}=e;return {...r,accountLabel:n}}async list(e={}){let n=new URLSearchParams;e.website&&n.set("website",e.website),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let r=n.toString()?`?${n.toString()}`:"",i=await Te(this.config,`/api/browser-credentials${r}`);return {credentials:i.credentials.map(s=>this.toMetadata(s)),total:i.total,count:i.count,offset:i.offset,hasMore:i.has_more??i.offset+i.count<i.total}}async create(e){let n=await Jo(this.config,e.password),r=await Te(this.config,"/api/browser-credentials",{method:"POST",body:JSON.stringify({website:e.website,account_label:e.accountLabel,email:e.email,encryptedPassword:n})});return {status:r.status,credential:this.toMetadata(r.credential)}}async delete(e){let n="id"in e?e:{website:e.website,account_label:e.accountLabel};return await Te(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function mn(t={}){return new at(t)}async function li(t){return (await Te({apiKey:t.apiKey,dashboardUrl:t.dashboardUrl},"/api/browser-login/mcp-config",{method:"POST",body:JSON.stringify({browserSessionId:t.browserSessionId,sessionTag:t.sessionTag,grantToken:t.grantToken,allow:Yo(t.config)})})).server}function Yo(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var hn="x-evolve-provider-runtime-binding";function Xo(t){return (t||process.env.EVOLVE_DASHBOARD_URL||s).replace(/\/$/,"")}async function Qo(t){return await t.text().catch(()=>"")}var Re=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ProviderRuntimeTokenRequestError";}};function di(t){return t instanceof Re&&t.status===404}async function yn(t,e,n={}){let r=await fetch(`${Xo(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Re(r.status,`Provider runtime token request failed (${r.status}): ${await Qo(r)}`);return await r.json()}function Zo(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.enabled===true&&(e.provider==="anthropic"||e.provider==="openai"||e.provider==="gemini"||e.provider==="dashscope"||e.provider==="kimi"||e.provider==="openrouter"||e.provider==="droid")&&(e.credentialMode==="provider_key"||e.credentialMode==="evolve_key")&&typeof e.token=="string"&&e.token.length>0&&typeof e.bindingSecret=="string"&&e.bindingSecret.length>0&&typeof e.baseUrl=="string"&&e.baseUrl.length>0&&typeof e.expiresAt=="string"&&e.expiresAt.length>0}async function ui(t,e){let n=await yn(t,"/api/provider-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!Zo(n))throw new Re(502,"Provider runtime token response was invalid");return n}async function pi(t,e){return (await yn(t,"/api/provider-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function gi(t,e){return (await yn(t,"/api/provider-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}var lt=18181,P="/tmp/evolve-managed-secrets",Pe=`${P}/proxy.py`,oe=`${P}/config.json`,Y=`${P}/ca.crt`,ct=`${P}/ca.key`,se=`${P}/ca-bundle.crt`,hi=["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","http_proxy","https_proxy","all_proxy","NO_PROXY","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"];function yi(){return [...hi]}var wi=String.raw`#!/usr/bin/env python3
|
|
221
|
+
import base64
|
|
222
|
+
import json
|
|
223
|
+
import os
|
|
224
|
+
import select
|
|
225
|
+
import secrets
|
|
226
|
+
import socket
|
|
227
|
+
import ssl
|
|
228
|
+
import subprocess
|
|
229
|
+
import sys
|
|
230
|
+
import tempfile
|
|
231
|
+
import threading
|
|
232
|
+
import urllib.error
|
|
233
|
+
import urllib.request
|
|
234
|
+
|
|
235
|
+
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]:
|
|
236
|
+
os.environ.pop(key, None)
|
|
237
|
+
|
|
238
|
+
CONFIG_PATH = sys.argv[1]
|
|
239
|
+
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
240
|
+
CONFIG = json.load(f)
|
|
241
|
+
try:
|
|
242
|
+
os.unlink(CONFIG_PATH)
|
|
243
|
+
except FileNotFoundError:
|
|
244
|
+
pass
|
|
245
|
+
|
|
246
|
+
MAX_BODY_BYTES = int(CONFIG.get("max_body_bytes", 10 * 1024 * 1024))
|
|
247
|
+
CONNECT_TIMEOUT_SECONDS = 15
|
|
248
|
+
SOCKET_TIMEOUT_SECONDS = 130
|
|
249
|
+
MAX_WORKERS = 100
|
|
250
|
+
WORKERS = threading.BoundedSemaphore(MAX_WORKERS)
|
|
251
|
+
HOST_PATTERNS = [h.lower() for h in CONFIG["hosts"]]
|
|
252
|
+
PLACEHOLDERS = set(CONFIG["placeholders"])
|
|
253
|
+
PLACEHOLDER_BYTES = [p.encode("utf-8") for p in CONFIG["placeholders"]]
|
|
254
|
+
BASE_DIR = CONFIG["base_dir"]
|
|
255
|
+
CERT_DIR = os.path.join(BASE_DIR, "certs")
|
|
256
|
+
os.makedirs(CERT_DIR, exist_ok=True)
|
|
257
|
+
CHANNEL_SECRET = secrets.token_urlsafe(32)
|
|
258
|
+
|
|
259
|
+
def register_channel():
|
|
260
|
+
payload = json.dumps({}).encode("utf-8")
|
|
261
|
+
req = urllib.request.Request(
|
|
262
|
+
CONFIG["channel_url"],
|
|
263
|
+
data=payload,
|
|
264
|
+
method="POST",
|
|
265
|
+
headers={
|
|
266
|
+
"content-type": "application/json",
|
|
267
|
+
"accept": "application/json",
|
|
268
|
+
"x-evolve-managed-secret-token": CONFIG["token"],
|
|
269
|
+
"x-evolve-managed-secret-binding": CONFIG["binding"],
|
|
270
|
+
"x-evolve-managed-secret-channel": CHANNEL_SECRET,
|
|
271
|
+
},
|
|
272
|
+
)
|
|
273
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
274
|
+
if resp.status < 200 or resp.status >= 300:
|
|
275
|
+
raise RuntimeError("managed secret channel registration failed")
|
|
276
|
+
|
|
277
|
+
def host_matches(pattern, host):
|
|
278
|
+
host = host.lower()
|
|
279
|
+
if pattern.startswith("*."):
|
|
280
|
+
base = pattern[2:]
|
|
281
|
+
return host != base and host.endswith("." + base)
|
|
282
|
+
return host == pattern
|
|
283
|
+
|
|
284
|
+
def is_managed_host(host):
|
|
285
|
+
clean = host.split(":", 1)[0].strip("[]").lower()
|
|
286
|
+
return any(host_matches(pattern, clean) for pattern in HOST_PATTERNS)
|
|
287
|
+
|
|
288
|
+
def safe_name(host):
|
|
289
|
+
return "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in host)[:180]
|
|
290
|
+
|
|
291
|
+
def ensure_cert(host):
|
|
292
|
+
name = safe_name(host)
|
|
293
|
+
cert = os.path.join(CERT_DIR, name + ".crt")
|
|
294
|
+
key = os.path.join(CERT_DIR, name + ".key")
|
|
295
|
+
if os.path.exists(cert) and os.path.exists(key):
|
|
296
|
+
return cert, key
|
|
297
|
+
csr = os.path.join(CERT_DIR, name + ".csr")
|
|
298
|
+
ext = os.path.join(CERT_DIR, name + ".ext")
|
|
299
|
+
san = "IP:" + host if host.replace(".", "").isdigit() else "DNS:" + host
|
|
300
|
+
with open(ext, "w", encoding="utf-8") as f:
|
|
301
|
+
f.write("basicConstraints=critical,CA:FALSE\n")
|
|
302
|
+
f.write("keyUsage=critical,digitalSignature,keyEncipherment\n")
|
|
303
|
+
f.write("subjectAltName=" + san + "\n")
|
|
304
|
+
f.write("extendedKeyUsage=serverAuth\n")
|
|
305
|
+
subprocess.run(
|
|
306
|
+
["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-subj", "/CN=" + host, "-out", csr],
|
|
307
|
+
check=True,
|
|
308
|
+
stdout=subprocess.DEVNULL,
|
|
309
|
+
stderr=subprocess.DEVNULL,
|
|
310
|
+
)
|
|
311
|
+
subprocess.run(
|
|
312
|
+
[
|
|
313
|
+
"openssl", "x509", "-req", "-in", csr,
|
|
314
|
+
"-CA", CONFIG["ca_cert"], "-CAkey", CONFIG["ca_key"], "-CAcreateserial",
|
|
315
|
+
"-out", cert, "-days", "30", "-sha256", "-extfile", ext,
|
|
316
|
+
],
|
|
317
|
+
check=True,
|
|
318
|
+
stdout=subprocess.DEVNULL,
|
|
319
|
+
stderr=subprocess.DEVNULL,
|
|
320
|
+
)
|
|
321
|
+
return cert, key
|
|
322
|
+
|
|
323
|
+
def pipe_raw(client, host, port):
|
|
324
|
+
upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS)
|
|
325
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
326
|
+
upstream.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
327
|
+
try:
|
|
328
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
329
|
+
sockets = [client, upstream]
|
|
330
|
+
while True:
|
|
331
|
+
readable, _, _ = select.select(sockets, [], [], 120)
|
|
332
|
+
if not readable:
|
|
333
|
+
break
|
|
334
|
+
for sock in readable:
|
|
335
|
+
data = sock.recv(65536)
|
|
336
|
+
if not data:
|
|
337
|
+
return
|
|
338
|
+
(upstream if sock is client else client).sendall(data)
|
|
339
|
+
finally:
|
|
340
|
+
upstream.close()
|
|
341
|
+
|
|
342
|
+
def recv_until(sock, marker, limit=65536):
|
|
343
|
+
data = b""
|
|
344
|
+
while marker not in data:
|
|
345
|
+
chunk = sock.recv(4096)
|
|
346
|
+
if not chunk:
|
|
347
|
+
break
|
|
348
|
+
data += chunk
|
|
349
|
+
if len(data) > limit:
|
|
350
|
+
raise RuntimeError("request headers too large")
|
|
351
|
+
return data
|
|
352
|
+
|
|
353
|
+
def parse_headers(blob):
|
|
354
|
+
head, rest = blob.split(b"\r\n\r\n", 1)
|
|
355
|
+
lines = head.decode("iso-8859-1").split("\r\n")
|
|
356
|
+
request_line = lines[0]
|
|
357
|
+
headers = {}
|
|
358
|
+
for line in lines[1:]:
|
|
359
|
+
if not line or ":" not in line:
|
|
360
|
+
continue
|
|
361
|
+
name, value = line.split(":", 1)
|
|
362
|
+
headers[name.strip()] = value.strip()
|
|
363
|
+
return request_line, headers, rest
|
|
364
|
+
|
|
365
|
+
def header_value(headers, name):
|
|
366
|
+
wanted = name.lower()
|
|
367
|
+
for key, value in headers.items():
|
|
368
|
+
if key.lower() == wanted:
|
|
369
|
+
return value
|
|
370
|
+
return None
|
|
371
|
+
|
|
372
|
+
def read_chunked_body(sock, initial):
|
|
373
|
+
data = initial
|
|
374
|
+
body = b""
|
|
375
|
+
while True:
|
|
376
|
+
while b"\r\n" not in data:
|
|
377
|
+
chunk = sock.recv(4096)
|
|
378
|
+
if not chunk:
|
|
379
|
+
raise RuntimeError("incomplete chunked request")
|
|
380
|
+
data += chunk
|
|
381
|
+
line, data = data.split(b"\r\n", 1)
|
|
382
|
+
size = int((line.split(b";", 1)[0].strip() or b"0"), 16)
|
|
383
|
+
if size == 0:
|
|
384
|
+
return body
|
|
385
|
+
if len(body) + size > MAX_BODY_BYTES:
|
|
386
|
+
raise RuntimeError("request body too large")
|
|
387
|
+
while len(data) < size + 2:
|
|
388
|
+
chunk = sock.recv(65536)
|
|
389
|
+
if not chunk:
|
|
390
|
+
raise RuntimeError("incomplete chunked request")
|
|
391
|
+
data += chunk
|
|
392
|
+
body += data[:size]
|
|
393
|
+
data = data[size + 2:]
|
|
394
|
+
|
|
395
|
+
def read_request(tls_sock):
|
|
396
|
+
blob = recv_until(tls_sock, b"\r\n\r\n")
|
|
397
|
+
if not blob:
|
|
398
|
+
return None
|
|
399
|
+
request_line, headers, rest = parse_headers(blob)
|
|
400
|
+
transfer_encoding = (header_value(headers, "Transfer-Encoding") or "").lower()
|
|
401
|
+
if "chunked" in transfer_encoding:
|
|
402
|
+
return request_line, headers, read_chunked_body(tls_sock, rest)
|
|
403
|
+
length = int(header_value(headers, "Content-Length") or "0")
|
|
404
|
+
if length > MAX_BODY_BYTES:
|
|
405
|
+
raise RuntimeError("request body too large")
|
|
406
|
+
body = rest
|
|
407
|
+
while len(body) < length:
|
|
408
|
+
chunk = tls_sock.recv(min(65536, length - len(body)))
|
|
409
|
+
if not chunk:
|
|
410
|
+
break
|
|
411
|
+
body += chunk
|
|
412
|
+
return request_line, headers, body[:length]
|
|
413
|
+
|
|
414
|
+
def uses_placeholder(path, headers, body):
|
|
415
|
+
if any(ph in path for ph in PLACEHOLDERS):
|
|
416
|
+
return True
|
|
417
|
+
if any(ph in value for ph in PLACEHOLDERS for value in headers.values()):
|
|
418
|
+
return True
|
|
419
|
+
return any(ph_b in body for ph_b in PLACEHOLDER_BYTES)
|
|
420
|
+
|
|
421
|
+
def call_dashboard(method, url, headers, body):
|
|
422
|
+
payload = json.dumps({
|
|
423
|
+
"method": method,
|
|
424
|
+
"url": url,
|
|
425
|
+
"headers": headers,
|
|
426
|
+
"bodyBase64": base64.b64encode(body).decode("ascii") if body else "",
|
|
427
|
+
}).encode("utf-8")
|
|
428
|
+
req = urllib.request.Request(
|
|
429
|
+
CONFIG["egress_url"],
|
|
430
|
+
data=payload,
|
|
431
|
+
method="POST",
|
|
432
|
+
headers={
|
|
433
|
+
"content-type": "application/json",
|
|
434
|
+
"accept": "application/json",
|
|
435
|
+
"x-evolve-managed-secret-token": CONFIG["token"],
|
|
436
|
+
"x-evolve-managed-secret-binding": CONFIG["binding"],
|
|
437
|
+
"x-evolve-managed-secret-channel": CHANNEL_SECRET,
|
|
438
|
+
},
|
|
439
|
+
)
|
|
440
|
+
try:
|
|
441
|
+
with urllib.request.urlopen(req, timeout=130) as resp:
|
|
442
|
+
return resp.status, resp.reason, json.loads(resp.read().decode("utf-8"))
|
|
443
|
+
except urllib.error.HTTPError as err:
|
|
444
|
+
text = err.read().decode("utf-8", "replace")
|
|
445
|
+
return err.code, "Managed Secret Egress Error", {"headers": {"content-type": "application/json"}, "bodyBase64": base64.b64encode(text.encode()).decode("ascii")}
|
|
446
|
+
|
|
447
|
+
def read_limited_response(stream):
|
|
448
|
+
chunks = []
|
|
449
|
+
total = 0
|
|
450
|
+
while True:
|
|
451
|
+
chunk = stream.read(65536)
|
|
452
|
+
if not chunk:
|
|
453
|
+
break
|
|
454
|
+
total += len(chunk)
|
|
455
|
+
if total > MAX_BODY_BYTES:
|
|
456
|
+
raise RuntimeError("response body too large")
|
|
457
|
+
chunks.append(chunk)
|
|
458
|
+
return b"".join(chunks)
|
|
459
|
+
|
|
460
|
+
def call_direct(method, url, headers, body):
|
|
461
|
+
hop_by_hop = {"connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "host", "content-length"}
|
|
462
|
+
request_headers = {k: v for k, v in headers.items() if k.lower() not in hop_by_hop}
|
|
463
|
+
req = urllib.request.Request(
|
|
464
|
+
url,
|
|
465
|
+
data=body if body else None,
|
|
466
|
+
method=method,
|
|
467
|
+
headers=request_headers,
|
|
468
|
+
)
|
|
469
|
+
try:
|
|
470
|
+
with urllib.request.urlopen(req, timeout=130) as resp:
|
|
471
|
+
return resp.status, resp.reason, {
|
|
472
|
+
"headers": dict(resp.headers.items()),
|
|
473
|
+
"bodyBase64": base64.b64encode(read_limited_response(resp)).decode("ascii"),
|
|
474
|
+
}
|
|
475
|
+
except urllib.error.HTTPError as err:
|
|
476
|
+
return err.code, err.reason, {
|
|
477
|
+
"headers": dict(err.headers.items()),
|
|
478
|
+
"bodyBase64": base64.b64encode(read_limited_response(err)).decode("ascii"),
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
def send_response(tls_sock, status, reason, result):
|
|
482
|
+
body = base64.b64decode(result.get("bodyBase64") or "")
|
|
483
|
+
headers = {str(k): str(v) for k, v in (result.get("headers") or {}).items()}
|
|
484
|
+
headers["content-length"] = str(len(body))
|
|
485
|
+
headers["connection"] = "close"
|
|
486
|
+
status_line = ("HTTP/1.1 %d %s\r\n" % (status, reason or "")).encode("ascii", "replace")
|
|
487
|
+
header_blob = b"".join((name + ": " + value + "\r\n").encode("iso-8859-1", "replace") for name, value in headers.items())
|
|
488
|
+
tls_sock.sendall(status_line + header_blob + b"\r\n" + body)
|
|
489
|
+
|
|
490
|
+
def dispatch_managed_request(method, url, headers, body):
|
|
491
|
+
if uses_placeholder(url, headers, body):
|
|
492
|
+
return call_dashboard(method, url, headers, body)
|
|
493
|
+
return call_direct(method, url, headers, body)
|
|
494
|
+
|
|
495
|
+
def handle_managed_connect(client, host, port):
|
|
496
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
497
|
+
cert, key = ensure_cert(host)
|
|
498
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
499
|
+
ctx.load_cert_chain(cert, key)
|
|
500
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
501
|
+
tls_sock = ctx.wrap_socket(client, server_side=True)
|
|
502
|
+
tls_sock.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
503
|
+
try:
|
|
504
|
+
request = read_request(tls_sock)
|
|
505
|
+
if not request:
|
|
506
|
+
return
|
|
507
|
+
request_line, headers, body = request
|
|
508
|
+
parts = request_line.split()
|
|
509
|
+
if len(parts) < 2:
|
|
510
|
+
raise RuntimeError("bad request line")
|
|
511
|
+
method, path = parts[0].upper(), parts[1]
|
|
512
|
+
if path.startswith("http://") or path.startswith("https://"):
|
|
513
|
+
url = path
|
|
514
|
+
else:
|
|
515
|
+
url = "https://%s%s" % (host if port == 443 else host + ":" + str(port), path)
|
|
516
|
+
status, reason, result = dispatch_managed_request(method, url, headers, body)
|
|
517
|
+
send_response(tls_sock, status, reason, result)
|
|
518
|
+
finally:
|
|
519
|
+
try:
|
|
520
|
+
tls_sock.close()
|
|
521
|
+
except Exception:
|
|
522
|
+
pass
|
|
523
|
+
|
|
524
|
+
def handle_client(client):
|
|
525
|
+
try:
|
|
526
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
527
|
+
blob = recv_until(client, b"\r\n\r\n")
|
|
528
|
+
if not blob:
|
|
529
|
+
return
|
|
530
|
+
request_line, headers, rest = parse_headers(blob)
|
|
531
|
+
parts = request_line.split()
|
|
532
|
+
if len(parts) < 3:
|
|
533
|
+
return
|
|
534
|
+
if parts[0].upper() == "CONNECT":
|
|
535
|
+
target = parts[1]
|
|
536
|
+
if ":" in target:
|
|
537
|
+
host, port_s = target.rsplit(":", 1)
|
|
538
|
+
port = int(port_s)
|
|
539
|
+
else:
|
|
540
|
+
host, port = target, 443
|
|
541
|
+
host = host.strip("[]")
|
|
542
|
+
if is_managed_host(host):
|
|
543
|
+
handle_managed_connect(client, host, port)
|
|
544
|
+
else:
|
|
545
|
+
pipe_raw(client, host, port)
|
|
546
|
+
return
|
|
547
|
+
client.sendall(b"HTTP/1.1 501 Not Implemented\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
|
|
548
|
+
except Exception as exc:
|
|
549
|
+
try:
|
|
550
|
+
body = json.dumps({"error": str(exc)}).encode("utf-8")
|
|
551
|
+
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\ncontent-type: application/json\r\ncontent-length: " + str(len(body)).encode() + b"\r\nconnection: close\r\n\r\n" + body)
|
|
552
|
+
except Exception:
|
|
553
|
+
pass
|
|
554
|
+
finally:
|
|
555
|
+
try:
|
|
556
|
+
client.close()
|
|
557
|
+
except Exception:
|
|
558
|
+
pass
|
|
559
|
+
|
|
560
|
+
def serve():
|
|
561
|
+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
562
|
+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
563
|
+
server.bind(("127.0.0.1", int(CONFIG["port"])))
|
|
564
|
+
server.listen(100)
|
|
565
|
+
while True:
|
|
566
|
+
client, _ = server.accept()
|
|
567
|
+
if not WORKERS.acquire(blocking=False):
|
|
568
|
+
try:
|
|
569
|
+
client.sendall(b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
|
|
570
|
+
except Exception:
|
|
571
|
+
pass
|
|
572
|
+
client.close()
|
|
573
|
+
continue
|
|
574
|
+
def run_client():
|
|
575
|
+
try:
|
|
576
|
+
handle_client(client)
|
|
577
|
+
finally:
|
|
578
|
+
WORKERS.release()
|
|
579
|
+
thread = threading.Thread(target=run_client, daemon=True)
|
|
580
|
+
thread.start()
|
|
581
|
+
|
|
582
|
+
if __name__ == "__main__":
|
|
583
|
+
register_channel()
|
|
584
|
+
serve()
|
|
585
|
+
`;function ea(t){return (t||process.env.EVOLVE_DASHBOARD_URL||s).replace(/\/$/,"")}function ta(t){let e=t.apiKey||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed secrets");return e}async function na(t){return await t.text().catch(()=>"")}async function dt(t,e,n={}){let r=await fetch(`${ea(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${ta(t)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Managed secrets request failed (${r.status}): ${await na(r)}`);return await r.json()}function wn(t={}){return {async list(){return (await dt(t,"/api/managed-secrets")).secrets??[]}}}function ra(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function fi(t){try{return new URL(t).protocol==="https:"}catch{return false}}function ia(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.token=="string"&&e.token.startsWith("evrt_")&&typeof e.bindingSecret=="string"&&e.bindingSecret.startsWith("evrb_")&&typeof e.egressUrl=="string"&&fi(e.egressUrl)&&typeof e.channelUrl=="string"&&fi(e.channelUrl)&&typeof e.expiresAt=="string"&&Array.isArray(e.env)&&e.env.every(n=>{if(!n||typeof n!="object"||Array.isArray(n))return false;let r=n;return typeof r.name=="string"&&typeof r.envName=="string"&&typeof r.placeholder=="string"&&r.placeholder.startsWith("evsec_")&&ra(r.allowedHosts)})}async function bi(t,e){let n=await dt(t,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!ia(n))throw new Error("Invalid managed secret runtime token response");return n}async function vi(t,e){return (await dt(t,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function Si(t,e){return (await dt(t,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}function sa(t){if(!Array.isArray(t)||t.length===0)throw new Error("withManagedSecrets() requires at least one secret");return t.map((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`managedSecrets[${n}] must be an object with a name`);let r=mi(e.name,`managedSecrets[${n}].name`),i=e.as===void 0?void 0:mi(e.as,`managedSecrets[${n}].as`);return i?{name:r,as:i}:{name:r}})}function mi(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} is required`);let n=t.trim().toUpperCase();if(!/^[A-Z_][A-Z0-9_]{0,127}$/.test(n))throw new Error(`${e} must be a valid environment variable name`);if(n.startsWith("EVOLVE_"))throw new Error(`${e} cannot use the reserved EVOLVE_ prefix`);return n}function oa(t){let e=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...hi]),n=r=>{r&&e.add(r);};n(t.apiKeyEnv),n(t.baseUrlEnv),n(t.customHeadersEnv),n(t.gatewayConfigEnv),t.spendTrackingEnvs&&(n(t.spendTrackingEnvs.sessionTagEnv),n(t.spendTrackingEnvs.runTagEnv));for(let r of Object.values(t.providerEnvMap??{}))n(r.keyEnv);return e}function xi(t,e){if(!t)return;let n=sa(t),r=oa(e),i=new Set;for(let s of n){let c=s.as||s.name;if(r.has(c))throw new Error(`${c} is reserved for Evolve-managed sandbox services and cannot be used as a managed secret env var`);if(i.has(c))throw new Error(`duplicate managed secret env var: ${c}`);i.add(c);}return n}function ki(t){let e={};for(let i of t.env)e[i.envName]=i.placeholder;let n=`http://127.0.0.1:${lt}`;e.HTTPS_PROXY=n,e.https_proxy=n,e.NODE_EXTRA_CA_CERTS=Y,e.SSL_CERT_FILE=se,e.REQUESTS_CA_BUNDLE=se,e.CURL_CA_BUNDLE=se,e.GIT_SSL_CAINFO=se;let r=new URL(t.egressUrl).hostname;return e.NO_PROXY=`localhost,127.0.0.1,::1,${r}`,e.no_proxy=e.NO_PROXY,e}function Ci(t){let e=Array.from(new Set(t.env.flatMap(n=>n.allowedHosts)));return JSON.stringify({egress_url:t.egressUrl,channel_url:t.channelUrl,token:t.token,binding:t.bindingSecret,hosts:e,placeholders:t.env.map(n=>n.placeholder),base_dir:P,ca_cert:Y,ca_key:ct,port:lt,max_body_bytes:10*1024*1024},null,2)}function Ei(){return ["umask 077",`mkdir -p ${P}/certs`,`chmod 700 ${P} ${P}/certs`,`chmod 700 ${Pe} 2>/dev/null || true`,`chmod 600 ${oe} 2>/dev/null || true`,`if [ ! -f ${ct} ]; then openssl genrsa -out ${ct} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${Y} ]; then openssl req -x509 -new -nodes -key ${ct} -sha256 -days 30 -subj "/CN=Evolve Managed Secrets" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ${Y} >/dev/null 2>&1; fi`,`SYSTEM_CA_BUNDLE=""; for p in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem; do if [ -f "$p" ]; then SYSTEM_CA_BUNDLE="$p"; break; fi; done; if [ -n "$SYSTEM_CA_BUNDLE" ]; then cat "$SYSTEM_CA_BUNDLE" ${Y} > ${se}; else cp ${Y} ${se}; fi`,`if command -v update-ca-certificates >/dev/null 2>&1; then cp ${Y} /usr/local/share/ca-certificates/evolve-managed-secrets.crt 2>/dev/null && update-ca-certificates >/dev/null 2>&1 || true; fi`].join(" && ")}function _i(){return `umask 077 && exec python3 ${Pe} ${oe}`}function Ti(){return `rm -f ${oe}`}var ut=256,Ri=100*1024*1024,Pi=500*1024*1024;function Ie(t){return `'${t.replaceAll("'",`'"'"'`)}'`}function aa(t){let e=t.trim();if(e==="")return [];let n=Buffer.from(e,"base64"),r=[],i=0;for(let s=0;s<n.length;s++)n[s]===0&&(r.push(n.toString("utf8",i,s)),i=s+1);return i<n.length&&r.push(n.toString("utf8",i,n.length)),r}async function Ii(t,e,n){if(n.length===0||n.length>ut)throw new Error(`collectArtifacts() requires between 1 and ${ut} paths.`);let r=n.map(u=>{if(!u||u.includes("\0"))throw new Error(`Invalid artifact path: ${JSON.stringify(u)}`);let p=posix.normalize(u);if(!posix.isAbsolute(p)&&(p===".."||p.startsWith("../")))throw new Error(`Artifact path escapes the working directory: ${u}`);return posix.isAbsolute(p)?p:posix.join(e,p)}),s=(await t.commands.run(r.map(u=>`if [ ! -e ${Ie(u)} ]; then echo MISSING ${Ie(u)}; elif [ ! -r ${Ie(u)} ]; then echo UNREADABLE ${Ie(u)}; fi`).join("; "),{cwd:e,timeoutMs:15e3})).stdout.split(`
|
|
586
|
+
`).map(u=>u.trim()).filter(Boolean);if(s.length>0)throw new Error(`Artifact roots are not collectable: ${s.join("; ")}`);let c;try{c=await t.commands.run(`set -o pipefail 2>/dev/null; find -- ${r.map(Ie).join(" ")} -type f -printf '%p\\0%s\\0' | base64 -w0`,{cwd:e,timeoutMs:3e4});}catch(u){throw new Error(`Artifact listing failed: ${u.message}`)}if(c.exitCode!==0)throw new Error(`Artifact listing failed (exit ${c.exitCode}): ${(c.stderr||"").slice(0,500)}`);let a=aa(c.stdout);if(a.length%2!==0)throw new Error("Sandbox returned malformed artifact metadata.");let l=new Map,d=0;for(let u=0;u<a.length;u+=2){let p=a[u],g=Number(a[u+1]);if(!Number.isSafeInteger(g)||g<0)throw new Error(`Sandbox returned an invalid artifact size: ${p}`);if(g>Ri)throw new Error(`Artifact exceeds ${Ri} bytes: ${p}`);l.has(p)||(l.set(p,g),d+=g);}if(l.size>ut)throw new Error(`Artifact collection exceeds ${ut} files.`);if(d>Pi)throw new Error(`Artifact collection exceeds ${Pi} bytes.`);let o={};for(let u of [...l.keys()].sort()){let p=r.some(m=>u===m||u.startsWith(`${m.replace(/\/$/,"")}/`));if(!posix.isAbsolute(u)||!p)throw new Error(`Sandbox returned an invalid artifact path: ${u}`);let g=posix.relative(e,u),f=g&&g!==".."&&!g.startsWith("../")?g:u;o[f]=await t.files.read(u);}return o}var pt="EVOLVE_PROVIDER_RUNTIME_BINDING",bn="gemini-api-key";function Ae(t){switch(t){case "claude":return "anthropic";case "codex":return "openai";case "gemini":return "gemini";case "qwen":return "dashscope";case "kimi":return "kimi";case "opencode":return "openrouter";case "droid":return "droid";default:return null}}function ua(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function Ai(t){return `${t}-${randomBytes(8).toString("hex")}`}function vn(t,e,n="newline"){let r=new Map;if(t){let i=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let s of i){let c=s.trim();if(!c)continue;let a=c.indexOf(":");if(a<=0)continue;let l=c.slice(0,a).trim(),d=c.slice(a+1).trim();r.set(l.toLowerCase(),`${l}: ${d}`);}}for(let[i,s]of Object.entries(e)){let c=i.toLowerCase();if(c===u&&r.has(c)&&n==="newline"){let a=r.get(c),l=a.slice(a.indexOf(":")+1).trim();r.set(c,`${i}: ${l},${s}`);}else r.set(c,`${i}: ${s}`);}return Array.from(r.values()).join(n==="comma"?", ":`
|
|
587
|
+
`)}var pa=262144,ga=128e3;function Oi(t,e){if(t.models.some(i=>i.alias===e||i.modelId===e))return true;let n=t.gatewayModelAliases;if(n&&(e in n||Object.values(n).includes(e)))return true;let r=t.directModelAliases;return !!(r&&(e in r||Object.values(r).includes(e)))}var fa=new Set(["low","medium","high","xhigh","max"]);function Mi(t){if(t)return fa.has(t)?t:void 0}function gt(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var Oe=class{agentConfig;options;sandbox;hasRun=false;workingDir;homeDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;providerRuntimeToken;managedSecretRuntimeToken;managedSecretProxy;credentialsSealed=false;skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(ye(e),Ht(n.observability),n.managedSecrets){if(e.isDirectMode)throw new Error("managed secrets are available only in gateway mode with EVOLVE_API_KEY");if(n.sandboxId)throw new Error("managed secrets cannot be used with an existing sandbox; grants are sandbox-scoped.");if(n.sandboxProvider&&!we(n.sandboxProvider))throw new Error("managed secrets require an Evolve-managed sandbox provider")}if(this.agentConfig=e,this.options=n,n.sandboxId&&n.sandboxCreateOptions?.user)throw new Error("sandbox user cannot be enforced when attaching to an existing sandbox; create a fresh sandbox with the user instead");if(this.homeDir=r(n.sandboxCreateOptions?.user,n.sandboxCreateOptions?.homeDir),this.homeDir!==q){if(n.storage)throw new Error("Checkpoint storage requires the default /home/user sandbox home directory; remove sandbox user/homeDir or storage");if(n.managedBrowser||n.browserCredentials)throw new Error("Managed browser features require the default /home/user sandbox home directory")}if(this.workingDir=n.workingDirectory||n.sandboxCreateOptions?.workingDirectory||`${this.homeDir}/workspace`,this.sandboxState=n.sandboxId?"ready":"stopped",n.workspaceMode==="task"&&[n.context,n.files,n.systemPrompt,n.browserPrompt,n.schema].some(Boolean))throw new Error('workspaceMode "task" cannot be combined with context, files, systemPrompt, browserPrompt, or schema; the task owns the working directory');if(this.skills=n.skills,this.storage=n.storage,n.schema)if(D(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 r=this.createAjvValidator();this.compiledValidator=r.compile(this.jsonSchema);}catch(r){throw new Error(`Invalid JSON Schema: ${r.message}`)}}this.registry=I(e.type),this.sessionTag=Ai(n.sessionTagPrefix||"evolve");}browserRuntimeInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl,sessionId:this.managedBrowserSession.sessionId,sessionTag:this.managedBrowserSession.sessionTag}}browserResponseInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl}}emitLifecycle(e,n){let r=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...r?{browser:r}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,r,i){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(r,i),s}finalizeOperation(e,n,r,i="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=i,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,i,s){let c=n==="run"?"run_background_complete":"command_background_complete",a=n==="run"?"run_background_failed":"command_background_failed",l=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async d=>{if(this.interruptedOperations.delete(e)||d.exitCode===130){this.finalizeOperation(e,i,l,"interrupted");return}n==="run"&&s&&await this.writeDroidSessionState(s);let u=d.exitCode===0?c:a,p=d.exitCode===0?"idle":"error";this.finalizeOperation(e,i,u,p);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,i,a,"error");});}createAjvValidator(){let n={...Ct[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 ca({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot create or attach another 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");let r=false;try{if(this.options.sandboxId)(this.options.mcpServers||this.options.integrations||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser||this.options.browserCredentials)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, integrations, plugins, context, files, systemPrompt, managed browser setup, and browser credentials"),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 {await this.ensureManagedBrowserSession(e),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let i=this.buildEnvironmentVariables();this.sandbox=await n.create(this.buildSandboxCreateOptions(i)),r=!0,await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox),await this.setupManagedBrowser(this.sandbox),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 r&&this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),i}return this.sandbox}resolveKimiMaxContextSize(){if(typeof this.agentConfig.maxContextSize=="number")return this.agentConfig.maxContextSize;let e=this.agentConfig.model||this.registry.defaultModel;return Oi(this.registry,e)||Oi(this.registry,this.resolveCommandModel(e))?this.registry.models.find(i=>i.alias===e||i.modelId===e)?.maxContextSize??this.registry.spendTrackingTomlProvider?.maxContextSize??pa:ga}reasoningEffort(){return Un(this.agentConfig.type,this.agentConfig.reasoningEffort)}buildKimiDirectModelEnvs(){let e=ge(this.reasoningEffort()),n=Mi(this.reasoningEffort()),r={KIMI_MODEL_NAME:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),KIMI_MODEL_API_KEY:this.agentConfig.apiKey,KIMI_MODEL_PROVIDER_TYPE:"kimi",KIMI_MODEL_MAX_CONTEXT_SIZE:String(this.resolveKimiMaxContextSize()),KIMI_MODEL_DEFAULT_THINKING:e?"true":"false",KIMI_MODEL_THINKING_MODE:e?"on":"off"};return n&&(r.KIMI_MODEL_THINKING_EFFORT=n),this.agentConfig.baseUrl&&(r.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl),r}buildEnvironmentVariables(){let e={},n=this.validatedUserSecretsForEnvironment();if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode)Object.assign(e,this.buildKimiDirectModelEnvs());else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){if(!(!this.agentConfig.isDirectMode&&Ae(this.agentConfig.type))){if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let r of Object.values(this.registry.providerEnvMap))e[r.keyEnv]=this.agentConfig.apiKey;else {let r=this.agentConfig.model?.split("/")[0],i=r?this.registry.providerEnvMap?.[r]:void 0,s=i?i.keyEnv:this.registry.apiKeyEnv,c=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:s;e[c]=this.agentConfig.apiKey;}}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let r=a(this.registry.gatewayPath),i=this.requireActiveProviderRuntimeToken();if(this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[t]:this.sessionTag,...this.providerRuntimeHeaderUpdates()}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=i?.baseUrl??r),i&&(this.shouldExposeProviderRuntimeTokenEnv()&&(e[this.registry.apiKeyEnv]=i.token),this.agentConfig.type==="gemini"&&(e.GEMINI_DEFAULT_AUTH_TYPE=bn),this.registry.spendTrackingEnvs&&(e[pt]=i.bindingSecret)),!i){if(Ae(this.agentConfig.type))throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);e[h]=this.agentConfig.apiKey;}}if(this.agentConfig.externalGateway&&this.registry.gatewayConfigEnv&&(e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.externalGateway&&this.agentConfig.type==="gemini"&&(e.GEMINI_CLI_TRUST_WORKSPACE="true"),this.agentConfig.type==="claude"&&(e.IS_SANDBOX="1"),this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,gn(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.managedSecretRuntimeToken&&Object.assign(e,ki(this.managedSecretRuntimeToken)),n&&Object.assign(e,n),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,i=this.registry.customHeadersFormat||"newline";e[r]=vn(e[r],{[t]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},i);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildSandboxCreateOptions(e){return {...this.options.sandboxCreateOptions,envs:e,workingDirectory:this.workingDir}}validatedUserSecretsForEnvironment(){let e={...this.options.sandboxCreateOptions?.envs,...this.options.secrets};if(Object.keys(e).length===0)return;let n=new Set;this.agentConfig.isDirectMode||(n.add(h),n.add(pt),this.agentConfig.type==="gemini"&&n.add("GEMINI_DEFAULT_AUTH_TYPE"));let r=s=>{s&&n.add(s);};r(this.registry.apiKeyEnv),r(this.registry.baseUrlEnv);for(let s of Object.values(this.registry.providerEnvMap??{}))r(s.keyEnv);if(this.managedSecretRuntimeToken)for(let s of yi())n.add(s);for(let s of this.managedSecretRuntimeToken?.env??[])r(s.envName);let i={};for(let[s,c]of Object.entries(e)){if(n.has(s))throw new Error(`${s} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);s!==this.registry.gatewayConfigEnv&&(i[s]=c);}return i}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await ai(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async ensureProviderRuntimeToken(){let e=Ae(this.agentConfig.type);if(this.agentConfig.isDirectMode||!e||!this.options.providerRouting||this.providerRuntimeToken)return;let n;try{n=await ui(this.options.providerRouting,{provider:e,sessionTag:this.sessionTag});}catch(r){throw di(r)?new Error(`${e} runtime token endpoint is required in gateway mode: ${r.message}`):r}this.providerRuntimeToken=n,this.providerRuntimeToken&&this.sandbox?.sandboxId&&await this.bindProviderRuntimeToken(this.sandbox.sandboxId);}async bindProviderRuntimeToken(e){if(!this.providerRuntimeToken||!this.options.providerRouting)return;if(!await pi(this.options.providerRouting,{token:this.providerRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind provider runtime token to sandbox")}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=gn(this.options.managedBrowser.provider,this.managedBrowserSession);for(let r of n.directories)await e.files.makeDir(r);for(let r of n.files)await e.files.write(r.path,r.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await ci(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}async closeProviderRuntimeToken(e=false){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let n=this.providerRuntimeToken,r;for(let s=0;s<3;s++)try{if(!await gi(this.options.providerRouting,{token:n.token}))throw new Error("Dashboard returned ok=false");this.providerRuntimeToken=void 0;return}catch(c){r=c,s<2&&await new Promise(a=>setTimeout(a,100*(s+1)));}let i=`Provider runtime token cleanup failed: ${r.message}`;if(e)throw new Error(i);console.warn(`[Evolve] ${i}`),this.providerRuntimeToken=void 0;}async ensureManagedSecretRuntimeToken(){this.managedSecretRuntimeToken||!this.options.managedSecrets||(this.managedSecretRuntimeToken=await bi({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{sessionTag:this.sessionTag,secrets:this.options.managedSecrets.secrets}));}async bindManagedSecretRuntimeToken(e){if(!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;if(!await vi({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:this.managedSecretRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind managed secret runtime token to sandbox")}async setupManagedSecretEgress(e){if(!this.managedSecretRuntimeToken)return;if(await e.files.makeDir(P),await e.commands.run(`umask 077 && mkdir -p ${P}/certs && chmod 700 ${P} ${P}/certs`,{timeoutMs:5e3}),await e.files.write(Pe,wi),await e.files.write(oe,Ci(this.managedSecretRuntimeToken)),await e.commands.run(`chmod 700 ${Pe} && chmod 600 ${oe}`,{timeoutMs:5e3}),await e.commands.run(Ei(),{timeoutMs:3e4}),this.managedSecretProxy=await e.commands.spawn(_i(),{timeoutMs:3e4}),(await e.commands.run(`python3 - <<'PY'
|
|
588
|
+
import socket, sys, time
|
|
589
|
+
for _ in range(50):
|
|
590
|
+
try:
|
|
591
|
+
s = socket.create_connection(("127.0.0.1", ${lt}), timeout=0.2)
|
|
592
|
+
s.close()
|
|
593
|
+
sys.exit(0)
|
|
594
|
+
except OSError:
|
|
595
|
+
time.sleep(0.1)
|
|
596
|
+
sys.exit(1)
|
|
597
|
+
PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy failed to start");await e.commands.run(Ti(),{timeoutMs:5e3});}async closeManagedSecretRuntimeToken(){let e=this.managedSecretProxy;if(this.managedSecretProxy=void 0,e&&await e.kill().catch(()=>false),!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;let n=this.managedSecretRuntimeToken,r;try{for(let i=0;i<3;i++)try{if(!await Si({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:n.token}))throw new Error("Dashboard returned ok=false");return}catch(s){r=s,i<2&&await new Promise(c=>setTimeout(c,100*(i+1)));}console.warn(`[Evolve] Managed secret runtime token cleanup failed: ${r.message}`);}finally{this.managedSecretRuntimeToken=void 0;}}buildGatewayConfigJson(e){let n=this.requireActiveProviderRuntimeToken(),r=this.agentConfig.externalGateway?this.agentConfig.baseUrl??gt(a(this.registry.gatewayPath)):n?.baseUrl??gt(a(this.registry.gatewayPath)),i=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),s={},c=this.options.secrets?.[this.registry.gatewayConfigEnv];if(c)try{s=JSON.parse(c);}catch{}let a$1=s.provider??{},l=a$1.litellm??{},d=l.options??{},o=l.models??{},u=o[i]??{},p=u.headers??{},g=this.agentConfig.type==="opencode"?Et(this.reasoningEffort()):void 0,f=u.variants??{},m=g?f[g]??{}:void 0;return s.provider={...a$1,litellm:{...l,npm:"@ai-sdk/openai-compatible",options:{...d,baseURL:r,apiKey:n?.token??this.agentConfig.apiKey},models:{...o,[i]:{...u,name:i,headers:{...p,...e},...g?{variants:{...f,[g]:{...m,reasoningEffort:g}}}:{}}}}},JSON.stringify(s)}activeProviderRuntimeToken(){let e=Ae(this.agentConfig.type);return e&&this.providerRuntimeToken?.provider===e?this.providerRuntimeToken:void 0}requireActiveProviderRuntimeToken(){let e=Ae(this.agentConfig.type),n=this.activeProviderRuntimeToken();if(!this.agentConfig.isDirectMode&&e&&!n)throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);return n}ensureSessionLogger(e){if(this.sessionLogger)return;let n=this.options.sandboxProvider;this.sessionLogger=new ve({provider:n?.name||n?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:e.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}async flushSessionLoggerWithTimeout(e=2e3){this.sessionLogger&&await Promise.race([this.sessionLogger.flush(),new Promise(n=>setTimeout(n,e))]);}requiresPreRunDashboardIngest(){return !!(this.activeProviderRuntimeToken()||this.managedSecretRuntimeToken)}providerRuntimeHeaderUpdates(){let e=this.activeProviderRuntimeToken();return e?{[hn]:e.bindingSecret}:{}}shouldExposeProviderRuntimeTokenEnv(){return this.agentConfig.type!=="kimi"&&!this.registry.gatewayConfigEnv}buildProviderRuntimeProcessEnvs(){if(this.agentConfig.externalGateway){if(this.agentConfig.type==="kimi")return this.buildKimiDirectModelEnvs();let r={[this.registry.apiKeyEnv]:this.agentConfig.apiKey};return this.registry.baseUrlEnv&&this.agentConfig.baseUrl&&(r[this.registry.baseUrlEnv]=this.agentConfig.baseUrl),this.registry.gatewayConfigEnv&&(r[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.type==="gemini"&&(r.GEMINI_CLI_TRUST_WORKSPACE="true"),r}let e=this.activeProviderRuntimeToken();if(!e)return {};let n={};if(this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.apiKeyEnv]=e.token),this.agentConfig.type==="gemini"&&(n.GEMINI_DEFAULT_AUTH_TYPE=bn),this.registry.baseUrlEnv&&this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.baseUrlEnv]=e.baseUrl),this.registry.spendTrackingEnvs&&(n[pt]=e.bindingSecret),this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,i=this.registry.customHeadersFormat||"newline";n[r]=vn(this.options.secrets?.[r],this.providerRuntimeHeaderUpdates(),i);}return n}buildRunEnvs(e){if(this.agentConfig.externalGateway)return this.buildProviderRuntimeProcessEnvs();if(this.agentConfig.isDirectMode)return;let n=this.buildProviderRuntimeProcessEnvs(),r=this.registry.customHeadersEnv;if(r){let s=this.options.secrets?.[r],c=this.registry.customHeadersFormat||"newline";return n[r]=vn(s,{[t]:this.sessionTag,[u]:`${v}${e}`,...this.providerRuntimeHeaderUpdates()},c),n}let i=this.registry.spendTrackingEnvs;return i?{...n,[i.sessionTagEnv]:this.sessionTag,[i.runTagEnv]:`${v}${e}`}:this.registry.gatewayConfigEnv?{...n,[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[t]:this.sessionTag,[u]:`${v}${e}`,...this.providerRuntimeHeaderUpdates()})}:Object.keys(n).length>0?n:void 0}async writeCodexGatewayProviderConfig(e){if(this.agentConfig.type==="codex"){if(this.agentConfig.externalGateway){await qe(e,this.agentConfig.baseUrl||a(),void 0,void 0,this.homeDir);return}this.agentConfig.isDirectMode||!this.registry.spendTrackingEnvs||await qe(e,this.activeProviderRuntimeToken()?.baseUrl||this.agentConfig.baseUrl||a(),this.registry.spendTrackingEnvs,this.activeProviderRuntimeToken()?{[hn]:pt}:void 0,this.homeDir);}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(s=>typeof s.sessionId=="string"&&s.sessionId.length>0)?.sessionId;if(r){this.droidSessionId=r;return}let i=this.extractDroidSessionId(e);i&&(this.droidSessionId=i);}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,r=n.sessionId??n.session_id;return typeof r=="string"&&r.length>0?r:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}droidSessionStatePath(){return `${this.homeDir}/.factory/evolve-session.json`}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(this.droidSessionStatePath());if(typeof n!="string")return;let r=JSON.parse(n);typeof r.sessionId=="string"&&r.sessionId.length>0&&(this.droidSessionId=r.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir(`${this.homeDir}/.factory`),await e.files.write(this.droidSessionStatePath(),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=A(this.registry.mcpConfig.settingsDir,this.homeDir);await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.agentConfig.type==="gemini"&&(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&await this.writeGeminiGatewayAuthSettings(e),this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async writeGeminiGatewayAuthSettings(e){let n=A(this.registry.mcpConfig.settingsDir,this.homeDir),r=`${n}/${this.registry.mcpConfig.filename}`;await e.files.makeDir(n);let i={};try{let a=await e.files.read(r);typeof a=="string"&&a.trim()&&(i=JSON.parse(a));}catch(a){let l=a.message||"";if(!/not found|no such file|does not exist/i.test(l))throw a}let s=typeof i.security=="object"&&i.security!==null?i.security:{},c=typeof s.auth=="object"&&s.auth!==null?s.auth:{};i.security={...s,auth:{...c,selectedType:bn}},await e.files.write(r,JSON.stringify(i,null,2));}async setupAgentPlugins(e){await Xr(this.agentConfig.type,e,this.options.plugins);}assertProviderRuntimeDoesNotExposeGatewayKey(e){if(!this.activeProviderRuntimeToken())return;let n=this.agentConfig.apiKey;for(let[r,i]of Object.entries(e))for(let s of Object.values(i.headers||{}))if(s.includes(n))throw new Error(`MCP server "${r}" would expose the Evolve API key inside the sandbox. Use managed agent-browser or remove this gateway-authenticated MCP server.`)}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge";if(r!=="task"){let s=r==="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 ${s}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let c=tn({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),a=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(a,c);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);}let i={...this.options.mcpServers};if(this.options.integrations){let s=await kr({...this.options.integrations,sessionTag:this.sessionTag});i={...i,integrations:{type:"http",url:s.url,headers:s.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let s=await li({apiKey:this.options.browserCredentials.apiKey,dashboardUrl:this.options.browserCredentials.dashboardUrl,browserSessionId:this.managedBrowserSession.id,sessionTag:this.managedBrowserSession.sessionTag,grantToken:this.managedBrowserSession.browserAuthGrantToken,config:this.options.browserCredentials.config});i={...i,[fn]:s};}Object.keys(i).length>0&&(this.assertProviderRuntimeDoesNotExposeGatewayKey(i),await $t(this.agentConfig.type,e,this.workingDir,i,this.homeDir)),await this.writeCodexGatewayProviderConfig(e),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Ve(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[t]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,r=A(n.sourceDir,this.homeDir),i=A(n.targetDir,this.homeDir);await e.files.makeDir(i);for(let s of this.skills){let c=`cp -r ${r}/${s} ${i}/ 2>/dev/null || true`;await e.commands.run(c,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let r=Object.entries(n).map(([s,c])=>({path:`${this.workingDir}/context/${s}`,data:c}));if(r.length===0)return;let i=new Set(r.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));i.size>0&&await e.commands.run(`mkdir -p ${Array.from(i).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([s,c])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:c}));if(r.length===0)return;let i=new Set(r.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));i.size>0&&await e.commands.run(`mkdir -p ${Array.from(i).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:ua(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.reasoningEffort(),isDirectMode:this.agentConfig.isDirectMode,isExternalGateway:!!this.agentConfig.externalGateway,skills:this.skills,homeDir:this.homeDir})}async writeKimiPerRunConfig(e,n){if(this.agentConfig.isDirectMode||!this.registry.spendTrackingTomlProvider)return;let r=this.requireActiveProviderRuntimeToken();await Ut(e,{...this.registry.spendTrackingTomlProvider,maxContextSize:this.resolveKimiMaxContextSize()},{[t]:this.sessionTag,[u]:`${v}${n}`,...this.providerRuntimeHeaderUpdates()},{baseUrl:gt(r?.baseUrl??a(this.registry.gatewayPath)),apiKey:r?.token??this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:ge(this.reasoningEffort()),thinkingEffort:Mi(this.reasoningEffort())},this.homeDir);}async run(e,n$1){if(this.credentialsSealed)throw new Error("Agent credentials are sealed; this Evolve instance cannot run the agent again");Wt(e);let{prompt:r,timeoutMs:i=n,background:s=false,checkpointComment:c}=e,{from:a$1}=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(a$1&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(a$1==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let b=await dn(this.storage);if(!b)throw new Error('No checkpoints found for from: "latest".');a$1=b.id;}if(a$1){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");await this.ensureManagedBrowserSession(n$1),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let b=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n$1,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create(this.buildSandboxCreateOptions(b)),await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox);let v=await jr(this.sandbox,this.storage,a$1);if(await this.setupManagedBrowser(this.sandbox),v.agentType&&v.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${v.agentType}, current: ${this.agentConfig.type})`);let C=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==C)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${C})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let _=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!_}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=a$1,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n$1,"sandbox_ready");}catch(v){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n$1,"sandbox_error"),v}}let l=await this.getSandbox(n$1);await this.ensureProviderRuntimeToken(),await this.loadDroidSessionState(l),this.lastRunTimestamp=Date.now(),this.ensureSessionLogger(l),this.sessionLogger?.writePrompt(r),this.requiresPreRunDashboardIngest()&&await this.flushSessionLoggerWithTimeout();let d=this.buildCommand(r),o=randomUUID(),u$1=this.buildRunEnvs(o);if(await this.writeCodexGatewayProviderConfig(l),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await Ve(l,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[t]:this.sessionTag,[u]:`${v}${o}`,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.agentConfig.type==="qwen"&&await Pt(l,ge(this.reasoningEffort()),this.homeDir),await this.writeKimiPerRunConfig(l,o),(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&this.registry.droidGatewaySettings){let b=!!this.agentConfig.externalGateway,v$1=b?void 0:this.requireActiveProviderRuntimeToken();await We(l,{...this.registry.droidGatewaySettings,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),baseUrl:b?this.agentConfig.baseUrl??a():gt(v$1?.baseUrl??a()),apiKeyEnv:this.registry.apiKeyEnv},b?{}:{[t]:this.sessionTag,[u]:`${v}${o}`,...this.providerRuntimeHeaderUpdates()},this.homeDir);}let p="",g=J(this.agentConfig.type),f=b=>{p+=b;let v=p.split(`
|
|
598
|
+
`);p=v.pop()??"";for(let C of v){if(!C.trim())continue;let _=g(C);if(this.captureDroidSession(C,_),this.sessionLogger?.writeEventParsed(C,_),n$1?.onStdout?.(C+`
|
|
599
|
+
`),_&&n$1?.onContent)for(let V of _)n$1.onContent(V);}},m=b=>{n$1?.onStderr?.(b);},h=await l.commands.spawn(d,{cwd:this.workingDir,timeoutMs:i,envs:u$1,onStdout:f,onStderr:m}),y=this.beginOperation("run",h,n$1,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(y,"run",h,n$1,l),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:0,stdout:`Background process started with ID ${h.processId}`,stderr:""};let w;try{w=await h.wait();}catch(b){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n$1,"run_failed","error"),b}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,n$1,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,n$1,"run_complete","idle"):this.finalizeOperation(y,n$1,"run_failed","error"),p.trim()){let b=g(p);if(this.captureDroidSession(p,b),this.sessionLogger?.writeEventParsed(p,b),n$1?.onStdout?.(p+`
|
|
600
|
+
`),b&&n$1?.onContent)for(let v of b)n$1.onContent(v);}await this.writeDroidSessionState(l),this.sessionLogger&&!s&&await this.flushSessionLoggerWithTimeout();let S;if(this.storage&&!s&&w.exitCode===0)try{S=await ln(l,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:c,parentId:this.lastCheckpointId}),this.lastCheckpointId=S.id;}catch(b){console.warn(`[Evolve] Auto-checkpoint failed: ${b.message}`);}return {sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:S}}async executeCommand(e,n$1={},r){let{timeoutMs:i=n,background:s=false}=n$1;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 c=await this.getSandbox(r);this.credentialsSealed||await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.requiresPreRunDashboardIngest()&&(this.ensureSessionLogger(c),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let a="",l="",d=h=>{a+=h,r?.onStdout?.(h);},o=h=>{l+=h,r?.onStderr?.(h);},u=this.credentialsSealed?{}:this.buildProviderRuntimeProcessEnvs(),p=await c.commands.spawn(e,{cwd:this.workingDir,timeoutMs:i,envs:Object.keys(u).length>0?u:void 0,onStdout:d,onStderr:o}),g=this.beginOperation("command",p,r,"command_start");if(s)return this.watchBackgroundOperation(g,"command",p,r),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let f;try{f=await p.wait();}catch(h){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,r,"command_failed","error"),h}return this.interruptedOperations.delete(g)||f.exitCode===130?this.finalizeOperation(g,r,"command_interrupted","interrupted"):f.exitCode===0?this.finalizeOperation(g,r,"command_complete","idle"):this.finalizeOperation(g,r,"command_failed","error"),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:f.exitCode,stdout:a||f.stdout||"",stderr:l||f.stderr||""}}async sealCredentials(){if(this.credentialsSealed)return;if(!this.sandbox)throw new Error("No active sandbox. Call run() or executeCommand() first.");if(this.activeCommand)throw new Error("Cannot seal credentials while a process is running.");if(this.agentConfig.isDirectMode&&!this.agentConfig.externalGateway)throw new Error("Credential sealing requires gateway mode; direct provider credentials cannot be revoked by Evolve");if([this.options.secrets&&Object.keys(this.options.secrets).length>0,this.options.sandboxCreateOptions?.envs&&Object.keys(this.options.sandboxCreateOptions.envs).length>0,this.options.managedSecrets,this.options.integrations,this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0,this.options.managedBrowser,this.options.browserCredentials].some(Boolean))throw new Error("Credential sealing requires a credential-minimal sandbox: omit secrets, managed secrets, integrations, MCP servers, and browser credentials");if(this.agentConfig.externalGateway){await this.agentConfig.externalGateway.revoke(),this.credentialsSealed=true;return}if(!this.providerRuntimeToken||!this.options.providerRouting)throw new Error("Cannot seal credentials: no active provider runtime token to revoke. Without a gateway-issued runtime token the sandbox may hold credentials Evolve cannot revoke, so sealing would be a false guarantee.");await this.closeProviderRuntimeToken(true),this.credentialsSealed=true;}isSealed(){return this.credentialsSealed}async collectArtifacts(e){if(!this.credentialsSealed)throw new Error("Call sealCredentials() before collecting artifacts.");if(!this.sandbox)throw new Error("No active sandbox.");if(this.activeCommand)throw new Error("Cannot collect artifacts while a process is running.");return Ii(this.sandbox,this.workingDir,e)}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 uploadFileFromPath(e,n){let r=await this.getSandbox(),i=e.startsWith("/")?e:`${this.workingDir}/${e}`,s=i.substring(0,i.lastIndexOf("/"));if(s&&await r.commands.run(`mkdir -p ${s}`,{timeoutMs:3e4}),r.files.writeFromPath){await r.files.writeFromPath(i,n);return}let{readFile:c}=await import('fs/promises');await r.files.write(i,await c(n));}async getOutputFiles(e=false){let n=await this.getSandbox(),r=`${this.workingDir}/output`,i=e?"":"-maxdepth 1",c=(await n.commands.run(`find ${r} ${i} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
601
|
+
`).filter(Boolean),a=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,l=[],d=`${r}/`;for(let f of c){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);a>0&&y<a||l.push(m);}let o={},u=await Promise.all(l.map(async f=>{try{let m=await n.files.read(f);return {relativePath:f.startsWith(d)?f.slice(d.length):f.split("/").pop()||f,content:m}}catch{return null}}));for(let f of u)f&&(o[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let p=o["result.json"];if(!p)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof p=="string"?p:new TextDecoder().decode(p);try{let f=JSON.parse(g);if(this.zodSchema){let m=this.zodSchema.safeParse(f);return m.success?{files:o,data:m.data}:{files:o,data:null,error:`Schema validation failed: ${m.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:o,data:f};{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(f){return {files:o,data:null,error:`Failed to parse result.json: ${f.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 ln(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.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");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(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),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,r=this.activeOperationKind,i=false;try{this.activeCommand?i=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(i=await this.sandbox.commands.kill(this.activeProcessId));}catch{i=false;}if(!i)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let s=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,s),i}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(r){n=r;}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession();}if(n)throw n;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=Ai(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 r=process.env.EVOLVE_DASHBOARD_URL||s,i=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!i.ok){let s=await i.text().catch(()=>"");throw new Error(`Spend query failed (${i.status}): ${s}`)}return i}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(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),i=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(i)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let c=new URLSearchParams({tag:n,runId:e.runId}),l=await(await this.fetchSpend(c)).json();return this.normalizeRunCost(l,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),i=e.index>0?e.index-1:r.runs.length+e.index,s=r.runs[i];if(!s)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return s}};function ma(t){return (t||process.env.EVOLVE_DASHBOARD_URL||s).replace(/\/$/,"")}function ha(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return e}async function ya(t){return await t.text().catch(()=>"")}async function Di(t,e,n={}){let r=await fetch(`${ma(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${ha(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await ya(r)}`);return r.status===204?{}:await r.json()}var ft=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await Di(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await Di(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function Sn(t={}){return new ft(t)}var Me=class extends EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(ye(e),tt(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},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}withManagedSecrets(e){return this.config.managedSecrets=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={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=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&&(D(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}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=Cr;static browserCredentials=mn;static browserProfiles=Sn;static managedSecrets=wn;async initializeAgent(){let e=nt(this.config.agent),n=I(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let r=xi(this.config.managedSecrets,n);if(r&&this.config.sandbox&&!we(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let i=this.config.sandbox??(r?await be(e.apiKey):await Yt()),s$1={},c,a,l=this.config.skills,d;if(this.config.browser){let p=ri(this.config.browser);if(d=p,p.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');s$1=g(e.apiKey);}if((p.provider==="actionbook"||p.provider==="agent-browser")&&(l=ii(p.provider,l),p.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${p.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);c=p.provider==="actionbook"?Xt:yr,a={provider:p.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||s,...p.profile?{profile:p.profile}:{}};}if(p.profile&&!p.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!d||d.provider!=="agent-browser"||!d.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let o=this.config.storage!==void 0?st(this.config.storage,!e.isDirectMode,s,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:i,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:r?{secrets:r,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||s}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s$1,...this.config.mcpServers},browserPrompt:c,managedBrowser:a,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||s,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||s}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||s},storage:o};this.agent=new Oe(e,u);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,i=this.listenerCount("lifecycle")>0;return {onStdout:e?s=>this.emit("stdout",s):void 0,onStderr:n?s=>this.emit("stderr",s):void 0,onContent:r?s=>this.emit("content",s):void 0,onLifecycle:i?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,...n.browser?{browser:n.browser}:{}});}async run({prompt:e,timeoutMs:n,background:r,from:i,checkpointComment:s}){if(i&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let c=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:i,checkpointComment:s},c)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.executeCommand(e,n,r)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return (await this.agent.getSandbox(e)).sandboxId}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials();}isSealed(){return this.agent?.isSealed()??false}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}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 uploadFileFromPath(e,n){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,n)}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=nt(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:s,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 pn(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return pn(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");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 ce=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 X=Symbol.for("evolve.SwarmResult"),le=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 xn=class t{config;semaphore;constructor(e={}){let n$1=e.concurrency??o;if(n$1>p)throw new Error(`concurrency=${n$1} exceeds max ${p}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:n$1,timeoutMs:e.timeoutMs??n,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations},this.semaphore=new ce(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:i,verify:s}=e,c=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs;if(i&&s)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,u)=>i?this.executeMapItemWithBestOf(o,r,u,a,e,l,c):s?this.executeMapItemWithVerify(o,r,u,a,e,l,c):c?O(p=>this.executeMapItem(o,r,u,a,e,l,p),c,u):this.executeMapItem(o,r,u,a,e,l)));return le.from(d)}async filter(e){let{items:n,prompt:r,condition:i,verify:s}=e,c=e.retry??this.config.retry,a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((u,p)=>s?this.executeFilterItemWithVerify(u,r,p,a,e,l,c):c?O(g=>this.executeFilterItem(u,r,p,a,e,l,g),c,p):this.executeFilterItem(u,r,p,a,e,l))),o=[];for(let u of d)if(u.status==="error")o.push(u);else if(u.data!==null)try{i(u.data)?o.push(u):o.push({...u,status:"filtered"});}catch(p){o.push({...u,status:"error",data:null,error:`Condition function threw: ${p.message}`});}return le.from(o)}async reduce(e){let{items:n,prompt:r,verify:i}=e,s=e.retry??this.config.retry,c=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,l=[],d=[];n.forEach((S,b)=>{l.push(this.getFiles(S)),d.push(this.getIndex(S,b));});let o={};l.forEach((S,b)=>{Object.entries(S).forEach(([v,C])=>{o[`item_${d[b]}/${v}`]=C;});});let u=rt(o),p=j(vr,{fileTree:u}),g=e.systemPrompt?`${p}
|
|
602
|
+
|
|
603
|
+
${e.systemPrompt}`:p,f=(S,b,v)=>({operationId:c,operation:"reduce",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:b,verifyRetry:v,...this.pipelineContextToMeta(e._pipelineContext)}),m=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,w=async(S,b,v,C)=>{let _=await this.semaphore.use(()=>this.execute(o,S,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:b,timeoutMs:a,observability:{swarmName:this.config.tag,operationName:e.name,operationId:c,operation:"reduce",role:"worker",errorRetry:v,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),V=f(_,v,C&&C>1?C-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:V,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:V}},k=`${this.config.tag}-reduce`;return i?this.runWithVerification((S,b,v)=>w(S,b,void 0,v),{originalPrompt:r,inputFiles:o,verifyConfig:i,timeoutMs:a,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:c,baseTag:k,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?O(S=>{let b=S>1?S-1:void 0,v=b?`${k}-er${b}`:k;return w(r,v,b)},s):w(r,k)}async bestOf(e){let{item:n,prompt:r,config:i}=e,s=e.retry??this.config.retry,c=i.n??i.taskAgents?.length;if(c===void 0)throw new Error("bestOf requires n or taskAgents");if(c<2)throw new Error("bestOf requires n >= 2");let a=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),o=i.mcpServers??this.config.mcpServers,u=i.judgeMcpServers??i.mcpServers??this.config.mcpServers,p=i.skills??this.config.skills,g=i.judgeSkills??i.skills??this.config.skills,f=i.integrations??this.config.integrations,m=i.judgeIntegrations??i.integrations??this.config.integrations,h=await Promise.all(Array.from({length:c},async(b,v)=>{let C=s?await O(_=>this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:a,config:i,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:p,integrations:f,timeoutMs:l,attempt:_}),s,v):await this.executeBestOfCandidate({inputFiles:d,prompt:r,candidateIndex:v,operationId:a,config:i,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:p,integrations:f,timeoutMs:l});return i.onCandidateComplete?.(0,v,C.status==="success"?"success":"error"),C})),y=s?await O(b=>this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:i,timeoutMs:l,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:g,integrations:m,attempt:b}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:r,candidates:h,config:i,timeoutMs:l,operationId:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:g,integrations:m}),w=h.findIndex(b=>b.status==="success"),k=y.decision?.winner??(w>=0?w:0);i.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let S={operationId:a,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:c};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:S,candidates:h}}async execute(e,n,r){let i=null,s="",c=r.tagPrefix,a={},l=null,d,o,u={...this.config.agent,...r.agent};try{i=new Me().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&i.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&i.withSystemPrompt(r.systemPrompt),r.mcpServers&&i.withMcpServers(r.mcpServers),r.skills?.length&&i.withSkills(r.skills),r.integrations&&i.withIntegrations(r.integrations),r.observability&&i.withObservability(r.observability),Object.keys(e).length>0&&i.withContext(e);let p=await i.run({prompt:n,timeoutMs:r.timeoutMs});s=p.sandboxId,c=i.getSessionTag()??r.tagPrefix;let g=null;try{g=await i.getOutputFiles(!0),a=g.files;}catch{}p.exitCode!==0?d=`Agent exited with code ${p.exitCode}`:r.schema?g?(l=g.data,g.error&&(d=g.error),g.rawData&&(o=g.rawData)):d="Failed to read output files from sandbox":l=a;}catch(p){if(d=p.message,i){c=i.getSessionTag()??r.tagPrefix;try{a=(await i.getOutputFiles(!0)).files;}catch{}}}finally{i&&await i.kill().catch(()=>{});}return {files:a,data:l,tag:c,sandboxId:s,error:d,rawData:o}}async executeMapItem(e,n,r,i,s,c,a=1){let l=this.getFiles(e),d=a>1?`${this.config.tag}-map-${r}-er${a-1}`:`${this.config.tag}-map-${r}`,o=this.evaluatePrompt(n,l,r);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:r});let u=s.mcpServers??this.config.mcpServers,p=s.skills??this.config.skills,g=s.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(l,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:d,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:s.name,operationId:i,operation:"map",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),m={operationId:i,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,i,s,c,a){let l=this.getFiles(e),d=`${this.config.tag}-map-${r}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,p=s.skills??this.config.skills,g=s.integrations??this.config.integrations,f=this.evaluatePrompt(n,l,r);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:r});let m=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(l,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:y,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:s.name,operationId:i,operation:"map",itemIndex:r,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),S={operationId:i,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:r,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(k,S)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:l,verifyConfig:o,timeoutMs:c,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:p,integrations:g,operationId:i,baseTag:d,retry:a,itemIndex:r,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,n,r,i,s,c,a){let l=this.getFiles(e),d=`${this.config.tag}-map-${r}`,o=this.evaluatePrompt(n,l,r);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:r});let u=s.bestOf,p=u.n??u.taskAgents?.length;if(p===void 0||p<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:i,operation:"map",tag:d,sandboxId:"",itemIndex:r});let g=s.mcpServers??this.config.mcpServers,f=u.mcpServers??g,m=u.judgeMcpServers??u.mcpServers??g,h=s.skills??this.config.skills,y=u.skills??h,w=u.judgeSkills??u.skills??h,k=s.integrations??this.config.integrations,S=u.integrations??k,b=u.judgeIntegrations??u.integrations??k,v=await Promise.all(Array.from({length:p},async(De,Ue)=>{let Cn=a?await O(Bi=>this.executeBestOfCandidate({inputFiles:l,prompt:o,candidateIndex:Ue,operationId:i,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:c,parentIndex:r,attempt:Bi,_pipelineContext:s._pipelineContext}),a,Ue):await this.executeBestOfCandidate({inputFiles:l,prompt:o,candidateIndex:Ue,operationId:i,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:y,integrations:S,timeoutMs:c,parentIndex:r,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(r,Ue,Cn.status==="success"?"success":"error"),Cn})),C=a?await O(De=>this.executeBestOfJudge({inputFiles:l,taskPrompt:o,candidates:v,config:u,timeoutMs:c,operationId:i,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:m,skills:w,integrations:b,parentIndex:r,attempt:De,_pipelineContext:s._pipelineContext}),{...a,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:o,candidates:v,config:u,timeoutMs:c,operationId:i,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:m,skills:w,integrations:b,parentIndex:r,_pipelineContext:s._pipelineContext}),_=v.findIndex(De=>De.status==="success"),V=C.decision?.winner??(_>=0?_:0),kn=v[V]??v[0];u.onJudgeComplete?.(r,V,C.decision?.reasoning??"Judge failed to provide reasoning");let $i={operationId:i,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:p,...this.pipelineContextToMeta(s._pipelineContext)};return {...kn,meta:{...kn.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:r,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:V,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:$i,candidates:v}}}async executeFilterItem(e,n,r,i,s,c,a=1){let l=this.getFiles(e),d=a>1?`${this.config.tag}-filter-${r}-er${a-1}`:`${this.config.tag}-filter-${r}`,o=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,p=s.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(l,n,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:u,integrations:p,tagPrefix:d,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:s.name,operationId:i,operation:"filter",itemIndex:r,role:"worker",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:i,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:r,errorRetry:a>1?a-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(g,f,l)}async executeFilterItemWithVerify(e,n,r,i,s,c,a){let l=this.getFiles(e),d=`${this.config.tag}-filter-${r}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,p=s.skills??this.config.skills,g=s.integrations??this.config.integrations,f=async(m,h,y)=>{let w=await this.semaphore.use(()=>this.execute(l,m,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:p,integrations:g,tagPrefix:h,timeoutMs:c,observability:{swarmName:this.config.tag,operationName:s.name,operationId:i,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),k={operationId:i,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(w,k,l)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:l,verifyConfig:o,timeoutMs:c,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:p,integrations:g,operationId:i,baseTag:d,retry:a,itemIndex:r,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:i,operationId:s,config:c,timeoutMs:a,parentIndex:l,attempt:d=1,_pipelineContext:o}=e,u=l!==void 0?`${this.config.tag}-map-${l}-bestof-cand-${i}`:`${this.config.tag}-bestof-cand-${i}`,p=d>1?`${u}-er${d-1}`:u,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:c.taskAgents?.[i],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:p,timeoutMs:a,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:l,role:"candidate",candidateIndex:i,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(o)}})),f={operationId:s,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:i,errorRetry:d>1?d-1:void 0,candidateIndex:i,...this.pipelineContextToMeta(o)};return this.buildResult(g,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((r,i)=>{r.status==="error"&&(n[`candidate_${i}/_failed.txt`]=`STATUS: FAILED
|
|
604
|
+
|
|
605
|
+
Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([s,c])=>{n[`candidate_${i}/${s}`]=c;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:i,operationId:s,parentIndex:c,attempt:a=1,_pipelineContext:l}=e,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=a>1?`${d}-er${a-1}`:d,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),p=rt(u),g=j(Qt,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:p}),f=z.object({winner:z.number().min(0).max(n.length-1),reasoning:z.string()}),m=await this.semaphore.use(()=>this.execute(u,wr,{systemPrompt:g,schema:f,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:o,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:c,role:"judge",errorRetry:a>1?a-1:void 0,...this.pipelineContextToObservability(l)}})),h=null;if(m.data&&!m.error)h=m.data;else if(m.rawData)try{let y=JSON.parse(m.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: ${m.error}`);}return {status:h?"success":"error",decision:h,tag:m.tag,sandboxId:m.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=z.object({passed:z.boolean(),reasoning:z.string(),feedback: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(([r,i])=>{n[`worker_output/${r}`]=i;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:i,workerTag:s,retryAttempt:c=1,operation:a,itemIndex:l,attemptIndex:d,_pipelineContext:o}=e,u=c>1?`${s}-verifier-er${c-1}`:`${s}-verifier`,p=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,f=n.verifierIntegrations??e.integrations,m=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=rt(m),y=j(Zt,{criteria:n.criteria,fileTree:h}),w=await this.semaphore.use(()=>this.execute(m,br,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:p,skills:g,integrations:f,tagPrefix:u,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:i,operation:a,itemIndex:l,role:"verifier",verifyRetry:d&&d>1?d-1:void 0,errorRetry:c>1?c-1:void 0,...this.pipelineContextToObservability(o)}})),k=null;if(w.data&&!w.error)k=w.data;else if(w.rawData)try{let S=JSON.parse(w.rawData);k={passed:!!S.passed,reasoning:S.reasoning??"Verification completed",feedback:S.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,n){return j(en,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:i,verifyConfig:s,timeoutMs:c,operationId:a,baseTag:l,retry:d,itemIndex:o=0,operation:u,_pipelineContext:p}=n,g=s.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let w=h>1?`${l}-vr${h-1}`:l,k=d?await O(v=>e(f,v>1?`${w}-er${v-1}`:w,h),d,o):await e(f,w,h);if(s.onWorkerComplete?.(o,h,k.status==="error"?"error":"success"),k.status==="error")return k;m=k;let S=d?await O(v=>this.executeVerify({inputFiles:i,outputFiles:k.files,taskPrompt:f,config:s,timeoutMs:c,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,retryAttempt:v,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:p}),{...d,retryOn:void 0}):await this.executeVerify({inputFiles:i,outputFiles:k.files,taskPrompt:f,config:s,timeoutMs:c,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:a,workerTag:w,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:p}),b={operationId:a,operation:"verify",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)};if(s.onVerifierComplete?.(o,h,S.decision?.passed??false,S.decision?.feedback),S.decision?.passed)return {...k,verify:{passed:true,reasoning:S.decision.reasoning,verifyMeta:b,attempts:h}};if(h<g){let v=S.decision?.feedback??S.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(r,v);}}let y=h>1?`${l}-vr${h-1}`:l;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:a,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)},attempts:h}}}generateOperationId(){return randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,r){if(typeof e=="string")return e;try{return e(n,r)}catch(i){return i}}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"]=D(e.schema)?ee(e.schema):te(e.schema)),Object.entries(e.inputFiles).forEach(([r,i])=>{n[`worker_task/input/${r}`]=i;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&X in e&&e[X]===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,r){let i=r??e.files;return e.error?{[X]:true,status:"error",data:null,files:i,meta:n,error:e.error,rawData:e.rawData}:{[X]:true,status:"success",data:e.data,files:i,meta:n}}buildErrorResult(e,n){return {[X]:true,status:"error",data:null,files:{},meta:n,error:e}}};var mt=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}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 ht(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=randomBytes(8).toString("hex"),r=[],i=e,s=Date.now();for(let a=0;a<this.steps.length;a++){let l=this.steps[a],d=l.config.name,o=Date.now();this.events.onStepStart?.({type:l.type,index:a,name:d,itemCount:i.length});let u={pipelineRunId:n,pipelineStepIndex:a};try{let p=await this.executeStep(l,i,a,d,u),g=Date.now()-o;if(r.push({type:l.type,index:a,durationMs:g,results:p.output}),this.events.onStepComplete?.({type:l.type,index:a,name:d,durationMs:g,successCount:p.successCount,errorCount:p.errorCount,filteredCount:p.filteredCount}),l.type==="reduce")return {pipelineRunId:n,steps:r,output:p.output,totalDurationMs:Date.now()-s};i=p.nextItems;}catch(p){throw this.events.onStepError?.({type:l.type,index:a,name:d,error:p instanceof Error?p:new Error(String(p))}),p}}let c=r[r.length-1];return {pipelineRunId:n,steps:r,output:c?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,r,i,s){if(e.type==="map"){let l=e.config,d=await this.swarm.map({items:n,...l,_pipelineContext:s,retry:this.wrapRetry(l.retry,r,i),verify:this.wrapVerify(l.verify,r,i),bestOf:this.wrapBestOf(l.bestOf,r,i)});return {output:[...d],nextItems:d.success,successCount:d.success.length,errorCount:d.error.length,filteredCount:0}}if(e.type==="filter"){let l=e.config,d=await this.swarm.filter({items:n,...l,_pipelineContext:s,retry:this.wrapRetry(l.retry,r,i),verify:this.wrapVerify(l.verify,r,i)}),o=l.emit??"success",u=o==="success"?d.success:o==="filtered"?d.filtered:[...d.success,...d.filtered];return {output:[...d],nextItems:u,successCount:d.success.length,errorCount:d.error.length,filteredCount:d.filtered.length}}let c=e.config,a=await this.swarm.reduce({items:n,...c,_pipelineContext:s,retry:this.wrapRetry(c.retry,r,i),verify:this.wrapVerify(c.verify,r,i)});return {output:a,nextItems:[],successCount:a.status==="success"?1:0,errorCount:a.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(i,s,c)=>{e.onItemRetry?.(i,s,c),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:i,attempt:s,error:c});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(i,s,c)=>{e.onWorkerComplete?.(i,s,c),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:i,attempt:s,status:c});},onVerifierComplete:(i,s,c,a)=>{e.onVerifierComplete?.(i,s,c,a),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:i,attempt:s,passed:c,feedback:a});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(i,s,c)=>{e.onCandidateComplete?.(i,s,c),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:i,candidateIndex:s,status:c});},onJudgeComplete:(i,s,c)=>{e.onJudgeComplete?.(i,s,c),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:i,winnerIndex:s,reasoning:c});}}}},ht=class t extends mt{constructor(e,n,r){super(e,n,r);}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]: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")}};var _a=6e5,Ta=5e3;function Ui(t,e,n){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be a positive number`);return r}function Ra(t){let e=t?.apiKey||process.env[h];if(!e)throw new Error(`sessions() requires an API key. Set ${h} or pass { apiKey } in config.`);let n=t?.dashboardUrl||s;async function r(a,l){let d=await fetch(`${n}${a}`,{...l,headers:{Authorization:`Bearer ${e}`,...l?.headers}});if(!d.ok){let o=await d.text().catch(()=>"");throw new Error(`Dashboard API error (${d.status}): ${o||d.statusText}`)}return d}function i(a){return {id:a.id,tag:a.tag,agent:a.agent,model:a.model||null,provider:a.provider,sandboxId:a.sandboxId||null,state:a.isEnded?"ended":"live",runtimeStatus:a.runtimeStatus||"unknown",cost:typeof a.cost=="number"?a.cost:null,createdAt:a.createdAt,endedAt:a.endedAt||null,stepCount:a.stepCount||0,toolStats:a.toolStats||null}}function s$1(a,l){if(a.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(a.status||"unknown")})`);if(typeof a.replayUrl!="string"||typeof a.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:a.sessionId||l,status:"ready",replayUrl:a.replayUrl,downloadUrl:a.downloadUrl,suggestedStartSeconds:typeof a.suggestedStartSeconds=="number"?a.suggestedStartSeconds:void 0,sizeBytes:typeof a.sizeBytes=="number"?a.sizeBytes:void 0,readyAt:typeof a.readyAt=="string"?a.readyAt:void 0}}let c=a=>new Promise(l=>setTimeout(l,a));return {async list(a){let l=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(a?.limit??20,200)),paginated:"true"});if(a?.cursor&&l.set("cursor",a.cursor),a?.state&&a.state!=="all"&&l.set("state",a.state),a?.agent&&l.set("agent",a.agent),a?.tagPrefix&&l.set("tagPrefix",a.tagPrefix),a?.sort){let u={newest:"desc",oldest:"asc",cost:"desc"};l.set("sortDirection",u[a.sort]),a.sort==="cost"?l.set("sortField","cost"):l.set("sortField","timestamp");}let o=await(await r(`/api/sessions?${l}`)).json();return {items:(o.items||[]).map(i),nextCursor:o.nextCursor||null,hasMore:!!o.hasMore}},async get(a){let d=await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json();return i(d)},async events(a,l){let d=new URLSearchParams;l?.since!=null&&d.set("since",String(l.since));let o=d.toString();return (await(await r(`/api/sessions/${encodeURIComponent(a)}/events${o?`?${o}`:""}`)).json()).events||[]},async download(a,l){let u=(await(await r(`/api/sessions/${encodeURIComponent(a)}`)).json()).tag||a,p=await fetch(`${n}/api/sessions/${encodeURIComponent(a)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!p.ok){let h=await p.text().catch(()=>"");throw new Error(`Download failed (${p.status}): ${h||p.statusText}`)}let g=l?.to||process.cwd();await mkdir(g,{recursive:true});let f=join(g,`${u}.jsonl`);if(!p.body)throw new Error("Download response has no body");let m=Readable.fromWeb(p.body);return await pipeline(m,createWriteStream(f)),f},async browserReplay(a,l){let d=Ui("timeoutMs",l?.timeoutMs,_a),o=Ui("intervalMs",l?.intervalMs,Ta),u=Date.now()+d,p=`/api/sessions/${encodeURIComponent(a)}/browser-replay`;for(;;){let g=u-Date.now();if(g<=0)throw new Error(`Browser replay timed out after ${d}ms`);let f;try{f=await fetch(`${n}${p}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,g))});}catch(h){let y=h.name;throw y==="AbortError"||y==="TimeoutError"?new Error(`Browser replay timed out after ${d}ms`):h}let m={};if(f.ok)m=await f.json();else {let h=await f.text().catch(()=>"");throw new Error(`Dashboard API error (${f.status}): ${h||f.statusText}`)}if(m.status==="ready")return s$1(m,a);if(m.status==="failed"){let h=typeof m.error=="string"?m.error:"unknown error";throw new Error(`Browser replay failed: ${h}`)}if(Date.now()>=u)throw new Error(`Browser replay timed out after ${d}ms`);await c(Math.min(o,Math.max(0,u-Date.now())));}}}}export{Z as AGENT_REGISTRY,es as AGENT_TYPES,Oe as Agent,Mn as BINARY_EFFORT_VALUES,Xt as BROWSER_ACTIONBOOK_PROMPT,fn as BROWSER_LOGIN_MCP_SERVER_NAME,at as BrowserCredentialsClient,ft as BrowserProfilesClient,Dn as DEFAULT_REASONING_EFFORT,Me as Evolve,H as EvolveConfigError,Qt as JUDGE_PROMPT,mt as Pipeline,On as REASONING_EFFORTS,en as RETRY_FEEDBACK_PROMPT,hr as SCHEMA_PROMPT,X as SWARM_RESULT_BRAND,mr as SYSTEM_PROMPT,ce as Semaphore,xn as Swarm,le as SwarmResultList,ht as TerminalPipeline,Ct as VALIDATION_PRESETS,Zt as VERIFY_PROMPT,gr as WORKSPACE_PROMPT,fr as WORKSPACE_SWE_PROMPT,j as applyTemplate,mn as browserCredentials,Sn as browserProfiles,tn as buildWorkerSystemPrompt,J as createAgentParser,Je as createClaudeParser,Ye as createCodexParser,Xe as createDroidParser,Qe as createGeminiParser,O as executeWithRetry,A as expandPath,I as getAgentConfig,F as getMcpSettingsDir,N as getMcpSettingsPath,ts as harnessEffortVocabulary,qn as isAgentWorkUpdate,_t as isValidAgentType,D as isZodSchema,te as jsonSchemaToString,Ks as managedSandbox,wn as managedSecrets,$s as parseNdjsonLine,Bs as parseNdjsonOutput,Hn as parseQwenOutput,Jn as readLocalDir,st as resolveStorageConfig,Yn as saveLocalDir,Ra as sessions,Do as storage,Ke as writeClaudeMcpConfig,He as writeCodexMcpConfig,We as writeDroidGatewaySettings,ze as writeDroidMcpConfig,je as writeGeminiMcpConfig,$t as writeMcpConfig,Ge as writeQwenMcpConfig,ee as zodSchemaToJson};
|