evolve-sdk 0.0.55.dev1170__tar.gz → 0.0.55.dev1181__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.
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/PKG-INFO +1 -1
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/bridge/dist/bridge.bundle.cjs +1 -1
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/__init__.py +1 -1
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/hosted.py +19 -7
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve_sdk.egg-info/PKG-INFO +1 -1
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/pyproject.toml +1 -1
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/LICENSE +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/MANIFEST.in +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/README.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/bridge/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/_http.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/agent.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/bridge.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/browser_credentials.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/browser_profiles.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/config.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/integrations.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/managed_secrets.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/pipeline/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/pipeline/pipeline.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/pipeline/types.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/agent_md/judge.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/agent_md/reduce.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/agent_md/verify.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/user/judge.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/user/retry_feedback.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/user/verify.md +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/py.typed +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/results.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/retry.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/schema.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/sessions_client.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/storage_client.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/swarm/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/swarm/results.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/swarm/swarm.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/swarm/types.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/utils.py +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve_sdk.egg-info/SOURCES.txt +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve_sdk.egg-info/dependency_links.txt +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve_sdk.egg-info/requires.txt +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve_sdk.egg-info/top_level.txt +0 -0
- {evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/setup.cfg +0 -0
|
@@ -911,7 +911,7 @@ PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy
|
|
|
911
911
|
`);f=T.pop()??"";for(let k of T){if(!k.trim())continue;let O=h(k);if(this.captureDroidSession(k,O),this.sessionLogger?.writeEventParsed(k,O),t?.onStdout?.(k+`
|
|
912
912
|
`),O&&t?.onContent)for(let R of O)t.onContent(R)}},y=x=>{t?.onStderr?.(x)},b=await c.commands.spawn(l,{cwd:this.workingDir,timeoutMs:r,envs:d,onStdout:g,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(x){throw this.interruptedOperations.delete(v),this.finalizeOperation(v,t,"run_failed","error"),x}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 x=h(f);if(this.captureDroidSession(f,x),this.sessionLogger?.writeEventParsed(f,x),t?.onStdout?.(f+`
|
|
913
913
|
`),x&&t?.onContent)for(let T of x)t.onContent(T)}await this.writeDroidSessionState(c),this.sessionLogger&&!a&&await this.flushSessionLoggerWithTimeout();let w;if(this.storage&&!a&&S.exitCode===0)try{w=await aXe(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:i,parentId:this.lastCheckpointId}),this.lastCheckpointId=w.id}catch(x){console.warn(`[Evolve] Auto-checkpoint failed: ${x.message}`)}return{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:u,exitCode: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=g=>{s+=g,n?.onStdout?.(g)},l=g=>{o+=g,n?.onStderr?.(g)},u=this.credentialsSealed?{}:this.buildProviderRuntimeProcessEnvs(),d=await i.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,envs:Object.keys(u).length>0?u:void 0,onStdout:c,onStderr:l}),f=this.beginOperation("command",d,n,"command_start");if(a)return this.watchBackgroundOperation(f,"command",d,n),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${d.processId}`,stderr:""};let h;try{h=await d.wait()}catch(g){throw this.interruptedOperations.delete(f),this.finalizeOperation(f,n,"command_failed","error"),g}return this.interruptedOperations.delete(f)||h.exitCode===130?this.finalizeOperation(f,n,"command_interrupted","interrupted"):h.exitCode===0?this.finalizeOperation(f,n,"command_complete","idle"):this.finalizeOperation(f,n,"command_failed","error"),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:h.exitCode,stdout:s||h.stdout||"",stderr:o||h.stderr||""}}async sealCredentials(){if(!this.credentialsSealed){if(!this.sandbox)throw new Error("No active sandbox. Call run() or executeCommand() first.");if(this.activeCommand)throw new Error("Cannot seal credentials while a process is running.");if(this.agentConfig.isDirectMode&&!this.agentConfig.externalGateway)throw new Error("Credential sealing requires gateway mode; direct provider credentials cannot be revoked by Evolve");if([this.options.secrets&&Object.keys(this.options.secrets).length>0,this.options.sandboxCreateOptions?.envs&&Object.keys(this.options.sandboxCreateOptions.envs).length>0,this.options.managedSecrets,this.options.integrations,this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0,this.options.managedBrowser,this.options.browserCredentials].some(Boolean))throw new Error("Credential sealing requires a credential-minimal sandbox: omit secrets, managed secrets, integrations, MCP servers, and browser credentials");if(this.agentConfig.externalGateway){await this.agentConfig.externalGateway.revoke(),this.credentialsSealed=!0;return}if(!this.providerRuntimeToken||!this.options.providerRouting)throw new Error("Cannot seal credentials: no active provider runtime token to revoke. Without a gateway-issued runtime token the sandbox may hold credentials Evolve cannot revoke, so sealing would be a false guarantee.");await this.closeProviderRuntimeToken(!0),this.credentialsSealed=!0}}isSealed(){return this.credentialsSealed}async collectArtifacts(e){if(!this.credentialsSealed)throw new Error("Call sealCredentials() before collecting artifacts.");if(!this.sandbox)throw new Error("No active sandbox.");if(this.activeCommand)throw new Error("Cannot collect artifacts while a process is running.");return l9t(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(`
|
|
914
|
-
`).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[h,g]=f.split("|");if(!h||!g)continue;let y=parseInt(g,10);i>0&&y<i||s.push(h)}let c={},l=await Promise.all(s.map(async f=>{try{let h=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:h}}catch{return null}}));for(let f of l)f&&(c[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return{files:c,data:null};let u=c["result.json"];if(!u)return{files:c,data:null,error:"Schema provided but agent did not create output/result.json"};let d=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(d);if(this.zodSchema){let h=this.zodSchema.safeParse(f);return h.success?{files:c,data:h.data}:{files:c,data:null,error:`Schema validation failed: ${h.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let h=this.compiledValidator.errors?.map(g=>`${g.instancePath} ${g.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${h}`,rawData:d}}}return{files:c,data:null}}catch(f){return{files:c,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:d}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let t=await aXe(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=bXe(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 m9t(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function g9t(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 y9t(e){return await e.text().catch(()=>"")}async function wXe(e,t,n={}){let r=await fetch(`${m9t(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${g9t(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 y9t(r)}`);return r.status===204?{}:await r.json()}var v9t=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 wXe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await wXe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function b9t(e={}){return new v9t(e)}var Tv=class extends xXe.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&&(VXe(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&&(gB(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=Sjt;static browserCredentials=Zjt;static browserProfiles=b9t;static managedSecrets=PB;async initializeAgent(){let e=ZKe(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=OQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!CZ(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 FZ(e.apiKey):await LYt()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=$jt(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=gQ(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"?ijt:ajt,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?YXe(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 h9t(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=ZKe(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 dXe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return dXe(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)}},S9t=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"),IXe=class hZe 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 hZe;return n.push(...t),n}},gOn=class fB{config;semaphore;constructor(t={}){let n=t.concurrency??yQ;if(n>kB)throw new Error(`concurrency=${n} exceeds max ${kB}. 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 S9t(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 IXe.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(h=>this.executeFilterItem(d,r,f,o,t,c,h),s,f):this.executeFilterItem(d,r,f,o,t,c))),u=[];for(let d of l)if(d.status==="error")u.push(d);else if(d.data!==null)try{a(d.data)?u.push(d):u.push({...d,status:"filtered"})}catch(f){u.push({...d,status:"error",data:null,error:`Condition function threw: ${f.message}`})}return IXe.from(u)}async reduce(t){let{items:n,prompt:r,verify:a}=t,i=t.retry??this.config.retry,s=this.generateOperationId(),o=t.timeoutMs??this.config.timeoutMs,c=[],l=[];n.forEach((x,T)=>{c.push(this.getFiles(x)),l.push(this.getIndex(x,T))});let u={};c.forEach((x,T)=>{Object.entries(x).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=SZ(u),f=Iv(ujt,{fileTree:d}),h=t.systemPrompt?`${f}
|
|
914
|
+
`).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[h,g]=f.split("|");if(!h||!g)continue;let y=parseInt(g,10);i>0&&y<i||s.push(h)}let c={},l=await Promise.all(s.map(async f=>{try{let h=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:h}}catch{return null}}));for(let f of l)f&&(c[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return{files:c,data:null};let u=c["result.json"];if(!u)return{files:c,data:null,error:"Schema provided but agent did not create output/result.json"};let d=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(d);if(this.zodSchema){let h=this.zodSchema.safeParse(f);return h.success?{files:c,data:h.data}:{files:c,data:null,error:`Schema validation failed: ${h.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let h=this.compiledValidator.errors?.map(g=>`${g.instancePath} ${g.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${h}`,rawData:d}}}return{files:c,data:null}}catch(f){return{files:c,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:d}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let t=await aXe(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=bXe(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 m9t(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function g9t(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 y9t(e){return await e.text().catch(()=>"")}async function wXe(e,t,n={}){let r=await fetch(`${m9t(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${g9t(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 y9t(r)}`);return r.status===204?{}:await r.json()}var v9t=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 wXe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await wXe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function b9t(e={}){return new v9t(e)}var Tv=class extends xXe.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&&(VXe(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&&(gB(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=Sjt;static browserCredentials=Zjt;static browserProfiles=b9t;static managedSecrets=PB;async initializeAgent(){let e=ZKe(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=OQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!CZ(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 FZ(e.apiKey):await LYt()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=$jt(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=gQ(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"?ijt:ajt,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?YXe(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 h9t(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=ZKe(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 dXe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return dXe(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)}},S9t=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"),IXe=class hZe 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 hZe;return n.push(...t),n}},SOn=class fB{config;semaphore;constructor(t={}){let n=t.concurrency??yQ;if(n>kB)throw new Error(`concurrency=${n} exceeds max ${kB}. 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 S9t(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 IXe.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(h=>this.executeFilterItem(d,r,f,o,t,c,h),s,f):this.executeFilterItem(d,r,f,o,t,c))),u=[];for(let d of l)if(d.status==="error")u.push(d);else if(d.data!==null)try{a(d.data)?u.push(d):u.push({...d,status:"filtered"})}catch(f){u.push({...d,status:"error",data:null,error:`Condition function threw: ${f.message}`})}return IXe.from(u)}async reduce(t){let{items:n,prompt:r,verify:a}=t,i=t.retry??this.config.retry,s=this.generateOperationId(),o=t.timeoutMs??this.config.timeoutMs,c=[],l=[];n.forEach((x,T)=>{c.push(this.getFiles(x)),l.push(this.getIndex(x,T))});let u={};c.forEach((x,T)=>{Object.entries(x).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=SZ(u),f=Iv(ujt,{fileTree:d}),h=t.systemPrompt?`${f}
|
|
915
915
|
|
|
916
916
|
${t.systemPrompt}`:f,g=(x,T,k)=>({operationId:s,operation:"reduce",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:t.name,inputCount:n.length,inputIndices:l,errorRetry:T,verifyRetry:k,...this.pipelineContextToMeta(t._pipelineContext)}),y=t.mcpServers??this.config.mcpServers,b=t.skills??this.config.skills,v=t.integrations??this.config.integrations,S=async(x,T,k,O)=>{let R=await this.semaphore.use(()=>this.execute(u,x,{systemPrompt:h,schema:t.schema,schemaOptions:t.schemaOptions,agent:t.agent,mcpServers: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)}})),F=g(R,k,O&&O>1?O-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:F,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:F}},w=`${this.config.tag}-reduce`;return a?this.runWithVerification((x,T,k)=>S(x,T,void 0,k),{originalPrompt:r,inputFiles:u,verifyConfig:a,timeoutMs:o,systemPrompt:h,schema:t.schema,mcpServers:y,skills:b,integrations:v,operationId:s,baseTag:w,retry:i,operation:"reduce",_pipelineContext:t._pipelineContext}):i?Mp(x=>{let T=x>1?x-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,h=a.judgeSkills??a.skills??this.config.skills,g=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:g,timeoutMs:c,attempt:R}),i,k):await this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:k,operationId:o,config:a,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:u,skills:f,integrations:g,timeoutMs:c});return a.onCandidateComplete?.(0,k,O.status==="success"?"success":"error"),O})),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:h,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:h,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 x={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:x,candidates:b}}async execute(t,n,r){let a=null,i="",s=r.tagPrefix,o={},c=null,l,u,d={...this.config.agent,...r.agent};try{a=new 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 h=null;try{h=await a.getOutputFiles(!0),o=h.files}catch{}f.exitCode!==0?l=`Agent exited with code ${f.exitCode}`:r.schema?h?(c=h.data,h.error&&(l=h.error),h.rawData&&(u=h.rawData)):l="Failed to read output files from sandbox":c=o}catch(f){if(l=f.message,a){s=a.getSessionTag()??r.tagPrefix;try{o=(await a.getOutputFiles(!0)).files}catch{}}}finally{a&&await a.kill().catch(()=>{})}return{files:o,data:c,tag:s,sandboxId:i,error:l,rawData:u}}async executeMapItem(t,n,r,a,i,s,o=1){let c=this.getFiles(t),l=o>1?`${this.config.tag}-map-${r}-er${o-1}`:`${this.config.tag}-map-${r}`,u=this.evaluatePrompt(n,c,r);if(u instanceof Error)return this.buildErrorResult(`Prompt function threw: ${u.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,h=i.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(c,u,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:h,tagPrefix:l,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:r,role:"worker",errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),y={operationId:a,operation:"map",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(g,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,h=i.integrations??this.config.integrations,g=this.evaluatePrompt(n,c,r);if(g instanceof Error)return this.buildErrorResult(`Prompt function threw: ${g.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let 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:h,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)}})),x={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,x)};return this.runWithVerification(y,{originalPrompt:g,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:h,operationId:a,baseTag:l,retry:o,itemIndex:r,operation:"map",_pipelineContext:i._pipelineContext})}async executeMapItemWithBestOf(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-map-${r}`,u=this.evaluatePrompt(n,c,r);if(u instanceof Error)return this.buildErrorResult(`Prompt function threw: ${u.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let d=i.bestOf,f=d.n??d.taskAgents?.length;if(f===void 0||f<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let h=i.mcpServers??this.config.mcpServers,g=d.mcpServers??h,y=d.judgeMcpServers??d.mcpServers??h,b=i.skills??this.config.skills,v=d.skills??b,S=d.judgeSkills??d.skills??b,w=i.integrations??this.config.integrations,x=d.integrations??w,T=d.judgeIntegrations??d.integrations??w,k=await Promise.all(Array.from({length:f},async(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:g,skills:v,integrations:x,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:g,skills:v,integrations:x,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"),F=O.decision?.winner??(R>=0?R:0),V=k[F]??k[0];d.onJudgeComplete?.(r,F,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:F,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,h=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:u,skills:d,integrations:f,tagPrefix:l,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:r,role:"worker",errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),g={operationId:a,operation:"filter",tag:h.tag,sandboxId:h.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(h,g,c)}async executeFilterItemWithVerify(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-filter-${r}`,u=i.verify,d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,h=i.integrations??this.config.integrations,g=async(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:h,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(g,{originalPrompt:n,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:h,operationId:a,baseTag:l,retry:o,itemIndex:r,operation:"filter",_pipelineContext:i._pipelineContext})}async executeBestOfCandidate(t){let{inputFiles:n,prompt:r,candidateIndex:a,operationId:i,config:s,timeoutMs:o,parentIndex:c,attempt:l=1,_pipelineContext:u}=t,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,f=l>1?`${d}-er${l-1}`:d,h=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,agent:s.taskAgents?.[a],mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations,tagPrefix:f,timeoutMs:o,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:c,role:"candidate",candidateIndex:a,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(u)}})),g={operationId:i,operation:"bestof-cand",tag:h.tag,sandboxId:h.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:l>1?l-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(u)};return this.buildResult(h,g)}buildJudgeContext(t){let n=this.buildEvaluatorContext({inputFiles:t.inputFiles,taskPrompt:t.taskPrompt,systemPrompt:t.systemPrompt,schema:t.schema});return t.candidates.forEach((r,a)=>{r.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
|
|
917
917
|
|
|
@@ -2899,8 +2899,9 @@ class JobImportSkippedTrial:
|
|
|
2899
2899
|
"""One trial a job import LEFT OUT, typed (spec ``JobImportSkippedTrial``):
|
|
2900
2900
|
the failure-envelope grammar plus the trial directory it names.
|
|
2901
2901
|
``trial_too_large`` is the one cause — the named ``details['file']`` is
|
|
2902
|
-
over the per-file cap, or ``agent
|
|
2903
|
-
session-tree cap (``limits['uploads']`` on
|
|
2902
|
+
over the per-file cap, or the ``agent/`` subtrees (``file`` spelled
|
|
2903
|
+
``agent/``) total over the session-tree cap (``limits['uploads']`` on
|
|
2904
|
+
the capability document), or
|
|
2904
2905
|
``agent/trajectory.json`` would cost more heap to parse than the
|
|
2905
2906
|
per-trial bound (its structure counted from the bytes, never parsed);
|
|
2906
2907
|
``details`` carry the ``bytes`` measured and the ``max_bytes`` bound.
|
|
@@ -7294,8 +7295,13 @@ class JobsClient:
|
|
|
7294
7295
|
``job.log``, and per trial its ``config.json``, ``lock.json``,
|
|
7295
7296
|
``result.json`` (``step_results`` on multi-step trials),
|
|
7296
7297
|
``trial.log``, ``agent/trajectory.json`` (the normalized ATIF
|
|
7297
|
-
trajectory),
|
|
7298
|
-
``
|
|
7298
|
+
trajectory), the harness stdout stream at Harbor's tee name for the
|
|
7299
|
+
harness (``agent/claude-code.txt``, ``agent/codex.txt``, ...),
|
|
7300
|
+
``agent/stderr.log``, ``agent/trace-parsed.jsonl``, the agent home
|
|
7301
|
+
at Harbor's session slot for the harness (``agent/sessions/``,
|
|
7302
|
+
``agent/qwen-sessions/``, ``agent/.kimi-code/``, ``agent/opencode/``)
|
|
7303
|
+
with the rest under ``agent/evolve-home/``, ``verifier/test-stdout.txt``,
|
|
7304
|
+
``verifier/reward.json``, the raw
|
|
7299
7305
|
``verifier/reward.txt`` (only when the grader wrote one),
|
|
7300
7306
|
``steps/<name>/verifier/reward.json`` (multi-step trials only),
|
|
7301
7307
|
``exception.txt``, and ``artifacts/`` with its always-present
|
|
@@ -7748,9 +7754,15 @@ class TrialsClient:
|
|
|
7748
7754
|
artifact — the harness's own native session file, reserved ahead of
|
|
7749
7755
|
its server wave; the server answers not-found for it until that wave
|
|
7750
7756
|
lands, and the refusal surfaces as the API error it is;
|
|
7751
|
-
``"agent-home"`` (the CLI's
|
|
7752
|
-
transcripts included by construction
|
|
7753
|
-
text
|
|
7757
|
+
``"agent-home"`` (the utf8 TEXT VIEW of the CLI's captured home,
|
|
7758
|
+
subagent transcripts included by construction; a file that is not
|
|
7759
|
+
UTF-8 text is left out and named in the capture record that rides
|
|
7760
|
+
the same dict as ``"/agent-home.json"``) answers a dict of sandbox
|
|
7761
|
+
path to text — a home over the server's whole-read ceiling raises the
|
|
7762
|
+
``EvolveAPIError`` of its 413 ``invalid_input`` (param ``format``);
|
|
7763
|
+
this SDK has no bytes door for the home, the job archive
|
|
7764
|
+
(``jobs.download()``) carries it whole. None = never stored (normal
|
|
7765
|
+
answer, not an error): a
|
|
7754
7766
|
QUEUED/CANCELLED trial, a harness that wrote nothing, or a purged
|
|
7755
7767
|
trace. ``"trace-parsed"`` is in the vocabulary but is not
|
|
7756
7768
|
a raw artifact — the parsed event trace rides ``trace()`` /
|
|
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
|
|
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
|
{evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve/prompts/user/retry_feedback.md
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolve_sdk-0.0.55.dev1170 → evolve_sdk-0.0.55.dev1181}/evolve_sdk.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|