evolve-sdk 0.0.55.dev1085__tar.gz → 0.0.55.dev1103__tar.gz

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.
Files changed (44) hide show
  1. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/PKG-INFO +1 -1
  2. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/bridge/dist/bridge.bundle.cjs +1 -1
  3. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/__init__.py +24 -1
  4. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/hosted.py +204 -0
  5. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve_sdk.egg-info/PKG-INFO +1 -1
  6. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/pyproject.toml +1 -1
  7. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/LICENSE +0 -0
  8. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/MANIFEST.in +0 -0
  9. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/README.md +0 -0
  10. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/bridge/__init__.py +0 -0
  11. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/_http.py +0 -0
  12. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/agent.py +0 -0
  13. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/bridge.py +0 -0
  14. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/browser_credentials.py +0 -0
  15. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/browser_profiles.py +0 -0
  16. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/config.py +0 -0
  17. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/integrations.py +0 -0
  18. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/managed_secrets.py +0 -0
  19. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/pipeline/__init__.py +0 -0
  20. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/pipeline/pipeline.py +0 -0
  21. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/pipeline/types.py +0 -0
  22. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/__init__.py +0 -0
  23. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/agent_md/judge.md +0 -0
  24. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/agent_md/reduce.md +0 -0
  25. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/agent_md/verify.md +0 -0
  26. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/user/judge.md +0 -0
  27. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/user/retry_feedback.md +0 -0
  28. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/prompts/user/verify.md +0 -0
  29. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/py.typed +0 -0
  30. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/results.py +0 -0
  31. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/retry.py +0 -0
  32. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/schema.py +0 -0
  33. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/sessions_client.py +0 -0
  34. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/storage_client.py +0 -0
  35. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/swarm/__init__.py +0 -0
  36. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/swarm/results.py +0 -0
  37. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/swarm/swarm.py +0 -0
  38. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/swarm/types.py +0 -0
  39. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve/utils.py +0 -0
  40. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve_sdk.egg-info/SOURCES.txt +0 -0
  41. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve_sdk.egg-info/dependency_links.txt +0 -0
  42. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve_sdk.egg-info/requires.txt +0 -0
  43. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/evolve_sdk.egg-info/top_level.txt +0 -0
  44. {evolve_sdk-0.0.55.dev1085 → evolve_sdk-0.0.55.dev1103}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolve-sdk
3
- Version: 0.0.55.dev1085
3
+ Version: 0.0.55.dev1103
4
4
  Summary: Pythonic SDK for multi-agent orchestration in E2B sandboxes
5
5
  Author-email: "Swarmlink, Inc." <brandomagnani@evolvingmachines.ai>
6
6
  License: Apache-2.0
@@ -908,7 +908,7 @@ PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy
908
908
  `);f=T.pop()??"";for(let k of T){if(!k.trim())continue;let O=h(k);if(this.captureDroidSession(k,O),this.sessionLogger?.writeEventParsed(k,O),t?.onStdout?.(k+`
909
909
  `),O&&t?.onContent)for(let R of O)t.onContent(R)}},v=x=>{t?.onStderr?.(x)},b=await c.commands.spawn(l,{cwd:this.workingDir,timeoutMs:r,envs:d,onStdout:g,onStderr:v}),y=this.beginOperation("run",b,t,"run_start");if(this.hasRun=!0,a)return this.watchBackgroundOperation(y,"run",b,t,c),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:u,exitCode:0,stdout:`Background process started with ID ${b.processId}`,stderr:""};let _;try{_=await b.wait()}catch(x){throw this.interruptedOperations.delete(y),this.finalizeOperation(y,t,"run_failed","error"),x}if(this.interruptedOperations.delete(y)||_.exitCode===130?this.finalizeOperation(y,t,"run_interrupted","interrupted"):_.exitCode===0?this.finalizeOperation(y,t,"run_complete","idle"):this.finalizeOperation(y,t,"run_failed","error"),f.trim()){let x=h(f);if(this.captureDroidSession(f,x),this.sessionLogger?.writeEventParsed(f,x),t?.onStdout?.(f+`
910
910
  `),x&&t?.onContent)for(let T of x)t.onContent(T)}await this.writeDroidSessionState(c),this.sessionLogger&&!a&&await this.flushSessionLoggerWithTimeout();let w;if(this.storage&&!a&&_.exitCode===0)try{w=await yKe(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:i,parentId:this.lastCheckpointId}),this.lastCheckpointId=w.id}catch(x){console.warn(`[Evolve] Auto-checkpoint failed: ${x.message}`)}return{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:u,exitCode:_.exitCode,stdout:_.stdout,stderr:_.stderr,checkpoint:w}}async executeCommand(e,t={},n){let{timeoutMs:r=PO,background:a=!1}=t;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let i=await this.getSandbox(n);this.credentialsSealed||await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.requiresPreRunDashboardIngest()&&(this.ensureSessionLogger(i),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let s="",o="",c=g=>{s+=g,n?.onStdout?.(g)},l=g=>{o+=g,n?.onStderr?.(g)},u=this.credentialsSealed?{}:this.buildProviderRuntimeProcessEnvs(),d=await i.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,envs:Object.keys(u).length>0?u:void 0,onStdout:c,onStderr:l}),f=this.beginOperation("command",d,n,"command_start");if(a)return this.watchBackgroundOperation(f,"command",d,n),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${d.processId}`,stderr:""};let h;try{h=await d.wait()}catch(g){throw this.interruptedOperations.delete(f),this.finalizeOperation(f,n,"command_failed","error"),g}return this.interruptedOperations.delete(f)||h.exitCode===130?this.finalizeOperation(f,n,"command_interrupted","interrupted"):h.exitCode===0?this.finalizeOperation(f,n,"command_complete","idle"):this.finalizeOperation(f,n,"command_failed","error"),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:h.exitCode,stdout:s||h.stdout||"",stderr:o||h.stderr||""}}async sealCredentials(){if(!this.credentialsSealed){if(!this.sandbox)throw new Error("No active sandbox. Call run() or executeCommand() first.");if(this.activeCommand)throw new Error("Cannot seal credentials while a process is running.");if(this.agentConfig.isDirectMode&&!this.agentConfig.externalGateway)throw new Error("Credential sealing requires gateway mode; direct provider credentials cannot be revoked by Evolve");if([this.options.secrets&&Object.keys(this.options.secrets).length>0,this.options.sandboxCreateOptions?.envs&&Object.keys(this.options.sandboxCreateOptions.envs).length>0,this.options.managedSecrets,this.options.integrations,this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0,this.options.managedBrowser,this.options.browserCredentials].some(Boolean))throw new Error("Credential sealing requires a credential-minimal sandbox: omit secrets, managed secrets, integrations, MCP servers, and browser credentials");if(this.agentConfig.externalGateway){await this.agentConfig.externalGateway.revoke(),this.credentialsSealed=!0;return}if(!this.providerRuntimeToken||!this.options.providerRouting)throw new Error("Cannot seal credentials: no active provider runtime token to revoke. Without a gateway-issued runtime token the sandbox may hold credentials Evolve cannot revoke, so sealing would be a false guarantee.");await this.closeProviderRuntimeToken(!0),this.credentialsSealed=!0}}isSealed(){return this.credentialsSealed}async collectArtifacts(e){if(!this.credentialsSealed)throw new Error("Call sealCredentials() before collecting artifacts.");if(!this.sandbox)throw new Error("No active sandbox.");if(this.activeCommand)throw new Error("Cannot collect artifacts while a process is running.");return ZYt(this.sandbox,this.workingDir,e)}async uploadContext(e){let t=await this.getSandbox();await this.uploadContextFiles(t,e)}async uploadFiles(e){let t=await this.getSandbox();await this.uploadWorkspaceFiles(t,e)}async uploadFileFromPath(e,t){let n=await this.getSandbox(),r=e.startsWith("/")?e:`${this.workingDir}/${e}`,a=r.substring(0,r.lastIndexOf("/"));if(a&&await n.commands.run(`mkdir -p ${a}`,{timeoutMs:3e4}),n.files.writeFromPath){await n.files.writeFromPath(r,t);return}let{readFile:i}=await import("fs/promises");await n.files.write(r,await i(t))}async getOutputFiles(e=!1){let t=await this.getSandbox(),n=`${this.workingDir}/output`,r=e?"":"-maxdepth 1",a=(await t.commands.run(`find ${n} ${r} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
911
- `).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[h,g]=f.split("|");if(!h||!g)continue;let v=parseInt(g,10);i>0&&v<i||s.push(h)}let c={},l=await Promise.all(s.map(async f=>{try{let h=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:h}}catch{return null}}));for(let f of l)f&&(c[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return{files:c,data:null};let u=c["result.json"];if(!u)return{files:c,data:null,error:"Schema provided but agent did not create output/result.json"};let d=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(d);if(this.zodSchema){let h=this.zodSchema.safeParse(f);return h.success?{files:c,data:h.data}:{files:c,data:null,error:`Schema validation failed: ${h.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let h=this.compiledValidator.errors?.map(g=>`${g.instancePath} ${g.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${h}`,rawData:d}}}return{files:c,data:null}}catch(f){return{files:c,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:d}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let t=await yKe(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=t.id,t}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=!0,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!1;let t=this.activeOperationId,n=this.activeOperationKind,r=!1;try{this.activeCommand?r=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(r=await this.sandbox.commands.kill(this.activeProcessId))}catch{r=!1}if(!r)return this.sandboxState="running",this.agentState="running",!1;t!==null&&this.interruptedOperations.add(t),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let a=n==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,a),r}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 t;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0)}catch(n){t=n}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession()}if(t)throw t;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=!1,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=RKe(this.options.sessionTagPrefix||"evolve")}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let t=this.agentConfig.apiKey;if(!t)throw new Error("Cost tracking requires an API key.");let n=process.env.EVOLVE_DASHBOARD_URL||ia,r=await fetch(`${n}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Spend query failed (${r.status}): ${a}`)}return r}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,t){return{...e,asOf:e.asOf??t.asOf,isComplete:e.isComplete??t.isComplete,truncated:e.truncated??t.truncated}}normalizeSessionCost(e){let t={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return{...e,runs:e.runs.map(n=>this.normalizeRunCost(n,t))}}async getSessionCost(){let e=this.resolveSpendTag(),t=new URLSearchParams({tag:e}),n=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(n)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let i=new URLSearchParams({tag:t,runId:e.runId}),s=await(await this.fetchSpend(i)).json();return this.normalizeRunCost(s,{asOf:new Date().toISOString(),isComplete:!1,truncated:!1})}let n=await this.getSessionCost(),r=e.index>0?e.index-1:n.runs.length+e.index,a=n.runs[r];if(!a)throw new Error(`Run index ${e.index} out of range. Session has ${n.runs.length} run(s).`);return a}};function ijt(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function ajt(e){let t=e||process.env.EVOLVE_API_KEY;if(!t)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return t}async function sjt(e){return await e.text().catch(()=>"")}async function MKe(e,t,n={}){let r=await fetch(`${ijt(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${ajt(e?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await sjt(r)}`);return r.status===204?{}:await r.json()}var ojt=class{constructor(e={}){this.config=e}toMetadata(e){return{id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return{profiles:(await MKe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await MKe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function cjt(e={}){return new ojt(e)}var Sv=class extends UKe.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=!1;constructor(){super()}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(ZKe(e),rXe(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),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:!0}){return e===!1?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let t=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...t],this}withSkills(e){return this.config.skills=e,this}withSchema(e,t){return this.config.schema=e,t&&(sB(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=t),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=lYt;static browserCredentials=qYt;static browserProfiles=cjt;static managedSecrets=SB;async initializeAgent(){let e=uKe(this.config.agent),t=vv(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let n=fQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!gZ(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let r=this.config.sandbox??(n?await wZ(e.apiKey):await O5t()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=RYt(this.config.browser);if(c=d,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.');a=eQ(e.apiKey)}if((d.provider==="actionbook"||d.provider==="agent-browser")&&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.`);i=d.provider==="actionbook"?W5t:Y5t,s={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,...d.profile?{profile:d.profile}:{}}}if(d.profile&&!d.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!c||c.provider!=="agent-browser"||!c.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let l=this.config.storage!==void 0?sXe(this.config.storage,!e.isDirectMode,ia,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:r,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:n?{secrets:n,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...a,...this.config.mcpServers},browserPrompt:i,managedBrowser:s,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia},storage:l};this.agent=new rjt(e,u)}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,n=this.listenerCount("content")>0,r=this.listenerCount("lifecycle")>0;return{onStdout:e?a=>this.emit("stdout",a):void 0,onStderr:t?a=>this.emit("stderr",a):void 0,onContent:n?a=>this.emit("content",a):void 0,onLifecycle:r?a=>this.emit("lifecycle",a):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let t=this.status();this.emit("lifecycle",{sandboxId:t.sandboxId,sandbox:t.sandbox,agent:t.agent,timestamp:new Date().toISOString(),reason:e,...t.browser?{browser:t.browser}:{}})}async run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i}){if(r&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i},s)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let n=this.createStreamCallbacks();return this.agent.executeCommand(e,t,n)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return(await this.agent.getSandbox(e)).sandboxId}async updateNetwork(e){if(!this.agent)throw new Error("No sandbox yet. Call prepareSandbox(), run() or executeCommand() before updateNetwork().");let t=await this.agent.getSandbox(this.createStreamCallbacks());if(typeof t.updateNetwork!="function")throw new Error(`The ${this.config.sandbox?.providerType??"configured"} sandbox provider cannot change network policy after start. Create the sandbox with the policy it needs for its whole lifetime, or use a provider that supports runtime changes.`);await t.updateNetwork(e)}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials()}isSealed(){return this.agent?.isSealed()??!1}resolvedSkills(){return this.agent?.resolvedSkills()??[]}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}async interrupt(){if(!this.agent)return!1;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async uploadFileFromPath(e,t){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,t)}async getOutputFiles(e=!1){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=uKe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:ia,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 IKe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return IKe(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),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=!1;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=!1,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)}},ljt=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++}},pO=Symbol.for("evolve.SwarmResult"),DKe=class TXe extends Array{get success(){return this.filter(t=>t.status==="success")}get filtered(){return this.filter(t=>t.status==="filtered")}get error(){return this.filter(t=>t.status==="error")}static from(t){let n=new TXe;return n.push(...t),n}},ekn=class nB{config;semaphore;constructor(t={}){let n=t.concurrency??tQ;if(n>yB)throw new Error(`concurrency=${n} exceeds max ${yB}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:t.agent,sandbox:t.sandbox,tag:t.tag??"swarm",concurrency:n,timeoutMs:t.timeoutMs??PO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new ljt(this.config.concurrency)}async map(t){let{items:n,prompt:r,bestOf:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(n.map((u,d)=>a?this.executeMapItemWithBestOf(u,r,d,o,t,c,s):i?this.executeMapItemWithVerify(u,r,d,o,t,c,s):s?Rp(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return DKe.from(l)}async filter(t){let{items:n,prompt:r,condition:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs,l=await Promise.all(n.map((d,f)=>i?this.executeFilterItemWithVerify(d,r,f,o,t,c,s):s?Rp(h=>this.executeFilterItem(d,r,f,o,t,c,h),s,f):this.executeFilterItem(d,r,f,o,t,c))),u=[];for(let d of l)if(d.status==="error")u.push(d);else if(d.data!==null)try{a(d.data)?u.push(d):u.push({...d,status:"filtered"})}catch(f){u.push({...d,status:"error",data:null,error:`Condition function threw: ${f.message}`})}return DKe.from(u)}async reduce(t){let{items:n,prompt:r,verify:a}=t,i=t.retry??this.config.retry,s=this.generateOperationId(),o=t.timeoutMs??this.config.timeoutMs,c=[],l=[];n.forEach((x,T)=>{c.push(this.getFiles(x)),l.push(this.getIndex(x,T))});let u={};c.forEach((x,T)=>{Object.entries(x).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=iZ(u),f=yv(Q5t,{fileTree:d}),h=t.systemPrompt?`${f}
911
+ `).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[h,g]=f.split("|");if(!h||!g)continue;let v=parseInt(g,10);i>0&&v<i||s.push(h)}let c={},l=await Promise.all(s.map(async f=>{try{let h=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:h}}catch{return null}}));for(let f of l)f&&(c[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return{files:c,data:null};let u=c["result.json"];if(!u)return{files:c,data:null,error:"Schema provided but agent did not create output/result.json"};let d=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(d);if(this.zodSchema){let h=this.zodSchema.safeParse(f);return h.success?{files:c,data:h.data}:{files:c,data:null,error:`Schema validation failed: ${h.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let h=this.compiledValidator.errors?.map(g=>`${g.instancePath} ${g.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${h}`,rawData:d}}}return{files:c,data:null}}catch(f){return{files:c,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:d}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let t=await yKe(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=t.id,t}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=!0,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!1;let t=this.activeOperationId,n=this.activeOperationKind,r=!1;try{this.activeCommand?r=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(r=await this.sandbox.commands.kill(this.activeProcessId))}catch{r=!1}if(!r)return this.sandboxState="running",this.agentState="running",!1;t!==null&&this.interruptedOperations.add(t),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let a=n==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,a),r}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 t;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0)}catch(n){t=n}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession()}if(t)throw t;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=!1,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=RKe(this.options.sessionTagPrefix||"evolve")}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let t=this.agentConfig.apiKey;if(!t)throw new Error("Cost tracking requires an API key.");let n=process.env.EVOLVE_DASHBOARD_URL||ia,r=await fetch(`${n}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Spend query failed (${r.status}): ${a}`)}return r}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,t){return{...e,asOf:e.asOf??t.asOf,isComplete:e.isComplete??t.isComplete,truncated:e.truncated??t.truncated}}normalizeSessionCost(e){let t={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return{...e,runs:e.runs.map(n=>this.normalizeRunCost(n,t))}}async getSessionCost(){let e=this.resolveSpendTag(),t=new URLSearchParams({tag:e}),n=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(n)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let i=new URLSearchParams({tag:t,runId:e.runId}),s=await(await this.fetchSpend(i)).json();return this.normalizeRunCost(s,{asOf:new Date().toISOString(),isComplete:!1,truncated:!1})}let n=await this.getSessionCost(),r=e.index>0?e.index-1:n.runs.length+e.index,a=n.runs[r];if(!a)throw new Error(`Run index ${e.index} out of range. Session has ${n.runs.length} run(s).`);return a}};function ijt(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function ajt(e){let t=e||process.env.EVOLVE_API_KEY;if(!t)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return t}async function sjt(e){return await e.text().catch(()=>"")}async function MKe(e,t,n={}){let r=await fetch(`${ijt(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${ajt(e?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await sjt(r)}`);return r.status===204?{}:await r.json()}var ojt=class{constructor(e={}){this.config=e}toMetadata(e){return{id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return{profiles:(await MKe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await MKe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function cjt(e={}){return new ojt(e)}var Sv=class extends UKe.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=!1;constructor(){super()}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(ZKe(e),rXe(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),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:!0}){return e===!1?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let t=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...t],this}withSkills(e){return this.config.skills=e,this}withSchema(e,t){return this.config.schema=e,t&&(sB(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=t),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=lYt;static browserCredentials=qYt;static browserProfiles=cjt;static managedSecrets=SB;async initializeAgent(){let e=uKe(this.config.agent),t=vv(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let n=fQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!gZ(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let r=this.config.sandbox??(n?await wZ(e.apiKey):await O5t()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=RYt(this.config.browser);if(c=d,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.');a=eQ(e.apiKey)}if((d.provider==="actionbook"||d.provider==="agent-browser")&&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.`);i=d.provider==="actionbook"?W5t:Y5t,s={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,...d.profile?{profile:d.profile}:{}}}if(d.profile&&!d.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!c||c.provider!=="agent-browser"||!c.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let l=this.config.storage!==void 0?sXe(this.config.storage,!e.isDirectMode,ia,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:r,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:n?{secrets:n,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...a,...this.config.mcpServers},browserPrompt:i,managedBrowser:s,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia},storage:l};this.agent=new rjt(e,u)}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,n=this.listenerCount("content")>0,r=this.listenerCount("lifecycle")>0;return{onStdout:e?a=>this.emit("stdout",a):void 0,onStderr:t?a=>this.emit("stderr",a):void 0,onContent:n?a=>this.emit("content",a):void 0,onLifecycle:r?a=>this.emit("lifecycle",a):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let t=this.status();this.emit("lifecycle",{sandboxId:t.sandboxId,sandbox:t.sandbox,agent:t.agent,timestamp:new Date().toISOString(),reason:e,...t.browser?{browser:t.browser}:{}})}async run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i}){if(r&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i},s)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let n=this.createStreamCallbacks();return this.agent.executeCommand(e,t,n)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return(await this.agent.getSandbox(e)).sandboxId}async updateNetwork(e){if(!this.agent)throw new Error("No sandbox yet. Call prepareSandbox(), run() or executeCommand() before updateNetwork().");let t=await this.agent.getSandbox(this.createStreamCallbacks());if(typeof t.updateNetwork!="function")throw new Error(`The ${this.config.sandbox?.providerType??"configured"} sandbox provider cannot change network policy after start. Create the sandbox with the policy it needs for its whole lifetime, or use a provider that supports runtime changes.`);await t.updateNetwork(e)}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials()}isSealed(){return this.agent?.isSealed()??!1}resolvedSkills(){return this.agent?.resolvedSkills()??[]}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}async interrupt(){if(!this.agent)return!1;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async uploadFileFromPath(e,t){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,t)}async getOutputFiles(e=!1){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=uKe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:ia,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 IKe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return IKe(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),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=!1;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=!1,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)}},ljt=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++}},pO=Symbol.for("evolve.SwarmResult"),DKe=class TXe extends Array{get success(){return this.filter(t=>t.status==="success")}get filtered(){return this.filter(t=>t.status==="filtered")}get error(){return this.filter(t=>t.status==="error")}static from(t){let n=new TXe;return n.push(...t),n}},tkn=class nB{config;semaphore;constructor(t={}){let n=t.concurrency??tQ;if(n>yB)throw new Error(`concurrency=${n} exceeds max ${yB}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:t.agent,sandbox:t.sandbox,tag:t.tag??"swarm",concurrency:n,timeoutMs:t.timeoutMs??PO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new ljt(this.config.concurrency)}async map(t){let{items:n,prompt:r,bestOf:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(n.map((u,d)=>a?this.executeMapItemWithBestOf(u,r,d,o,t,c,s):i?this.executeMapItemWithVerify(u,r,d,o,t,c,s):s?Rp(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return DKe.from(l)}async filter(t){let{items:n,prompt:r,condition:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs,l=await Promise.all(n.map((d,f)=>i?this.executeFilterItemWithVerify(d,r,f,o,t,c,s):s?Rp(h=>this.executeFilterItem(d,r,f,o,t,c,h),s,f):this.executeFilterItem(d,r,f,o,t,c))),u=[];for(let d of l)if(d.status==="error")u.push(d);else if(d.data!==null)try{a(d.data)?u.push(d):u.push({...d,status:"filtered"})}catch(f){u.push({...d,status:"error",data:null,error:`Condition function threw: ${f.message}`})}return DKe.from(u)}async reduce(t){let{items:n,prompt:r,verify:a}=t,i=t.retry??this.config.retry,s=this.generateOperationId(),o=t.timeoutMs??this.config.timeoutMs,c=[],l=[];n.forEach((x,T)=>{c.push(this.getFiles(x)),l.push(this.getIndex(x,T))});let u={};c.forEach((x,T)=>{Object.entries(x).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=iZ(u),f=yv(Q5t,{fileTree:d}),h=t.systemPrompt?`${f}
912
912
 
913
913
  ${t.systemPrompt}`:f,g=(x,T,k)=>({operationId:s,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:t.name,inputCount:n.length,inputIndices:l,errorRetry:T,verifyRetry:k,...this.pipelineContextToMeta(t._pipelineContext)}),v=t.mcpServers??this.config.mcpServers,b=t.skills??this.config.skills,y=t.integrations??this.config.integrations,_=async(x,T,k,O)=>{let R=await this.semaphore.use(()=>this.execute(u,x,{systemPrompt:h,schema:t.schema,schemaOptions:t.schemaOptions,agent:t.agent,mcpServers:v,skills:b,integrations:y,tagPrefix:T,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:t.name,operationId:s,operation:"reduce",role:"worker",errorRetry:k,verifyRetry:O&&O>1?O-1:void 0,...this.pipelineContextToObservability(t._pipelineContext)}})),F=g(R,k,O&&O>1?O-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:F,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:F}},w=`${this.config.tag}-reduce`;return a?this.runWithVerification((x,T,k)=>_(x,T,void 0,k),{originalPrompt:r,inputFiles:u,verifyConfig:a,timeoutMs:o,systemPrompt:h,schema:t.schema,mcpServers:v,skills:b,integrations:y,operationId:s,baseTag:w,retry:i,operation:"reduce",_pipelineContext:t._pipelineContext}):i?Rp(x=>{let T=x>1?x-1:void 0,k=T?`${w}-er${T}`:w;return _(r,k,T)},i):_(r,w)}async bestOf(t){let{item:n,prompt:r,config:a}=t,i=t.retry??this.config.retry,s=a.n??a.taskAgents?.length;if(s===void 0)throw new Error("bestOf requires n or taskAgents");if(s<2)throw new Error("bestOf requires n >= 2");let o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs,l=this.getFiles(n),u=a.mcpServers??this.config.mcpServers,d=a.judgeMcpServers??a.mcpServers??this.config.mcpServers,f=a.skills??this.config.skills,h=a.judgeSkills??a.skills??this.config.skills,g=a.integrations??this.config.integrations,v=a.judgeIntegrations??a.integrations??this.config.integrations,b=await Promise.all(Array.from({length:s},async(T,k)=>{let O=i?await Rp(R=>this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:k,operationId:o,config:a,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:u,skills:f,integrations:g,timeoutMs:c,attempt:R}),i,k):await this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:k,operationId:o,config:a,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:u,skills:f,integrations:g,timeoutMs:c});return a.onCandidateComplete?.(0,k,O.status==="success"?"success":"error"),O})),y=i?await Rp(T=>this.executeBestOfJudge({inputFiles:l,taskPrompt:r,candidates:b,config:a,timeoutMs:c,operationId:o,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:d,skills:h,integrations:v,attempt:T}),{...i,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:r,candidates:b,config:a,timeoutMs:c,operationId:o,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:d,skills:h,integrations:v}),_=b.findIndex(T=>T.status==="success"),w=y.decision?.winner??(_>=0?_:0);a.onJudgeComplete?.(0,w,y.decision?.reasoning??"Judge failed to provide reasoning");let x={operationId:o,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:t.name,candidateCount:s};return{winner:b[w]??b[0],winnerIndex:w,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:x,candidates:b}}async execute(t,n,r){let a=null,i="",s=r.tagPrefix,o={},c=null,l,u,d={...this.config.agent,...r.agent};try{a=new Sv().withAgent(d).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&a.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&a.withSystemPrompt(r.systemPrompt),r.mcpServers&&a.withMcpServers(r.mcpServers),r.skills?.length&&a.withSkills(r.skills),r.integrations&&a.withIntegrations(r.integrations),r.observability&&a.withObservability(r.observability),Object.keys(t).length>0&&a.withContext(t);let f=await a.run({prompt:n,timeoutMs:r.timeoutMs});i=f.sandboxId,s=a.getSessionTag()??r.tagPrefix;let h=null;try{h=await a.getOutputFiles(!0),o=h.files}catch{}f.exitCode!==0?l=`Agent exited with code ${f.exitCode}`:r.schema?h?(c=h.data,h.error&&(l=h.error),h.rawData&&(u=h.rawData)):l="Failed to read output files from sandbox":c=o}catch(f){if(l=f.message,a){s=a.getSessionTag()??r.tagPrefix;try{o=(await a.getOutputFiles(!0)).files}catch{}}}finally{a&&await a.kill().catch(()=>{})}return{files:o,data:c,tag:s,sandboxId:i,error:l,rawData:u}}async executeMapItem(t,n,r,a,i,s,o=1){let c=this.getFiles(t),l=o>1?`${this.config.tag}-map-${r}-er${o-1}`:`${this.config.tag}-map-${r}`,u=this.evaluatePrompt(n,c,r);if(u instanceof Error)return this.buildErrorResult(`Prompt function threw: ${u.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,h=i.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(c,u,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:h,tagPrefix:l,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:r,role:"worker",errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),v={operationId:a,operation:"map",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(g,v)}async executeMapItemWithVerify(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-map-${r}`,u=i.verify,d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,h=i.integrations??this.config.integrations,g=this.evaluatePrompt(n,c,r);if(g instanceof Error)return this.buildErrorResult(`Prompt function threw: ${g.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let v=async(b,y,_)=>{let w=await this.semaphore.use(()=>this.execute(c,b,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:h,tagPrefix:y,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:r,role:"worker",verifyRetry:_&&_>1?_-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),x={operationId:a,operation:"map",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,verifyRetry:_&&_>1?_-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(w,x)};return this.runWithVerification(v,{originalPrompt:g,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:h,operationId:a,baseTag:l,retry:o,itemIndex:r,operation:"map",_pipelineContext:i._pipelineContext})}async executeMapItemWithBestOf(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-map-${r}`,u=this.evaluatePrompt(n,c,r);if(u instanceof Error)return this.buildErrorResult(`Prompt function threw: ${u.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let d=i.bestOf,f=d.n??d.taskAgents?.length;if(f===void 0||f<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let h=i.mcpServers??this.config.mcpServers,g=d.mcpServers??h,v=d.judgeMcpServers??d.mcpServers??h,b=i.skills??this.config.skills,y=d.skills??b,_=d.judgeSkills??d.skills??b,w=i.integrations??this.config.integrations,x=d.integrations??w,T=d.judgeIntegrations??d.integrations??w,k=await Promise.all(Array.from({length:f},async(Ue,ee)=>{let E=o?await Rp(J=>this.executeBestOfCandidate({inputFiles:c,prompt:u,candidateIndex:ee,operationId:a,config:d,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:g,skills:y,integrations:x,timeoutMs:s,parentIndex:r,attempt:J,_pipelineContext:i._pipelineContext}),o,ee):await this.executeBestOfCandidate({inputFiles:c,prompt:u,candidateIndex:ee,operationId:a,config:d,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:g,skills:y,integrations:x,timeoutMs:s,parentIndex:r,_pipelineContext:i._pipelineContext});return d.onCandidateComplete?.(r,ee,E.status==="success"?"success":"error"),E})),O=o?await Rp(Ue=>this.executeBestOfJudge({inputFiles:c,taskPrompt:u,candidates:k,config:d,timeoutMs:s,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:v,skills:_,integrations:T,parentIndex:r,attempt:Ue,_pipelineContext:i._pipelineContext}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:u,candidates:k,config:d,timeoutMs:s,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:v,skills:_,integrations:T,parentIndex:r,_pipelineContext:i._pipelineContext}),R=k.findIndex(Ue=>Ue.status==="success"),F=O.decision?.winner??(R>=0?R:0),L=k[F]??k[0];d.onJudgeComplete?.(r,F,O.decision?.reasoning??"Judge failed to provide reasoning");let V={operationId:a,operation:"bestof-judge",tag:O.tag,sandboxId:O.sandboxId,swarmName:this.config.tag,operationName:i.name,candidateCount:f,...this.pipelineContextToMeta(i._pipelineContext)};return{...L,meta:{...L.meta,operation:"map",swarmName:this.config.tag,operationName:i.name,itemIndex:r,...this.pipelineContextToMeta(i._pipelineContext)},bestOf:{winnerIndex:F,judgeReasoning:O.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:V,candidates:k}}}async executeFilterItem(t,n,r,a,i,s,o=1){let c=this.getFiles(t),l=o>1?`${this.config.tag}-filter-${r}-er${o-1}`:`${this.config.tag}-filter-${r}`,u=i.mcpServers??this.config.mcpServers,d=i.skills??this.config.skills,f=i.integrations??this.config.integrations,h=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:u,skills:d,integrations:f,tagPrefix:l,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:r,role:"worker",errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),g={operationId:a,operation:"filter",tag:h.tag,sandboxId:h.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(h,g,c)}async executeFilterItemWithVerify(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-filter-${r}`,u=i.verify,d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,h=i.integrations??this.config.integrations,g=async(v,b,y)=>{let _=await this.semaphore.use(()=>this.execute(c,v,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:h,tagPrefix:b,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),w={operationId:a,operation:"filter",tag:_.tag,sandboxId:_.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(_,w,c)};return this.runWithVerification(g,{originalPrompt:n,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:h,operationId:a,baseTag:l,retry:o,itemIndex:r,operation:"filter",_pipelineContext:i._pipelineContext})}async executeBestOfCandidate(t){let{inputFiles:n,prompt:r,candidateIndex:a,operationId:i,config:s,timeoutMs:o,parentIndex:c,attempt:l=1,_pipelineContext:u}=t,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,f=l>1?`${d}-er${l-1}`:d,h=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,agent:s.taskAgents?.[a],mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations,tagPrefix:f,timeoutMs:o,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:c,role:"candidate",candidateIndex:a,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(u)}})),g={operationId:i,operation:"bestof-cand",tag:h.tag,sandboxId:h.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:l>1?l-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(u)};return this.buildResult(h,g)}buildJudgeContext(t){let n=this.buildEvaluatorContext({inputFiles:t.inputFiles,taskPrompt:t.taskPrompt,systemPrompt:t.systemPrompt,schema:t.schema});return t.candidates.forEach((r,a)=>{r.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
914
914
 
@@ -57,6 +57,12 @@ from .hosted import (
57
57
  AttemptPhase,
58
58
  AuthClient,
59
59
  AuthStatus,
60
+ Organization,
61
+ OrganizationDetail,
62
+ OrgQuota,
63
+ OrgRole,
64
+ OrgUsage,
65
+ OrgsClient,
60
66
  CapabilityDocument,
61
67
  CompareCell,
62
68
  CompareCoverage,
@@ -404,6 +410,16 @@ def auth(config: Optional[HostedClientConfig] = None) -> AuthClient:
404
410
  return AuthClient(config)
405
411
 
406
412
 
413
+ def orgs(config: Optional[HostedClientConfig] = None) -> OrgsClient:
414
+ """Create a standalone hosted-evals organizations client (the read pair).
415
+
416
+ ``list()`` — every organization you belong to; ``get(slug)`` — one
417
+ organization's role, member count, quota and usage. Uses EVOLVE_API_KEY
418
+ unless HostedClientConfig(api_key=...) is provided.
419
+ """
420
+ return OrgsClient(config)
421
+
422
+
407
423
  def managed_secrets(config: Optional[ManagedSecretsClientConfig] = None) -> ManagedSecretsClient:
408
424
  """Create a standalone managed secrets client.
409
425
 
@@ -447,7 +463,7 @@ async def list_checkpoints(
447
463
  await store.close()
448
464
 
449
465
 
450
- __version__ = '0.0.55.dev1085'
466
+ __version__ = '0.0.55.dev1103'
451
467
 
452
468
  __all__ = [
453
469
  # Main classes
@@ -526,6 +542,7 @@ __all__ = [
526
542
  'TrialsClient',
527
543
  'AnalysesClient',
528
544
  'AuthClient',
545
+ 'OrgsClient',
529
546
  'EvolveAPIError',
530
547
  'EvolveDigestMismatchError',
531
548
  'EvolveIncompleteDownloadError',
@@ -632,12 +649,18 @@ __all__ = [
632
649
  'DatasetImportPage',
633
650
  'ApiKey',
634
651
  'AuthStatus',
652
+ 'Organization',
653
+ 'OrganizationDetail',
654
+ 'OrgQuota',
655
+ 'OrgRole',
656
+ 'OrgUsage',
635
657
  'datasets',
636
658
  'agents',
637
659
  'jobs',
638
660
  'trials',
639
661
  'analyses',
640
662
  'skills',
663
+ 'orgs',
641
664
  'auth',
642
665
  'hosted',
643
666
  'meta',
@@ -137,9 +137,16 @@ _TERMINAL_EVENT_TYPES = {'job.completed', 'job.cancelled', 'job.failed'}
137
137
  HostedErrorCode = Literal[
138
138
  'missing_authorization',
139
139
  'invalid_api_key',
140
+ # A valid key created read-only, presented to a mutating route (403).
141
+ 'read_only_key',
140
142
  'credential_service_unavailable',
141
143
  'rate_limited',
142
144
  'insufficient_credits',
145
+ # The owning organization's queued-trial ceiling would be crossed by
146
+ # this create (429, no Retry-After — the wait is not a known number).
147
+ # Harbor's hosted refusal: the message starts ``hosted quota exceeded:``;
148
+ # details carry {quota, limit, used, requested, org}.
149
+ 'quota_exceeded',
143
150
  'invalid_json',
144
151
  'invalid_input',
145
152
  'invalid_limit',
@@ -214,6 +221,11 @@ HostedErrorCode = Literal[
214
221
  'secret_ambiguous',
215
222
  'secret_brokered_unsupported',
216
223
  'secret_exists',
224
+ # A selected task's environment.env asks for a ``${VAR}`` the job
225
+ # attaches no secret for, and the declaration states no default —
226
+ # refused at job create (attach-is-consent). Not secret_not_found: the
227
+ # row usually exists in the owner's vault; the remedy is to attach it.
228
+ 'secret_not_attached',
217
229
  'agent_version_not_found',
218
230
  'agent_version_unresolvable',
219
231
  'agent_kwarg_unsupported',
@@ -296,6 +308,16 @@ HostedErrorCode = Literal[
296
308
  # distinct from rate_limited for the same reason: nothing was
297
309
  # rate-counted and there is no Retry-After — the server's disk is busy.
298
310
  'too_many_concurrent_package_downloads',
311
+ # Team accounts (orgs, members, invite links)
312
+ 'org_not_found',
313
+ 'org_slug_taken',
314
+ 'org_forbidden',
315
+ 'org_personal_immutable',
316
+ 'org_last_owner',
317
+ 'org_in_use',
318
+ 'org_member_not_found',
319
+ 'invite_not_found',
320
+ 'invite_invalid',
299
321
  'internal_error',
300
322
  ]
301
323
 
@@ -500,6 +522,9 @@ VerifierEnvironmentMode = Literal['shared', 'separate']
500
522
  AttemptPhase = Literal[
501
523
  'prepare', 'build', 'boot', 'install', 'agent', 'verify', 'persist'
502
524
  ]
525
+ #: The caller's role in an organization: owner manages, member reads and
526
+ #: runs (spec ``OrgRole``).
527
+ OrgRole = Literal['owner', 'member']
503
528
 
504
529
 
505
530
  @dataclass
@@ -2517,6 +2542,80 @@ class AuthStatus:
2517
2542
  key: ApiKey
2518
2543
 
2519
2544
 
2545
+ @dataclass
2546
+ class Organization:
2547
+ """An organization the caller belongs to (``GET /api/orgs`` item; Harbor's
2548
+ ``auth org list`` row)."""
2549
+ org_id: str
2550
+ #: URL-safe handle, globally unique — the ``<slug>`` every org verb takes.
2551
+ slug: str
2552
+ display_name: str
2553
+ #: True for the auto-created personal org — the invisible default owner
2554
+ #: of everything created without naming an org.
2555
+ personal: bool
2556
+ #: The CALLER'S role; None when the read implies no membership.
2557
+ role: Optional[OrgRole] = None
2558
+ created_at: str = ''
2559
+
2560
+
2561
+ @dataclass
2562
+ class OrgQuota:
2563
+ """An organization's ceilings, every one EFFECTIVE — the value the
2564
+ platform administrator set, else the fleet default. ``0`` means paused:
2565
+ creates are refused ``quota_exceeded``, queued work waits. Set only from
2566
+ the platform administrator's dashboard session; the SDK reads them."""
2567
+ #: Trials running at once (RUNNING or SCORING); work beyond it waits.
2568
+ max_concurrent_trials: int
2569
+ #: Trials waiting in the queue — the one refusal (``quota_exceeded``) on
2570
+ #: job create.
2571
+ max_queued_trials: int
2572
+ #: Dataset imports a worker holds at once; further imports wait.
2573
+ max_concurrent_imports: int
2574
+ #: Trace analyses running at once; further analyses wait.
2575
+ max_concurrent_analyses: int
2576
+ #: Managed-agent sessions open at once (recorded and read back; not yet
2577
+ #: enforced by the box-create doors).
2578
+ max_concurrent_sessions: int
2579
+ #: Model spend allowed this calendar month, USD; None = no monthly budget.
2580
+ monthly_budget_usd: Optional[float]
2581
+ #: Sandboxes of this organization in flight on e2b at once — trials, trace
2582
+ #: analyses, regrade verifiers and managed sessions together; work beyond
2583
+ #: it waits; 0 pauses the organization on that provider; fleet default =
2584
+ #: the platform's own e2b ceiling.
2585
+ max_concurrent_sandboxes_e2b: int
2586
+ #: The same ceiling on daytona.
2587
+ max_concurrent_sandboxes_daytona: int
2588
+ #: The same ceiling on modal.
2589
+ max_concurrent_sandboxes_modal: int
2590
+
2591
+
2592
+ @dataclass
2593
+ class OrgUsage:
2594
+ """The live load beside the ceilings — what ``evolve auth org show``
2595
+ prints as N/M."""
2596
+ in_flight_trials: int
2597
+ queued_trials: int
2598
+ in_flight_imports: int
2599
+ in_flight_analyses: int
2600
+ #: Sessions not yet ended; always 0 on a shared org (sessions carry no
2601
+ #: organization).
2602
+ active_sessions: int
2603
+ #: Recorded model spend since the first of the current calendar month (UTC).
2604
+ month_spend_usd: float
2605
+
2606
+
2607
+ @dataclass
2608
+ class OrganizationDetail(Organization):
2609
+ """One organization in depth (``GET /api/orgs/{org}``): the row, the
2610
+ member count, its quota and usage."""
2611
+ # Keyword-only so the three can stay required behind the row's defaulted
2612
+ # ``role`` / ``created_at``; no default quota — an all-zero one would read
2613
+ # "paused everywhere", a silent zero.
2614
+ member_count: int = field(kw_only=True)
2615
+ quota: OrgQuota = field(kw_only=True)
2616
+ usage: OrgUsage = field(kw_only=True)
2617
+
2618
+
2520
2619
  # The ONE page envelope, on every collection this surface returns — top level
2521
2620
  # or nested. ``next_cursor`` means one thing everywhere: pass it back as
2522
2621
  # ``cursor=`` for the next page, and None means there is no next page. It never
@@ -3216,6 +3315,66 @@ def _map_auth_status(data: Dict[str, Any]) -> AuthStatus:
3216
3315
  )
3217
3316
 
3218
3317
 
3318
+ def _map_organization(data: Dict[str, Any]) -> Organization:
3319
+ role = data.get('role')
3320
+ return Organization(
3321
+ org_id=data.get('org_id', ''),
3322
+ slug=data.get('slug', ''),
3323
+ display_name=data.get('display_name', ''),
3324
+ personal=data.get('personal') is True,
3325
+ role=role if role in ('owner', 'member') else None,
3326
+ created_at=data.get('created_at', ''),
3327
+ )
3328
+
3329
+
3330
+ def _map_organization_detail(data: Dict[str, Any]) -> OrganizationDetail:
3331
+ def count(source: Dict[str, Any], key: str) -> int:
3332
+ value = source.get(key)
3333
+ return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0
3334
+
3335
+ quota = data.get('quota') if isinstance(data.get('quota'), dict) else {}
3336
+ usage = data.get('usage') if isinstance(data.get('usage'), dict) else {}
3337
+ budget = quota.get('monthly_budget_usd')
3338
+ base = _map_organization(data)
3339
+ return OrganizationDetail(
3340
+ org_id=base.org_id,
3341
+ slug=base.slug,
3342
+ display_name=base.display_name,
3343
+ personal=base.personal,
3344
+ role=base.role,
3345
+ created_at=base.created_at,
3346
+ member_count=count(data, 'member_count'),
3347
+ quota=OrgQuota(
3348
+ max_concurrent_trials=count(quota, 'max_concurrent_trials'),
3349
+ max_queued_trials=count(quota, 'max_queued_trials'),
3350
+ max_concurrent_imports=count(quota, 'max_concurrent_imports'),
3351
+ max_concurrent_analyses=count(quota, 'max_concurrent_analyses'),
3352
+ max_concurrent_sessions=count(quota, 'max_concurrent_sessions'),
3353
+ monthly_budget_usd=(
3354
+ float(budget)
3355
+ if isinstance(budget, (int, float)) and not isinstance(budget, bool)
3356
+ else None
3357
+ ),
3358
+ max_concurrent_sandboxes_e2b=count(quota, 'max_concurrent_sandboxes_e2b'),
3359
+ max_concurrent_sandboxes_daytona=count(quota, 'max_concurrent_sandboxes_daytona'),
3360
+ max_concurrent_sandboxes_modal=count(quota, 'max_concurrent_sandboxes_modal'),
3361
+ ),
3362
+ usage=OrgUsage(
3363
+ in_flight_trials=count(usage, 'in_flight_trials'),
3364
+ queued_trials=count(usage, 'queued_trials'),
3365
+ in_flight_imports=count(usage, 'in_flight_imports'),
3366
+ in_flight_analyses=count(usage, 'in_flight_analyses'),
3367
+ active_sessions=count(usage, 'active_sessions'),
3368
+ month_spend_usd=(
3369
+ float(usage.get('month_spend_usd'))
3370
+ if isinstance(usage.get('month_spend_usd'), (int, float))
3371
+ and not isinstance(usage.get('month_spend_usd'), bool)
3372
+ else 0.0
3373
+ ),
3374
+ ),
3375
+ )
3376
+
3377
+
3219
3378
  def _page_parts(data: Any) -> 'tuple[List[Any], Optional[str], bool]':
3220
3379
  """The one page envelope, unpacked: (items, next_cursor, has_more)."""
3221
3380
  page = data if isinstance(data, dict) else {}
@@ -7216,6 +7375,43 @@ class AuthClient:
7216
7375
  return _map_auth_status(raw)
7217
7376
 
7218
7377
 
7378
+ class OrgsClient:
7379
+ """Client for the caller's organizations — the read pair.
7380
+
7381
+ Created via the standalone ``orgs()`` factory. ``list()`` is Harbor's
7382
+ ``harbor auth org list`` shape; ``get()`` is the hosted extension that
7383
+ reads one organization's quota and usage. Creating, renaming, deleting,
7384
+ members and invite links are served by the API and stay outside the SDK
7385
+ until a wave asks for them; quotas are set only from the platform
7386
+ administrator's dashboard session, so no SDK method could ever set one.
7387
+ Requires ``EVOLVE_API_KEY`` unless ``HostedClientConfig(api_key=...)`` is
7388
+ given.
7389
+ """
7390
+
7391
+ def __init__(self, config: Optional[HostedClientConfig] = None):
7392
+ self._http = _HostedHttp('orgs', config)
7393
+
7394
+ async def __aenter__(self) -> 'OrgsClient':
7395
+ return self
7396
+
7397
+ async def __aexit__(self, *args: Any) -> None:
7398
+ await self.close()
7399
+
7400
+ async def close(self) -> None:
7401
+ return None
7402
+
7403
+ async def list(self) -> List[Organization]:
7404
+ """Every organization the caller belongs to, personal first (``GET /api/orgs``)."""
7405
+ raw = await self._http.request_json('/api/orgs')
7406
+ items = raw.get('items') if isinstance(raw.get('items'), list) else []
7407
+ return [_map_organization(item) for item in items if isinstance(item, dict)]
7408
+
7409
+ async def get(self, org: str) -> OrganizationDetail:
7410
+ """One organization by slug (or id): role, member count, quota, usage (``GET /api/orgs/{org}``)."""
7411
+ raw = await self._http.request_json(f'/api/orgs/{urllib.parse.quote(org, safe="")}')
7412
+ return _map_organization_detail(raw)
7413
+
7414
+
7219
7415
  def _parse_dataset_ref(ref: str) -> 'tuple[str, Optional[str]]':
7220
7416
  at = ref.find('@')
7221
7417
  if at == -1:
@@ -7266,6 +7462,7 @@ class HostedEvolve:
7266
7462
  self._trials: Optional[TrialsClient] = None
7267
7463
  self._analyses: Optional[AnalysesClient] = None
7268
7464
  self._skills: Optional[SkillsClient] = None
7465
+ self._orgs: Optional[OrgsClient] = None
7269
7466
 
7270
7467
  @property
7271
7468
  def datasets(self) -> DatasetsClient:
@@ -7309,6 +7506,13 @@ class HostedEvolve:
7309
7506
  self._skills = SkillsClient(self._config)
7310
7507
  return self._skills
7311
7508
 
7509
+ @property
7510
+ def orgs(self) -> OrgsClient:
7511
+ """Your organizations: list them, read one's quota and usage."""
7512
+ if self._orgs is None:
7513
+ self._orgs = OrgsClient(self._config)
7514
+ return self._orgs
7515
+
7312
7516
  async def meta(self) -> CapabilityDocument:
7313
7517
  """The capability document. Public: no API key required.
7314
7518
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolve-sdk
3
- Version: 0.0.55.dev1085
3
+ Version: 0.0.55.dev1103
4
4
  Summary: Pythonic SDK for multi-agent orchestration in E2B sandboxes
5
5
  Author-email: "Swarmlink, Inc." <brandomagnani@evolvingmachines.ai>
6
6
  License: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "evolve-sdk"
7
- version = "0.0.55.dev1085"
7
+ version = "0.0.55.dev1103"
8
8
  description = "Pythonic SDK for multi-agent orchestration in E2B sandboxes"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"