@evolvingmachines/sdk 0.0.25 → 0.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +6 -6
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -19,7 +19,7 @@ ${d}
|
|
|
19
19
|
\`\`\``:d}});else if(Array.isArray(d)){for(let f of d)if(f.type==="text"){let g=f.text;m.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
20
20
|
${g}
|
|
21
21
|
\`\`\``:g}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:m}}function a(l,o){let u=bn[l]||"other",d=[],m=[],f=l;switch(l){case "Read":case "read_file":f=`Read ${o.file_path||o.absolute_path||"file"}`,(o.file_path||o.absolute_path)&&m.push({path:o.file_path||o.absolute_path});break;case "Write":case "write_file":f=`Write ${o.file_path||"file"}`,o.file_path&&(m.push({path:o.file_path}),d.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":f=`Edit ${o.file_path||"file"}`,o.file_path&&m.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":f=o.command?`\`${o.command}\``:"Run command",o.description&&d.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":f=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=o.query?`"${o.query}"`:"Web search";break;case "Glob":f=`Find ${o.pattern||"files"}`,o.path&&m.push({path:o.path});break;case "Grep":f=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${o.path||"directory"}`,o.path&&m.push({path:o.path});break;case "Task":f=o.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=l;}return {title:f,kind:u,content:d,locations:m}}}function nt(t){return le()(t)}function M(t){switch(t){case "claude":return re();case "codex":return ae();case "gemini":return ce();case "qwen":return le();case "kimi":return Ae();case "opencode":return $e();default:return ()=>null}}function xn(t,e){let n=e.trim();return n?M(t)(n):null}function wn(t,e){let n=[],i=e.split(`
|
|
22
|
-
`),c=M(t);for(let s of i){let r=s.trim();if(!r)continue;let p=c(r);p&&n.push(...p);}return n}function z(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function ot(){return `${z()}`}function it(){return `${z()}/e2b`}function st(t){return {"browser-use":{type:"http",url:`${z()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var A="EVOLVE_API_KEY",pe="E2B_API_KEY",ue="DAYTONA_API_KEY",de="MODAL_TOKEN_ID",De="MODAL_TOKEN_SECRET",rt="claude",J=36e5,at=4,Ue=100,ct="/home/user/workspace",O=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",lt=".evolve-sdk/observability/sessions",pt=100,ut=5e3,me=3,Fe=1e3;function E(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function
|
|
22
|
+
`),c=M(t);for(let s of i){let r=s.trim();if(!r)continue;let p=c(r);p&&n.push(...p);}return n}function z(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function ot(){return `${z()}`}function it(){return `${z()}/e2b`}function st(t){return {"browser-use":{type:"http",url:`${z()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var A="EVOLVE_API_KEY",pe="E2B_API_KEY",ue="DAYTONA_API_KEY",de="MODAL_TOKEN_ID",De="MODAL_TOKEN_SECRET",rt="claude",J=36e5,at=4,Ue=100,ct="/home/user/workspace",O=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",lt=".evolve-sdk/observability/sessions",pt=100,ut=5e3,me=3,Fe=1e3;function E(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function B(t){return JSON.stringify(kn__default.default(t,{target:"jsonSchema7"}),null,2)}function j(t){return JSON.stringify(t,null,2)}function dt(t,e=false){let n={};function i(c,s){for(let r of R__namespace.readdirSync(c)){let p=G__namespace.join(c,r),a=s?`${s}/${r}`:r;R__namespace.statSync(p).isDirectory()?e&&i(p,a):n[a]=R__namespace.readFileSync(p);}}return i(t,""),n}function mt(t,e){for(let[n,i]of Object.entries(e)){let c=G__namespace.join(t,n),s=G__namespace.dirname(c);R__namespace.mkdirSync(s,{recursive:true});let r;i instanceof ArrayBuffer||i instanceof Uint8Array?r=Buffer.from(i):r=i,R__namespace.writeFileSync(c,r);}}function Cn(t){let e=t.replace(/^~/,process.env.HOME||"");if(!R__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return R__namespace.readFileSync(e,"utf-8")}function Le(t){let e=t?.type??rt,n=P(e);if(t?.oauthToken){if(e!=="claude")throw new Error(`oauthToken is only supported for claude agent (Claude Max subscription), not ${e}. Use providerApiKey for ${e} instead.`);return {type:e,apiKey:t.oauthToken,isDirectMode:true,isOAuth:true,model:t.model,reasoningEffort:t.reasoningEffort,betas:t.betas}}if(t?.providerApiKey){let r=t.providerBaseUrl??process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:r,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort,betas:t.betas}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort,betas:t.betas};let i=process.env[A];if(i)return {type:e,apiKey:i,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas};if(n.providerEnvMap){let p=(t?.model??n.defaultModel)?.split("/")[0],a=p?n.providerEnvMap[p]:void 0,l=a?process.env[a.keyEnv]:void 0;if(l){let o=process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:l,baseUrl:o,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}}let c=process.env[n.apiKeyEnv];if(c){let r=process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:c,baseUrl:r,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}if(n.oauthEnv){let r=process.env[n.oauthEnv];if(r){if(n.oauthFileName){let p=Cn(r);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:p,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}return {type:e,apiKey:r,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}}let s=n.oauthEnv?n.oauthFileName?`, or ${n.oauthEnv}`:`, oauthToken, or ${n.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${s}, or ${A} / ${n.apiKeyEnv} env var.`)}async function Ne(){let t=process.env[pe];if(t)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return s({apiKey:t})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${pe} is set but @evolvingmachines/e2b failed to load.
|
|
23
23
|
Try reinstalling: npm install @evolvingmachines/sdk`):r}let e=process.env[ue];if(e)try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return s({apiKey:e})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${ue} is set but @evolvingmachines/daytona failed to load.
|
|
24
24
|
Try installing: npm install @evolvingmachines/daytona`):r}let n=process.env[de],i=process.env[De];if(n&&i)try{let{createModalProvider:s}=await import('@evolvingmachines/modal');return s({tokenId:n,tokenSecret:i})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${de} is set but @evolvingmachines/modal failed to load.
|
|
25
25
|
Try installing: npm install @evolvingmachines/modal`):r}let c=process.env[A];if(c)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=it(),s({apiKey:c})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${A} is set but @evolvingmachines/e2b failed to load.
|
|
@@ -194,10 +194,10 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
194
194
|
{{feedback}}
|
|
195
195
|
|
|
196
196
|
Make sure your output addresses all the feedback points above.
|
|
197
|
-
`;var St=ft,_t=gt,Tt=ht,Et=yt,
|
|
197
|
+
`;var St=ft,_t=gt,Tt=ht,Et=yt,Be=vt,Rt=wt,je=bt,Pt=kt,Ot=xt,Ke=Ct;function I(t,e){let n=t;for(let[i,c]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${i}\\}\\}`,"g"),c);return n}function Ve(t){let e=t.mode==="swe"?_t:St,n=I(e,{workingDir:t.workingDir}).trim();if(t.systemPrompt&&(n+=`
|
|
198
198
|
|
|
199
199
|
|
|
200
|
-
${I(Tt,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let i=E(t.schema)?
|
|
200
|
+
${I(Tt,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let i=E(t.schema)?B(t.schema):j(t.schema);n+=`
|
|
201
201
|
|
|
202
202
|
|
|
203
203
|
${I(Et,{schema:i}).trim()}`;}return n}function ge(t){let e=[...new Set(Object.keys(t).map(a=>a.split("/")[0]))].sort((a,l)=>a==="worker_task"?-1:l==="worker_task"?1:a.localeCompare(l));if(!e.length)return `context/
|
|
@@ -206,8 +206,8 @@ ${I(Et,{schema:i}).trim()}`;}return n}function ge(t){let e=[...new Set(Object.ke
|
|
|
206
206
|
`)?e:e+`
|
|
207
207
|
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let n=JSON.stringify(e)+`
|
|
208
208
|
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&(this.eventBuffer.push(e),this.scheduleFlush());}writeMeta(){let e={_meta:{tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandbox_id:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability)}},n=JSON.stringify(e)+`
|
|
209
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=pt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},ut));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let i=1;i<=me;i++)try{let c=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(c.ok)return;if(c.status===429||c.status===401||c.status>=500){if(i===me){console.debug(`[SessionLogger] Dashboard ${c.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Fe*i);continue}console.debug(`[SessionLogger] Dashboard ${c.status}, dropping events`);return}catch(c){i===me?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",c),this.requeueEvents(e)):await this.delay(Fe*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!O.startsWith("https://")&&!O.includes("localhost")&&!O.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var he="COMPOSIO_API_KEY";function At(t){return new core.Composio({apiKey:process.env[he]})}function We(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function ye(t,e,n){We(t);let i=At(),c={};return e?.toolkits&&(c.toolkits=e.toolkits),e?.tools&&(c.tools=e.tools),e?.authConfigs&&(c.authConfigs=e.authConfigs),e?.connectedAccounts&&(c.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(c.manageConnections=e.manageConnections),await i.create(t,Object.keys(c).length>0?c:void 0)}async function $t(t,e,n,i){We(t);let c=At(),p=(await c.toolkits.get(e)).authConfigDetails?.find(a=>a.mode==="API_KEY");if(!p)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await c.connectedAccounts.initiate(t,p.name,{config:core.AuthScheme.APIKey({api_key:n})});}async function ze(t,e){if(We(t),e?.keys)for(let[i,c]of Object.entries(e.keys))try{await $t(t,i,c);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let n=await ye(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function Dt(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function Vn(){return new core.Composio({apiKey:process.env[he]})}async function Ut(t,e){Dt(t);let i=await(await ye(t,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function Ft(t,e){let n=await Je(t),i={};for(let c of n)i[c.toolkit]=c.connected;return e?i[e]??false:i}async function Je(t){return Dt(t),(await Vn().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var Ge={auth:Ut,status:Ft,connections:Je};var Lt=Symbol.for("evolve:awsSdkCache"),Nt=Symbol.for("evolve:s3ClientCache");var Wn=3600,zn=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Jn(t){if(t.startsWith("s3://")){let c=t.slice(5),s=c.indexOf("/");return s===-1?{bucket:c,prefix:""}:{bucket:c.slice(0,s),prefix:c.slice(s+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,i=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:i.join("/")};if(i.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:i[0],prefix:i.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function be(t,e,n,i){if(!t?.url&&!t?.bucket){if(!e)throw new Error("Storage requires either a URL (BYOK mode) or gateway API key. Use .withStorage({ url: 's3://bucket/prefix' }) or configure EVOLVE_API_KEY for gateway mode.");return {bucket:"",prefix:"",region:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:i}}let c=t?.bucket||"",s=t?.prefix||"",r=t?.endpoint;if(t?.url){let p=Jn(t.url);c=c||p.bucket,s=s||p.prefix,r=r||p.endpoint;}if(!c)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:c,prefix:s,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:r,credentials:t?.credentials,mode:"byok"}}function
|
|
210
|
-
`).pop()?.trim();if(!a||a.length!==64)throw new Error(`Invalid checkpoint hash: ${a}`);let l=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(l.stdout.trim(),10),u=Number.isNaN(o)?void 0:o,d;try{if(e.mode==="byok"){let m=Wt(e,a);if(!await
|
|
209
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await promises.appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=pt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},ut));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let i=1;i<=me;i++)try{let c=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(c.ok)return;if(c.status===429||c.status===401||c.status>=500){if(i===me){console.debug(`[SessionLogger] Dashboard ${c.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Fe*i);continue}console.debug(`[SessionLogger] Dashboard ${c.status}, dropping events`);return}catch(c){i===me?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",c),this.requeueEvents(e)):await this.delay(Fe*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!O.startsWith("https://")&&!O.includes("localhost")&&!O.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var he="COMPOSIO_API_KEY";function At(t){return new core.Composio({apiKey:process.env[he]})}function We(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function ye(t,e,n){We(t);let i=At(),c={};return e?.toolkits&&(c.toolkits=e.toolkits),e?.tools&&(c.tools=e.tools),e?.authConfigs&&(c.authConfigs=e.authConfigs),e?.connectedAccounts&&(c.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(c.manageConnections=e.manageConnections),await i.create(t,Object.keys(c).length>0?c:void 0)}async function $t(t,e,n,i){We(t);let c=At(),p=(await c.toolkits.get(e)).authConfigDetails?.find(a=>a.mode==="API_KEY");if(!p)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await c.connectedAccounts.initiate(t,p.name,{config:core.AuthScheme.APIKey({api_key:n})});}async function ze(t,e){if(We(t),e?.keys)for(let[i,c]of Object.entries(e.keys))try{await $t(t,i,c);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let n=await ye(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function Dt(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function Vn(){return new core.Composio({apiKey:process.env[he]})}async function Ut(t,e){Dt(t);let i=await(await ye(t,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function Ft(t,e){let n=await Je(t),i={};for(let c of n)i[c.toolkit]=c.connected;return e?i[e]??false:i}async function Je(t){return Dt(t),(await Vn().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var Ge={auth:Ut,status:Ft,connections:Je};var Lt=Symbol.for("evolve:awsSdkCache"),Nt=Symbol.for("evolve:s3ClientCache");var Wn=3600,zn=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Jn(t){if(t.startsWith("s3://")){let c=t.slice(5),s=c.indexOf("/");return s===-1?{bucket:c,prefix:""}:{bucket:c.slice(0,s),prefix:c.slice(s+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,i=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:i.join("/")};if(i.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:i[0],prefix:i.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function be(t,e,n,i){if(!t?.url&&!t?.bucket){if(!e)throw new Error("Storage requires either a URL (BYOK mode) or gateway API key. Use .withStorage({ url: 's3://bucket/prefix' }) or configure EVOLVE_API_KEY for gateway mode.");return {bucket:"",prefix:"",region:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:i}}let c=t?.bucket||"",s=t?.prefix||"",r=t?.endpoint;if(t?.url){let p=Jn(t.url);c=c||p.bucket,s=s||p.prefix,r=r||p.endpoint;}if(!c)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:c,prefix:s,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:r,credentials:t?.credentials,mode:"byok"}}function Bt(t){if(t.includes(".."))throw new Error(`settingsDir must not contain '..': ${t}`);let e;if(t.startsWith("~/"))e=t.slice(2);else if(t.startsWith("/home/user/"))e=t.slice(11);else if(t.startsWith("."))e=t;else throw new Error(`Unexpected settingsDir: ${t}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${t}`);return e}function Gn(t){if(t.includes(".."))throw new Error(`workingDir must not contain '..': ${t}`);if(!t.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${t}. Must start with /home/user/.`);let e=t.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${t}`);return e}function ve(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Yn(t,e){let n=P(t),i=Gn(e),c=n.checkpointDirs?.length?n.checkpointDirs.map(p=>Bt(p)):[Bt(n.mcpConfig.settingsDir)],s=[...zn.map(p=>`--exclude=${ve(p)}`),`--exclude=${ve(i+"/temp")}`].join(" "),r=[ve(i+"/"),...c.map(p=>ve(p+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${s} ${r}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function K(){let t=globalThis[Lt];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[i,c]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[Lt]={s3:i,presigner:c},{s3:i,presigner:c}}catch{throw new Error("Storage requires @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner. Install: npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner")}}async function H(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,i=globalThis[Nt];if(i?.key===n)return i.client;let{s3:c}=await K(),s=new c.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Nt]={client:s,key:n},s}async function Kt(t,e,n){let{s3:i,presigner:c}=await K(),s=await H(t),r=n==="put"?new i.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new i.GetObjectCommand({Bucket:t.bucket,Key:e});return c.getSignedUrl(s,r,{expiresIn:Wn})}async function jt(t,e){let{s3:n}=await K(),i=await H(t);try{return await i.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(c){let s=c?.name||c?.message||"";if(c?.$metadata?.httpStatusCode===404||s==="NotFound"||s==="NoSuchKey")return false;throw c}}async function Vt(t,e){let{s3:n}=await K(),s=await(await(await H(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!s)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(s)}async function Hn(t,e,n){let{s3:i}=await K();await(await H(t)).send(new i.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Wt(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function zt(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function qn(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Jt(t,e,n,i){let c=await fetch(`${t.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:n,action:i})});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway presign failed (${c.status}): ${s}`)}return c.json()}async function Zn(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify(e)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${i}`)}return n.json()}async function Qn(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${e}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let i=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${i}`)}return n.json()}async function Ye(t,e,n,i,c){let s=new Date().toISOString(),r=Yn(n,i),p=await t.commands.run(r,{timeoutMs:12e4});if(p.exitCode!==0)throw new Error(`Checkpoint tar failed: ${p.stderr}`);let a=p.stdout.trim().split(`
|
|
210
|
+
`).pop()?.trim();if(!a||a.length!==64)throw new Error(`Invalid checkpoint hash: ${a}`);let l=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(l.stdout.trim(),10),u=Number.isNaN(o)?void 0:o,d;try{if(e.mode==="byok"){let m=Wt(e,a);if(!await jt(e,m)){let h=await Kt(e,m,"put"),b=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(b.exitCode!==0)throw new Error(`Checkpoint upload failed: ${b.stderr}`);if(!await jt(e,m))throw new Error("Checkpoint upload verification failed (HeadObject)")}d=qn();let g={id:d,hash:a,tag:c.tag,timestamp:s,sizeBytes:u,agentType:n,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment,sandboxId:t.sandboxId};await Hn(e,zt(e,d),g);}else {let m=await Jt(e,c.tag,a,"put");if(!m.alreadyExists){let g=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${m.url}"`,{timeoutMs:3e5});if(g.exitCode!==0)throw new Error(`Checkpoint upload failed: ${g.stderr}`)}d=(await Zn(e,{tag:c.tag,hash:a,sizeBytes:u??0,agentType:n,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:d,hash:a,tag:c.tag,timestamp:s,sizeBytes:u,agentType:n,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment}}async function Gt(t,e,n){let i,c,s={};if(e.mode==="byok"){let l=zt(e,n),o;try{o=await Vt(e,l);}catch(u){let d=u.name;throw d==="AccessDenied"||d==="InvalidAccessKeyId"||d==="SignatureDoesNotMatch"||d==="ExpiredToken"||d==="NetworkingError"||d==="TimeoutError"?u:new Error(`Checkpoint ${n} not found`)}i=o.hash,s={agentType:o.agentType,workspaceMode:o.workspaceMode},c=await Kt(e,Wt(e,i),"get");}else {let l=await Qn(e,n);i=l.hash,s={agentType:l.agentType,workspaceMode:l.workspaceMode},c=(await Jt(e,l.tag,i,"get")).url;}let r=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${c}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(r.exitCode!==0)throw new Error(`Checkpoint download failed: ${r.stderr}`);let p=r.stdout.trim().split(`
|
|
211
211
|
`).pop()?.trim();if(p!==i)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${i}, got ${p})`);let a=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${a.stderr}`);return s}function Xn(t){let e=process.env.EVOLVE_API_KEY,n=!t.url&&!t.bucket&&!!e;return be(t,n,O,e)}async function Yt(t,e){let{s3:n}=await K(),i=await H(t),s=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,r=[],p;do{let d={Bucket:t.bucket,Prefix:s,...p&&{ContinuationToken:p}},m=await i.send(new n.ListObjectsV2Command(d));if(m.Contents)for(let f of m.Contents)f.Key?.endsWith(".json")&&f.LastModified&&r.push({key:f.Key,lastModified:f.LastModified});p=m.IsTruncated?m.NextContinuationToken:void 0;}while(p);if(r.length===0)return [];r.sort((d,m)=>{let f=m.lastModified.getTime()-d.lastModified.getTime();return f!==0?f:m.key<d.key?-1:m.key>d.key?1:0});let l=!!e?.tag?r:e?.limit?r.slice(0,e.limit):r,u=(await Promise.all(l.map(async d=>{try{return await Vt(t,d.key)}catch{return null}}))).filter(d=>d!==null);return e?.tag&&(u=u.filter(d=>d.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function Ht(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let i=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,c=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${c.status}): ${s}`)}return c.json()}async function He(t,e){let n=Xn(t),i=e?.limit&&e.limit>0?Math.min(e.limit,500):100;return n.mode==="byok"?Yt(n,{limit:i,tag:e?.tag}):Ht(n,{limit:i,tag:e?.tag})}async function qt(t){return t.mode==="byok"?(await Yt(t,{limit:1}))[0]??null:(await Ht(t,{limit:1}))[0]??null}function to(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}var q=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||ct,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,this.storage=n.storage,n.schema)if(E(n.schema))this.zodSchema=n.schema,n.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=n.schema,this.schemaOptions=n.schemaOptions;try{let i=this.createAjvValidator();this.compiledValidator=i.compile(this.jsonSchema);}catch(i){throw new Error(`Invalid JSON Schema: ${i.message}`)}}this.registry=P(e.type);}emitLifecycle(e,n){e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,i,c){let s=++this.nextOperationId;return this.activeOperationId=s,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(i,c),s}finalizeOperation(e,n,i,c="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=c,this.emitLifecycle(n,i),true)}watchBackgroundOperation(e,n,i,c){let s=n==="run"?"run_background_complete":"command_background_complete",r=n==="run"?"run_background_failed":"command_background_failed",p=n==="run"?"run_interrupted":"command_interrupted";i.wait().then(a=>{if(this.interruptedOperations.delete(e)||a.exitCode===130){this.finalizeOperation(e,c,p,"interrupted");return}let o=a.exitCode===0?s:r,u=a.exitCode===0?"idle":"error";this.finalizeOperation(e,c,o,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,c,r,"error");});}createAjvValidator(){let n={...ke[this.schemaOptions?.mode||"loose"],...this.schemaOptions?.coerceTypes!==void 0&&{coerceTypes:this.schemaOptions.coerceTypes},...this.schemaOptions?.removeAdditional!==void 0&&{removeAdditional:this.schemaOptions.removeAdditional},...this.schemaOptions?.useDefaults!==void 0&&{useDefaults:this.schemaOptions.useDefaults},...this.schemaOptions?.allErrors!==void 0&&{allErrors:this.schemaOptions.allErrors}};return new eo__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, context, files, and systemPrompt"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {let i=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:i,workingDirectory:this.workingDir}),await this.setupAgentAuth(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(i){throw this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),i}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let n of Object.values(this.registry.providerEnvMap))e[n.keyEnv]=this.agentConfig.apiKey;else {let n=this.agentConfig.model?.split("/")[0],i=n?this.registry.providerEnvMap?.[n]:void 0,c=i?i.keyEnv:this.registry.apiKeyEnv,s=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:c;e[s]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=this.registry.usePassthroughGateway?ot():z();if(this.registry.gatewayConfigEnv){let i=this.agentConfig.model||this.registry.defaultModel;e[this.registry.gatewayConfigEnv]=JSON.stringify({provider:{litellm:{npm:"@ai-sdk/openai-compatible",options:{baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{[i]:{name:i}}}}});}else e[this.registry.baseUrlEnv]=n;e.EVOLVE_API_KEY=this.agentConfig.apiKey;}return this.options.secrets&&Object.assign(e,this.options.secrets),e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e,n){let i=this.options.workspaceMode||"knowledge",c=i==="swe"?`${this.workingDir}/repo ${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`:`${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`;if(await e.commands.run(`mkdir -p ${c}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let r=Ve({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:i}),p=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(p,r);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let s={...this.options.mcpServers};if(this.options.composio){let r=await ze(this.options.composio.userId,this.options.composio.config);s={...s,composio:{type:"http",url:r.url,headers:r.headers}};}Object.keys(s).length>0&&await Pe(this.agentConfig.type,e,this.workingDir,s),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:i,targetDir:c}=n;await e.files.makeDir(c);for(let s of this.skills){let r=`cp -r ${i}/${s} ${c}/ 2>/dev/null || true`;await e.commands.run(r,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let i=Object.entries(n).map(([s,r])=>({path:`${this.workingDir}/context/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,n){let i=Object.entries(n).map(([s,r])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:to(e),model:this.agentConfig.model||this.registry.defaultModel,isResume:this.hasRun,reasoningEffort:this.agentConfig.reasoningEffort,betas:this.agentConfig.betas,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,n){let{prompt:i,timeoutMs:c=J,background:s=false,checkpointComment:r}=e,{from:p}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(p&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(p==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let y=await qt(this.storage);if(!y)throw new Error('No checkpoints found for from: "latest".');p=y.id;}if(p){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let y=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:y,workingDirectory:this.workingDir});let v=await Gt(this.sandbox,this.storage,p);if(v.agentType&&v.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${v.agentType}, current: ${this.agentConfig.type})`);let w=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==w)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${w})`);await this.setupAgentAuth(this.sandbox);let k=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!k}),this.hasRun=!0,this.lastCheckpointId=p,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(v){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),v}}let a=await this.getSandbox(n);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let y=this.options.sandboxProvider;this.sessionLogger=new Y({provider:y?.name||y?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:a.sandboxId,tagPrefix:this.options.sessionTagPrefix,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(i);let l=this.buildCommand(i),o="",u=M(this.agentConfig.type),d=y=>{o+=y;let v=o.split(`
|
|
212
212
|
`);o=v.pop()??"";for(let w of v){if(!w.trim())continue;let k=u(w);if(this.sessionLogger?.writeEventParsed(w,k),n?.onStdout?.(w+`
|
|
213
213
|
`),k&&n?.onContent)for(let C of k)n.onContent(C);}},m=y=>{n?.onStderr?.(y);},f=await a.commands.spawn(l,{cwd:this.workingDir,timeoutMs:c,onStdout:d,onStderr:m}),g=this.beginOperation("run",f,n,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(g,"run",f,n),{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with ID ${f.processId}`,stderr:""};let h;try{h=await f.wait();}catch(y){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,n,"run_failed","error"),y}if(this.interruptedOperations.delete(g)||h.exitCode===130?this.finalizeOperation(g,n,"run_interrupted","interrupted"):h.exitCode===0?this.finalizeOperation(g,n,"run_complete","idle"):this.finalizeOperation(g,n,"run_failed","error"),o.trim()){let y=u(o);if(this.sessionLogger?.writeEventParsed(o,y),n?.onStdout?.(o+`
|
|
@@ -216,4 +216,4 @@ ${I(Et,{schema:i}).trim()}`;}return n}function ge(t){let e=[...new Set(Object.ke
|
|
|
216
216
|
|
|
217
217
|
${e.systemPrompt}`:d,f=(v,w,k)=>({operationId:r,operation:"reduce",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:l,errorRetry:w,verifyRetry:k,...this.pipelineContextToMeta(e._pipelineContext)}),g=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,b=e.composio??this.config.composio,x=async(v,w,k,C)=>{let S=await this.semaphore.use(()=>this.execute(o,v,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:g,skills:h,composio:b,tagPrefix:w,timeoutMs:p,observability:{swarmName:this.config.tag,operationName:e.name,operationId:r,operation:"reduce",role:"worker",errorRetry:k,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),U=f(S,k,C&&C>1?C-1:void 0);return S.error?{status:"error",data:null,files:S.files,meta:U,error:S.error,rawData:S.rawData}:{status:"success",data:S.data,files:S.files,meta:U}},y=`${this.config.tag}-reduce`;return c?this.runWithVerification((v,w,k)=>x(v,w,void 0,k),{originalPrompt:i,inputFiles:o,verifyConfig:c,timeoutMs:p,systemPrompt:m,schema:e.schema,mcpServers:g,skills:h,composio:b,operationId:r,baseTag:y,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?_(v=>{let w=v>1?v-1:void 0,k=w?`${y}-er${w}`:y;return x(i,k,w)},s):x(i,y)}async bestOf(e){let{item:n,prompt:i,config:c}=e,s=e.retry??this.config.retry,r=c.n??c.taskAgents?.length;if(r===void 0)throw new Error("bestOf requires n or taskAgents");if(r<2)throw new Error("bestOf requires n >= 2");let p=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,l=this.getFiles(n),o=c.mcpServers??this.config.mcpServers,u=c.judgeMcpServers??c.mcpServers??this.config.mcpServers,d=c.skills??this.config.skills,m=c.judgeSkills??c.skills??this.config.skills,f=c.composio??this.config.composio,g=c.judgeComposio??c.composio??this.config.composio,h=await Promise.all(Array.from({length:r},async(w,k)=>{let C=s?await _(S=>this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:k,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a,attempt:S}),s,k):await this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:k,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a});return c.onCandidateComplete?.(0,k,C.status==="success"?"success":"error"),C})),b=s?await _(w=>this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g,attempt:w}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g}),x=h.findIndex(w=>w.status==="success"),y=b.decision?.winner??(x>=0?x:0);c.onJudgeComplete?.(0,y,b.decision?.reasoning??"Judge failed to provide reasoning");let v={operationId:p,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:r};return {winner:h[y]??h[0],winnerIndex:y,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:v,candidates:h}}async execute(e,n,i){let c=null,s="",r=i.tagPrefix,p={},a=null,l,o,u={...this.config.agent,...i.agent};try{c=new Z().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&c.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&c.withSystemPrompt(i.systemPrompt),i.mcpServers&&c.withMcpServers(i.mcpServers),i.skills?.length&&c.withSkills(i.skills),i.composio&&c.withComposio(i.composio.userId,i.composio.config),i.observability&&c.withObservability(i.observability),Object.keys(e).length>0&&c.withContext(e);let d=await c.run({prompt:n,timeoutMs:i.timeoutMs});s=d.sandboxId,r=c.getSessionTag()??i.tagPrefix;let m=null;try{m=await c.getOutputFiles(!0),p=m.files;}catch{}d.exitCode!==0?l=`Agent exited with code ${d.exitCode}`:i.schema?m?(a=m.data,m.error&&(l=m.error),m.rawData&&(o=m.rawData)):l="Failed to read output files from sandbox":a=p;}catch(d){if(l=d.message,c){r=c.getSessionTag()??i.tagPrefix;try{p=(await c.getOutputFiles(!0)).files;}catch{}}}finally{c&&await c.kill().catch(()=>{});}return {files:p,data:a,tag:r,sandboxId:s,error:l,rawData:o}}async executeMapItem(e,n,i,c,s,r,p=1){let a=this.getFiles(e),l=p>1?`${this.config.tag}-map-${i}-er${p-1}`:`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(n,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=await this.semaphore.use(()=>this.execute(a,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:l,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),g={operationId:c,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(f,g)}async executeMapItemWithVerify(e,n,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-map-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=this.evaluatePrompt(n,a,i);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let g=async(h,b,x)=>{let y=await this.semaphore.use(()=>this.execute(a,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:b,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),v={operationId:c,operation:"map",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(y,v)};return this.runWithVerification(g,{originalPrompt:f,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:l,retry:p,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,n,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(n,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let u=s.bestOf,d=u.n??u.taskAgents?.length;if(d===void 0||d<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let m=s.mcpServers??this.config.mcpServers,f=u.mcpServers??m,g=u.judgeMcpServers??u.mcpServers??m,h=s.skills??this.config.skills,b=u.skills??h,x=u.judgeSkills??u.skills??h,y=s.composio??this.config.composio,v=u.composio??y,w=u.judgeComposio??u.composio??y,k=await Promise.all(Array.from({length:d},async(Q,X)=>{let Qe=p?await _(Qt=>this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:X,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:b,composio:v,timeoutMs:r,parentIndex:i,attempt:Qt,_pipelineContext:s._pipelineContext}),p,X):await this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:X,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:b,composio:v,timeoutMs:r,parentIndex:i,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(i,X,Qe.status==="success"?"success":"error"),Qe})),C=p?await _(Q=>this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:k,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:w,parentIndex:i,attempt:Q,_pipelineContext:s._pipelineContext}),{...p,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:k,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:w,parentIndex:i,_pipelineContext:s._pipelineContext}),S=k.findIndex(Q=>Q.status==="success"),U=C.decision?.winner??(S>=0?S:0),Ze=k[U]??k[0];u.onJudgeComplete?.(i,U,C.decision?.reasoning??"Judge failed to provide reasoning");let Zt={operationId:c,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...Ze,meta:{...Ze.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:U,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Zt,candidates:k}}}async executeFilterItem(e,n,i,c,s,r,p=1){let a=this.getFiles(e),l=p>1?`${this.config.tag}-filter-${i}-er${p-1}`:`${this.config.tag}-filter-${i}`,o=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,d=s.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(a,n,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:u,composio:d,tagPrefix:l,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:c,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(m,f,a)}async executeFilterItemWithVerify(e,n,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-filter-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=async(g,h,b)=>{let x=await this.semaphore.use(()=>this.execute(a,g,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:h,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),y={operationId:c,operation:"filter",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(x,y,a)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:l,retry:p,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:i,candidateIndex:c,operationId:s,config:r,timeoutMs:p,parentIndex:a,attempt:l=1,_pipelineContext:o}=e,u=a!==void 0?`${this.config.tag}-map-${a}-bestof-cand-${c}`:`${this.config.tag}-bestof-cand-${c}`,d=l>1?`${u}-er${l-1}`:u,m=await this.semaphore.use(()=>this.execute(n,i,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:r.taskAgents?.[c],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:p,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"candidate",candidateIndex:c,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o)}})),f={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:c,errorRetry:l>1?l-1:void 0,candidateIndex:c,...this.pipelineContextToMeta(o)};return this.buildResult(m,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((i,c)=>{i.status==="error"&&(n[`candidate_${c}/_failed.txt`]=`STATUS: FAILED
|
|
218
218
|
|
|
219
|
-
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,r])=>{n[`candidate_${c}/${s}`]=r;});}),n}async executeBestOfJudge(e){let{candidates:n,config:i,timeoutMs:c,operationId:s,parentIndex:r,attempt:p=1,_pipelineContext:a}=e,l=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=p>1?`${l}-er${p-1}`:l,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),d=ge(u),m=I(je,{candidateCount:String(n.length),criteria:i.judgeCriteria,fileTree:d}),f=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),g=await this.semaphore.use(()=>this.execute(u,Rt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let b=JSON.parse(g.rawData);console.warn(`Judge returned invalid winner ${b.winner}, defaulting to candidate 0`),h={winner:0,reasoning:b.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${g.error}`);}return {status:h?"success":"error",decision:h,tag:g.tag,sandboxId:g.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,c])=>{n[`worker_output/${i}`]=c;}),n}async executeVerify(e){let{config:n,timeoutMs:i,operationId:c,workerTag:s,retryAttempt:r=1,operation:p,itemIndex:a,attemptIndex:l,_pipelineContext:o}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=n.verifierMcpServers??e.mcpServers,m=n.verifierSkills??e.skills,f=n.verifierComposio??e.composio,g=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=ge(g),b=I(Be,{criteria:n.criteria,fileTree:h}),x=await this.semaphore.use(()=>this.execute(g,Pt,{systemPrompt:b,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:c,operation:p,itemIndex:a,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(o)}})),y=null;if(x.data&&!x.error)y=x.data;else if(x.rawData)try{let v=JSON.parse(x.rawData);y={passed:!!v.passed,reasoning:v.reasoning??"Verification completed",feedback:v.feedback};}catch{console.warn(`Verify validation failed: ${x.error}`);}return {status:y?"success":"error",decision:y,tag:x.tag,sandboxId:x.sandboxId,error:y?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return I(Ke,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:i,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:p,baseTag:a,retry:l,itemIndex:o=0,operation:u,_pipelineContext:d}=n,m=s.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=i,g=null,h=0;for(;h<m;){h++;let x=h>1?`${a}-vr${h-1}`:a,y=l?await _(k=>e(f,k>1?`${x}-er${k-1}`:x,h),l,o):await e(f,x,h);if(s.onWorkerComplete?.(o,h,y.status==="error"?"error":"success"),y.status==="error")return y;g=y;let v=l?await _(k=>this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,retryAttempt:k,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),w={operationId:p,operation:"verify",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,v.decision?.passed??false,v.decision?.feedback),v.decision?.passed)return {...y,verify:{passed:true,reasoning:v.decision.reasoning,verifyMeta:w,attempts:h}};if(h<m){let k=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(i,k);}}let b=h>1?`${a}-vr${h-1}`:a;return {...g,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:p,operation:"verify",tag:`${b}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,i){if(typeof e=="string")return e;try{return e(n,i)}catch(c){return c}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=E(e.schema)?j(e.schema):B(e.schema)),Object.entries(e.inputFiles).forEach(([i,c])=>{n[`worker_task/input/${i}`]=c;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&$ in e&&e[$]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,i){let c=i??e.files;return e.error?{[$]:true,status:"error",data:null,files:c,meta:n,error:e.error,rawData:e.rawData}:{[$]:true,status:"success",data:e.data,files:c,meta:n}}buildErrorResult(e,n){return {[$]:true,status:"error",data:null,files:{},meta:n,error:e}}};var xe=class t{swarm;steps;events;constructor(e,n=[],i={}){this.swarm=e,this.steps=n,this.events=i;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new we(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),i=[],c=e,s=Date.now();for(let p=0;p<this.steps.length;p++){let a=this.steps[p],l=a.config.name,o=Date.now();this.events.onStepStart?.({type:a.type,index:p,name:l,itemCount:c.length});let u={pipelineRunId:n,pipelineStepIndex:p};try{let d=await this.executeStep(a,c,p,l,u),m=Date.now()-o;if(i.push({type:a.type,index:p,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:p,name:l,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:n,steps:i,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:p,name:l,error:d instanceof Error?d:new Error(String(d))}),d}}let r=i[i.length-1];return {pipelineRunId:n,steps:i,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,i,c,s){if(e.type==="map"){let a=e.config,l=await this.swarm.map({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c),bestOf:this.wrapBestOf(a.bestOf,i,c)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,l=await this.swarm.filter({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c)}),o=a.emit??"success",u=o==="success"?l.success:o==="filtered"?l.filtered:[...l.success,...l.filtered];return {output:[...l],nextItems:u,successCount:l.success.length,errorCount:l.error.length,filteredCount:l.filtered.length}}let r=e.config,p=await this.swarm.reduce({items:n,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,c),verify:this.wrapVerify(r.verify,i,c)});return {output:p,nextItems:[],successCount:p.status==="success"?1:0,errorCount:p.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,i){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,n,i){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,p)=>{e.onVerifierComplete?.(c,s,r,p),this.events.onVerifierComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,passed:r,feedback:p});}}}wrapBestOf(e,n,i){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:n,stepName:i,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:n,stepName:i,itemIndex:c,winnerIndex:s,reasoning:r});}}}},we=class t extends xe{constructor(e,n,i){super(e,n,i);}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}map(){throw new Error("Cannot add steps after reduce")}filter(){throw new Error("Cannot add steps after reduce")}reduce(){throw new Error("Cannot add steps after reduce")}};Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Ce;exports.AGENT_TYPES=Xt;exports.Agent=q;exports.Evolve=Z;exports.JUDGE_PROMPT=je;exports.Pipeline=xe;exports.RETRY_FEEDBACK_PROMPT=Ke;exports.SCHEMA_PROMPT=Et;exports.SWARM_RESULT_BRAND=$;exports.SYSTEM_PROMPT=Tt;exports.Semaphore=V;exports.Swarm=qe;exports.SwarmResultList=W;exports.TerminalPipeline=we;exports.VALIDATION_PRESETS=ke;exports.VERIFY_PROMPT=Be;exports.WORKSPACE_PROMPT=St;exports.WORKSPACE_SWE_PROMPT=_t;exports.applyTemplate=I;exports.buildWorkerSystemPrompt=Ve;exports.createAgentParser=M;exports.createClaudeParser=re;exports.createCodexParser=ae;exports.createGeminiParser=ce;exports.executeWithRetry=_;exports.expandPath=Se;exports.getAgentConfig=P;exports.getMcpSettingsDir=L;exports.getMcpSettingsPath=F;exports.isValidAgentType=en;exports.isZodSchema=E;exports.jsonSchemaToString=B;exports.listCheckpoints=He;exports.parseNdjsonLine=xn;exports.parseNdjsonOutput=wn;exports.parseQwenOutput=nt;exports.readLocalDir=dt;exports.resolveStorageConfig=be;exports.saveLocalDir=mt;exports.writeClaudeMcpConfig=ne;exports.writeCodexMcpConfig=se;exports.writeGeminiMcpConfig=oe;exports.writeMcpConfig=Pe;exports.writeQwenMcpConfig=ie;exports.zodSchemaToJson=j;
|
|
219
|
+
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,r])=>{n[`candidate_${c}/${s}`]=r;});}),n}async executeBestOfJudge(e){let{candidates:n,config:i,timeoutMs:c,operationId:s,parentIndex:r,attempt:p=1,_pipelineContext:a}=e,l=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=p>1?`${l}-er${p-1}`:l,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),d=ge(u),m=I(Be,{candidateCount:String(n.length),criteria:i.judgeCriteria,fileTree:d}),f=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),g=await this.semaphore.use(()=>this.execute(u,Rt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let b=JSON.parse(g.rawData);console.warn(`Judge returned invalid winner ${b.winner}, defaulting to candidate 0`),h={winner:0,reasoning:b.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${g.error}`);}return {status:h?"success":"error",decision:h,tag:g.tag,sandboxId:g.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=zod.z.object({passed:zod.z.boolean(),reasoning:zod.z.string(),feedback:zod.z.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,c])=>{n[`worker_output/${i}`]=c;}),n}async executeVerify(e){let{config:n,timeoutMs:i,operationId:c,workerTag:s,retryAttempt:r=1,operation:p,itemIndex:a,attemptIndex:l,_pipelineContext:o}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=n.verifierMcpServers??e.mcpServers,m=n.verifierSkills??e.skills,f=n.verifierComposio??e.composio,g=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=ge(g),b=I(je,{criteria:n.criteria,fileTree:h}),x=await this.semaphore.use(()=>this.execute(g,Pt,{systemPrompt:b,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:c,operation:p,itemIndex:a,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(o)}})),y=null;if(x.data&&!x.error)y=x.data;else if(x.rawData)try{let v=JSON.parse(x.rawData);y={passed:!!v.passed,reasoning:v.reasoning??"Verification completed",feedback:v.feedback};}catch{console.warn(`Verify validation failed: ${x.error}`);}return {status:y?"success":"error",decision:y,tag:x.tag,sandboxId:x.sandboxId,error:y?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return I(Ke,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:i,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:p,baseTag:a,retry:l,itemIndex:o=0,operation:u,_pipelineContext:d}=n,m=s.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=i,g=null,h=0;for(;h<m;){h++;let x=h>1?`${a}-vr${h-1}`:a,y=l?await _(k=>e(f,k>1?`${x}-er${k-1}`:x,h),l,o):await e(f,x,h);if(s.onWorkerComplete?.(o,h,y.status==="error"?"error":"success"),y.status==="error")return y;g=y;let v=l?await _(k=>this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,retryAttempt:k,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),w={operationId:p,operation:"verify",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,v.decision?.passed??false,v.decision?.feedback),v.decision?.passed)return {...y,verify:{passed:true,reasoning:v.decision.reasoning,verifyMeta:w,attempts:h}};if(h<m){let k=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(i,k);}}let b=h>1?`${a}-vr${h-1}`:a;return {...g,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:p,operation:"verify",tag:`${b}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return crypto.randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,i){if(typeof e=="string")return e;try{return e(n,i)}catch(c){return c}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=E(e.schema)?B(e.schema):j(e.schema)),Object.entries(e.inputFiles).forEach(([i,c])=>{n[`worker_task/input/${i}`]=c;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&$ in e&&e[$]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,i){let c=i??e.files;return e.error?{[$]:true,status:"error",data:null,files:c,meta:n,error:e.error,rawData:e.rawData}:{[$]:true,status:"success",data:e.data,files:c,meta:n}}buildErrorResult(e,n){return {[$]:true,status:"error",data:null,files:{},meta:n,error:e}}};var xe=class t{swarm;steps;events;constructor(e,n=[],i={}){this.swarm=e,this.steps=n,this.events=i;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new we(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),i=[],c=e,s=Date.now();for(let p=0;p<this.steps.length;p++){let a=this.steps[p],l=a.config.name,o=Date.now();this.events.onStepStart?.({type:a.type,index:p,name:l,itemCount:c.length});let u={pipelineRunId:n,pipelineStepIndex:p};try{let d=await this.executeStep(a,c,p,l,u),m=Date.now()-o;if(i.push({type:a.type,index:p,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:p,name:l,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:n,steps:i,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:p,name:l,error:d instanceof Error?d:new Error(String(d))}),d}}let r=i[i.length-1];return {pipelineRunId:n,steps:i,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,i,c,s){if(e.type==="map"){let a=e.config,l=await this.swarm.map({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c),bestOf:this.wrapBestOf(a.bestOf,i,c)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,l=await this.swarm.filter({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c)}),o=a.emit??"success",u=o==="success"?l.success:o==="filtered"?l.filtered:[...l.success,...l.filtered];return {output:[...l],nextItems:u,successCount:l.success.length,errorCount:l.error.length,filteredCount:l.filtered.length}}let r=e.config,p=await this.swarm.reduce({items:n,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,c),verify:this.wrapVerify(r.verify,i,c)});return {output:p,nextItems:[],successCount:p.status==="success"?1:0,errorCount:p.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,i){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,n,i){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,p)=>{e.onVerifierComplete?.(c,s,r,p),this.events.onVerifierComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,passed:r,feedback:p});}}}wrapBestOf(e,n,i){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:n,stepName:i,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:n,stepName:i,itemIndex:c,winnerIndex:s,reasoning:r});}}}},we=class t extends xe{constructor(e,n,i){super(e,n,i);}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}map(){throw new Error("Cannot add steps after reduce")}filter(){throw new Error("Cannot add steps after reduce")}reduce(){throw new Error("Cannot add steps after reduce")}};Object.defineProperty(exports,"E2BProvider",{enumerable:true,get:function(){return e2b.E2BProvider}});Object.defineProperty(exports,"createE2BProvider",{enumerable:true,get:function(){return e2b.createE2BProvider}});Object.defineProperty(exports,"DaytonaProvider",{enumerable:true,get:function(){return daytona.DaytonaProvider}});Object.defineProperty(exports,"createDaytonaProvider",{enumerable:true,get:function(){return daytona.createDaytonaProvider}});Object.defineProperty(exports,"ModalProvider",{enumerable:true,get:function(){return modal.ModalProvider}});Object.defineProperty(exports,"createModalProvider",{enumerable:true,get:function(){return modal.createModalProvider}});exports.AGENT_REGISTRY=Ce;exports.AGENT_TYPES=Xt;exports.Agent=q;exports.Evolve=Z;exports.JUDGE_PROMPT=Be;exports.Pipeline=xe;exports.RETRY_FEEDBACK_PROMPT=Ke;exports.SCHEMA_PROMPT=Et;exports.SWARM_RESULT_BRAND=$;exports.SYSTEM_PROMPT=Tt;exports.Semaphore=V;exports.Swarm=qe;exports.SwarmResultList=W;exports.TerminalPipeline=we;exports.VALIDATION_PRESETS=ke;exports.VERIFY_PROMPT=je;exports.WORKSPACE_PROMPT=St;exports.WORKSPACE_SWE_PROMPT=_t;exports.applyTemplate=I;exports.buildWorkerSystemPrompt=Ve;exports.createAgentParser=M;exports.createClaudeParser=re;exports.createCodexParser=ae;exports.createGeminiParser=ce;exports.executeWithRetry=_;exports.expandPath=Se;exports.getAgentConfig=P;exports.getMcpSettingsDir=L;exports.getMcpSettingsPath=F;exports.isValidAgentType=en;exports.isZodSchema=E;exports.jsonSchemaToString=j;exports.listCheckpoints=He;exports.parseNdjsonLine=xn;exports.parseNdjsonOutput=wn;exports.parseQwenOutput=nt;exports.readLocalDir=dt;exports.resolveStorageConfig=be;exports.saveLocalDir=mt;exports.writeClaudeMcpConfig=ne;exports.writeCodexMcpConfig=se;exports.writeGeminiMcpConfig=oe;exports.writeMcpConfig=Pe;exports.writeQwenMcpConfig=ie;exports.zodSchemaToJson=B;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import * as zod from 'zod';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { EventEmitter } from 'events';
|
|
4
|
-
export { E2BProvider, createE2BProvider } from '@evolvingmachines/e2b';
|
|
5
|
-
export { DaytonaProvider, createDaytonaProvider } from '@evolvingmachines/daytona';
|
|
6
|
-
export { ModalProvider, createModalProvider } from '@evolvingmachines/modal';
|
|
4
|
+
export { E2BConfig, E2BProvider, createE2BProvider } from '@evolvingmachines/e2b';
|
|
5
|
+
export { DaytonaConfig, DaytonaProvider, createDaytonaProvider } from '@evolvingmachines/daytona';
|
|
6
|
+
export { ModalConfig, ModalProvider, createModalProvider } from '@evolvingmachines/modal';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* ACP-inspired output types for unified agent event streaming.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import * as zod from 'zod';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { EventEmitter } from 'events';
|
|
4
|
-
export { E2BProvider, createE2BProvider } from '@evolvingmachines/e2b';
|
|
5
|
-
export { DaytonaProvider, createDaytonaProvider } from '@evolvingmachines/daytona';
|
|
6
|
-
export { ModalProvider, createModalProvider } from '@evolvingmachines/modal';
|
|
4
|
+
export { E2BConfig, E2BProvider, createE2BProvider } from '@evolvingmachines/e2b';
|
|
5
|
+
export { DaytonaConfig, DaytonaProvider, createDaytonaProvider } from '@evolvingmachines/daytona';
|
|
6
|
+
export { ModalConfig, ModalProvider, createModalProvider } from '@evolvingmachines/modal';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* ACP-inspired output types for unified agent event streaming.
|
package/dist/index.js
CHANGED
|
@@ -19,7 +19,7 @@ ${d}
|
|
|
19
19
|
\`\`\``:d}});else if(Array.isArray(d)){for(let f of d)if(f.type==="text"){let g=f.text;m.push({type:"content",content:{type:"text",text:u?`\`\`\`
|
|
20
20
|
${g}
|
|
21
21
|
\`\`\``:g}});}}return {sessionUpdate:"tool_call_update",toolCallId:o,status:u?"failed":"completed",content:m}}function a(l,o){let u=bn[l]||"other",d=[],m=[],f=l;switch(l){case "Read":case "read_file":f=`Read ${o.file_path||o.absolute_path||"file"}`,(o.file_path||o.absolute_path)&&m.push({path:o.file_path||o.absolute_path});break;case "Write":case "write_file":f=`Write ${o.file_path||"file"}`,o.file_path&&(m.push({path:o.file_path}),d.push({type:"diff",path:o.file_path,oldText:null,newText:o.content||""}));break;case "Edit":case "edit_file":f=`Edit ${o.file_path||"file"}`,o.file_path&&m.push({path:o.file_path});break;case "Bash":case "shell":case "run_shell_command":f=o.command?`\`${o.command}\``:"Run command",o.description&&d.push({type:"content",content:{type:"text",text:o.description}});break;case "WebFetch":f=o.url?`Fetch ${o.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=o.query?`"${o.query}"`:"Web search";break;case "Glob":f=`Find ${o.pattern||"files"}`,o.path&&m.push({path:o.path});break;case "Grep":f=`grep "${o.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${o.path||"directory"}`,o.path&&m.push({path:o.path});break;case "Task":f=o.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=l;}return {title:f,kind:u,content:d,locations:m}}}function nt(t){return le()(t)}function M(t){switch(t){case "claude":return re();case "codex":return ae();case "gemini":return ce();case "qwen":return le();case "kimi":return Ae();case "opencode":return $e();default:return ()=>null}}function xn(t,e){let n=e.trim();return n?M(t)(n):null}function wn(t,e){let n=[],i=e.split(`
|
|
22
|
-
`),c=M(t);for(let s of i){let r=s.trim();if(!r)continue;let p=c(r);p&&n.push(...p);}return n}function z(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function ot(){return `${z()}`}function it(){return `${z()}/e2b`}function st(t){return {"browser-use":{type:"http",url:`${z()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var A="EVOLVE_API_KEY",pe="E2B_API_KEY",ue="DAYTONA_API_KEY",de="MODAL_TOKEN_ID",De="MODAL_TOKEN_SECRET",rt="claude",J=36e5,at=4,Ue=100,ct="/home/user/workspace",O=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",lt=".evolve-sdk/observability/sessions",pt=100,ut=5e3,me=3,Fe=1e3;function E(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function
|
|
22
|
+
`),c=M(t);for(let s of i){let r=s.trim();if(!r)continue;let p=c(r);p&&n.push(...p);}return n}function z(){return process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app"}function ot(){return `${z()}`}function it(){return `${z()}/e2b`}function st(t){return {"browser-use":{type:"http",url:`${z()}/browser_use/mcp`,headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var A="EVOLVE_API_KEY",pe="E2B_API_KEY",ue="DAYTONA_API_KEY",de="MODAL_TOKEN_ID",De="MODAL_TOKEN_SECRET",rt="claude",J=36e5,at=4,Ue=100,ct="/home/user/workspace",O=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",lt=".evolve-sdk/observability/sessions",pt=100,ut=5e3,me=3,Fe=1e3;function E(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function B(t){return JSON.stringify(kn(t,{target:"jsonSchema7"}),null,2)}function j(t){return JSON.stringify(t,null,2)}function dt(t,e=false){let n={};function i(c,s){for(let r of R.readdirSync(c)){let p=G.join(c,r),a=s?`${s}/${r}`:r;R.statSync(p).isDirectory()?e&&i(p,a):n[a]=R.readFileSync(p);}}return i(t,""),n}function mt(t,e){for(let[n,i]of Object.entries(e)){let c=G.join(t,n),s=G.dirname(c);R.mkdirSync(s,{recursive:true});let r;i instanceof ArrayBuffer||i instanceof Uint8Array?r=Buffer.from(i):r=i,R.writeFileSync(c,r);}}function Cn(t){let e=t.replace(/^~/,process.env.HOME||"");if(!R.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return R.readFileSync(e,"utf-8")}function Le(t){let e=t?.type??rt,n=P(e);if(t?.oauthToken){if(e!=="claude")throw new Error(`oauthToken is only supported for claude agent (Claude Max subscription), not ${e}. Use providerApiKey for ${e} instead.`);return {type:e,apiKey:t.oauthToken,isDirectMode:true,isOAuth:true,model:t.model,reasoningEffort:t.reasoningEffort,betas:t.betas}}if(t?.providerApiKey){let r=t.providerBaseUrl??process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:r,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort,betas:t.betas}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort,betas:t.betas};let i=process.env[A];if(i)return {type:e,apiKey:i,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas};if(n.providerEnvMap){let p=(t?.model??n.defaultModel)?.split("/")[0],a=p?n.providerEnvMap[p]:void 0,l=a?process.env[a.keyEnv]:void 0;if(l){let o=process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:l,baseUrl:o,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}}let c=process.env[n.apiKeyEnv];if(c){let r=process.env[n.baseUrlEnv]??n.defaultBaseUrl;return {type:e,apiKey:c,baseUrl:r,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}if(n.oauthEnv){let r=process.env[n.oauthEnv];if(r){if(n.oauthFileName){let p=Cn(r);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:p,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}return {type:e,apiKey:r,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort,betas:t?.betas}}}let s=n.oauthEnv?n.oauthFileName?`, or ${n.oauthEnv}`:`, oauthToken, or ${n.oauthEnv}`:"";throw new Error(`No API key found for ${e}. Set apiKey (gateway), providerApiKey (direct)${s}, or ${A} / ${n.apiKeyEnv} env var.`)}async function Ne(){let t=process.env[pe];if(t)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return s({apiKey:t})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${pe} is set but @evolvingmachines/e2b failed to load.
|
|
23
23
|
Try reinstalling: npm install @evolvingmachines/sdk`):r}let e=process.env[ue];if(e)try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return s({apiKey:e})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${ue} is set but @evolvingmachines/daytona failed to load.
|
|
24
24
|
Try installing: npm install @evolvingmachines/daytona`):r}let n=process.env[de],i=process.env[De];if(n&&i)try{let{createModalProvider:s}=await import('@evolvingmachines/modal');return s({tokenId:n,tokenSecret:i})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${de} is set but @evolvingmachines/modal failed to load.
|
|
25
25
|
Try installing: npm install @evolvingmachines/modal`):r}let c=process.env[A];if(c)try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL=it(),s({apiKey:c})}catch(s){let r=s;throw r.message?.includes("Cannot find module")||r.message?.includes("MODULE_NOT_FOUND")?new Error(`${A} is set but @evolvingmachines/e2b failed to load.
|
|
@@ -194,10 +194,10 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
194
194
|
{{feedback}}
|
|
195
195
|
|
|
196
196
|
Make sure your output addresses all the feedback points above.
|
|
197
|
-
`;var St=ft,_t=gt,Tt=ht,Et=yt,
|
|
197
|
+
`;var St=ft,_t=gt,Tt=ht,Et=yt,Be=vt,Rt=wt,je=bt,Pt=kt,Ot=xt,Ke=Ct;function I(t,e){let n=t;for(let[i,c]of Object.entries(e))n=n.replace(new RegExp(`\\{\\{${i}\\}\\}`,"g"),c);return n}function Ve(t){let e=t.mode==="swe"?_t:St,n=I(e,{workingDir:t.workingDir}).trim();if(t.systemPrompt&&(n+=`
|
|
198
198
|
|
|
199
199
|
|
|
200
|
-
${I(Tt,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let i=E(t.schema)?
|
|
200
|
+
${I(Tt,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let i=E(t.schema)?B(t.schema):j(t.schema);n+=`
|
|
201
201
|
|
|
202
202
|
|
|
203
203
|
${I(Et,{schema:i}).trim()}`;}return n}function ge(t){let e=[...new Set(Object.keys(t).map(a=>a.split("/")[0]))].sort((a,l)=>a==="worker_task"?-1:l==="worker_task"?1:a.localeCompare(l));if(!e.length)return `context/
|
|
@@ -206,8 +206,8 @@ ${I(Et,{schema:i}).trim()}`;}return n}function ge(t){let e=[...new Set(Object.ke
|
|
|
206
206
|
`)?e:e+`
|
|
207
207
|
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{});}bufferForDashboard(e){this.eventBuffer.push(e),this.scheduleFlush();}write(e){this.metaWritten||this.writeMeta();let n=JSON.stringify(e)+`
|
|
208
208
|
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&(this.eventBuffer.push(e),this.scheduleFlush());}writeMeta(){let e={_meta:{tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandbox_id:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability)}},n=JSON.stringify(e)+`
|
|
209
|
-
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=pt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},ut));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let i=1;i<=me;i++)try{let c=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(c.ok)return;if(c.status===429||c.status===401||c.status>=500){if(i===me){console.debug(`[SessionLogger] Dashboard ${c.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Fe*i);continue}console.debug(`[SessionLogger] Dashboard ${c.status}, dropping events`);return}catch(c){i===me?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",c),this.requeueEvents(e)):await this.delay(Fe*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!O.startsWith("https://")&&!O.includes("localhost")&&!O.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var he="COMPOSIO_API_KEY";function At(t){return new Composio({apiKey:process.env[he]})}function We(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function ye(t,e,n){We(t);let i=At(),c={};return e?.toolkits&&(c.toolkits=e.toolkits),e?.tools&&(c.tools=e.tools),e?.authConfigs&&(c.authConfigs=e.authConfigs),e?.connectedAccounts&&(c.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(c.manageConnections=e.manageConnections),await i.create(t,Object.keys(c).length>0?c:void 0)}async function $t(t,e,n,i){We(t);let c=At(),p=(await c.toolkits.get(e)).authConfigDetails?.find(a=>a.mode==="API_KEY");if(!p)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await c.connectedAccounts.initiate(t,p.name,{config:AuthScheme.APIKey({api_key:n})});}async function ze(t,e){if(We(t),e?.keys)for(let[i,c]of Object.entries(e.keys))try{await $t(t,i,c);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let n=await ye(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function Dt(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function Vn(){return new Composio({apiKey:process.env[he]})}async function Ut(t,e){Dt(t);let i=await(await ye(t,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function Ft(t,e){let n=await Je(t),i={};for(let c of n)i[c.toolkit]=c.connected;return e?i[e]??false:i}async function Je(t){return Dt(t),(await Vn().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var Ge={auth:Ut,status:Ft,connections:Je};var Lt=Symbol.for("evolve:awsSdkCache"),Nt=Symbol.for("evolve:s3ClientCache");var Wn=3600,zn=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Jn(t){if(t.startsWith("s3://")){let c=t.slice(5),s=c.indexOf("/");return s===-1?{bucket:c,prefix:""}:{bucket:c.slice(0,s),prefix:c.slice(s+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,i=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:i.join("/")};if(i.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:i[0],prefix:i.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function be(t,e,n,i){if(!t?.url&&!t?.bucket){if(!e)throw new Error("Storage requires either a URL (BYOK mode) or gateway API key. Use .withStorage({ url: 's3://bucket/prefix' }) or configure EVOLVE_API_KEY for gateway mode.");return {bucket:"",prefix:"",region:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:i}}let c=t?.bucket||"",s=t?.prefix||"",r=t?.endpoint;if(t?.url){let p=Jn(t.url);c=c||p.bucket,s=s||p.prefix,r=r||p.endpoint;}if(!c)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:c,prefix:s,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:r,credentials:t?.credentials,mode:"byok"}}function
|
|
210
|
-
`).pop()?.trim();if(!a||a.length!==64)throw new Error(`Invalid checkpoint hash: ${a}`);let l=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(l.stdout.trim(),10),u=Number.isNaN(o)?void 0:o,d;try{if(e.mode==="byok"){let m=Wt(e,a);if(!await
|
|
209
|
+
`;this.localQueue=this.localQueue.then(()=>this.appendLocal(n)).catch(()=>{}),this.apiKey&&this.eventBuffer.push(e),this.metaWritten=true;}async appendLocal(e){try{await this.dirReady,await appendFile(this.localFilePath,e,"utf-8");}catch(n){console.debug("[SessionLogger] Local write failed:",n);}}scheduleFlush(){if(this.eventBuffer.length>=pt){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},ut));}flushDashboard(){if(!this.apiKey||this.eventBuffer.length===0)return;let e=this.eventBuffer.splice(0);this.dashboardQueue=this.dashboardQueue.then(()=>this.sendToDashboard(e)).catch(()=>{});}async sendToDashboard(e){let n={tag:this.tag,provider:this.provider,agent:this.agent,model:this.model,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.filterUndefined(this.observability),events:e};for(let i=1;i<=me;i++)try{let c=await fetch(`${this.dashboardUrl}/api/sessions/ingest`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)});if(c.ok)return;if(c.status===429||c.status===401||c.status>=500){if(i===me){console.debug(`[SessionLogger] Dashboard ${c.status} after ${i} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Fe*i);continue}console.debug(`[SessionLogger] Dashboard ${c.status}, dropping events`);return}catch(c){i===me?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",c),this.requeueEvents(e)):await this.delay(Fe*i);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){if(e.apiKey&&!O.startsWith("https://")&&!O.includes("localhost")&&!O.includes("127.0.0.1"))throw new Error("Dashboard URL must use HTTPS when API key is provided")}delay(e){return new Promise(n=>setTimeout(n,e))}filterUndefined(e){return e?Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0)):{}}};var he="COMPOSIO_API_KEY";function At(t){return new Composio({apiKey:process.env[he]})}function We(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}async function ye(t,e,n){We(t);let i=At(),c={};return e?.toolkits&&(c.toolkits=e.toolkits),e?.tools&&(c.tools=e.tools),e?.authConfigs&&(c.authConfigs=e.authConfigs),e?.connectedAccounts&&(c.connectedAccounts=e.connectedAccounts),e?.manageConnections!==void 0&&(c.manageConnections=e.manageConnections),await i.create(t,Object.keys(c).length>0?c:void 0)}async function $t(t,e,n,i){We(t);let c=At(),p=(await c.toolkits.get(e)).authConfigDetails?.find(a=>a.mode==="API_KEY");if(!p)throw new Error(`Toolkit "${e}" does not support API key authentication. Get an OAuth URL via Evolve.composio.auth() instead.`);await c.connectedAccounts.initiate(t,p.name,{config:AuthScheme.APIKey({api_key:n})});}async function ze(t,e){if(We(t),e?.keys)for(let[i,c]of Object.entries(e.keys))try{await $t(t,i,c);}catch(s){throw new Error(`Failed to create API key connection for "${i}": ${s.message}`)}let n=await ye(t,{toolkits:e?.toolkits,tools:e?.tools,authConfigs:e?.authConfigs,connectedAccounts:e?.connectedAccounts,manageConnections:e?.manageConnections});return {url:n.mcp.url,headers:n.mcp.headers}}function Dt(t){if(!t?.trim())throw new Error("userId is required and cannot be empty")}function Vn(){return new Composio({apiKey:process.env[he]})}async function Ut(t,e){Dt(t);let i=await(await ye(t,{manageConnections:false})).authorize(e);return {url:i.redirectUrl,connectionId:i.id}}async function Ft(t,e){let n=await Je(t),i={};for(let c of n)i[c.toolkit]=c.connected;return e?i[e]??false:i}async function Je(t){return Dt(t),(await Vn().connectedAccounts.list({userIds:[t],statuses:["ACTIVE"]})).items.map(i=>({toolkit:i.toolkit.slug,connected:i.status==="ACTIVE",accountId:i.id}))}var Ge={auth:Ut,status:Ft,connections:Je};var Lt=Symbol.for("evolve:awsSdkCache"),Nt=Symbol.for("evolve:s3ClientCache");var Wn=3600,zn=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Jn(t){if(t.startsWith("s3://")){let c=t.slice(5),s=c.indexOf("/");return s===-1?{bucket:c,prefix:""}:{bucket:c.slice(0,s),prefix:c.slice(s+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,i=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:i.join("/")};if(i.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:i[0],prefix:i.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function be(t,e,n,i){if(!t?.url&&!t?.bucket){if(!e)throw new Error("Storage requires either a URL (BYOK mode) or gateway API key. Use .withStorage({ url: 's3://bucket/prefix' }) or configure EVOLVE_API_KEY for gateway mode.");return {bucket:"",prefix:"",region:t?.region||"us-east-1",mode:"gateway",gatewayUrl:n,gatewayApiKey:i}}let c=t?.bucket||"",s=t?.prefix||"",r=t?.endpoint;if(t?.url){let p=Jn(t.url);c=c||p.bucket,s=s||p.prefix,r=r||p.endpoint;}if(!c)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:c,prefix:s,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:r,credentials:t?.credentials,mode:"byok"}}function Bt(t){if(t.includes(".."))throw new Error(`settingsDir must not contain '..': ${t}`);let e;if(t.startsWith("~/"))e=t.slice(2);else if(t.startsWith("/home/user/"))e=t.slice(11);else if(t.startsWith("."))e=t;else throw new Error(`Unexpected settingsDir: ${t}. Expected ~/ or /home/user/ prefix.`);if(!e||e.startsWith("/"))throw new Error(`settingsDir resolves to invalid path: ${t}`);return e}function Gn(t){if(t.includes(".."))throw new Error(`workingDir must not contain '..': ${t}`);if(!t.startsWith("/home/user/"))throw new Error(`Unexpected workingDir: ${t}. Must start with /home/user/.`);let e=t.slice(11).replace(/\/+$/,"");if(!e||e.startsWith("/")||e.includes("//"))throw new Error(`workingDir resolves to invalid path: ${t}`);return e}function ve(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Yn(t,e){let n=P(t),i=Gn(e),c=n.checkpointDirs?.length?n.checkpointDirs.map(p=>Bt(p)):[Bt(n.mcpConfig.settingsDir)],s=[...zn.map(p=>`--exclude=${ve(p)}`),`--exclude=${ve(i+"/temp")}`].join(" "),r=[ve(i+"/"),...c.map(p=>ve(p+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${s} ${r}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function K(){let t=globalThis[Lt];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[i,c]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[Lt]={s3:i,presigner:c},{s3:i,presigner:c}}catch{throw new Error("Storage requires @aws-sdk/client-s3 and @aws-sdk/s3-request-presigner. Install: npm i @aws-sdk/client-s3 @aws-sdk/s3-request-presigner")}}async function H(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,i=globalThis[Nt];if(i?.key===n)return i.client;let{s3:c}=await K(),s=new c.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[Nt]={client:s,key:n},s}async function Kt(t,e,n){let{s3:i,presigner:c}=await K(),s=await H(t),r=n==="put"?new i.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new i.GetObjectCommand({Bucket:t.bucket,Key:e});return c.getSignedUrl(s,r,{expiresIn:Wn})}async function jt(t,e){let{s3:n}=await K(),i=await H(t);try{return await i.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(c){let s=c?.name||c?.message||"";if(c?.$metadata?.httpStatusCode===404||s==="NotFound"||s==="NoSuchKey")return false;throw c}}async function Vt(t,e){let{s3:n}=await K(),s=await(await(await H(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!s)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(s)}async function Hn(t,e,n){let{s3:i}=await K();await(await H(t)).send(new i.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Wt(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function zt(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function qn(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function Jt(t,e,n,i){let c=await fetch(`${t.gatewayUrl}/api/checkpoints/presign`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify({tag:e,hash:n,action:i})});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway presign failed (${c.status}): ${s}`)}return c.json()}async function Zn(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.gatewayApiKey}`},body:JSON.stringify(e)});if(!n.ok){let i=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${i}`)}return n.json()}async function Qn(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${e}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let i=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${i}`)}return n.json()}async function Ye(t,e,n,i,c){let s=new Date().toISOString(),r=Yn(n,i),p=await t.commands.run(r,{timeoutMs:12e4});if(p.exitCode!==0)throw new Error(`Checkpoint tar failed: ${p.stderr}`);let a=p.stdout.trim().split(`
|
|
210
|
+
`).pop()?.trim();if(!a||a.length!==64)throw new Error(`Invalid checkpoint hash: ${a}`);let l=await t.commands.run("stat -c '%s' /tmp/evolve-ckpt.tar.gz 2>/dev/null || stat -f '%z' /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4}),o=parseInt(l.stdout.trim(),10),u=Number.isNaN(o)?void 0:o,d;try{if(e.mode==="byok"){let m=Wt(e,a);if(!await jt(e,m)){let h=await Kt(e,m,"put"),b=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(b.exitCode!==0)throw new Error(`Checkpoint upload failed: ${b.stderr}`);if(!await jt(e,m))throw new Error("Checkpoint upload verification failed (HeadObject)")}d=qn();let g={id:d,hash:a,tag:c.tag,timestamp:s,sizeBytes:u,agentType:n,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment,sandboxId:t.sandboxId};await Hn(e,zt(e,d),g);}else {let m=await Jt(e,c.tag,a,"put");if(!m.alreadyExists){let g=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${m.url}"`,{timeoutMs:3e5});if(g.exitCode!==0)throw new Error(`Checkpoint upload failed: ${g.stderr}`)}d=(await Zn(e,{tag:c.tag,hash:a,sizeBytes:u??0,agentType:n,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:d,hash:a,tag:c.tag,timestamp:s,sizeBytes:u,agentType:n,model:c.model,workspaceMode:c.workspaceMode,parentId:c.parentId,comment:c.comment}}async function Gt(t,e,n){let i,c,s={};if(e.mode==="byok"){let l=zt(e,n),o;try{o=await Vt(e,l);}catch(u){let d=u.name;throw d==="AccessDenied"||d==="InvalidAccessKeyId"||d==="SignatureDoesNotMatch"||d==="ExpiredToken"||d==="NetworkingError"||d==="TimeoutError"?u:new Error(`Checkpoint ${n} not found`)}i=o.hash,s={agentType:o.agentType,workspaceMode:o.workspaceMode},c=await Kt(e,Wt(e,i),"get");}else {let l=await Qn(e,n);i=l.hash,s={agentType:l.agentType,workspaceMode:l.workspaceMode},c=(await Jt(e,l.tag,i,"get")).url;}let r=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${c}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(r.exitCode!==0)throw new Error(`Checkpoint download failed: ${r.stderr}`);let p=r.stdout.trim().split(`
|
|
211
211
|
`).pop()?.trim();if(p!==i)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${i}, got ${p})`);let a=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(a.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${a.stderr}`);return s}function Xn(t){let e=process.env.EVOLVE_API_KEY,n=!t.url&&!t.bucket&&!!e;return be(t,n,O,e)}async function Yt(t,e){let{s3:n}=await K(),i=await H(t),s=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,r=[],p;do{let d={Bucket:t.bucket,Prefix:s,...p&&{ContinuationToken:p}},m=await i.send(new n.ListObjectsV2Command(d));if(m.Contents)for(let f of m.Contents)f.Key?.endsWith(".json")&&f.LastModified&&r.push({key:f.Key,lastModified:f.LastModified});p=m.IsTruncated?m.NextContinuationToken:void 0;}while(p);if(r.length===0)return [];r.sort((d,m)=>{let f=m.lastModified.getTime()-d.lastModified.getTime();return f!==0?f:m.key<d.key?-1:m.key>d.key?1:0});let l=!!e?.tag?r:e?.limit?r.slice(0,e.limit):r,u=(await Promise.all(l.map(async d=>{try{return await Vt(t,d.key)}catch{return null}}))).filter(d=>d!==null);return e?.tag&&(u=u.filter(d=>d.tag===e.tag)),e?.limit&&u.length>e.limit&&(u=u.slice(0,e.limit)),u}async function Ht(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let i=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,c=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!c.ok){let s=await c.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${c.status}): ${s}`)}return c.json()}async function He(t,e){let n=Xn(t),i=e?.limit&&e.limit>0?Math.min(e.limit,500):100;return n.mode==="byok"?Yt(n,{limit:i,tag:e?.tag}):Ht(n,{limit:i,tag:e?.tag})}async function qt(t){return t.mode==="byok"?(await Yt(t,{limit:1}))[0]??null:(await Ht(t,{limit:1}))[0]??null}function to(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}var q=class{agentConfig;options;sandbox;hasRun=false;workingDir;lastRunTimestamp;registry;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";skills;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(this.agentConfig=e,this.options=n,this.workingDir=n.workingDirectory||ct,this.sandboxState=n.sandboxId?"ready":"stopped",this.skills=n.skills,this.storage=n.storage,n.schema)if(E(n.schema))this.zodSchema=n.schema,n.schemaOptions&&console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead");else {this.jsonSchema=n.schema,this.schemaOptions=n.schemaOptions;try{let i=this.createAjvValidator();this.compiledValidator=i.compile(this.jsonSchema);}catch(i){throw new Error(`Invalid JSON Schema: ${i.message}`)}}this.registry=P(e.type);}emitLifecycle(e,n){e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,i,c){let s=++this.nextOperationId;return this.activeOperationId=s,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(i,c),s}finalizeOperation(e,n,i,c="idle",s="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=s,this.agentState=c,this.emitLifecycle(n,i),true)}watchBackgroundOperation(e,n,i,c){let s=n==="run"?"run_background_complete":"command_background_complete",r=n==="run"?"run_background_failed":"command_background_failed",p=n==="run"?"run_interrupted":"command_interrupted";i.wait().then(a=>{if(this.interruptedOperations.delete(e)||a.exitCode===130){this.finalizeOperation(e,c,p,"interrupted");return}let o=a.exitCode===0?s:r,u=a.exitCode===0?"idle":"error";this.finalizeOperation(e,c,o,u);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,c,r,"error");});}createAjvValidator(){let n={...ke[this.schemaOptions?.mode||"loose"],...this.schemaOptions?.coerceTypes!==void 0&&{coerceTypes:this.schemaOptions.coerceTypes},...this.schemaOptions?.removeAdditional!==void 0&&{removeAdditional:this.schemaOptions.removeAdditional},...this.schemaOptions?.useDefaults!==void 0&&{useDefaults:this.schemaOptions.useDefaults},...this.schemaOptions?.allErrors!==void 0&&{allErrors:this.schemaOptions.allErrors}};return new eo({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let n=this.options.sandboxProvider;this.sandboxState="booting",this.emitLifecycle(e,"sandbox_boot");try{if(this.options.sandboxId)(this.options.mcpServers||this.options.context||this.options.files||this.options.systemPrompt)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, context, files, and systemPrompt"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {let i=this.buildEnvironmentVariables();this.sandbox=await n.create({envs:i,workingDirectory:this.workingDir}),await this.setupAgentAuth(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(i){throw this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),i}return this.sandbox}buildEnvironmentVariables(){let e={};if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let n of Object.values(this.registry.providerEnvMap))e[n.keyEnv]=this.agentConfig.apiKey;else {let n=this.agentConfig.model?.split("/")[0],i=n?this.registry.providerEnvMap?.[n]:void 0,c=i?i.keyEnv:this.registry.apiKeyEnv,s=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:c;e[s]=this.agentConfig.apiKey;}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth)this.agentConfig.baseUrl&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let n=this.registry.usePassthroughGateway?ot():z();if(this.registry.gatewayConfigEnv){let i=this.agentConfig.model||this.registry.defaultModel;e[this.registry.gatewayConfigEnv]=JSON.stringify({provider:{litellm:{npm:"@ai-sdk/openai-compatible",options:{baseURL:`${n}/v1`,apiKey:this.agentConfig.apiKey},models:{[i]:{name:i}}}}});}else e[this.registry.baseUrlEnv]=n;e.EVOLVE_API_KEY=this.agentConfig.apiKey;}return this.options.secrets&&Object.assign(e,this.options.secrets),e}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=this.registry.mcpConfig.settingsDir.replace(/^~/,"/home/user");await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async setupWorkspace(e,n){let i=this.options.workspaceMode||"knowledge",c=i==="swe"?`${this.workingDir}/repo ${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`:`${this.workingDir}/context ${this.workingDir}/scripts ${this.workingDir}/temp ${this.workingDir}/output`;if(await e.commands.run(`mkdir -p ${c}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let r=Ve({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,schema:this.zodSchema||this.jsonSchema,mode:i}),p=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(p,r);}this.options.context&&await this.uploadContextFiles(e,this.options.context),this.options.files&&await this.uploadWorkspaceFiles(e,this.options.files);let s={...this.options.mcpServers};if(this.options.composio){let r=await ze(this.options.composio.userId,this.options.composio.config);s={...s,composio:{type:"http",url:r.url,headers:r.headers}};}Object.keys(s).length>0&&await Pe(this.agentConfig.type,e,this.workingDir,s),this.skills?.length&&await this.setupSkills(e);}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,{sourceDir:i,targetDir:c}=n;await e.files.makeDir(c);for(let s of this.skills){let r=`cp -r ${i}/${s} ${c}/ 2>/dev/null || true`;await e.commands.run(r,{timeoutMs:3e4});}}async uploadContextFiles(e,n){let i=Object.entries(n).map(([s,r])=>({path:`${this.workingDir}/context/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}async uploadWorkspaceFiles(e,n){let i=Object.entries(n).map(([s,r])=>({path:s.startsWith("/")?s:`${this.workingDir}/${s}`,data:r}));if(i.length===0)return;let c=new Set(i.map(s=>s.path.substring(0,s.path.lastIndexOf("/"))).filter(Boolean));c.size>0&&await e.commands.run(`mkdir -p ${Array.from(c).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(i);}buildCommand(e){return this.registry.buildCommand({prompt:to(e),model:this.agentConfig.model||this.registry.defaultModel,isResume:this.hasRun,reasoningEffort:this.agentConfig.reasoningEffort,betas:this.agentConfig.betas,isDirectMode:this.agentConfig.isDirectMode,skills:this.skills})}async run(e,n){let{prompt:i,timeoutMs:c=J,background:s=false,checkpointComment:r}=e,{from:p}=e;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background run to finish, or create a new Evolve instance.");if(p&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(p==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let y=await qt(this.storage);if(!y)throw new Error('No checkpoints found for from: "latest".');p=y.id;}if(p){if(!this.storage)throw new Error("Storage not configured. Call .withStorage() before using 'from'.");if(!this.options.sandboxProvider)throw new Error("No sandbox provider configured");let y=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create({envs:y,workingDirectory:this.workingDir});let v=await Gt(this.sandbox,this.storage,p);if(v.agentType&&v.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${v.agentType}, current: ${this.agentConfig.type})`);let w=this.options.workspaceMode||"knowledge";if(v.workspaceMode&&v.workspaceMode!==w)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${v.workspaceMode}, current: ${w})`);await this.setupAgentAuth(this.sandbox);let k=!!(this.options.systemPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!k}),this.hasRun=!0,this.lastCheckpointId=p,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(v){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),v}}let a=await this.getSandbox(n);if(this.lastRunTimestamp=Date.now(),!this.sessionLogger){let y=this.options.sandboxProvider;this.sessionLogger=new Y({provider:y?.name||y?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:a.sandboxId,tagPrefix:this.options.sessionTagPrefix,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:this.options.observability});}this.sessionLogger.writePrompt(i);let l=this.buildCommand(i),o="",u=M(this.agentConfig.type),d=y=>{o+=y;let v=o.split(`
|
|
212
212
|
`);o=v.pop()??"";for(let w of v){if(!w.trim())continue;let k=u(w);if(this.sessionLogger?.writeEventParsed(w,k),n?.onStdout?.(w+`
|
|
213
213
|
`),k&&n?.onContent)for(let C of k)n.onContent(C);}},m=y=>{n?.onStderr?.(y);},f=await a.commands.spawn(l,{cwd:this.workingDir,timeoutMs:c,onStdout:d,onStderr:m}),g=this.beginOperation("run",f,n,"run_start");if(this.hasRun=true,s)return this.watchBackgroundOperation(g,"run",f,n),{sandboxId:a.sandboxId,exitCode:0,stdout:`Background process started with ID ${f.processId}`,stderr:""};let h;try{h=await f.wait();}catch(y){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,n,"run_failed","error"),y}if(this.interruptedOperations.delete(g)||h.exitCode===130?this.finalizeOperation(g,n,"run_interrupted","interrupted"):h.exitCode===0?this.finalizeOperation(g,n,"run_complete","idle"):this.finalizeOperation(g,n,"run_failed","error"),o.trim()){let y=u(o);if(this.sessionLogger?.writeEventParsed(o,y),n?.onStdout?.(o+`
|
|
@@ -216,4 +216,4 @@ ${I(Et,{schema:i}).trim()}`;}return n}function ge(t){let e=[...new Set(Object.ke
|
|
|
216
216
|
|
|
217
217
|
${e.systemPrompt}`:d,f=(v,w,k)=>({operationId:r,operation:"reduce",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:l,errorRetry:w,verifyRetry:k,...this.pipelineContextToMeta(e._pipelineContext)}),g=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,b=e.composio??this.config.composio,x=async(v,w,k,C)=>{let S=await this.semaphore.use(()=>this.execute(o,v,{systemPrompt:m,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:g,skills:h,composio:b,tagPrefix:w,timeoutMs:p,observability:{swarmName:this.config.tag,operationName:e.name,operationId:r,operation:"reduce",role:"worker",errorRetry:k,verifyRetry:C&&C>1?C-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),U=f(S,k,C&&C>1?C-1:void 0);return S.error?{status:"error",data:null,files:S.files,meta:U,error:S.error,rawData:S.rawData}:{status:"success",data:S.data,files:S.files,meta:U}},y=`${this.config.tag}-reduce`;return c?this.runWithVerification((v,w,k)=>x(v,w,void 0,k),{originalPrompt:i,inputFiles:o,verifyConfig:c,timeoutMs:p,systemPrompt:m,schema:e.schema,mcpServers:g,skills:h,composio:b,operationId:r,baseTag:y,retry:s,operation:"reduce",_pipelineContext:e._pipelineContext}):s?_(v=>{let w=v>1?v-1:void 0,k=w?`${y}-er${w}`:y;return x(i,k,w)},s):x(i,y)}async bestOf(e){let{item:n,prompt:i,config:c}=e,s=e.retry??this.config.retry,r=c.n??c.taskAgents?.length;if(r===void 0)throw new Error("bestOf requires n or taskAgents");if(r<2)throw new Error("bestOf requires n >= 2");let p=this.generateOperationId(),a=e.timeoutMs??this.config.timeoutMs,l=this.getFiles(n),o=c.mcpServers??this.config.mcpServers,u=c.judgeMcpServers??c.mcpServers??this.config.mcpServers,d=c.skills??this.config.skills,m=c.judgeSkills??c.skills??this.config.skills,f=c.composio??this.config.composio,g=c.judgeComposio??c.composio??this.config.composio,h=await Promise.all(Array.from({length:r},async(w,k)=>{let C=s?await _(S=>this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:k,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a,attempt:S}),s,k):await this.executeBestOfCandidate({inputFiles:l,prompt:i,candidateIndex:k,operationId:p,config:c,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:o,skills:d,composio:f,timeoutMs:a});return c.onCandidateComplete?.(0,k,C.status==="success"?"success":"error"),C})),b=s?await _(w=>this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g,attempt:w}),{...s,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:i,candidates:h,config:c,timeoutMs:a,operationId:p,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:u,skills:m,composio:g}),x=h.findIndex(w=>w.status==="success"),y=b.decision?.winner??(x>=0?x:0);c.onJudgeComplete?.(0,y,b.decision?.reasoning??"Judge failed to provide reasoning");let v={operationId:p,operation:"bestof-judge",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:r};return {winner:h[y]??h[0],winnerIndex:y,judgeReasoning:b.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:v,candidates:h}}async execute(e,n,i){let c=null,s="",r=i.tagPrefix,p={},a=null,l,o,u={...this.config.agent,...i.agent};try{c=new Z().withAgent(u).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(i.tagPrefix),i.schema&&c.withSchema(i.schema,i.schemaOptions),i.systemPrompt&&c.withSystemPrompt(i.systemPrompt),i.mcpServers&&c.withMcpServers(i.mcpServers),i.skills?.length&&c.withSkills(i.skills),i.composio&&c.withComposio(i.composio.userId,i.composio.config),i.observability&&c.withObservability(i.observability),Object.keys(e).length>0&&c.withContext(e);let d=await c.run({prompt:n,timeoutMs:i.timeoutMs});s=d.sandboxId,r=c.getSessionTag()??i.tagPrefix;let m=null;try{m=await c.getOutputFiles(!0),p=m.files;}catch{}d.exitCode!==0?l=`Agent exited with code ${d.exitCode}`:i.schema?m?(a=m.data,m.error&&(l=m.error),m.rawData&&(o=m.rawData)):l="Failed to read output files from sandbox":a=p;}catch(d){if(l=d.message,c){r=c.getSessionTag()??i.tagPrefix;try{p=(await c.getOutputFiles(!0)).files;}catch{}}}finally{c&&await c.kill().catch(()=>{});}return {files:p,data:a,tag:r,sandboxId:s,error:l,rawData:o}}async executeMapItem(e,n,i,c,s,r,p=1){let a=this.getFiles(e),l=p>1?`${this.config.tag}-map-${i}-er${p-1}`:`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(n,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=await this.semaphore.use(()=>this.execute(a,o,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:l,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),g={operationId:c,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(f,g)}async executeMapItemWithVerify(e,n,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-map-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=this.evaluatePrompt(n,a,i);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let g=async(h,b,x)=>{let y=await this.semaphore.use(()=>this.execute(a,h,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:b,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"map",itemIndex:i,role:"worker",verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),v={operationId:c,operation:"map",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(y,v)};return this.runWithVerification(g,{originalPrompt:f,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:l,retry:p,itemIndex:i,operation:"map",_pipelineContext:s._pipelineContext})}async executeMapItemWithBestOf(e,n,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-map-${i}`,o=this.evaluatePrompt(n,a,i);if(o instanceof Error)return this.buildErrorResult(`Prompt function threw: ${o.message}`,{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let u=s.bestOf,d=u.n??u.taskAgents?.length;if(d===void 0||d<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:c,operation:"map",tag:l,sandboxId:"",itemIndex:i});let m=s.mcpServers??this.config.mcpServers,f=u.mcpServers??m,g=u.judgeMcpServers??u.mcpServers??m,h=s.skills??this.config.skills,b=u.skills??h,x=u.judgeSkills??u.skills??h,y=s.composio??this.config.composio,v=u.composio??y,w=u.judgeComposio??u.composio??y,k=await Promise.all(Array.from({length:d},async(Q,X)=>{let Qe=p?await _(Qt=>this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:X,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:b,composio:v,timeoutMs:r,parentIndex:i,attempt:Qt,_pipelineContext:s._pipelineContext}),p,X):await this.executeBestOfCandidate({inputFiles:a,prompt:o,candidateIndex:X,operationId:c,config:u,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:f,skills:b,composio:v,timeoutMs:r,parentIndex:i,_pipelineContext:s._pipelineContext});return u.onCandidateComplete?.(i,X,Qe.status==="success"?"success":"error"),Qe})),C=p?await _(Q=>this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:k,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:w,parentIndex:i,attempt:Q,_pipelineContext:s._pipelineContext}),{...p,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:a,taskPrompt:o,candidates:k,config:u,timeoutMs:r,operationId:c,systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,mcpServers:g,skills:x,composio:w,parentIndex:i,_pipelineContext:s._pipelineContext}),S=k.findIndex(Q=>Q.status==="success"),U=C.decision?.winner??(S>=0?S:0),Ze=k[U]??k[0];u.onJudgeComplete?.(i,U,C.decision?.reasoning??"Judge failed to provide reasoning");let Zt={operationId:c,operation:"bestof-judge",tag:C.tag,sandboxId:C.sandboxId,swarmName:this.config.tag,operationName:s.name,candidateCount:d,...this.pipelineContextToMeta(s._pipelineContext)};return {...Ze,meta:{...Ze.meta,operation:"map",swarmName:this.config.tag,operationName:s.name,itemIndex:i,...this.pipelineContextToMeta(s._pipelineContext)},bestOf:{winnerIndex:U,judgeReasoning:C.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:Zt,candidates:k}}}async executeFilterItem(e,n,i,c,s,r,p=1){let a=this.getFiles(e),l=p>1?`${this.config.tag}-filter-${i}-er${p-1}`:`${this.config.tag}-filter-${i}`,o=s.mcpServers??this.config.mcpServers,u=s.skills??this.config.skills,d=s.composio??this.config.composio,m=await this.semaphore.use(()=>this.execute(a,n,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:o,skills:u,composio:d,tagPrefix:l,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),f={operationId:c,operation:"filter",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,errorRetry:p>1?p-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(m,f,a)}async executeFilterItemWithVerify(e,n,i,c,s,r,p){let a=this.getFiles(e),l=`${this.config.tag}-filter-${i}`,o=s.verify,u=s.mcpServers??this.config.mcpServers,d=s.skills??this.config.skills,m=s.composio??this.config.composio,f=async(g,h,b)=>{let x=await this.semaphore.use(()=>this.execute(a,g,{systemPrompt:s.systemPrompt,schema:s.schema,schemaOptions:s.schemaOptions,agent:s.agent,mcpServers:u,skills:d,composio:m,tagPrefix:h,timeoutMs:r,observability:{swarmName:this.config.tag,operationName:s.name,operationId:c,operation:"filter",itemIndex:i,role:"worker",verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(s._pipelineContext)}})),y={operationId:c,operation:"filter",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:s.name,itemIndex:i,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToMeta(s._pipelineContext)};return this.buildResult(x,y,a)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:a,verifyConfig:o,timeoutMs:r,systemPrompt:s.systemPrompt,schema:s.schema,mcpServers:u,skills:d,composio:m,operationId:c,baseTag:l,retry:p,itemIndex:i,operation:"filter",_pipelineContext:s._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:i,candidateIndex:c,operationId:s,config:r,timeoutMs:p,parentIndex:a,attempt:l=1,_pipelineContext:o}=e,u=a!==void 0?`${this.config.tag}-map-${a}-bestof-cand-${c}`:`${this.config.tag}-bestof-cand-${c}`,d=l>1?`${u}-er${l-1}`:u,m=await this.semaphore.use(()=>this.execute(n,i,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:r.taskAgents?.[c],mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:d,timeoutMs:p,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:a,role:"candidate",candidateIndex:c,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(o)}})),f={operationId:s,operation:"bestof-cand",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,itemIndex:c,errorRetry:l>1?l-1:void 0,candidateIndex:c,...this.pipelineContextToMeta(o)};return this.buildResult(m,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((i,c)=>{i.status==="error"&&(n[`candidate_${c}/_failed.txt`]=`STATUS: FAILED
|
|
218
218
|
|
|
219
|
-
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,r])=>{n[`candidate_${c}/${s}`]=r;});}),n}async executeBestOfJudge(e){let{candidates:n,config:i,timeoutMs:c,operationId:s,parentIndex:r,attempt:p=1,_pipelineContext:a}=e,l=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=p>1?`${l}-er${p-1}`:l,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),d=ge(u),m=I(je,{candidateCount:String(n.length),criteria:i.judgeCriteria,fileTree:d}),f=z$1.object({winner:z$1.number().min(0).max(n.length-1),reasoning:z$1.string()}),g=await this.semaphore.use(()=>this.execute(u,Rt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let b=JSON.parse(g.rawData);console.warn(`Judge returned invalid winner ${b.winner}, defaulting to candidate 0`),h={winner:0,reasoning:b.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${g.error}`);}return {status:h?"success":"error",decision:h,tag:g.tag,sandboxId:g.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=z$1.object({passed:z$1.boolean(),reasoning:z$1.string(),feedback:z$1.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,c])=>{n[`worker_output/${i}`]=c;}),n}async executeVerify(e){let{config:n,timeoutMs:i,operationId:c,workerTag:s,retryAttempt:r=1,operation:p,itemIndex:a,attemptIndex:l,_pipelineContext:o}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=n.verifierMcpServers??e.mcpServers,m=n.verifierSkills??e.skills,f=n.verifierComposio??e.composio,g=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=ge(g),b=I(Be,{criteria:n.criteria,fileTree:h}),x=await this.semaphore.use(()=>this.execute(g,Pt,{systemPrompt:b,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:c,operation:p,itemIndex:a,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(o)}})),y=null;if(x.data&&!x.error)y=x.data;else if(x.rawData)try{let v=JSON.parse(x.rawData);y={passed:!!v.passed,reasoning:v.reasoning??"Verification completed",feedback:v.feedback};}catch{console.warn(`Verify validation failed: ${x.error}`);}return {status:y?"success":"error",decision:y,tag:x.tag,sandboxId:x.sandboxId,error:y?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return I(Ke,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:i,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:p,baseTag:a,retry:l,itemIndex:o=0,operation:u,_pipelineContext:d}=n,m=s.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=i,g=null,h=0;for(;h<m;){h++;let x=h>1?`${a}-vr${h-1}`:a,y=l?await _(k=>e(f,k>1?`${x}-er${k-1}`:x,h),l,o):await e(f,x,h);if(s.onWorkerComplete?.(o,h,y.status==="error"?"error":"success"),y.status==="error")return y;g=y;let v=l?await _(k=>this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,retryAttempt:k,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),w={operationId:p,operation:"verify",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,v.decision?.passed??false,v.decision?.feedback),v.decision?.passed)return {...y,verify:{passed:true,reasoning:v.decision.reasoning,verifyMeta:w,attempts:h}};if(h<m){let k=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(i,k);}}let b=h>1?`${a}-vr${h-1}`:a;return {...g,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:p,operation:"verify",tag:`${b}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,i){if(typeof e=="string")return e;try{return e(n,i)}catch(c){return c}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=E(e.schema)?j(e.schema):B(e.schema)),Object.entries(e.inputFiles).forEach(([i,c])=>{n[`worker_task/input/${i}`]=c;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&$ in e&&e[$]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,i){let c=i??e.files;return e.error?{[$]:true,status:"error",data:null,files:c,meta:n,error:e.error,rawData:e.rawData}:{[$]:true,status:"success",data:e.data,files:c,meta:n}}buildErrorResult(e,n){return {[$]:true,status:"error",data:null,files:{},meta:n,error:e}}};var xe=class t{swarm;steps;events;constructor(e,n=[],i={}){this.swarm=e,this.steps=n,this.events=i;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new we(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=randomBytes(8).toString("hex"),i=[],c=e,s=Date.now();for(let p=0;p<this.steps.length;p++){let a=this.steps[p],l=a.config.name,o=Date.now();this.events.onStepStart?.({type:a.type,index:p,name:l,itemCount:c.length});let u={pipelineRunId:n,pipelineStepIndex:p};try{let d=await this.executeStep(a,c,p,l,u),m=Date.now()-o;if(i.push({type:a.type,index:p,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:p,name:l,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:n,steps:i,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:p,name:l,error:d instanceof Error?d:new Error(String(d))}),d}}let r=i[i.length-1];return {pipelineRunId:n,steps:i,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,i,c,s){if(e.type==="map"){let a=e.config,l=await this.swarm.map({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c),bestOf:this.wrapBestOf(a.bestOf,i,c)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,l=await this.swarm.filter({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c)}),o=a.emit??"success",u=o==="success"?l.success:o==="filtered"?l.filtered:[...l.success,...l.filtered];return {output:[...l],nextItems:u,successCount:l.success.length,errorCount:l.error.length,filteredCount:l.filtered.length}}let r=e.config,p=await this.swarm.reduce({items:n,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,c),verify:this.wrapVerify(r.verify,i,c)});return {output:p,nextItems:[],successCount:p.status==="success"?1:0,errorCount:p.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,i){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,n,i){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,p)=>{e.onVerifierComplete?.(c,s,r,p),this.events.onVerifierComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,passed:r,feedback:p});}}}wrapBestOf(e,n,i){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:n,stepName:i,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:n,stepName:i,itemIndex:c,winnerIndex:s,reasoning:r});}}}},we=class t extends xe{constructor(e,n,i){super(e,n,i);}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}map(){throw new Error("Cannot add steps after reduce")}filter(){throw new Error("Cannot add steps after reduce")}reduce(){throw new Error("Cannot add steps after reduce")}};export{Ce as AGENT_REGISTRY,Xt as AGENT_TYPES,q as Agent,Z as Evolve,je as JUDGE_PROMPT,xe as Pipeline,Ke as RETRY_FEEDBACK_PROMPT,Et as SCHEMA_PROMPT,$ as SWARM_RESULT_BRAND,Tt as SYSTEM_PROMPT,V as Semaphore,qe as Swarm,W as SwarmResultList,we as TerminalPipeline,ke as VALIDATION_PRESETS,Be as VERIFY_PROMPT,St as WORKSPACE_PROMPT,_t as WORKSPACE_SWE_PROMPT,I as applyTemplate,Ve as buildWorkerSystemPrompt,M as createAgentParser,re as createClaudeParser,ae as createCodexParser,ce as createGeminiParser,_ as executeWithRetry,Se as expandPath,P as getAgentConfig,L as getMcpSettingsDir,F as getMcpSettingsPath,en as isValidAgentType,E as isZodSchema,B as jsonSchemaToString,He as listCheckpoints,xn as parseNdjsonLine,wn as parseNdjsonOutput,nt as parseQwenOutput,dt as readLocalDir,be as resolveStorageConfig,mt as saveLocalDir,ne as writeClaudeMcpConfig,se as writeCodexMcpConfig,oe as writeGeminiMcpConfig,Pe as writeMcpConfig,ie as writeQwenMcpConfig,j as zodSchemaToJson};
|
|
219
|
+
Error: ${i.error??"Unknown error"}`),Object.entries(i.files).forEach(([s,r])=>{n[`candidate_${c}/${s}`]=r;});}),n}async executeBestOfJudge(e){let{candidates:n,config:i,timeoutMs:c,operationId:s,parentIndex:r,attempt:p=1,_pipelineContext:a}=e,l=r!==void 0?`${this.config.tag}-map-${r}-bestof-judge`:`${this.config.tag}-bestof-judge`,o=p>1?`${l}-er${p-1}`:l,u=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),d=ge(u),m=I(Be,{candidateCount:String(n.length),criteria:i.judgeCriteria,fileTree:d}),f=z$1.object({winner:z$1.number().min(0).max(n.length-1),reasoning:z$1.string()}),g=await this.semaphore.use(()=>this.execute(u,Rt,{systemPrompt:m,schema:f,agent:i.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,composio:e.composio,tagPrefix:o,timeoutMs:c,observability:{swarmName:this.config.tag,operationId:s,operation:"map",itemIndex:r,role:"judge",errorRetry:p>1?p-1:void 0,...this.pipelineContextToObservability(a)}})),h=null;if(g.data&&!g.error)h=g.data;else if(g.rawData)try{let b=JSON.parse(g.rawData);console.warn(`Judge returned invalid winner ${b.winner}, defaulting to candidate 0`),h={winner:0,reasoning:b.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${g.error}`);}return {status:h?"success":"error",decision:h,tag:g.tag,sandboxId:g.sandboxId,error:h?void 0:"Judge failed to produce valid decision"}}static DEFAULT_VERIFY_MAX_ATTEMPTS=3;static VerifyDecisionSchema=z$1.object({passed:z$1.boolean(),reasoning:z$1.string(),feedback:z$1.string().optional()});buildVerifyContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return Object.entries(e.outputFiles).forEach(([i,c])=>{n[`worker_output/${i}`]=c;}),n}async executeVerify(e){let{config:n,timeoutMs:i,operationId:c,workerTag:s,retryAttempt:r=1,operation:p,itemIndex:a,attemptIndex:l,_pipelineContext:o}=e,u=r>1?`${s}-verifier-er${r-1}`:`${s}-verifier`,d=n.verifierMcpServers??e.mcpServers,m=n.verifierSkills??e.skills,f=n.verifierComposio??e.composio,g=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=ge(g),b=I(je,{criteria:n.criteria,fileTree:h}),x=await this.semaphore.use(()=>this.execute(g,Pt,{systemPrompt:b,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:d,skills:m,composio:f,tagPrefix:u,timeoutMs:i,observability:{swarmName:this.config.tag,operationId:c,operation:p,itemIndex:a,role:"verifier",verifyRetry:l&&l>1?l-1:void 0,errorRetry:r>1?r-1:void 0,...this.pipelineContextToObservability(o)}})),y=null;if(x.data&&!x.error)y=x.data;else if(x.rawData)try{let v=JSON.parse(x.rawData);y={passed:!!v.passed,reasoning:v.reasoning??"Verification completed",feedback:v.feedback};}catch{console.warn(`Verify validation failed: ${x.error}`);}return {status:y?"success":"error",decision:y,tag:x.tag,sandboxId:x.sandboxId,error:y?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return I(Ke,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:i,inputFiles:c,verifyConfig:s,timeoutMs:r,operationId:p,baseTag:a,retry:l,itemIndex:o=0,operation:u,_pipelineContext:d}=n,m=s.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=i,g=null,h=0;for(;h<m;){h++;let x=h>1?`${a}-vr${h-1}`:a,y=l?await _(k=>e(f,k>1?`${x}-er${k-1}`:x,h),l,o):await e(f,x,h);if(s.onWorkerComplete?.(o,h,y.status==="error"?"error":"success"),y.status==="error")return y;g=y;let v=l?await _(k=>this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,retryAttempt:k,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),{...l,retryOn:void 0}):await this.executeVerify({inputFiles:c,outputFiles:y.files,taskPrompt:f,config:s,timeoutMs:r,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,composio:n.composio,operationId:p,workerTag:x,operation:u,itemIndex:o,attemptIndex:h,_pipelineContext:d}),w={operationId:p,operation:"verify",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)};if(s.onVerifierComplete?.(o,h,v.decision?.passed??false,v.decision?.feedback),v.decision?.passed)return {...y,verify:{passed:true,reasoning:v.decision.reasoning,verifyMeta:w,attempts:h}};if(h<m){let k=v.decision?.feedback??v.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(i,k);}}let b=h>1?`${a}-vr${h-1}`:a;return {...g,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:p,operation:"verify",tag:`${b}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(d)},attempts:h}}}generateOperationId(){return randomBytes(8).toString("hex")}pipelineContextToObservability(e){return e?{pipelineRunId:e.pipelineRunId,pipelineStepIndex:e.pipelineStepIndex}:{}}pipelineContextToMeta(e){return {pipelineRunId:e?.pipelineRunId,pipelineStepIndex:e?.pipelineStepIndex}}evaluatePrompt(e,n,i){if(typeof e=="string")return e;try{return e(n,i)}catch(c){return c}}buildEvaluatorContext(e){let n={};return e.systemPrompt&&(n["worker_task/system_prompt.txt"]=e.systemPrompt),n["worker_task/user_prompt.txt"]=e.taskPrompt,e.schema&&(n["worker_task/schema.json"]=E(e.schema)?B(e.schema):j(e.schema)),Object.entries(e.inputFiles).forEach(([i,c])=>{n[`worker_task/input/${i}`]=c;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&$ in e&&e[$]===true}getFiles(e){if(this.isSwarmResult(e)){let n={...e.files};return n["result.json"]&&(n["data.json"]=n["result.json"],delete n["result.json"]),n}return e}getIndex(e,n){return this.isSwarmResult(e)?e.meta.itemIndex:n}buildResult(e,n,i){let c=i??e.files;return e.error?{[$]:true,status:"error",data:null,files:c,meta:n,error:e.error,rawData:e.rawData}:{[$]:true,status:"success",data:e.data,files:c,meta:n}}buildErrorResult(e,n){return {[$]:true,status:"error",data:null,files:{},meta:n,error:e}}};var xe=class t{swarm;steps;events;constructor(e,n=[],i={}){this.swarm=e,this.steps=n,this.events=i;}map(e){return new t(this.swarm,[...this.steps,{type:"map",config:e}],this.events)}filter(e){return new t(this.swarm,[...this.steps,{type:"filter",config:e}],this.events)}reduce(e){return new we(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=randomBytes(8).toString("hex"),i=[],c=e,s=Date.now();for(let p=0;p<this.steps.length;p++){let a=this.steps[p],l=a.config.name,o=Date.now();this.events.onStepStart?.({type:a.type,index:p,name:l,itemCount:c.length});let u={pipelineRunId:n,pipelineStepIndex:p};try{let d=await this.executeStep(a,c,p,l,u),m=Date.now()-o;if(i.push({type:a.type,index:p,durationMs:m,results:d.output}),this.events.onStepComplete?.({type:a.type,index:p,name:l,durationMs:m,successCount:d.successCount,errorCount:d.errorCount,filteredCount:d.filteredCount}),a.type==="reduce")return {pipelineRunId:n,steps:i,output:d.output,totalDurationMs:Date.now()-s};c=d.nextItems;}catch(d){throw this.events.onStepError?.({type:a.type,index:p,name:l,error:d instanceof Error?d:new Error(String(d))}),d}}let r=i[i.length-1];return {pipelineRunId:n,steps:i,output:r?.results??[],totalDurationMs:Date.now()-s}}async executeStep(e,n,i,c,s){if(e.type==="map"){let a=e.config,l=await this.swarm.map({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c),bestOf:this.wrapBestOf(a.bestOf,i,c)});return {output:[...l],nextItems:l.success,successCount:l.success.length,errorCount:l.error.length,filteredCount:0}}if(e.type==="filter"){let a=e.config,l=await this.swarm.filter({items:n,...a,_pipelineContext:s,retry:this.wrapRetry(a.retry,i,c),verify:this.wrapVerify(a.verify,i,c)}),o=a.emit??"success",u=o==="success"?l.success:o==="filtered"?l.filtered:[...l.success,...l.filtered];return {output:[...l],nextItems:u,successCount:l.success.length,errorCount:l.error.length,filteredCount:l.filtered.length}}let r=e.config,p=await this.swarm.reduce({items:n,...r,_pipelineContext:s,retry:this.wrapRetry(r.retry,i,c),verify:this.wrapVerify(r.verify,i,c)});return {output:p,nextItems:[],successCount:p.status==="success"?1:0,errorCount:p.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,i){if(e)return {...e,onItemRetry:(c,s,r)=>{e.onItemRetry?.(c,s,r),this.events.onItemRetry?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,error:r});}}}wrapVerify(e,n,i){if(e)return {...e,onWorkerComplete:(c,s,r)=>{e.onWorkerComplete?.(c,s,r),this.events.onWorkerComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,status:r});},onVerifierComplete:(c,s,r,p)=>{e.onVerifierComplete?.(c,s,r,p),this.events.onVerifierComplete?.({stepIndex:n,stepName:i,itemIndex:c,attempt:s,passed:r,feedback:p});}}}wrapBestOf(e,n,i){if(e)return {...e,onCandidateComplete:(c,s,r)=>{e.onCandidateComplete?.(c,s,r),this.events.onCandidateComplete?.({stepIndex:n,stepName:i,itemIndex:c,candidateIndex:s,status:r});},onJudgeComplete:(c,s,r)=>{e.onJudgeComplete?.(c,s,r),this.events.onJudgeComplete?.({stepIndex:n,stepName:i,itemIndex:c,winnerIndex:s,reasoning:r});}}}},we=class t extends xe{constructor(e,n,i){super(e,n,i);}on(e,n){if(typeof e=="string"){let i=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[i]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}map(){throw new Error("Cannot add steps after reduce")}filter(){throw new Error("Cannot add steps after reduce")}reduce(){throw new Error("Cannot add steps after reduce")}};export{Ce as AGENT_REGISTRY,Xt as AGENT_TYPES,q as Agent,Z as Evolve,Be as JUDGE_PROMPT,xe as Pipeline,Ke as RETRY_FEEDBACK_PROMPT,Et as SCHEMA_PROMPT,$ as SWARM_RESULT_BRAND,Tt as SYSTEM_PROMPT,V as Semaphore,qe as Swarm,W as SwarmResultList,we as TerminalPipeline,ke as VALIDATION_PRESETS,je as VERIFY_PROMPT,St as WORKSPACE_PROMPT,_t as WORKSPACE_SWE_PROMPT,I as applyTemplate,Ve as buildWorkerSystemPrompt,M as createAgentParser,re as createClaudeParser,ae as createCodexParser,ce as createGeminiParser,_ as executeWithRetry,Se as expandPath,P as getAgentConfig,L as getMcpSettingsDir,F as getMcpSettingsPath,en as isValidAgentType,E as isZodSchema,j as jsonSchemaToString,He as listCheckpoints,xn as parseNdjsonLine,wn as parseNdjsonOutput,nt as parseQwenOutput,dt as readLocalDir,be as resolveStorageConfig,mt as saveLocalDir,ne as writeClaudeMcpConfig,se as writeCodexMcpConfig,oe as writeGeminiMcpConfig,Pe as writeMcpConfig,ie as writeQwenMcpConfig,B as zodSchemaToJson};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evolvingmachines/sdk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.26",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"ai",
|
|
6
6
|
"agents",
|
|
@@ -92,9 +92,9 @@
|
|
|
92
92
|
"dependencies": {
|
|
93
93
|
"@agentclientprotocol/sdk": "^0.5.1",
|
|
94
94
|
"@composio/core": "^0.5.1",
|
|
95
|
-
"@evolvingmachines/e2b": "
|
|
96
|
-
"@evolvingmachines/daytona": "
|
|
97
|
-
"@evolvingmachines/modal": "
|
|
95
|
+
"@evolvingmachines/e2b": ">=0.0.25",
|
|
96
|
+
"@evolvingmachines/daytona": ">=0.0.25",
|
|
97
|
+
"@evolvingmachines/modal": ">=0.0.25",
|
|
98
98
|
"ajv": "^8.17.1",
|
|
99
99
|
"p-map": "^7.0.2",
|
|
100
100
|
"zod": "^3.24.0",
|