evolve-sdk 0.0.55.dev1192__tar.gz → 0.0.55.dev1198__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.dev1192 → evolve_sdk-0.0.55.dev1198}/PKG-INFO +1 -1
  2. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/bridge/dist/bridge.bundle.cjs +1 -1
  3. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/__init__.py +1 -1
  4. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/hosted.py +54 -10
  5. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve_sdk.egg-info/PKG-INFO +1 -1
  6. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/pyproject.toml +1 -1
  7. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/LICENSE +0 -0
  8. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/MANIFEST.in +0 -0
  9. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/README.md +0 -0
  10. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/bridge/__init__.py +0 -0
  11. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/_http.py +0 -0
  12. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/agent.py +0 -0
  13. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/bridge.py +0 -0
  14. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/browser_credentials.py +0 -0
  15. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/browser_profiles.py +0 -0
  16. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/config.py +0 -0
  17. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/integrations.py +0 -0
  18. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/managed_secrets.py +0 -0
  19. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/pipeline/__init__.py +0 -0
  20. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/pipeline/pipeline.py +0 -0
  21. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/pipeline/types.py +0 -0
  22. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/__init__.py +0 -0
  23. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/agent_md/judge.md +0 -0
  24. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/agent_md/reduce.md +0 -0
  25. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/agent_md/verify.md +0 -0
  26. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/user/judge.md +0 -0
  27. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/user/retry_feedback.md +0 -0
  28. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/prompts/user/verify.md +0 -0
  29. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/py.typed +0 -0
  30. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/results.py +0 -0
  31. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/retry.py +0 -0
  32. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/schema.py +0 -0
  33. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/sessions_client.py +0 -0
  34. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/storage_client.py +0 -0
  35. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/swarm/__init__.py +0 -0
  36. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/swarm/results.py +0 -0
  37. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/swarm/swarm.py +0 -0
  38. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/swarm/types.py +0 -0
  39. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve/utils.py +0 -0
  40. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve_sdk.egg-info/SOURCES.txt +0 -0
  41. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve_sdk.egg-info/dependency_links.txt +0 -0
  42. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve_sdk.egg-info/requires.txt +0 -0
  43. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/evolve_sdk.egg-info/top_level.txt +0 -0
  44. {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1198}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolve-sdk
3
- Version: 0.0.55.dev1192
3
+ Version: 0.0.55.dev1198
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
@@ -899,7 +899,7 @@ PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy
899
899
  `);f=T.pop()??"";for(let k of T){if(!k.trim())continue;let O=p(k);if(this.captureDroidSession(k,O),this.sessionLogger?.writeEventParsed(k,O),t?.onStdout?.(k+`
900
900
  `),O&&t?.onContent)for(let R of O)t.onContent(R)}},y=I=>{t?.onStderr?.(I)},b=await c.commands.spawn(l,{cwd:this.workingDir,timeoutMs:r,envs:d,onStdout:m,onStderr:y}),v=this.beginOperation("run",b,t,"run_start");if(this.hasRun=!0,a)return this.watchBackgroundOperation(v,"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 S;try{S=await b.wait()}catch(I){throw this.interruptedOperations.delete(v),this.finalizeOperation(v,t,"run_failed","error"),I}if(this.interruptedOperations.delete(v)||S.exitCode===130?this.finalizeOperation(v,t,"run_interrupted","interrupted"):S.exitCode===0?this.finalizeOperation(v,t,"run_complete","idle"):this.finalizeOperation(v,t,"run_failed","error"),f.trim()){let I=p(f);if(this.captureDroidSession(f,I),this.sessionLogger?.writeEventParsed(f,I),t?.onStdout?.(f+`
901
901
  `),I&&t?.onContent)for(let T of I)t.onContent(T)}await this.writeDroidSessionState(c),this.sessionLogger&&!a&&await this.flushSessionLoggerWithTimeout();let w;if(this.storage&&!a&&S.exitCode===0)try{w=await cXe(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(I){console.warn(`[Evolve] Auto-checkpoint failed: ${I.message}`)}return{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:u,exitCode:S.exitCode,stdout:S.stdout,stderr:S.stderr,checkpoint:w}}async executeCommand(e,t={},n){let{timeoutMs:r=FO,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=m=>{s+=m,n?.onStdout?.(m)},l=m=>{o+=m,n?.onStderr?.(m)},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 p;try{p=await d.wait()}catch(m){throw this.interruptedOperations.delete(f),this.finalizeOperation(f,n,"command_failed","error"),m}return this.interruptedOperations.delete(f)||p.exitCode===130?this.finalizeOperation(f,n,"command_interrupted","interrupted"):p.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:p.exitCode,stdout:s||p.stdout||"",stderr:o||p.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 f9t(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(`
902
- `).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[p,m]=f.split("|");if(!p||!m)continue;let y=parseInt(m,10);i>0&&y<i||s.push(p)}let c={},l=await Promise.all(s.map(async f=>{try{let p=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:p}}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 p=this.zodSchema.safeParse(f);return p.success?{files:c,data:p.data}:{files:c,data:null,error:`Schema validation failed: ${p.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let p=this.compiledValidator.errors?.map(m=>`${m.instancePath} ${m.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${p}`,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 cXe(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=wXe(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 v9t(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function b9t(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 S9t(e){return await e.text().catch(()=>"")}async function EXe(e,t,n={}){let r=await fetch(`${v9t(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${b9t(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 S9t(r)}`);return r.status===204?{}:await r.json()}var _9t=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 EXe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await EXe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function w9t(e={}){return new _9t(e)}var Tv=class extends kXe.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&&(zXe(e),jXe(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&&(vB(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=IYt;static browserCredentials=t9t;static browserProfiles=w9t;static managedSecrets=CB;async initializeAgent(){let e=tXe(this.config.agent),t=xv(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=RQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!DZ(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 qZ(e.apiKey):await $jt()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=JYt(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=bQ(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"?oYt:cYt,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?XXe(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 y9t(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=tXe(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 hXe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return hXe(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)}},I9t=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++}},_O=Symbol.for("evolve.SwarmResult"),TXe=class yZe 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 yZe;return n.push(...t),n}},EOn=class pB{config;semaphore;constructor(t={}){let n=t.concurrency??SQ;if(n>AB)throw new Error(`concurrency=${n} exceeds max ${AB}. 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??FO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new I9t(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?Mp(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return TXe.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?Mp(p=>this.executeFilterItem(d,r,f,o,t,c,p),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 TXe.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((I,T)=>{c.push(this.getFiles(I)),l.push(this.getIndex(I,T))});let u={};c.forEach((I,T)=>{Object.entries(I).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=wZ(u),f=Iv(pYt,{fileTree:d}),p=t.systemPrompt?`${f}
902
+ `).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[p,m]=f.split("|");if(!p||!m)continue;let y=parseInt(m,10);i>0&&y<i||s.push(p)}let c={},l=await Promise.all(s.map(async f=>{try{let p=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:p}}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 p=this.zodSchema.safeParse(f);return p.success?{files:c,data:p.data}:{files:c,data:null,error:`Schema validation failed: ${p.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let p=this.compiledValidator.errors?.map(m=>`${m.instancePath} ${m.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${p}`,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 cXe(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=wXe(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 v9t(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function b9t(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 S9t(e){return await e.text().catch(()=>"")}async function EXe(e,t,n={}){let r=await fetch(`${v9t(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${b9t(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 S9t(r)}`);return r.status===204?{}:await r.json()}var _9t=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 EXe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await EXe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function w9t(e={}){return new _9t(e)}var Tv=class extends kXe.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&&(zXe(e),jXe(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&&(vB(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=IYt;static browserCredentials=t9t;static browserProfiles=w9t;static managedSecrets=CB;async initializeAgent(){let e=tXe(this.config.agent),t=xv(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=RQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!DZ(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 qZ(e.apiKey):await $jt()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=JYt(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=bQ(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"?oYt:cYt,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?XXe(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 y9t(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=tXe(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 hXe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return hXe(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)}},I9t=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++}},_O=Symbol.for("evolve.SwarmResult"),TXe=class yZe 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 yZe;return n.push(...t),n}},kOn=class pB{config;semaphore;constructor(t={}){let n=t.concurrency??SQ;if(n>AB)throw new Error(`concurrency=${n} exceeds max ${AB}. 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??FO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new I9t(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?Mp(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return TXe.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?Mp(p=>this.executeFilterItem(d,r,f,o,t,c,p),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 TXe.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((I,T)=>{c.push(this.getFiles(I)),l.push(this.getIndex(I,T))});let u={};c.forEach((I,T)=>{Object.entries(I).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=wZ(u),f=Iv(pYt,{fileTree:d}),p=t.systemPrompt?`${f}
903
903
 
904
904
  ${t.systemPrompt}`:f,m=(I,T,k)=>({operationId:s,operation:"reduce",tag:I.tag,sandboxId:I.sandboxId,swarmName:this.config.tag,operationName:t.name,inputCount:n.length,inputIndices:l,errorRetry:T,verifyRetry:k,...this.pipelineContextToMeta(t._pipelineContext)}),y=t.mcpServers??this.config.mcpServers,b=t.skills??this.config.skills,v=t.integrations??this.config.integrations,S=async(I,T,k,O)=>{let R=await this.semaphore.use(()=>this.execute(u,I,{systemPrompt:p,schema:t.schema,schemaOptions:t.schemaOptions,agent:t.agent,mcpServers:y,skills:b,integrations:v,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)}})),B=m(R,k,O&&O>1?O-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:B,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:B}},w=`${this.config.tag}-reduce`;return a?this.runWithVerification((I,T,k)=>S(I,T,void 0,k),{originalPrompt:r,inputFiles:u,verifyConfig:a,timeoutMs:o,systemPrompt:p,schema:t.schema,mcpServers:y,skills:b,integrations:v,operationId:s,baseTag:w,retry:i,operation:"reduce",_pipelineContext:t._pipelineContext}):i?Mp(I=>{let T=I>1?I-1:void 0,k=T?`${w}-er${T}`:w;return S(r,k,T)},i):S(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,p=a.judgeSkills??a.skills??this.config.skills,m=a.integrations??this.config.integrations,y=a.judgeIntegrations??a.integrations??this.config.integrations,b=await Promise.all(Array.from({length:s},async(T,k)=>{let O=i?await Mp(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:m,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:m,timeoutMs:c});return a.onCandidateComplete?.(0,k,O.status==="success"?"success":"error"),O})),v=i?await Mp(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:p,integrations:y,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:p,integrations:y}),S=b.findIndex(T=>T.status==="success"),w=v.decision?.winner??(S>=0?S:0);a.onJudgeComplete?.(0,w,v.decision?.reasoning??"Judge failed to provide reasoning");let I={operationId:o,operation:"bestof-judge",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:t.name,candidateCount:s};return{winner:b[w]??b[0],winnerIndex:w,judgeReasoning:v.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:I,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 Tv().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 p=null;try{p=await a.getOutputFiles(!0),o=p.files}catch{}f.exitCode!==0?l=`Agent exited with code ${f.exitCode}`:r.schema?p?(c=p.data,p.error&&(l=p.error),p.rawData&&(u=p.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,p=i.integrations??this.config.integrations,m=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:p,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)}})),y={operationId:a,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(m,y)}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,p=i.integrations??this.config.integrations,m=this.evaluatePrompt(n,c,r);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let y=async(b,v,S)=>{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:p,tagPrefix:v,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:r,role:"worker",verifyRetry:S&&S>1?S-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),I={operationId:a,operation:"map",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,verifyRetry:S&&S>1?S-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(w,I)};return this.runWithVerification(y,{originalPrompt:m,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:p,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 p=i.mcpServers??this.config.mcpServers,m=d.mcpServers??p,y=d.judgeMcpServers??d.mcpServers??p,b=i.skills??this.config.skills,v=d.skills??b,S=d.judgeSkills??d.skills??b,w=i.integrations??this.config.integrations,I=d.integrations??w,T=d.judgeIntegrations??d.integrations??w,k=await Promise.all(Array.from({length:f},async(Pe,ee)=>{let E=o?await Mp(G=>this.executeBestOfCandidate({inputFiles:c,prompt:u,candidateIndex:ee,operationId:a,config:d,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:v,integrations:I,timeoutMs:s,parentIndex:r,attempt:G,_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:m,skills:v,integrations:I,timeoutMs:s,parentIndex:r,_pipelineContext:i._pipelineContext});return d.onCandidateComplete?.(r,ee,E.status==="success"?"success":"error"),E})),O=o?await Mp(Pe=>this.executeBestOfJudge({inputFiles:c,taskPrompt:u,candidates:k,config:d,timeoutMs:s,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:y,skills:S,integrations:T,parentIndex:r,attempt:Pe,_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:y,skills:S,integrations:T,parentIndex:r,_pipelineContext:i._pipelineContext}),R=k.findIndex(Pe=>Pe.status==="success"),B=O.decision?.winner??(R>=0?R:0),V=k[B]??k[0];d.onJudgeComplete?.(r,B,O.decision?.reasoning??"Judge failed to provide reasoning");let L={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{...V,meta:{...V.meta,operation:"map",swarmName:this.config.tag,operationName:i.name,itemIndex:r,...this.pipelineContextToMeta(i._pipelineContext)},bestOf:{winnerIndex:B,judgeReasoning:O.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:L,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,p=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)}})),m={operationId:a,operation:"filter",tag:p.tag,sandboxId:p.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(p,m,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,p=i.integrations??this.config.integrations,m=async(y,b,v)=>{let S=await this.semaphore.use(()=>this.execute(c,y,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:p,tagPrefix:b,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:r,role:"worker",verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),w={operationId:a,operation:"filter",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(S,w,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:p,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,p=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)}})),m={operationId:i,operation:"bestof-cand",tag:p.tag,sandboxId:p.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:l>1?l-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(u)};return this.buildResult(p,m)}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
905
905
 
@@ -490,7 +490,7 @@ async def list_checkpoints(
490
490
  await store.close()
491
491
 
492
492
 
493
- __version__ = '0.0.55.dev1192'
493
+ __version__ = '0.0.55.dev1198'
494
494
 
495
495
  __all__ = [
496
496
  # Main classes
@@ -1838,13 +1838,20 @@ class CheckConfigInput(TypedDict, total=False):
1838
1838
 
1839
1839
 
1840
1840
  class CheckSource(TypedDict):
1841
- """What was checked — the uploaded archive, by identity (spec ``CheckSource``)."""
1842
- #: Always ``'archive'``.
1841
+ """What was checked, by identity (spec ``CheckSource``) — two forms told
1842
+ apart by ``type``: ``'archive'`` (the uploaded tar's sha256 and compressed
1843
+ ``bytes``; ``dataset`` None) or ``'dataset'`` (the resolved
1844
+ ``name@version`` in ``dataset`` and the sha256 of the version's retained
1845
+ task package; ``bytes`` None — a package's size is not a recorded fact,
1846
+ so the wire invents none)."""
1847
+ #: ``'archive'`` or ``'dataset'``.
1843
1848
  type: str
1844
- #: SHA-256 of the archive as uploaded.
1849
+ #: SHA-256 of the archive as uploaded, or of the version's retained task package.
1845
1850
  sha256: str
1846
- #: The archive's compressed size.
1847
- bytes: int
1851
+ #: The archive's compressed size on the archive form; None on the dataset form.
1852
+ bytes: Optional[int]
1853
+ #: The resolved ``name@version`` on the dataset form; None on the archive form.
1854
+ dataset: Optional[str]
1848
1855
 
1849
1856
 
1850
1857
  class TaskCheck(TypedDict):
@@ -2463,6 +2470,10 @@ class JobTaskRollup:
2463
2470
  mean_reward: Optional[float]
2464
2471
  #: Measured spend across the task's settled trials.
2465
2472
  cost_usd: Optional[float]
2473
+ #: The task's LATEST quality check among the checks you may read that ran
2474
+ #: on a dataset version this job spans (``checks().create(dataset=...)``);
2475
+ #: None = never checked. The job page's CHECK tab reads it.
2476
+ check: Optional[TaskCheck]
2466
2477
 
2467
2478
 
2468
2479
  @dataclass
@@ -3730,6 +3741,8 @@ def _map_job_task_rollup(data: Dict[str, Any]) -> JobTaskRollup:
3730
3741
  trials=_map_trial_tally(data.get('trials')),
3731
3742
  mean_reward=float(mean_reward) if isinstance(mean_reward, (int, float)) else None,
3732
3743
  cost_usd=float(cost_usd) if isinstance(cost_usd, (int, float)) else None,
3744
+ # The wire's TaskCheck or None, passed through: the row IS the answer.
3745
+ check=cast(TaskCheck, data['check']) if isinstance(data.get('check'), dict) else None,
3733
3746
  )
3734
3747
 
3735
3748
 
@@ -8146,8 +8159,9 @@ class ChecksClient:
8146
8159
 
8147
8160
  async def create(
8148
8161
  self,
8149
- directory: str,
8162
+ directory: Optional[str] = None,
8150
8163
  *,
8164
+ dataset: Optional[str] = None,
8151
8165
  model_name: Optional[str] = None,
8152
8166
  rubric: Optional[Rubric] = None,
8153
8167
  prompt: Optional[str] = None,
@@ -8162,10 +8176,16 @@ class ChecksClient:
8162
8176
  """Check task quality against a rubric — Harbor's ``harbor check
8163
8177
  <PATH>`` (their cli/analyze.py:84-207), hosted.
8164
8178
 
8165
- ``directory`` is Harbor's PATH: one task directory, or a directory of
8166
- task directories, tarred and streamed from disk a directory only,
8167
- as Harbor's PATH is (their checker.py:125-130 refuses anything else);
8168
- no ready-packed archive form. Which task directories are checked is
8179
+ ONE source: ``directory`` Harbor's PATH: one task directory, or a
8180
+ directory of task directories, tarred and streamed from disk, a
8181
+ directory only, as Harbor's PATH is (their checker.py:125-130 refuses
8182
+ anything else; no ready-packed archive form) or ``dataset``, a
8183
+ PUBLISHED dataset (``'name'`` for its active version, or
8184
+ ``'name@version'``), the hosted form and a recorded deviation: Harbor's
8185
+ check takes a local path only; here the checker reads the version's
8186
+ retained task package, nothing is uploaded, and the job page's CHECK
8187
+ tab lists these checks by task. Both or neither is a ``ValueError``
8188
+ at the keyboard. Which task directories are checked is
8169
8189
  Harbor's own resolution (checker.py:
8170
8190
  116-141): the root when it is a task directory (task.toml +
8171
8191
  environment/ + instruction.md + tests/), else every top-level
@@ -8194,7 +8214,21 @@ class ChecksClient:
8194
8214
  ``limits['uploads']['check_archive_bytes']``),
8195
8215
  ``too_many_concurrent_check_uploads`` (the server is already
8196
8216
  spooling its bound of check archives — retry when one finishes).
8217
+ The dataset form resolves under the job-create door's own refusals:
8218
+ ``dataset_not_found`` (404), ``dataset_version_not_found`` (404),
8219
+ ``no_active_version`` (400), ``version_not_ready`` (409), and
8220
+ ``invalid_input`` on ``dataset`` (400) for a version whose task
8221
+ package was not retained.
8222
+
8223
+ Each task's result (``results[i]['id']``) is also a run of its own,
8224
+ read like an analysis run — the checker's transcript, raw streams,
8225
+ agent home and ``check-result.json``; those reads ride the
8226
+ dashboard's traces feed (not on the contract) and are
8227
+ TypeScript-and-CLI today: ``evolve check trace`` and ``evolve check
8228
+ download``.
8197
8229
  """
8230
+ if (directory is None) == (dataset is None):
8231
+ raise ValueError('checks().create() takes exactly one source: directory or dataset')
8198
8232
  knobs: Dict[str, Any] = {}
8199
8233
  if model_name is not None:
8200
8234
  knobs['model_name'] = model_name
@@ -8218,6 +8252,16 @@ class ChecksClient:
8218
8252
  # sent before the archive so the server rules it before a byte of
8219
8253
  # the upload — the analyze door's acceptance, under ``check.*``.
8220
8254
  fields: Dict[str, Optional[str]] = {'config': json.dumps(knobs)}
8255
+ if dataset is not None:
8256
+ # THE DATASET FORM: no archive travels — the ``dataset`` part
8257
+ # names the published version (the metadata-only multipart body
8258
+ # every no-archive route takes).
8259
+ if dataset.strip() == '':
8260
+ raise ValueError('checks().create(): dataset must be "name" or "name@version"')
8261
+ body, content_type = _multipart_body({**fields, 'dataset': dataset.strip()})
8262
+ raw = await self._http.request_upload('/api/checks', body, {'Content-Type': content_type})
8263
+ return _map_check(raw)
8264
+ assert directory is not None
8221
8265
  path = os.path.abspath(directory)
8222
8266
  # Harbor's own first refusal: "Path '{path}' does not exist"
8223
8267
  # (checker.py:66-67), at the keyboard, before any tar.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolve-sdk
3
- Version: 0.0.55.dev1192
3
+ Version: 0.0.55.dev1198
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.dev1192"
7
+ version = "0.0.55.dev1198"
8
8
  description = "Pythonic SDK for multi-agent orchestration in E2B sandboxes"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"