@evolvingmachines/sdk 0.0.38 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -7
- package/dist/index.d.ts +3 -7
- package/dist/index.js +1 -1
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -248,7 +248,7 @@ cdp_endpoint = ${JSON.stringify(e.cdpUrl)}
|
|
|
248
248
|
`);u=S.pop()??"";for(let b of S){if(!b.trim())continue;let _=g(b);if(this.captureDroidSession(b,_),this.sessionLogger?.writeEventParsed(b,_),n?.onStdout?.(b+`
|
|
249
249
|
`),_&&n?.onContent)for(let L of _)n.onContent(L);}},f=v=>{n?.onStderr?.(v);},h=await c.commands.spawn(d,{cwd:this.workingDir,timeoutMs:a,envs:p,onStdout:m,onStderr:f}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,i)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.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(v){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n,"run_failed","error"),v}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,n,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,n,"run_complete","idle"):this.finalizeOperation(y,n,"run_failed","error"),u.trim()){let v=g(u);if(this.captureDroidSession(u,v),this.sessionLogger?.writeEventParsed(u,v),n?.onStdout?.(u+`
|
|
250
250
|
`),v&&n?.onContent)for(let S of v)n.onContent(S);}await this.writeDroidSessionState(c),this.sessionLogger&&!i&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let x;if(this.storage&&!i&&w.exitCode===0)try{x=await Ct(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:l,parentId:this.lastCheckpointId}),this.lastCheckpointId=x.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:x}}async executeCommand(e,n={},s){let{timeoutMs:a=oe,background:i=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let l=await this.getSandbox(s);this.lastRunTimestamp=Date.now();let r="",c="",d=f=>{r+=f,s?.onStdout?.(f);},o=f=>{c+=f,s?.onStderr?.(f);},p=await l.commands.spawn(e,{cwd:this.workingDir,timeoutMs:a,onStdout:d,onStderr:o}),u=this.beginOperation("command",p,s,"command_start");if(i)return this.watchBackgroundOperation(u,"command",p,s),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let g;try{g=await p.wait();}catch(f){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,s,"command_failed","error"),f}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,s,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,s,"command_complete","idle"):this.finalizeOperation(u,s,"command_failed","error"),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:g.exitCode,stdout:r||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),s=`${this.workingDir}/output`,a=e?"":"-maxdepth 1",l=(await n.commands.run(`find ${s} ${a} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
251
|
-
`).filter(Boolean),r=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${s}/`;for(let m of l){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);r>0&&y<r||c.push(f);}let o={},p=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(d)?m.slice(d.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of p)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await Ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=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,s=this.activeOperationKind,a=false;try{this.activeCommand?a=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(a=await this.sandbox.commands.kill(this.activeProcessId));}catch{a=false;}if(!a)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let i=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,i),a}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(s){n=s;}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=as(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 s=process.env.EVOLVE_DASHBOARD_URL||R,a=await fetch(`${s}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Spend query failed (${a.status}): ${i}`)}return a}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(s=>this.normalizeRunCost(s,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),a=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(a)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let s=await this.getSessionCost(),a=e.index>0?e.index-1:s.runs.length+e.index,i=s.runs[a];if(!i)throw new Error(`Run index ${e.index} out of range. Session has ${s.runs.length} run(s).`);return i}};var pe=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"actionbook",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}withStorage(e){return this.config.storage=e||{},this}static composio=wt;async initializeAgent(){let e=Me(this.config.agent),n=this.config.sandbox??await lt(),s={},a,i,l=this.config.skills;if(this.config.browser){let d=es(this.config.browser);if(d.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=Ot(e.apiKey);}if((d.provider==="actionbook"||d.provider==="agent-browser")&&(l=ts(d.provider,l),d.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);a=d.provider==="actionbook"?dt:pn,i={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||R};}}let r=this.config.storage!==void 0?Fe(this.config.storage,!e.isDirectMode,R,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s,...this.config.mcpServers},browserPrompt:a,managedBrowser:i,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:r};this.agent=new de(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,a=this.listenerCount("lifecycle")>0;return {onStdout:e?i=>this.emit("stdout",i):void 0,onStderr:n?i=>this.emit("stderr",i):void 0,onContent:s?i=>this.emit("content",i):void 0,onLifecycle:a?i=>this.emit("lifecycle",i):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:s,from:a,checkpointComment:i}){if(a&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s,from:a,checkpointComment:i},l)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Me(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:R,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 Et(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Et(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 z=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 Rt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??At;if(n>Ze)throw new Error(`concurrency=${n} exceeds max ${Ze}. 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??oe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,p)=>a?this.executeMapItemWithBestOf(o,s,p,r,e,c,l):i?this.executeMapItemWithVerify(o,s,p,r,e,c,l):l?P(u=>this.executeMapItem(o,s,p,r,e,c,u),l,p):this.executeMapItem(o,s,p,r,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:s,condition:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>i?this.executeFilterItemWithVerify(p,s,u,r,e,c,l):l?P(g=>this.executeFilterItem(p,s,u,r,e,c,g),l,u):this.executeFilterItem(p,s,u,r,e,c))),o=[];for(let p of d)if(p.status==="error")o.push(p);else if(p.data!==null)try{a(p.data)?o.push(p):o.push({...p,status:"filtered"});}catch(u){o.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:s,verify:a}=e,i=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((x,v)=>{c.push(this.getFiles(x)),d.push(this.getIndex(x,v));});let o={};c.forEach((x,v)=>{Object.entries(x).forEach(([S,b])=>{o[`item_${d[v]}/${S}`]=b;});});let p=Ae(o),u=B(mn,{fileTree:p}),g=e.systemPrompt?`${u}
|
|
251
|
+
`).filter(Boolean),r=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${s}/`;for(let m of l){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);r>0&&y<r||c.push(f);}let o={},p=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(d)?m.slice(d.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of p)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await Ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=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,s=this.activeOperationKind,a=false;try{this.activeCommand?a=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(a=await this.sandbox.commands.kill(this.activeProcessId));}catch{a=false;}if(!a)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let i=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,i),a}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(s){n=s;}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=as(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 s=process.env.EVOLVE_DASHBOARD_URL||R,a=await fetch(`${s}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Spend query failed (${a.status}): ${i}`)}return a}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(s=>this.normalizeRunCost(s,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),a=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(a)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let s=await this.getSessionCost(),a=e.index>0?e.index-1:s.runs.length+e.index,i=s.runs[a];if(!i)throw new Error(`Run index ${e.index} out of range. Session has ${s.runs.length} run(s).`);return i}};var pe=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}withStorage(e){return this.config.storage=e||{},this}static composio=wt;async initializeAgent(){let e=Me(this.config.agent),n=this.config.sandbox??await lt(),s={},a,i,l=this.config.skills;if(this.config.browser){let d=es(this.config.browser);if(d.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=Ot(e.apiKey);}if((d.provider==="actionbook"||d.provider==="agent-browser")&&(l=ts(d.provider,l),d.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);a=d.provider==="actionbook"?dt:pn,i={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||R};}}let r=this.config.storage!==void 0?Fe(this.config.storage,!e.isDirectMode,R,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s,...this.config.mcpServers},browserPrompt:a,managedBrowser:i,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:r};this.agent=new de(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,a=this.listenerCount("lifecycle")>0;return {onStdout:e?i=>this.emit("stdout",i):void 0,onStderr:n?i=>this.emit("stderr",i):void 0,onContent:s?i=>this.emit("content",i):void 0,onLifecycle:a?i=>this.emit("lifecycle",i):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:s,from:a,checkpointComment:i}){if(a&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s,from:a,checkpointComment:i},l)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Me(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:R,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 Et(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Et(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 z=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 Rt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??At;if(n>Ze)throw new Error(`concurrency=${n} exceeds max ${Ze}. 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??oe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,p)=>a?this.executeMapItemWithBestOf(o,s,p,r,e,c,l):i?this.executeMapItemWithVerify(o,s,p,r,e,c,l):l?P(u=>this.executeMapItem(o,s,p,r,e,c,u),l,p):this.executeMapItem(o,s,p,r,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:s,condition:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>i?this.executeFilterItemWithVerify(p,s,u,r,e,c,l):l?P(g=>this.executeFilterItem(p,s,u,r,e,c,g),l,u):this.executeFilterItem(p,s,u,r,e,c))),o=[];for(let p of d)if(p.status==="error")o.push(p);else if(p.data!==null)try{a(p.data)?o.push(p):o.push({...p,status:"filtered"});}catch(u){o.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:s,verify:a}=e,i=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((x,v)=>{c.push(this.getFiles(x)),d.push(this.getIndex(x,v));});let o={};c.forEach((x,v)=>{Object.entries(x).forEach(([S,b])=>{o[`item_${d[v]}/${S}`]=b;});});let p=Ae(o),u=B(mn,{fileTree:p}),g=e.systemPrompt?`${u}
|
|
252
252
|
|
|
253
253
|
${e.systemPrompt}`:u,m=(x,v,S)=>({operationId:l,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:v,verifyRetry:S,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(x,v,S,b)=>{let _=await this.semaphore.use(()=>this.execute(o,x,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:e.name,operationId:l,operation:"reduce",role:"worker",errorRetry:S,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),L=m(_,S,b&&b>1?b-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:L,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:L}},k=`${this.config.tag}-reduce`;return a?this.runWithVerification((x,v,S)=>w(x,v,void 0,S),{originalPrompt:s,inputFiles:o,verifyConfig:a,timeoutMs:r,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:l,baseTag:k,retry:i,operation:"reduce",_pipelineContext:e._pipelineContext}):i?P(x=>{let v=x>1?x-1:void 0,S=v?`${k}-er${v}`:k;return w(s,S,v)},i):w(s,k)}async bestOf(e){let{item:n,prompt:s,config:a}=e,i=e.retry??this.config.retry,l=a.n??a.taskAgents?.length;if(l===void 0)throw new Error("bestOf requires n or taskAgents");if(l<2)throw new Error("bestOf requires n >= 2");let r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),o=a.mcpServers??this.config.mcpServers,p=a.judgeMcpServers??a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,g=a.judgeSkills??a.skills??this.config.skills,m=a.composio??this.config.composio,f=a.judgeComposio??a.composio??this.config.composio,h=await Promise.all(Array.from({length:l},async(v,S)=>{let b=i?await P(_=>this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:S,operationId:r,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c,attempt:_}),i,S):await this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:S,operationId:r,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c});return a.onCandidateComplete?.(0,S,b.status==="success"?"success":"error"),b})),y=i?await P(v=>this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:a,timeoutMs:c,operationId:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f,attempt:v}),{...i,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:a,timeoutMs:c,operationId:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);a.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:r,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:l};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:h}}async execute(e,n,s){let a=null,i="",l=s.tagPrefix,r={},c=null,d,o,p={...this.config.agent,...s.agent};try{a=new pe().withAgent(p).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(s.tagPrefix),s.schema&&a.withSchema(s.schema,s.schemaOptions),s.systemPrompt&&a.withSystemPrompt(s.systemPrompt),s.mcpServers&&a.withMcpServers(s.mcpServers),s.skills?.length&&a.withSkills(s.skills),s.composio&&a.withComposio(s.composio.userId,s.composio.config),s.observability&&a.withObservability(s.observability),Object.keys(e).length>0&&a.withContext(e);let u=await a.run({prompt:n,timeoutMs:s.timeoutMs});i=u.sandboxId,l=a.getSessionTag()??s.tagPrefix;let g=null;try{g=await a.getOutputFiles(!0),r=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:s.schema?g?(c=g.data,g.error&&(d=g.error),g.rawData&&(o=g.rawData)):d="Failed to read output files from sandbox":c=r;}catch(u){if(d=u.message,a){l=a.getSessionTag()??s.tagPrefix;try{r=(await a.getOutputFiles(!0)).files;}catch{}}}finally{a&&await a.kill().catch(()=>{});}return {files:r,data:c,tag:l,sandboxId:i,error:d,rawData:o}}async executeMapItem(e,n,s,a,i,l,r=1){let c=this.getFiles(e),d=r>1?`${this.config.tag}-map-${s}-er${r-1}`:`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(c,o,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:s,role:"worker",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),f={operationId:a,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,errorRetry:r>1?r-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=i.verify,p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=this.evaluatePrompt(n,c,s);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let f=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:y,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:s,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),x={operationId:a,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(k,x)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:p,skills:u,composio:g,operationId:a,baseTag:d,retry:r,itemIndex:s,operation:"map",_pipelineContext:i._pipelineContext})}async executeMapItemWithBestOf(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=i.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:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let g=i.mcpServers??this.config.mcpServers,m=p.mcpServers??g,f=p.judgeMcpServers??p.mcpServers??g,h=i.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,k=i.composio??this.config.composio,x=p.composio??k,v=p.judgeComposio??p.composio??k,S=await Promise.all(Array.from({length:u},async(ue,ge)=>{let It=r?await P(ps=>this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:a,config:p,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:y,composio:x,timeoutMs:l,parentIndex:s,attempt:ps,_pipelineContext:i._pipelineContext}),r,ge):await this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:a,config:p,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:y,composio:x,timeoutMs:l,parentIndex:s,_pipelineContext:i._pipelineContext});return p.onCandidateComplete?.(s,ge,It.status==="success"?"success":"error"),It})),b=r?await P(ue=>this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:S,config:p,timeoutMs:l,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,attempt:ue,_pipelineContext:i._pipelineContext}),{...r,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:S,config:p,timeoutMs:l,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,_pipelineContext:i._pipelineContext}),_=S.findIndex(ue=>ue.status==="success"),L=b.decision?.winner??(_>=0?_:0),Pt=S[L]??S[0];p.onJudgeComplete?.(s,L,b.decision?.reasoning??"Judge failed to provide reasoning");let ds={operationId:a,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:i.name,candidateCount:u,...this.pipelineContextToMeta(i._pipelineContext)};return {...Pt,meta:{...Pt.meta,operation:"map",swarmName:this.config.tag,operationName:i.name,itemIndex:s,...this.pipelineContextToMeta(i._pipelineContext)},bestOf:{winnerIndex:L,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:ds,candidates:S}}}async executeFilterItem(e,n,s,a,i,l,r=1){let c=this.getFiles(e),d=r>1?`${this.config.tag}-filter-${s}-er${r-1}`:`${this.config.tag}-filter-${s}`,o=i.mcpServers??this.config.mcpServers,p=i.skills??this.config.skills,u=i.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:o,skills:p,composio:u,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:s,role:"worker",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),m={operationId:a,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,errorRetry:r>1?r-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(g,m,c)}async executeFilterItemWithVerify(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-filter-${s}`,o=i.verify,p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,f,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:h,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:s,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),k={operationId:a,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(w,k,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:p,skills:u,composio:g,operationId:a,baseTag:d,retry:r,itemIndex:s,operation:"filter",_pipelineContext:i._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:s,candidateIndex:a,operationId:i,config:l,timeoutMs:r,parentIndex:c,attempt:d=1,_pipelineContext:o}=e,p=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,u=d>1?`${p}-er${d-1}`:p,g=await this.semaphore.use(()=>this.execute(n,s,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:l.taskAgents?.[a],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:u,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:c,role:"candidate",candidateIndex:a,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(o)}})),m={operationId:i,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:d>1?d-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(o)};return this.buildResult(g,m)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((s,a)=>{s.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
|
|
254
254
|
|
package/dist/index.d.cts
CHANGED
|
@@ -1506,15 +1506,11 @@ declare class Evolve extends EventEmitter {
|
|
|
1506
1506
|
/**
|
|
1507
1507
|
* Enable browser automation.
|
|
1508
1508
|
*
|
|
1509
|
-
* .withBrowser() defaults to
|
|
1510
|
-
* transport in gateway mode.
|
|
1511
|
-
* skills-only mode, or "browser-use" to use the browser-use MCP server.
|
|
1509
|
+
* .withBrowser() defaults to agent-browser with Evolve-managed remote browser
|
|
1510
|
+
* transport in gateway mode.
|
|
1512
1511
|
*
|
|
1513
1512
|
* @example
|
|
1514
|
-
* kit.withBrowser(
|
|
1515
|
-
*
|
|
1516
|
-
* @example
|
|
1517
|
-
* kit.withBrowser() // defaults to remote managed Actionbook
|
|
1513
|
+
* kit.withBrowser() // defaults to remote managed agent-browser
|
|
1518
1514
|
*
|
|
1519
1515
|
* @example
|
|
1520
1516
|
* kit.withBrowser({ provider: "agent-browser", remote: true }) // managed remote agent-browser
|
package/dist/index.d.ts
CHANGED
|
@@ -1506,15 +1506,11 @@ declare class Evolve extends EventEmitter {
|
|
|
1506
1506
|
/**
|
|
1507
1507
|
* Enable browser automation.
|
|
1508
1508
|
*
|
|
1509
|
-
* .withBrowser() defaults to
|
|
1510
|
-
* transport in gateway mode.
|
|
1511
|
-
* skills-only mode, or "browser-use" to use the browser-use MCP server.
|
|
1509
|
+
* .withBrowser() defaults to agent-browser with Evolve-managed remote browser
|
|
1510
|
+
* transport in gateway mode.
|
|
1512
1511
|
*
|
|
1513
1512
|
* @example
|
|
1514
|
-
* kit.withBrowser(
|
|
1515
|
-
*
|
|
1516
|
-
* @example
|
|
1517
|
-
* kit.withBrowser() // defaults to remote managed Actionbook
|
|
1513
|
+
* kit.withBrowser() // defaults to remote managed agent-browser
|
|
1518
1514
|
*
|
|
1519
1515
|
* @example
|
|
1520
1516
|
* kit.withBrowser({ provider: "agent-browser", remote: true }) // managed remote agent-browser
|
package/dist/index.js
CHANGED
|
@@ -248,7 +248,7 @@ cdp_endpoint = ${JSON.stringify(e.cdpUrl)}
|
|
|
248
248
|
`);u=S.pop()??"";for(let b of S){if(!b.trim())continue;let _=g(b);if(this.captureDroidSession(b,_),this.sessionLogger?.writeEventParsed(b,_),n?.onStdout?.(b+`
|
|
249
249
|
`),_&&n?.onContent)for(let L of _)n.onContent(L);}},f=v=>{n?.onStderr?.(v);},h=await c.commands.spawn(d,{cwd:this.workingDir,timeoutMs:a,envs:p,onStdout:m,onStderr:f}),y=this.beginOperation("run",h,n,"run_start");if(this.hasRun=true,i)return this.watchBackgroundOperation(y,"run",h,n,c),{sandboxId:c.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(v){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,n,"run_failed","error"),v}if(this.interruptedOperations.delete(y)||w.exitCode===130?this.finalizeOperation(y,n,"run_interrupted","interrupted"):w.exitCode===0?this.finalizeOperation(y,n,"run_complete","idle"):this.finalizeOperation(y,n,"run_failed","error"),u.trim()){let v=g(u);if(this.captureDroidSession(u,v),this.sessionLogger?.writeEventParsed(u,v),n?.onStdout?.(u+`
|
|
250
250
|
`),v&&n?.onContent)for(let S of v)n.onContent(S);}await this.writeDroidSessionState(c),this.sessionLogger&&!i&&await Promise.race([this.sessionLogger.flush(),new Promise(v=>setTimeout(v,2e3))]);let x;if(this.storage&&!i&&w.exitCode===0)try{x=await Ct(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:l,parentId:this.lastCheckpointId}),this.lastCheckpointId=x.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:o,exitCode:w.exitCode,stdout:w.stdout,stderr:w.stderr,checkpoint:x}}async executeCommand(e,n={},s){let{timeoutMs:a=oe,background:i=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let l=await this.getSandbox(s);this.lastRunTimestamp=Date.now();let r="",c="",d=f=>{r+=f,s?.onStdout?.(f);},o=f=>{c+=f,s?.onStderr?.(f);},p=await l.commands.spawn(e,{cwd:this.workingDir,timeoutMs:a,onStdout:d,onStderr:o}),u=this.beginOperation("command",p,s,"command_start");if(i)return this.watchBackgroundOperation(u,"command",p,s),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let g;try{g=await p.wait();}catch(f){throw this.interruptedOperations.delete(u),this.finalizeOperation(u,s,"command_failed","error"),f}return this.interruptedOperations.delete(u)||g.exitCode===130?this.finalizeOperation(u,s,"command_interrupted","interrupted"):g.exitCode===0?this.finalizeOperation(u,s,"command_complete","idle"):this.finalizeOperation(u,s,"command_failed","error"),{sandboxId:l.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:g.exitCode,stdout:r||g.stdout||"",stderr:c||g.stderr||""}}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async getOutputFiles(e=false){let n=await this.getSandbox(),s=`${this.workingDir}/output`,a=e?"":"-maxdepth 1",l=(await n.commands.run(`find ${s} ${a} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
251
|
-
`).filter(Boolean),r=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${s}/`;for(let m of l){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);r>0&&y<r||c.push(f);}let o={},p=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(d)?m.slice(d.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of p)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await Ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=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,s=this.activeOperationKind,a=false;try{this.activeCommand?a=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(a=await this.sandbox.commands.kill(this.activeProcessId));}catch{a=false;}if(!a)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let i=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,i),a}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(s){n=s;}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=as(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 s=process.env.EVOLVE_DASHBOARD_URL||R,a=await fetch(`${s}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Spend query failed (${a.status}): ${i}`)}return a}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(s=>this.normalizeRunCost(s,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),a=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(a)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let s=await this.getSessionCost(),a=e.index>0?e.index-1:s.runs.length+e.index,i=s.runs[a];if(!i)throw new Error(`Run index ${e.index} out of range. Session has ${s.runs.length} run(s).`);return i}};var pe=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){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:"actionbook",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}withStorage(e){return this.config.storage=e||{},this}static composio=wt;async initializeAgent(){let e=Me(this.config.agent),n=this.config.sandbox??await lt(),s={},a,i,l=this.config.skills;if(this.config.browser){let d=es(this.config.browser);if(d.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=Ot(e.apiKey);}if((d.provider==="actionbook"||d.provider==="agent-browser")&&(l=ts(d.provider,l),d.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);a=d.provider==="actionbook"?dt:pn,i={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||R};}}let r=this.config.storage!==void 0?Fe(this.config.storage,!e.isDirectMode,R,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s,...this.config.mcpServers},browserPrompt:a,managedBrowser:i,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:r};this.agent=new de(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,a=this.listenerCount("lifecycle")>0;return {onStdout:e?i=>this.emit("stdout",i):void 0,onStderr:n?i=>this.emit("stderr",i):void 0,onContent:s?i=>this.emit("content",i):void 0,onLifecycle:a?i=>this.emit("lifecycle",i):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:s,from:a,checkpointComment:i}){if(a&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s,from:a,checkpointComment:i},l)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Me(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:R,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 Et(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Et(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 z=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 Rt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??At;if(n>Ze)throw new Error(`concurrency=${n} exceeds max ${Ze}. 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??oe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,p)=>a?this.executeMapItemWithBestOf(o,s,p,r,e,c,l):i?this.executeMapItemWithVerify(o,s,p,r,e,c,l):l?P(u=>this.executeMapItem(o,s,p,r,e,c,u),l,p):this.executeMapItem(o,s,p,r,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:s,condition:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>i?this.executeFilterItemWithVerify(p,s,u,r,e,c,l):l?P(g=>this.executeFilterItem(p,s,u,r,e,c,g),l,u):this.executeFilterItem(p,s,u,r,e,c))),o=[];for(let p of d)if(p.status==="error")o.push(p);else if(p.data!==null)try{a(p.data)?o.push(p):o.push({...p,status:"filtered"});}catch(u){o.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:s,verify:a}=e,i=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((x,v)=>{c.push(this.getFiles(x)),d.push(this.getIndex(x,v));});let o={};c.forEach((x,v)=>{Object.entries(x).forEach(([S,b])=>{o[`item_${d[v]}/${S}`]=b;});});let p=Ae(o),u=B(mn,{fileTree:p}),g=e.systemPrompt?`${u}
|
|
251
|
+
`).filter(Boolean),r=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,c=[],d=`${s}/`;for(let m of l){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);r>0&&y<r||c.push(f);}let o={},p=await Promise.all(c.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(d)?m.slice(d.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of p)m&&(o[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:o,data:null};let u=o["result.json"];if(!u)return {files:o,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof u=="string"?u:new TextDecoder().decode(u);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:o,data:f.data}:{files:o,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:o,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:o,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:o,data:null}}catch(m){return {files:o,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await Ct(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=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,s=this.activeOperationKind,a=false;try{this.activeCommand?a=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(a=await this.sandbox.commands.kill(this.activeProcessId));}catch{a=false;}if(!a)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let i=s==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,i),a}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(s){n=s;}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=as(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 s=process.env.EVOLVE_DASHBOARD_URL||R,a=await fetch(`${s}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`Spend query failed (${a.status}): ${i}`)}return a}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(s=>this.normalizeRunCost(s,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),a=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(a)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let l=new URLSearchParams({tag:n,runId:e.runId}),c=await(await this.fetchSpend(l)).json();return this.normalizeRunCost(c,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let s=await this.getSessionCost(),a=e.index>0?e.index-1:s.runs.length+e.index,i=s.runs[a];if(!i)throw new Error(`Run index ${e.index} out of range. Session has ${s.runs.length} run(s).`);return i}};var pe=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){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}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(M(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withComposio(e,n){return this.config.composio={userId:e,config:n},this}withStorage(e){return this.config.storage=e||{},this}static composio=wt;async initializeAgent(){let e=Me(this.config.agent),n=this.config.sandbox??await lt(),s={},a,i,l=this.config.skills;if(this.config.browser){let d=es(this.config.browser);if(d.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=Ot(e.apiKey);}if((d.provider==="actionbook"||d.provider==="agent-browser")&&(l=ts(d.provider,l),d.managed)){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);a=d.provider==="actionbook"?dt:pn,i={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||R};}}let r=this.config.storage!==void 0?Fe(this.config.storage,!e.isDirectMode,R,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:n,secrets:this.config.secrets,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...s,...this.config.mcpServers},browserPrompt:a,managedBrowser:i,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,composio:this.config.composio,storage:r};this.agent=new de(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,s=this.listenerCount("content")>0,a=this.listenerCount("lifecycle")>0;return {onStdout:e?i=>this.emit("stdout",i):void 0,onStderr:n?i=>this.emit("stderr",i):void 0,onContent:s?i=>this.emit("content",i):void 0,onLifecycle:a?i=>this.emit("lifecycle",i):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:s,from:a,checkpointComment:i}){if(a&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let l=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:s,from:a,checkpointComment:i},l)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.executeCommand(e,n,s)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=Me(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:R,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 Et(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Et(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 z=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 Rt=class t{config;semaphore;constructor(e={}){let n=e.concurrency??At;if(n>Ze)throw new Error(`concurrency=${n} exceeds max ${Ze}. 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??oe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio},this.semaphore=new ee(this.config.concurrency);}async map(e){let{items:n,prompt:s,bestOf:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let d=await Promise.all(n.map((o,p)=>a?this.executeMapItemWithBestOf(o,s,p,r,e,c,l):i?this.executeMapItemWithVerify(o,s,p,r,e,c,l):l?P(u=>this.executeMapItem(o,s,p,r,e,c,u),l,p):this.executeMapItem(o,s,p,r,e,c)));return te.from(d)}async filter(e){let{items:n,prompt:s,condition:a,verify:i}=e,l=e.retry??this.config.retry,r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=await Promise.all(n.map((p,u)=>i?this.executeFilterItemWithVerify(p,s,u,r,e,c,l):l?P(g=>this.executeFilterItem(p,s,u,r,e,c,g),l,u):this.executeFilterItem(p,s,u,r,e,c))),o=[];for(let p of d)if(p.status==="error")o.push(p);else if(p.data!==null)try{a(p.data)?o.push(p):o.push({...p,status:"filtered"});}catch(u){o.push({...p,status:"error",data:null,error:`Condition function threw: ${u.message}`});}return te.from(o)}async reduce(e){let{items:n,prompt:s,verify:a}=e,i=e.retry??this.config.retry,l=this.generateOperationId(),r=e.timeoutMs??this.config.timeoutMs,c=[],d=[];n.forEach((x,v)=>{c.push(this.getFiles(x)),d.push(this.getIndex(x,v));});let o={};c.forEach((x,v)=>{Object.entries(x).forEach(([S,b])=>{o[`item_${d[v]}/${S}`]=b;});});let p=Ae(o),u=B(mn,{fileTree:p}),g=e.systemPrompt?`${u}
|
|
252
252
|
|
|
253
253
|
${e.systemPrompt}`:u,m=(x,v,S)=>({operationId:l,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:d,errorRetry:v,verifyRetry:S,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.composio??this.config.composio,w=async(x,v,S,b)=>{let _=await this.semaphore.use(()=>this.execute(o,x,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,composio:y,tagPrefix:v,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:e.name,operationId:l,operation:"reduce",role:"worker",errorRetry:S,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),L=m(_,S,b&&b>1?b-1:void 0);return _.error?{status:"error",data:null,files:_.files,meta:L,error:_.error,rawData:_.rawData}:{status:"success",data:_.data,files:_.files,meta:L}},k=`${this.config.tag}-reduce`;return a?this.runWithVerification((x,v,S)=>w(x,v,void 0,S),{originalPrompt:s,inputFiles:o,verifyConfig:a,timeoutMs:r,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,composio:y,operationId:l,baseTag:k,retry:i,operation:"reduce",_pipelineContext:e._pipelineContext}):i?P(x=>{let v=x>1?x-1:void 0,S=v?`${k}-er${v}`:k;return w(s,S,v)},i):w(s,k)}async bestOf(e){let{item:n,prompt:s,config:a}=e,i=e.retry??this.config.retry,l=a.n??a.taskAgents?.length;if(l===void 0)throw new Error("bestOf requires n or taskAgents");if(l<2)throw new Error("bestOf requires n >= 2");let r=this.generateOperationId(),c=e.timeoutMs??this.config.timeoutMs,d=this.getFiles(n),o=a.mcpServers??this.config.mcpServers,p=a.judgeMcpServers??a.mcpServers??this.config.mcpServers,u=a.skills??this.config.skills,g=a.judgeSkills??a.skills??this.config.skills,m=a.composio??this.config.composio,f=a.judgeComposio??a.composio??this.config.composio,h=await Promise.all(Array.from({length:l},async(v,S)=>{let b=i?await P(_=>this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:S,operationId:r,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c,attempt:_}),i,S):await this.executeBestOfCandidate({inputFiles:d,prompt:s,candidateIndex:S,operationId:r,config:a,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:u,composio:m,timeoutMs:c});return a.onCandidateComplete?.(0,S,b.status==="success"?"success":"error"),b})),y=i?await P(v=>this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:a,timeoutMs:c,operationId:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f,attempt:v}),{...i,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:d,taskPrompt:s,candidates:h,config:a,timeoutMs:c,operationId:r,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:p,skills:g,composio:f}),w=h.findIndex(v=>v.status==="success"),k=y.decision?.winner??(w>=0?w:0);a.onJudgeComplete?.(0,k,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:r,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:l};return {winner:h[k]??h[0],winnerIndex:k,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:h}}async execute(e,n,s){let a=null,i="",l=s.tagPrefix,r={},c=null,d,o,p={...this.config.agent,...s.agent};try{a=new pe().withAgent(p).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(s.tagPrefix),s.schema&&a.withSchema(s.schema,s.schemaOptions),s.systemPrompt&&a.withSystemPrompt(s.systemPrompt),s.mcpServers&&a.withMcpServers(s.mcpServers),s.skills?.length&&a.withSkills(s.skills),s.composio&&a.withComposio(s.composio.userId,s.composio.config),s.observability&&a.withObservability(s.observability),Object.keys(e).length>0&&a.withContext(e);let u=await a.run({prompt:n,timeoutMs:s.timeoutMs});i=u.sandboxId,l=a.getSessionTag()??s.tagPrefix;let g=null;try{g=await a.getOutputFiles(!0),r=g.files;}catch{}u.exitCode!==0?d=`Agent exited with code ${u.exitCode}`:s.schema?g?(c=g.data,g.error&&(d=g.error),g.rawData&&(o=g.rawData)):d="Failed to read output files from sandbox":c=r;}catch(u){if(d=u.message,a){l=a.getSessionTag()??s.tagPrefix;try{r=(await a.getOutputFiles(!0)).files;}catch{}}}finally{a&&await a.kill().catch(()=>{});}return {files:r,data:c,tag:l,sandboxId:i,error:d,rawData:o}}async executeMapItem(e,n,s,a,i,l,r=1){let c=this.getFiles(e),d=r>1?`${this.config.tag}-map-${s}-er${r-1}`:`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(c,o,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:s,role:"worker",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),f={operationId:a,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,errorRetry:r>1?r-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=i.verify,p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=this.evaluatePrompt(n,c,s);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let f=async(h,y,w)=>{let k=await this.semaphore.use(()=>this.execute(c,h,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:y,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:s,role:"worker",verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),x={operationId:a,operation:"map",tag:k.tag,sandboxId:k.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,verifyRetry:w&&w>1?w-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(k,x)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:p,skills:u,composio:g,operationId:a,baseTag:d,retry:r,itemIndex:s,operation:"map",_pipelineContext:i._pipelineContext})}async executeMapItemWithBestOf(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-map-${s}`,o=this.evaluatePrompt(n,c,s);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let p=i.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:a,operation:"map",tag:d,sandboxId:"",itemIndex:s});let g=i.mcpServers??this.config.mcpServers,m=p.mcpServers??g,f=p.judgeMcpServers??p.mcpServers??g,h=i.skills??this.config.skills,y=p.skills??h,w=p.judgeSkills??p.skills??h,k=i.composio??this.config.composio,x=p.composio??k,v=p.judgeComposio??p.composio??k,S=await Promise.all(Array.from({length:u},async(ue,ge)=>{let It=r?await P(ps=>this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:a,config:p,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:y,composio:x,timeoutMs:l,parentIndex:s,attempt:ps,_pipelineContext:i._pipelineContext}),r,ge):await this.executeBestOfCandidate({inputFiles:c,prompt:o,candidateIndex:ge,operationId:a,config:p,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:y,composio:x,timeoutMs:l,parentIndex:s,_pipelineContext:i._pipelineContext});return p.onCandidateComplete?.(s,ge,It.status==="success"?"success":"error"),It})),b=r?await P(ue=>this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:S,config:p,timeoutMs:l,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,attempt:ue,_pipelineContext:i._pipelineContext}),{...r,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:o,candidates:S,config:p,timeoutMs:l,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:f,skills:w,composio:v,parentIndex:s,_pipelineContext:i._pipelineContext}),_=S.findIndex(ue=>ue.status==="success"),L=b.decision?.winner??(_>=0?_:0),Pt=S[L]??S[0];p.onJudgeComplete?.(s,L,b.decision?.reasoning??"Judge failed to provide reasoning");let ds={operationId:a,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:i.name,candidateCount:u,...this.pipelineContextToMeta(i._pipelineContext)};return {...Pt,meta:{...Pt.meta,operation:"map",swarmName:this.config.tag,operationName:i.name,itemIndex:s,...this.pipelineContextToMeta(i._pipelineContext)},bestOf:{winnerIndex:L,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:ds,candidates:S}}}async executeFilterItem(e,n,s,a,i,l,r=1){let c=this.getFiles(e),d=r>1?`${this.config.tag}-filter-${s}-er${r-1}`:`${this.config.tag}-filter-${s}`,o=i.mcpServers??this.config.mcpServers,p=i.skills??this.config.skills,u=i.composio??this.config.composio,g=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:o,skills:p,composio:u,tagPrefix:d,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:s,role:"worker",errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),m={operationId:a,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,errorRetry:r>1?r-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(g,m,c)}async executeFilterItemWithVerify(e,n,s,a,i,l,r){let c=this.getFiles(e),d=`${this.config.tag}-filter-${s}`,o=i.verify,p=i.mcpServers??this.config.mcpServers,u=i.skills??this.config.skills,g=i.composio??this.config.composio,m=async(f,h,y)=>{let w=await this.semaphore.use(()=>this.execute(c,f,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:p,skills:u,composio:g,tagPrefix:h,timeoutMs:l,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:s,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),k={operationId:a,operation:"filter",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:s,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(w,k,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:o,timeoutMs:l,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:p,skills:u,composio:g,operationId:a,baseTag:d,retry:r,itemIndex:s,operation:"filter",_pipelineContext:i._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:s,candidateIndex:a,operationId:i,config:l,timeoutMs:r,parentIndex:c,attempt:d=1,_pipelineContext:o}=e,p=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,u=d>1?`${p}-er${d-1}`:p,g=await this.semaphore.use(()=>this.execute(n,s,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:l.taskAgents?.[a],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:u,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:c,role:"candidate",candidateIndex:a,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(o)}})),m={operationId:i,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:d>1?d-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(o)};return this.buildResult(g,m)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((s,a)=>{s.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
|
|
254
254
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evolvingmachines/sdk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.39",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"ai",
|
|
6
6
|
"agents",
|
|
@@ -97,9 +97,9 @@
|
|
|
97
97
|
"dependencies": {
|
|
98
98
|
"@agentclientprotocol/sdk": "^0.5.1",
|
|
99
99
|
"@composio/core": "^0.10.0",
|
|
100
|
-
"@evolvingmachines/e2b": "^0.0.
|
|
101
|
-
"@evolvingmachines/daytona": "^0.0.
|
|
102
|
-
"@evolvingmachines/modal": "^0.0.
|
|
100
|
+
"@evolvingmachines/e2b": "^0.0.39",
|
|
101
|
+
"@evolvingmachines/daytona": "^0.0.39",
|
|
102
|
+
"@evolvingmachines/modal": "^0.0.39",
|
|
103
103
|
"ajv": "^8.17.1",
|
|
104
104
|
"p-map": "^7.0.2",
|
|
105
105
|
"zod": "^3.24.0",
|