evolvingmachines-evolve 0.0.64__tar.gz → 0.0.65.dev1527__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.
- {evolvingmachines_evolve-0.0.64/evolvingmachines_evolve.egg-info → evolvingmachines_evolve-0.0.65.dev1527}/PKG-INFO +1 -1
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/bridge/dist/bridge.bundle.cjs +1 -1
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/__init__.py +13 -1
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/hosted.py +154 -8
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527/evolvingmachines_evolve.egg-info}/PKG-INFO +1 -1
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/pyproject.toml +1 -1
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/LICENSE +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/MANIFEST.in +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/README.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/bridge/__init__.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/_http.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/agent.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/bridge.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/browser_credentials.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/browser_profiles.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/config.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/integrations.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/managed_secrets.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/pipeline/__init__.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/pipeline/pipeline.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/pipeline/types.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/__init__.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/agent_md/judge.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/agent_md/reduce.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/agent_md/verify.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/user/judge.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/user/retry_feedback.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/user/verify.md +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/py.typed +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/results.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/retry.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/sandbox_view.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/schema.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/sessions_client.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/storage_client.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/__init__.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/results.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/swarm.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/types.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/utils.py +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolvingmachines_evolve.egg-info/SOURCES.txt +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolvingmachines_evolve.egg-info/dependency_links.txt +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolvingmachines_evolve.egg-info/requires.txt +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolvingmachines_evolve.egg-info/top_level.txt +0 -0
- {evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/setup.cfg +0 -0
|
@@ -898,7 +898,7 @@ PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy
|
|
|
898
898
|
`);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+`
|
|
899
899
|
`),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+`
|
|
900
900
|
`),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 rZe(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=YO,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 KKt(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(`
|
|
901
|
-
`).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 rZe(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=mZe(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||zi,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 nXt(e){return(e||process.env.EVOLVE_DASHBOARD_URL||zi).replace(/\/$/,"")}function rXt(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 iXt(e){return await e.text().catch(()=>"")}async function yZe(e,t,n={}){let r=await fetch(`${nXt(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${rXt(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 iXt(r)}`);return r.status===204?{}:await r.json()}var aXt=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 yZe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await yZe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function sXt(e={}){return new aXt(e)}var Rv=class extends bZe.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&&(DZe(e),VZe(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&&(RB(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}withOrg(e){return this.config.org=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=sKt;static browserCredentials=FKt;static browserProfiles=sXt;static managedSecrets=WB;async initializeAgent(){let e=KXe(this.config.agent),t=Av(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=cee(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!oQ(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 pQ(e.apiKey):await hQ()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=OKt(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=WQ(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"?z9t:G9t,s={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||zi,...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?zZe(this.config.storage,!e.isDirectMode,zi,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||zi}: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||zi,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,org:this.config.org,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||zi}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||zi},storage:l};this.agent=new tXt(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=KXe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:zi,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 lZe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return lZe(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)}},oXt=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++}},CO=Symbol.for("evolve.SwarmResult"),vZe=class lQe 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 lQe;return n.push(...t),n}},IPn=class EB{config;semaphore;constructor(t={}){let n=t.concurrency??jQ;if(n>zB)throw new Error(`concurrency=${n} exceeds max ${zB}. 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??YO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new oXt(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?Up(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return vZe.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?Up(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 vZe.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=jZ(u),f=Ov(Y9t,{fileTree:d}),p=t.systemPrompt?`${f}
|
|
901
|
+
`).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 rZe(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=mZe(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||zi,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 nXt(e){return(e||process.env.EVOLVE_DASHBOARD_URL||zi).replace(/\/$/,"")}function rXt(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 iXt(e){return await e.text().catch(()=>"")}async function yZe(e,t,n={}){let r=await fetch(`${nXt(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${rXt(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 iXt(r)}`);return r.status===204?{}:await r.json()}var aXt=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 yZe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await yZe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function sXt(e={}){return new aXt(e)}var Rv=class extends bZe.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&&(DZe(e),VZe(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&&(RB(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}withOrg(e){return this.config.org=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=sKt;static browserCredentials=FKt;static browserProfiles=sXt;static managedSecrets=WB;async initializeAgent(){let e=KXe(this.config.agent),t=Av(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=cee(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!oQ(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 pQ(e.apiKey):await hQ()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=OKt(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=WQ(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"?z9t:G9t,s={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||zi,...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?zZe(this.config.storage,!e.isDirectMode,zi,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||zi}: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||zi,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,org:this.config.org,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||zi}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||zi},storage:l};this.agent=new tXt(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=KXe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:zi,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 lZe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return lZe(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)}},oXt=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++}},CO=Symbol.for("evolve.SwarmResult"),vZe=class lQe 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 lQe;return n.push(...t),n}},xPn=class EB{config;semaphore;constructor(t={}){let n=t.concurrency??jQ;if(n>zB)throw new Error(`concurrency=${n} exceeds max ${zB}. 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??YO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new oXt(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?Up(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return vZe.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?Up(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 vZe.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=jZ(u),f=Ov(Y9t,{fileTree:d}),p=t.systemPrompt?`${f}
|
|
902
902
|
|
|
903
903
|
${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?Up(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 Up(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 Up(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 Rv().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 Up(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 Up(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
|
|
904
904
|
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/__init__.py
RENAMED
|
@@ -50,7 +50,12 @@ from .hosted import (
|
|
|
50
50
|
CheckStatus,
|
|
51
51
|
ChecksClient,
|
|
52
52
|
TaskCheck,
|
|
53
|
+
CheckRow,
|
|
54
|
+
CheckTaskTally,
|
|
55
|
+
JobListItem,
|
|
56
|
+
JobListKind,
|
|
53
57
|
JobListScope,
|
|
58
|
+
JobViewer,
|
|
54
59
|
AgentArm,
|
|
55
60
|
AgentCapability,
|
|
56
61
|
AgentDatasetStats,
|
|
@@ -64,6 +69,7 @@ from .hosted import (
|
|
|
64
69
|
AnalysisFailure,
|
|
65
70
|
AnalyzeConfig,
|
|
66
71
|
AnalyzeConfigInput,
|
|
72
|
+
AnalyzeDefaults,
|
|
67
73
|
ApiKey,
|
|
68
74
|
AttemptPhase,
|
|
69
75
|
AuthClient,
|
|
@@ -543,7 +549,7 @@ async def list_checkpoints(
|
|
|
543
549
|
await store.close()
|
|
544
550
|
|
|
545
551
|
|
|
546
|
-
__version__ = '0.0.
|
|
552
|
+
__version__ = '0.0.65.dev1527'
|
|
547
553
|
|
|
548
554
|
__all__ = [
|
|
549
555
|
# Main classes
|
|
@@ -679,6 +685,7 @@ __all__ = [
|
|
|
679
685
|
'JobStatus',
|
|
680
686
|
'AnalyzeConfig',
|
|
681
687
|
'AnalyzeConfigInput',
|
|
688
|
+
'AnalyzeDefaults',
|
|
682
689
|
'AnalysisCheck',
|
|
683
690
|
'AnalysisEvidence',
|
|
684
691
|
'AnalysisFailure',
|
|
@@ -758,6 +765,11 @@ __all__ = [
|
|
|
758
765
|
'AnalysisPage',
|
|
759
766
|
'CheckPage',
|
|
760
767
|
'JobListScope',
|
|
768
|
+
'JobListKind',
|
|
769
|
+
'JobListItem',
|
|
770
|
+
'CheckRow',
|
|
771
|
+
'CheckTaskTally',
|
|
772
|
+
'JobViewer',
|
|
761
773
|
'AnalysisStatus',
|
|
762
774
|
'AnalysisLabel',
|
|
763
775
|
'CheckStatus',
|
|
@@ -571,6 +571,15 @@ EvalSandboxProvider = Literal['e2b', 'daytona', 'modal']
|
|
|
571
571
|
#: it (``invalid_input``).
|
|
572
572
|
JobListScope = Literal['my', 'shared', 'org']
|
|
573
573
|
|
|
574
|
+
#: The jobs list's ``kind``: a check is a job, so ``'all'`` lists both (the ruling and the
|
|
575
|
+
#: Harbor lines live on the spec's ``JobListKind`` parameter).
|
|
576
|
+
JobListKind = Literal['job', 'check', 'all']
|
|
577
|
+
#: The caller's relation to a job on a read (``Job.viewer``): ``creator`` made
|
|
578
|
+
#: it, ``member`` belongs to its organization, ``shared`` reads it through an
|
|
579
|
+
#: email share, ``link`` through its unlisted link. Acting verbs (analyze,
|
|
580
|
+
#: cancel, resume, retry, regrade) are open to ``creator`` and ``member`` only.
|
|
581
|
+
JobViewer = Literal['creator', 'member', 'shared', 'link']
|
|
582
|
+
|
|
574
583
|
#: An analysis's own lifecycle ladder — lowercase, the object's Harbor
|
|
575
584
|
#: dialect (spec ``TrialAnalysis.status``).
|
|
576
585
|
AnalysisStatus = Literal['queued', 'running', 'completed', 'failed']
|
|
@@ -1616,7 +1625,7 @@ class RubricCriterion(TypedDict):
|
|
|
1616
1625
|
"""
|
|
1617
1626
|
#: Criterion identifier, snake_case (it keys the result's ``checks``).
|
|
1618
1627
|
#: The platform's default rubrics name seven criteria for analyze and
|
|
1619
|
-
#:
|
|
1628
|
+
#: thirteen for check.
|
|
1620
1629
|
name: str
|
|
1621
1630
|
#: What the criterion evaluates, one sentence.
|
|
1622
1631
|
description: str
|
|
@@ -1743,6 +1752,21 @@ class AnalyzeConfigInput(TypedDict, total=False):
|
|
|
1743
1752
|
#: ``n_trials`` matching trials to settle. An integer of at least 1;
|
|
1744
1753
|
#: anything else is refused ``invalid_input`` naming ``analyze.n_trials``.
|
|
1745
1754
|
n_trials: int
|
|
1755
|
+
#: Analyze only these trials of the job — Harbor's ``harbor analyze
|
|
1756
|
+
#: <trial directory>`` for one trial (their cli/analyze.py:242-245), given
|
|
1757
|
+
#: as ids here; combinable with ``passing``/``failing`` (a listed trial on
|
|
1758
|
+
#: the other side of the filter is skipped) and applied before
|
|
1759
|
+
#: ``n_trials`` (Harbor's one-trial path skips its filter and cap,
|
|
1760
|
+
#: analyzer.py:180-181 before :189-191; hosted, both apply to the named
|
|
1761
|
+
#: trials too). An id that is not a trial of this job is refused
|
|
1762
|
+
#: ``invalid_input`` naming ``analyze.trial_ids`` with the unknown ids
|
|
1763
|
+
#: named in the message and in ``details['unknown_trial_ids']``; a list
|
|
1764
|
+
#: that leaves nothing analyzable is the 409 ``no_analyzable_trials``; an
|
|
1765
|
+
#: empty list, a duplicate, an empty string or a non-string is refused
|
|
1766
|
+
#: ``invalid_input``. Only :meth:`JobsClient.analyze` takes it: on
|
|
1767
|
+
#: ``start(analyze=...)`` (the embedded trigger) it is refused — the
|
|
1768
|
+
#: trials do not exist yet.
|
|
1769
|
+
trial_ids: List[str]
|
|
1746
1770
|
|
|
1747
1771
|
|
|
1748
1772
|
class AnalyzeConfig(TypedDict):
|
|
@@ -1785,6 +1809,10 @@ class AnalyzeConfig(TypedDict):
|
|
|
1785
1809
|
#: The trial cap as stored (``AnalyzeConfigInput['n_trials']``); None =
|
|
1786
1810
|
#: no cap.
|
|
1787
1811
|
n_trials: Optional[int]
|
|
1812
|
+
#: Always None on the job body today: the stored policy is the
|
|
1813
|
+
#: create-time one, which refuses ``trial_ids``; a manual wave's named
|
|
1814
|
+
#: trials are the analysis rows it enqueues.
|
|
1815
|
+
trial_ids: Optional[List[str]]
|
|
1788
1816
|
|
|
1789
1817
|
|
|
1790
1818
|
class AnalysisEvidence(TypedDict):
|
|
@@ -1954,7 +1982,7 @@ class CheckConfigInput(TypedDict, total=False):
|
|
|
1954
1982
|
``openrouter/deepseek/deepseek-v4.1-flash`` — one roster, one default
|
|
1955
1983
|
for both rubric agents, a
|
|
1956
1984
|
recorded deviation), ``rubric`` (default: the platform's check rubric,
|
|
1957
|
-
|
|
1985
|
+
thirteen criteria) and
|
|
1958
1986
|
``prompt`` (the TEXT of Harbor's ``-p/--prompt`` file, replacing the
|
|
1959
1987
|
platform's default check body; rendered with ``{task_path}``, ``{file_tree}``,
|
|
1960
1988
|
``{criteria_guidance}``; the output contract appended after it exactly
|
|
@@ -2088,6 +2116,22 @@ class Check(TypedDict):
|
|
|
2088
2116
|
finished_at: Optional[str]
|
|
2089
2117
|
|
|
2090
2118
|
|
|
2119
|
+
class AnalyzeDefaults(TypedDict):
|
|
2120
|
+
"""The policy an empty analyze config resolves to (``GET
|
|
2121
|
+
/api/analyses/defaults``): each key the value :class:`AnalyzeConfig`
|
|
2122
|
+
echoes for a job created with ``analyze={}``, except ``prompt``, which
|
|
2123
|
+
``AnalyzeConfig`` serves as None and this serves as the template text. A
|
|
2124
|
+
plain wire dict at runtime.
|
|
2125
|
+
"""
|
|
2126
|
+
model_name: str
|
|
2127
|
+
rubric: Rubric
|
|
2128
|
+
#: The built-in analyze prompt template, unrendered — pass it as ``prompt`` to run the default body explicitly, or edit it from here.
|
|
2129
|
+
prompt: str
|
|
2130
|
+
#: The effort the default model runs at when the config names none.
|
|
2131
|
+
reasoning_effort: str
|
|
2132
|
+
sandbox_provider: EvalSandboxProvider
|
|
2133
|
+
|
|
2134
|
+
|
|
2091
2135
|
class CheckDefaults(TypedDict):
|
|
2092
2136
|
"""The policy an empty check config resolves to (``GET
|
|
2093
2137
|
/api/checks/defaults``): each key the value :class:`Check` echoes for a
|
|
@@ -2104,6 +2148,42 @@ class CheckDefaults(TypedDict):
|
|
|
2104
2148
|
sandbox_provider: EvalSandboxProvider
|
|
2105
2149
|
|
|
2106
2150
|
|
|
2151
|
+
class CheckTaskTally(TypedDict):
|
|
2152
|
+
"""Spec ``CheckTaskTally``. A stopped task check is stored ``failed`` with the stop phase; the tally
|
|
2153
|
+
counts it under ``stopped``, never ``failed``. ``byStatus`` keeps the wire's frozen camelCase key."""
|
|
2154
|
+
total: int
|
|
2155
|
+
byStatus: Dict[str, int]
|
|
2156
|
+
|
|
2157
|
+
|
|
2158
|
+
@dataclass
|
|
2159
|
+
class CheckRow:
|
|
2160
|
+
"""Spec ``CheckRow``, one row of ``jobs().list(kind='check' | 'all')``: a check is a job, so it lists beside them.
|
|
2161
|
+
Not a :class:`Job` (no arms, attempts, caps, retry policy, trials, upload provenance), so those fields are absent, never faked."""
|
|
2162
|
+
id: str
|
|
2163
|
+
#: Check.name — Harbor's ``--job-name``: the caller's, or the accept stamp.
|
|
2164
|
+
name: str
|
|
2165
|
+
status: CheckStatus
|
|
2166
|
+
source: CheckSource
|
|
2167
|
+
#: The checker's model.
|
|
2168
|
+
model_name: str
|
|
2169
|
+
#: The effort every task's checker ran at.
|
|
2170
|
+
reasoning_effort: str
|
|
2171
|
+
sandbox_provider: EvalSandboxProvider
|
|
2172
|
+
#: The owning organization's slug (every check has one).
|
|
2173
|
+
org: str
|
|
2174
|
+
visibility: str
|
|
2175
|
+
#: How many task checks, and how they break down; done = completed + failed + stopped.
|
|
2176
|
+
tasks: CheckTaskTally
|
|
2177
|
+
#: The sum of the measured task costs; None when none was measured.
|
|
2178
|
+
cost_usd: Optional[float]
|
|
2179
|
+
#: The accept instant; the list orders it with the jobs' ``started_at``.
|
|
2180
|
+
created_at: str
|
|
2181
|
+
#: When the last task settled; None until every task has.
|
|
2182
|
+
finished_at: Optional[str]
|
|
2183
|
+
#: ``'check'`` — tells the row from a :class:`Job` (whose ``kind`` is ``'job'``).
|
|
2184
|
+
kind: str = field(default='check', kw_only=True)
|
|
2185
|
+
|
|
2186
|
+
|
|
2107
2187
|
class JobRetryConfig(TypedDict):
|
|
2108
2188
|
"""The RESOLVED auto-retry policy a job runs under — the spec's
|
|
2109
2189
|
``RetryConfig`` schema, echoed on every job body as ``Job.retry``: the
|
|
@@ -2259,6 +2339,15 @@ class Job:
|
|
|
2259
2339
|
#: ``jobs().shares(id)`` lists them. Always ``'PRIVATE'`` on a regrade job;
|
|
2260
2340
|
#: a server older than the field reads as ``'PRIVATE'``.
|
|
2261
2341
|
visibility: str = field(default='PRIVATE', kw_only=True)
|
|
2342
|
+
#: The row's kind on the jobs list (:data:`JobListItem`): always ``'job'``
|
|
2343
|
+
#: on a Job body, a regrade included; a :class:`CheckRow` says ``'check'``.
|
|
2344
|
+
kind: str = field(default='job', kw_only=True)
|
|
2345
|
+
#: The caller's relation on a read (:data:`JobViewer`). None on the
|
|
2346
|
+
#: responses that echo a job the caller just acted on (create, analyze,
|
|
2347
|
+
#: cancel, resume, retry, regrade), where the caller is the
|
|
2348
|
+
#: creator or a member by construction, and on list rows (batched; read
|
|
2349
|
+
#: one job to learn it); None too from a server older than the field.
|
|
2350
|
+
viewer: Optional[JobViewer] = field(default=None, kw_only=True)
|
|
2262
2351
|
|
|
2263
2352
|
|
|
2264
2353
|
@dataclass
|
|
@@ -3536,9 +3625,14 @@ class OrgJoined:
|
|
|
3536
3625
|
# (On the wire the envelope keys are the frozen items/nextCursor/hasMore.)
|
|
3537
3626
|
|
|
3538
3627
|
|
|
3628
|
+
#: One row of the jobs list (spec ``JobListItem``): a :class:`Job`, or a :class:`CheckRow` when
|
|
3629
|
+
#: ``jobs().list()`` asked for ``kind='check'`` or ``'all'``; ``row.kind`` tells them apart.
|
|
3630
|
+
JobListItem = Union[Job, CheckRow]
|
|
3631
|
+
|
|
3632
|
+
|
|
3539
3633
|
@dataclass
|
|
3540
3634
|
class JobPage:
|
|
3541
|
-
items: List[
|
|
3635
|
+
items: List[JobListItem]
|
|
3542
3636
|
next_cursor: Optional[str]
|
|
3543
3637
|
has_more: bool
|
|
3544
3638
|
|
|
@@ -4440,6 +4534,14 @@ def _map_job(data: Dict[str, Any]) -> Job:
|
|
|
4440
4534
|
finished_at=data.get('finished_at'),
|
|
4441
4535
|
org=data['org'] if isinstance(data.get('org'), str) else None,
|
|
4442
4536
|
visibility='LINK' if data.get('visibility') == 'LINK' else 'PRIVATE',
|
|
4537
|
+
# A Job body always says job; an older server that sends no kind is one.
|
|
4538
|
+
kind='job',
|
|
4539
|
+
# The read relation; None from an acting verb's echo and from an older server alike.
|
|
4540
|
+
viewer=(
|
|
4541
|
+
cast(JobViewer, data['viewer'])
|
|
4542
|
+
if data.get('viewer') in ('creator', 'member', 'shared', 'link')
|
|
4543
|
+
else None
|
|
4544
|
+
),
|
|
4443
4545
|
)
|
|
4444
4546
|
|
|
4445
4547
|
|
|
@@ -4640,6 +4742,33 @@ def _map_check(data: Any) -> Check:
|
|
|
4640
4742
|
)
|
|
4641
4743
|
|
|
4642
4744
|
|
|
4745
|
+
def _map_check_row(data: Dict[str, Any]) -> CheckRow:
|
|
4746
|
+
"""The jobs list's CheckRow: the wire's source and tally verbatim (the spec
|
|
4747
|
+
requires both, every count included; a count nobody sent is never 0), money read as the Job's."""
|
|
4748
|
+
return CheckRow(
|
|
4749
|
+
id=str(data.get('id', '')),
|
|
4750
|
+
name=str(data.get('name', '')),
|
|
4751
|
+
status=cast(CheckStatus, data.get('status')),
|
|
4752
|
+
source=cast(CheckSource, data['source']),
|
|
4753
|
+
model_name=str(data.get('model_name', '')),
|
|
4754
|
+
reasoning_effort=str(data.get('reasoning_effort', '')),
|
|
4755
|
+
sandbox_provider=cast(EvalSandboxProvider, data.get('sandbox_provider')),
|
|
4756
|
+
org=str(data.get('org', '')),
|
|
4757
|
+
# The share link's switch; an older server that sends none reads as PRIVATE (_map_job's rule).
|
|
4758
|
+
visibility='LINK' if data.get('visibility') == 'LINK' else 'PRIVATE',
|
|
4759
|
+
tasks=cast(CheckTaskTally, data['tasks']),
|
|
4760
|
+
cost_usd=_optional_float(data.get('cost_usd')),
|
|
4761
|
+
created_at=str(data.get('created_at', '')),
|
|
4762
|
+
finished_at=data.get('finished_at'),
|
|
4763
|
+
)
|
|
4764
|
+
|
|
4765
|
+
|
|
4766
|
+
def _map_job_list_item(data: Dict[str, Any]) -> 'JobListItem':
|
|
4767
|
+
"""One row of GET /api/jobs (spec ``JobListItem``): a CheckRow when the
|
|
4768
|
+
server says ``kind: "check"``, else the Job body."""
|
|
4769
|
+
return _map_check_row(data) if data.get('kind') == 'check' else _map_job(data)
|
|
4770
|
+
|
|
4771
|
+
|
|
4643
4772
|
def _map_timing(data: Any) -> Optional[TimingInfo]:
|
|
4644
4773
|
if not isinstance(data, dict):
|
|
4645
4774
|
return None
|
|
@@ -7671,6 +7800,7 @@ class JobsClient:
|
|
|
7671
7800
|
*,
|
|
7672
7801
|
search: Optional[str] = None,
|
|
7673
7802
|
scope: Optional[JobListScope] = None,
|
|
7803
|
+
kind: Optional[JobListKind] = None,
|
|
7674
7804
|
limit: Optional[int] = None,
|
|
7675
7805
|
cursor: Optional[str] = None,
|
|
7676
7806
|
) -> _PaginatedList:
|
|
@@ -7682,15 +7812,17 @@ class JobsClient:
|
|
|
7682
7812
|
``scope`` is Harbor's ``--scope`` — ``'my'`` (yours, the server's
|
|
7683
7813
|
default), ``'shared'`` (your organizations' jobs that teammates
|
|
7684
7814
|
created) or ``'org'`` (every job in your organizations, yours
|
|
7685
|
-
included)
|
|
7815
|
+
included); ``kind`` lists checks alone (``'check'``) or jobs and checks
|
|
7816
|
+
merged (``'all'``, rows told apart by ``kind``) — a check is a job.
|
|
7817
|
+
All three ride every page fetch.
|
|
7686
7818
|
"""
|
|
7687
7819
|
async def fetch_page(page_limit, page_cursor) -> JobPage:
|
|
7688
7820
|
raw = await self._http.request_json(
|
|
7689
|
-
f'/api/jobs{_page_query(page_limit, page_cursor, search=search, scope=scope)}'
|
|
7821
|
+
f'/api/jobs{_page_query(page_limit, page_cursor, search=search, scope=scope, kind=kind)}'
|
|
7690
7822
|
)
|
|
7691
7823
|
items, next_cursor, has_more = _page_parts(raw)
|
|
7692
7824
|
return JobPage(
|
|
7693
|
-
items=[
|
|
7825
|
+
items=[_map_job_list_item(item) for item in items],
|
|
7694
7826
|
next_cursor=next_cursor,
|
|
7695
7827
|
has_more=has_more,
|
|
7696
7828
|
)
|
|
@@ -8144,6 +8276,7 @@ class JobsClient:
|
|
|
8144
8276
|
passing: Optional[bool] = None,
|
|
8145
8277
|
failing: Optional[bool] = None,
|
|
8146
8278
|
n_trials: Optional[int] = None,
|
|
8279
|
+
trial_ids: Optional[List[str]] = None,
|
|
8147
8280
|
) -> Job:
|
|
8148
8281
|
"""Analyze a terminal job's trial traces (rubric-driven, Harbor's
|
|
8149
8282
|
``harbor analyze``), server-side.
|
|
@@ -8188,7 +8321,11 @@ class JobsClient:
|
|
|
8188
8321
|
beneath the organization's ``max_concurrent_analyses`` (Harbor's
|
|
8189
8322
|
``-n/--n-concurrent``; omitted = the ceiling alone). ``passing`` and
|
|
8190
8323
|
``failing`` together are refused ``invalid_input`` — Harbor's own
|
|
8191
|
-
"Cannot use both --passing and --failing".
|
|
8324
|
+
"Cannot use both --passing and --failing". ``trial_ids`` names the
|
|
8325
|
+
trials to analyze (Harbor's ``harbor analyze <trial directory>``,
|
|
8326
|
+
by id), applied with the filter and before the cap; an id that is
|
|
8327
|
+
not this job's is refused ``invalid_input`` naming
|
|
8328
|
+
``analyze.trial_ids`` with the unknown ids in the details.
|
|
8192
8329
|
|
|
8193
8330
|
The server owns every acceptance refusal, surfaced typed:
|
|
8194
8331
|
``job_not_terminal``, ``invalid_rubric`` (unknown keys named, empty
|
|
@@ -8222,6 +8359,8 @@ class JobsClient:
|
|
|
8222
8359
|
body['failing'] = failing
|
|
8223
8360
|
if n_trials is not None:
|
|
8224
8361
|
body['n_trials'] = n_trials
|
|
8362
|
+
if trial_ids is not None:
|
|
8363
|
+
body['trial_ids'] = list(trial_ids)
|
|
8225
8364
|
raw = await self._http.request_json(
|
|
8226
8365
|
f'/api/jobs/{urllib.parse.quote(id)}/analyze', method='POST', body=body
|
|
8227
8366
|
)
|
|
@@ -9352,6 +9491,13 @@ class AnalysesClient:
|
|
|
9352
9491
|
fetch_page, lambda page: page.items, limit=limit, cursor=cursor
|
|
9353
9492
|
)
|
|
9354
9493
|
|
|
9494
|
+
async def defaults(self) -> AnalyzeDefaults:
|
|
9495
|
+
"""The defaults an analysis runs under when its config names nothing
|
|
9496
|
+
(``GET /api/analyses/defaults``): model, effort, provider, rubric and
|
|
9497
|
+
the unrendered prompt template (:class:`AnalyzeDefaults`)."""
|
|
9498
|
+
raw = await self._http.request_json('/api/analyses/defaults')
|
|
9499
|
+
return cast(AnalyzeDefaults, raw)
|
|
9500
|
+
|
|
9355
9501
|
async def download(
|
|
9356
9502
|
self,
|
|
9357
9503
|
analysis_id: str,
|
|
@@ -9472,7 +9618,7 @@ class ChecksClient:
|
|
|
9472
9618
|
first ``n_tasks``. The policy knobs are :class:`CheckConfigInput`'s.
|
|
9473
9619
|
Every argument omitted means the defaults:
|
|
9474
9620
|
openrouter/deepseek/deepseek-v4.1-flash at its
|
|
9475
|
-
per-model effort over the platform's default check rubric (
|
|
9621
|
+
per-model effort over the platform's default check rubric (thirteen
|
|
9476
9622
|
criteria), on the platform's analysis default provider.
|
|
9477
9623
|
|
|
9478
9624
|
THE RESPONSE IS THE ACCEPTED CHECK (202): one ``results`` entry per
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "evolvingmachines-evolve"
|
|
7
|
-
version = "0.0.
|
|
7
|
+
version = "0.0.65.dev1527"
|
|
8
8
|
description = "Pythonic SDK for multi-agent orchestration in E2B sandboxes"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/bridge/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/browser_profiles.py
RENAMED
|
File without changes
|
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/integrations.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/managed_secrets.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/pipeline/types.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/prompts/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/sandbox_view.py
RENAMED
|
File without changes
|
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/sessions_client.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/storage_client.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/__init__.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/results.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/swarm.py
RENAMED
|
File without changes
|
{evolvingmachines_evolve-0.0.64 → evolvingmachines_evolve-0.0.65.dev1527}/evolve/swarm/types.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|