@evolvingmachines/evolve 0.0.60 → 0.0.61
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/chunk-N2LMMVL4.js +427 -0
- package/dist/cli/index.cjs +38 -37
- package/dist/cli/index.d.cts +3 -1
- package/dist/cli/index.d.ts +3 -1
- package/dist/cli/index.js +29 -28
- package/dist/index.cjs +54 -54
- package/dist/index.d.cts +111 -7
- package/dist/index.d.ts +111 -7
- package/dist/index.js +38 -38
- package/dist/{types-DlpTxdR_.d.cts → types-CMEpx9QI.d.cts} +313 -5
- package/dist/{types-DlpTxdR_.d.ts → types-CMEpx9QI.d.ts} +313 -5
- package/hosted-error-codes.json +6 -0
- package/package.json +5 -5
- package/skills/evolve-evals/references/cli-reference/analysis.mdx +69 -0
- package/skills/evolve-evals/references/cli-reference/check.mdx +86 -0
- package/skills/evolve-evals/references/cli-reference/dataset.mdx +13 -0
- package/skills/evolve-evals/references/cli-reference/run.mdx +6 -0
- package/skills/evolve-evals/references/cli-reference/trial.mdx +71 -2
- package/skills/evolve-evals/references/core-concepts/trial-outputs.mdx +14 -0
- package/skills/evolve-evals/references/sdk/python.mdx +22 -0
- package/skills/evolve-evals/references/sdk/typescript.mdx +22 -0
- package/skills/evolve-evals/references/sdk-reference/analyses.mdx +70 -0
- package/skills/evolve-evals/references/sdk-reference/checks.mdx +105 -4
- package/skills/evolve-evals/references/sdk-reference/datasets.mdx +40 -0
- package/skills/evolve-evals/references/sdk-reference/errors.mdx +11 -0
- package/skills/evolve-evals/references/sdk-reference/jobs.mdx +1 -1
- package/skills/evolve-evals/references/sdk-reference/trials.mdx +70 -0
- package/spec/openapi.yaml +3021 -360
- package/dist/chunk-JS2UTK2I.js +0 -427
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var ac=require('zlib'),Q=require('fs'),promises=require('fs/promises'),os$1=require('os'),X=require('path'),promises$1=require('stream/promises'),tarStream=require('tar-stream'),crypto=require('crypto'),http=require('http'),https=require('https'),events=require('events'),xu=require('ajv'),smolToml=require('smol-toml'),child_process=require('child_process'),util=require('util'),Wc=require('zod-to-json-schema'),zod=require('zod'),e2b=require('@evolvingmachines/e2b'),daytona=require('@evolvingmachines/daytona'),modal=require('@evolvingmachines/modal'),stream=require('stream');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ac__default=/*#__PURE__*/_interopDefault(ac);var Q__namespace=/*#__PURE__*/_interopNamespace(Q);var X__namespace=/*#__PURE__*/_interopNamespace(X);var xu__default=/*#__PURE__*/_interopDefault(xu);var Wc__default=/*#__PURE__*/_interopDefault(Wc);var wl=Object.defineProperty;var ze=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ot=(t,e)=>{for(var n in e)wl(t,n,{get:e[n],enumerable:true});};var hr={};Ot(hr,{MAX_INLINE_ARCHIVE_BYTES:()=>vi,crc32Fallback:()=>wi,extractTarGz:()=>Pc,shouldStore:()=>_i,tarGzTopLevelName:()=>Ac,tarGzipDirectory:()=>Tc,tarGzipDirectoryToFile:()=>ki});async function kc(t){let e=[],n=async r=>{let s=r===""?t:X.join(t,r),o=await promises.readdir(s,{withFileTypes:true});o.sort((d,u)=>d.name<u.name?-1:d.name>u.name?1:0);for(let d of o){if(wc.has(d.name))continue;let u=r===""?d.name:`${r}/${d.name}`,l=X.join(s,d.name),i=await promises.lstat(l);i.isSymbolicLink()||(i.isDirectory()?await n(u):i.isFile()&&e.push({rel:u,abs:l,mode:i.mode&73?493:420,size:i.size}));}};return await n(""),e.sort((r,s)=>r.rel<s.rel?-1:r.rel>s.rel?1:0)}async function _i(t,e){if(e<vc)return false;let n=await promises.open(t,"r"),r;try{let o=Buffer.allocUnsafe(gi),{bytesRead:d}=await n.read(o,0,gi,0);r=o.subarray(0,d);}finally{await n.close();}return r.length===0?false:ac.deflateRawSync(r,{level:1}).length*20>=r.length*19}function wi(t,e=0){let n=~e;for(let r=0;r<t.length;r++)n=Cc[(n^t[r])&255]^n>>>8;return ~n>>>0}async function Ec(t){let e=Symbol("pending"),n=await Promise.race([t,Promise.resolve(e)]);return n===e?null:n}async function ki(t,e){let n=await kc(t),r=tarStream.pack(),s=Q.createWriteStream(e);s.on("error",()=>{}),r.on("error",()=>{});let o=new mr(s),d=r[Symbol.asyncIterator](),u=null,l=()=>u??=d.next();try{for(let{rel:i,abs:a,mode:c,size:p}of n){await o.setStored(await _i(a,p));let g=r.entry({name:i,size:p,mode:c,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"}),m=promises$1.pipeline(Q.createReadStream(a),g),f=!1,h=null;for(m.then(()=>{},()=>{}).then(()=>{f=!0,h?.(mi);});;){if(!f){let b=await new Promise((_,w)=>{h=_,l().then(_,w);});if(h=null,b===mi)continue;if(u=null,b.done)break;await o.write(b.value);continue}await new Promise(b=>setImmediate(b));let y=await Ec(l());if(y===null||(u=null,y.done))break;await o.write(y.value);}await m;}for(r.finalize();;){let i=await l();if(u=null,i.done)break;await o.write(i.value);}await o.close(),s.end(),await promises$1.finished(s);}catch(i){throw u?.catch(()=>{}),r.destroy(),s.destroy(),i}}async function Tc(t,e=vi){let n=await promises.mkdtemp(X.join(os$1.tmpdir(),"evolve-tar-"));try{let r=X.join(n,"archive.tar.gz");await ki(t,r);let{size:s}=await promises.stat(r);if(s>e)throw new Error(`directory ${t} tars to ${s} bytes compressed \u2014 over the ${e}-byte cap for in-memory archives. Only the sandbox skill mount uses this path; a skill folder this large is not mountable.`);return await promises.readFile(r)}finally{await promises.rm(n,{recursive:true,force:true});}}async function Pc(t,e,n){let r=tarStream.extract(),s=[],o=(async()=>{for await(let d of r){let u=d.header.name,l=u.split("/").filter(a=>a!==""&&a!==".");if(u.startsWith("/")||u.includes("\\")||l.length===0||l.some(a=>a===".."))throw new Error(`refusing to extract "${u}": the path escapes the target directory`);if(l[0]!==n)throw new Error(`refusing to extract "${u}": entry outside ${n}/`);if(d.header.type==="directory"){await promises.mkdir(X.join(e,...l),{recursive:true}),d.resume();continue}if(d.header.type!=="file")throw new Error(`refusing to extract "${u}": unsupported entry type "${d.header.type}"`);let i=X.join(e,...l);await promises.mkdir(X.dirname(i),{recursive:true}),await promises$1.pipeline(d,Q.createWriteStream(i)),s.push(l.join("/"));}})();try{await Promise.all([promises$1.pipeline(Q.createReadStream(t),ac.createGunzip(),r),o]);}catch(d){throw r.destroy(),d}return s}async function Ac(t){let e=tarStream.extract(),n=null,r=(async()=>{for await(let s of e){let o=s.header.name,d=o.split("/").filter(u=>u!==""&&u!==".");if(o.startsWith("/")||o.includes("\\")||d.length===0||d.some(u=>u===".."))throw new Error(`refusing to extract "${o}": the path escapes the target directory`);if(n===null)n=d[0];else if(d[0]!==n)throw new Error(`refusing to extract "${o}": the archive holds more than one top-level directory (${n}/)`);s.resume();}})();try{await Promise.all([promises$1.pipeline(Q.createReadStream(t),ac.createGunzip(),e),r]);}catch(s){throw e.destroy(),s}if(n===null)throw new Error("refusing to extract: the archive holds no entries");return n}var wc,vc,gi,Sc,xc,gr,Cc,Rc,mr,mi,vi,yr=ze(()=>{wc=new Set([".git",".DS_Store",".venv"]);vc=64*1024,gi=128*1024,Sc=65535,xc=1024*1024,gr=32*1024;Cc=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n;}return t})(),Rc=ac__default.default.crc32??wi,mr=class t{constructor(e){this.sink=e;}static HEADER=Buffer.from([31,139,8,0,0,0,0,0,0,255]);static FINAL_BLOCK=Buffer.from([1,0,0,255,255]);crc=0;plainLength=0;held=[];heldBytes=0;window=null;stored=false;started=false;async setStored(e){e!==this.stored&&(await this.drainHeld(true),this.stored=e);}async write(e){this.started||(this.started=true,await this.out(t.HEADER)),this.held.push(e),this.heldBytes+=e.length,await this.drainHeld(false);}async close(){this.started||(this.started=true,await this.out(t.HEADER)),await this.drainHeld(true),await this.out(t.FINAL_BLOCK);let e=Buffer.allocUnsafe(8);e.writeUInt32LE(this.crc>>>0,0),e.writeUInt32LE(this.plainLength%4294967296,4),await this.out(e);}async drainHeld(e){let n=this.stored?Sc:xc;for(;this.heldBytes>=n||e&&this.heldBytes>0;){let r=this.held.length===1?this.held[0]:Buffer.concat(this.held,this.heldBytes),s=Math.min(n,r.length),o=r.subarray(s);this.held=o.length>0?[o]:[],this.heldBytes=o.length,await this.emitBlock(r.subarray(0,s));}}async emitBlock(e){if(this.crc=Rc(e,this.crc),this.plainLength+=e.length,this.stored){let n=Buffer.allocUnsafe(5+e.length);n[0]=0,n.writeUInt16LE(e.length,1),n.writeUInt16LE(e.length^65535,3),e.copy(n,5),await this.out(n);}else await this.out(ac.deflateRawSync(e,{level:9,finishFlush:ac.constants.Z_SYNC_FLUSH,...this.window?{dictionary:this.window}:{}}));this.window=e.length>=gr?Buffer.from(e.subarray(e.length-gr)):this.window?Buffer.concat([this.window,e]).subarray(-gr):Buffer.from(e);}out(e){return new Promise((n,r)=>{this.sink.write(e,s=>s==null?n():r(s));})}},mi=Symbol("feed settled");vi=256*1024*1024;});var Li={};Ot(Li,{ManagedModalProvider:()=>Lr,ManagedModalWriteLimitError:()=>cn,_testManagedModalSandbox:()=>ed});function Zc(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return new Uint8Array(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);throw new Error(`Unsupported data type: ${typeof t}`)}function Ui(t){return {sandboxId:t.sandboxId,image:t.image??"",metadata:t.metadata??{},startedAt:t.startedAt??""}}var cn,dn,Dr,Ur,st,Lr,ed,$i=ze(()=>{cn=class extends Error{bytes;constructor(e,n){super(`Managed Modal ${e} body is ${n} bytes; the managed door caps every request at 1048576 bytes (1 MiB) of wire bytes, base64 inflation included. Split the payload into smaller writes.`),this.name="ManagedModalWriteLimitError",this.bytes=n;}};dn=class{constructor(e){this.config=e;}async request(e,n,r){let s=await fetch(`${this.config.baseUrl}${n}`,{...r,headers:{authorization:`Bearer ${this.config.apiKey}`,...r.headers??{}}});if(!s.ok){let o="";try{o=(await s.json())?.error??"";}catch{}throw new Error(`Managed Modal ${e} failed (${s.status})${o?`: ${o}`:""}`)}return s}json(e){return {method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}}},Dr=class{constructor(e,n){this.door=e;this.sandboxId=n;}async run(e,n){let r=await this.door.request("exec",`/sandboxes/${encodeURIComponent(this.sandboxId)}/exec`,this.door.json({command:e,...n?.cwd?{cwd:n.cwd}:{},...n?.envs?{envs:n.envs}:{},...n?.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}})),s="",o="",d,u=l=>{if(!l.trim())return;let i;try{i=JSON.parse(l);}catch{throw new Error(`Managed Modal exec stream carried a garbled record: ${l}`)}i.stream==="stdout"&&typeof i.data=="string"?(s+=i.data,n?.onStdout?.(i.data)):i.stream==="stderr"&&typeof i.data=="string"?(o+=i.data,n?.onStderr?.(i.data)):d=i;};if(r.body){let l=r.body.getReader(),i=new TextDecoder,a="";for(;;){let{done:c,value:p}=await l.read();if(c)break;a+=i.decode(p,{stream:true});let g;for(;(g=a.indexOf(`
|
|
2
2
|
`))!==-1;)u(a.slice(0,g)),a=a.slice(g+1);}a+=i.decode(),u(a);}else for(let l of (await r.text()).split(`
|
|
3
3
|
`))u(l);if(d?.error!==void 0)throw new Error(`Managed Modal exec failed: ${d.error}`);if(typeof d?.exitCode!="number")throw new Error("Managed Modal exec stream ended without a terminal record \u2014 the connection died mid-run.");return {exitCode:d.exitCode,stdout:s,stderr:o}}async spawn(e,n){let r=this.run(e,n);return r.catch(()=>{}),{processId:`managed-modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:()=>r,kill:async()=>false}}async list(){return (await this.run("ps -eo pid,comm,args")).stdout.trim().split(`
|
|
4
|
-
`).slice(1).filter(r=>r.trim()).map(r=>{let s=r.trim().split(/\s+/);return {processId:s[0],cmd:s[1]||"",args:s.slice(2),envs:{}}})}async kill(e){return /^\d+$/.test(e)?(await this.run(`kill -9 ${e}`)).exitCode===0:false}},
|
|
4
|
+
`).slice(1).filter(r=>r.trim()).map(r=>{let s=r.trim().split(/\s+/);return {processId:s[0],cmd:s[1]||"",args:s.slice(2),envs:{}}})}async kill(e){return /^\d+$/.test(e)?(await this.run(`kill -9 ${e}`)).exitCode===0:false}},Ur=class{constructor(e,n){this.door=e;this.sandboxId=n;}filesPath(e){return `/sandboxes/${encodeURIComponent(this.sandboxId)}/files/${e}`}encodeContent(e){return typeof e=="string"?{content:e}:{content:Buffer.from(Zc(e)).toString("base64"),encoding:"base64"}}boundedJson(e,n){let r=this.door.json(n),s=Buffer.byteLength(r.body,"utf8");if(s>1048576)throw new cn(e,s);return r}async read(e){let r=await(await this.door.request("file read",this.filesPath("read"),this.door.json({path:e}))).json();return r.encoding==="base64"?new Uint8Array(Buffer.from(r.content??"","base64")):r.content??""}async write(e,n){await this.door.request("file write",this.filesPath("write"),this.boundedJson("file write",{path:e,...this.encodeContent(n)}));}async writeBatch(e){e.length!==0&&await this.door.request("file writeBatch",this.filesPath("writeBatch"),this.boundedJson("file writeBatch",{files:e.map(n=>({path:n.path,...this.encodeContent(n.data)}))}));}async makeDir(e){await this.door.request("makeDir",this.filesPath("makeDir"),this.door.json({path:e}));}};st=class{constructor(e,n){this.door=e;this.sandboxId=n;this.commands=new Dr(e,n),this.files=new Ur(e,n);}commands;files;async getHost(e){throw new Error("Managed Modal sandboxes expose no tunnels, so getHost() is unavailable through the managed door.")}async kill(){try{await this.door.request("kill",`/sandboxes/${encodeURIComponent(this.sandboxId)}`,{method:"DELETE"});}catch(e){if(e instanceof Error&&e.message.includes("(404)"))return;throw e}}async pause(){throw new Error("Modal does not support pause/resume. Persist progress with Evolve checkpoints and resume in a fresh sandbox, or use kill() to terminate.")}async isRunning(){try{return await this.getInfo(),!0}catch(e){if(e instanceof Error&&e.message.includes("(404)"))return false;throw e}}async getInfo(){let e=await this.door.request("get",`/sandboxes/${encodeURIComponent(this.sandboxId)}`,{method:"GET"});return Ui(await e.json())}},Lr=class{providerType="modal";name="Managed Modal";door;constructor(e){this.door=new dn(e);}async create(e){if(e.resources!==void 0)throw new Error("Managed Modal sandboxes are platform-sized; `resources` cannot be enforced through the managed door.");if(e.network!==void 0)throw new Error("Managed Modal sandboxes run the platform's network policy; `network` cannot be enforced through the managed door.");if(e.user!==void 0)throw new Error("Managed Modal sandboxes run as the platform's sandbox user; `user` cannot be enforced through the managed door.");if(e.idleTimeoutMs!==void 0)throw new Error("The managed Modal door takes no idle timeout; bound the sandbox with `timeoutMs` instead.");if(e.bootCommand!==void 0)throw new Error("Managed Modal sandboxes boot the platform image as configured; `bootCommand` cannot be enforced through the managed door.");let r=await(await this.door.request("create","/sandboxes",this.door.json({...e.image?{image:e.image}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.workingDirectory?{workingDirectory:e.workingDirectory}:{},...e.envs?{envs:e.envs}:{},...e.metadata?{metadata:e.metadata}:{}}))).json();return new st(this.door,r.sandboxId)}async connect(e,n){let r=new st(this.door,e);return await r.getInfo(),r}async list(e){if(e?.state&&!e.state.includes("running"))return [];let s=((await(await this.door.request("list","/sandboxes",{method:"GET"})).json()).sandboxes??[]).map(Ui);if(e?.metadata){let o=Object.entries(e.metadata);s=s.filter(d=>o.every(([u,l])=>d.metadata[u]===l));}return e?.limit!==void 0&&(s=s.slice(0,e.limit)),s}async listAll(e){if(e?.state&&!e.state.includes("running"))return {sandboxes:[],complete:true,pagesFetched:0};let n;try{n=await this.list({...e,limit:void 0});}catch(o){return {sandboxes:[],complete:false,pagesFetched:0,error:`sandbox list failed: ${o instanceof Error?o.message:String(o)}`}}let r=e?.limit!==void 0?n.slice(0,e.limit):n,s=r.length<n.length;return {sandboxes:r,complete:!s,pagesFetched:1,...s?{error:`stopped at the requested limit of ${e?.limit} with more sandboxes available`}:{}}}},ed=(t,e)=>new st(new dn(t),e);});function kt(t,e){try{let o=JSON.parse(t)?.error?.retryAfterSec;if(typeof o=="number"&&Number.isFinite(o))return o}catch{}let n=e.headers?.get?.("retry-after");if(typeof n!="string"||n.trim()==="")return;let r=Number(n);return Number.isFinite(r)?r:void 0}var bs=ze(()=>{});var Ua={};Ot(Ua,{RESUMABLE_UPLOAD_CHUNK_BYTES:()=>Ia,RESUMABLE_UPLOAD_MAX_ATTEMPTS:()=>vt,RESUMABLE_UPLOAD_MAX_RATE_LIMIT_WAITS:()=>Oa,RESUMABLE_UPLOAD_MAX_RETRY_AFTER_SEC:()=>Ma,RESUMABLE_UPLOAD_THRESHOLD_BYTES:()=>St,retryAfterWaitMs:()=>Da,setResumableUploadThresholdBytes:()=>Qu,uploadArchiveResumable:()=>rp});function Qu(t){St=t;}async function ep(t){let e=await promises.open(t,"r");try{let n=crypto.createHash("sha256"),r=Buffer.alloc(1024*1024);for(;;){let{bytesRead:s}=await e.read(r,0,r.length);if(s===0)break;n.update(r.subarray(0,s));}return n.digest("hex")}finally{await e.close();}}function ws(t){return Math.min(500*2**(t-1),4e3)}function Da(t,e){let n=t===void 0?0:t*1e3;return Math.min(Math.max(n,ws(e)),Ma*1e3)}async function _s(t,e,n){let r=new AbortController,s=setTimeout(()=>r.abort(),n);s.unref?.();try{return await fetch(t,{...e,signal:r.signal})}finally{clearTimeout(s);}}async function Pn(t){for(let e=0;;e+=1){let n=await t();if(!tp(n)||e>=Oa)return n;let r=await n.text().catch(()=>"");await ks(Da(kt(r,n),e+1));}}function np(t,e,n){return new Promise((r,s)=>{let o=new URL(t),u=(o.protocol==="https:"?https.request:http.request)(o,{method:"POST",headers:e}),l=setTimeout(()=>{u.destroy(new Error(`finalize timed out: no response for ${Math.round(n/1e3)}s`));},n);l.unref?.(),u.on("error",i=>{clearTimeout(l),s(i);}),u.on("response",i=>{let a=[];i.on("data",c=>a.push(c)),i.on("error",c=>{clearTimeout(l),s(c);}),i.on("end",()=>{clearTimeout(l);let c=new Headers;for(let[m,f]of Object.entries(i.headers))if(typeof f=="string")c.set(m,f);else if(Array.isArray(f))for(let h of f)c.append(m,h);let p=i.statusCode??0,g=p!==204&&p!==205&&p!==304;r(new Response(g?Buffer.concat(a):null,{status:p,statusText:i.statusMessage??"",headers:c}));});}),u.end();})}async function rp(t){let e=t.timeoutMs??Zu,n=t.chunkBytes??Ia,{size:r}=await promises.stat(t.file.path),s=await ep(t.file.path),o=`${t.baseUrl}${t.sessionsPath??"/api/datasets/publish/uploads"}`,d={...t.headers,"Content-Type":"application/json"},u={size:r,sha256:s};for(let[g,m]of Object.entries(t.fields))m!==void 0&&(u[g]=m);let l=await Pn(()=>_s(o,{method:"POST",headers:d,body:JSON.stringify(u)},e));if(!l.ok)return l;let i=await l.json(),a=`${o}/${i.id}`;typeof i.import_id=="string"&&i.import_id!==""&&t.onRegistered?.(i.import_id);let c=async()=>{let g=await Pn(()=>_s(a,{method:"HEAD",headers:t.headers},e));if(!g.ok)throw new Error(`upload session probe failed: HTTP ${g.status}`);let m=Number(g.headers.get("upload-offset"));if(!Number.isInteger(m))throw new Error("upload session probe did not return Upload-Offset");return m},p=await promises.open(t.file.path,"r");try{let g=0,m=0,f=Buffer.alloc(n);for(;g<r;){let y=Math.min(n,r-g),{bytesRead:b}=await p.read(f,0,y,g);if(b!==y)throw new Error(`archive shrank mid-upload: read ${b} of ${y} bytes at offset ${g}`);let _=f.subarray(0,y),w=crypto.createHash("sha256").update(_).digest(),S;try{S=await Pn(()=>_s(a,{method:"PATCH",headers:{...t.headers,"Content-Type":"application/offset+octet-stream","Upload-Offset":String(g),"Upload-Checksum":`sha256 ${w.toString("base64")}`},body:new Uint8Array(_)},e));}catch(x){if(m+=1,m>=vt)throw x;await ks(ws(m));try{g=await c();}catch{}continue}if(S.status===409){if(m+=1,m>=vt)return S;g=await c();continue}if(!S.ok)return S;let v=Number(S.headers.get("upload-offset"));if(!Number.isInteger(v)||v<=g)throw new Error("resumable upload did not advance Upload-Offset");g=v,m=0,t.onBytes?.(g,r);}let h;for(let y=1;y<=vt;y++)try{return await Pn(()=>np(`${a}/complete`,t.headers,e))}catch(b){h=b,y<vt&&await ks(ws(y));}throw h}finally{await p.close();}}var St,Ia,vt,Oa,Ma,Zu,ks,tp,vs=ze(()=>{bs();St=256*1024*1024;Ia=6*1024*1024,vt=4,Oa=3,Ma=60,Zu=6e5;ks=t=>new Promise(e=>setTimeout(e,t));tp=t=>t.status===429||t.status===503;});var Ka={};Ot(Ka,{EvolveUploadTimeoutError:()=>exports.EvolveUploadTimeoutError,UPLOAD_TIMEOUT_MS:()=>As,postMultipartFile:()=>hp});function Ja(t,e){return new Promise((n,r)=>{t.write(e,s=>s?r(s):n());})}async function hp(t){let e=`----evolve${crypto.randomUUID().replace(/-/g,"")}`,n=[];for(let[_,w]of Object.entries(t.fields))w!==void 0&&n.push(`--${e}\r
|
|
5
5
|
Content-Disposition: form-data; name="${_}"\r
|
|
6
6
|
\r
|
|
7
7
|
${w}\r
|
|
@@ -11,23 +11,23 @@ Content-Type: application/gzip\r
|
|
|
11
11
|
\r
|
|
12
12
|
`);let r=Buffer.from(n.join(""),"utf8"),s=Buffer.from(`\r
|
|
13
13
|
--${e}--\r
|
|
14
|
-
`,"utf8"),{size:o}=await promises.stat(t.file.path),d=new URL(t.url),l=(d.protocol==="https:"?https.request:http.request)(d,{method:t.method,headers:{...t.headers,"Content-Type":`multipart/form-data; boundary=${e}`,"Content-Length":String(r.length+o+s.length)}}),i=t.timeoutMs??Ss,a,c,p=new Promise((_,w)=>{c=w;});p.catch(()=>{});let g=_=>Promise.race([_,p]),f,m=()=>{f!==void 0&&clearTimeout(f),f=setTimeout(()=>{a=new exports.EvolveUploadTimeoutError(t.url,i),l.destroy(a),c(a);},i),f.unref();};l.on("error",_=>c(a??_)),m();let h,y=new Promise((_,w)=>{l.on("response",S=>{h=S,m(),_(S);}),l.on("error",S=>{h===void 0&&w(S);});});y.catch(()=>{});let b=Q.createReadStream(t.file.path);try{let _=(async()=>{await Da(l,r),m();let P=0;for await(let I of b)await Da(l,I),m(),P+=I.length,t.onBytes?.(P,o);await new Promise(I=>{l.end(s,I);});})();try{await g(_);}catch(P){if(b.destroy(),h===void 0)throw l.destroy(),a??P}let w=await g(y).catch(P=>{throw a??P}),S=(async()=>{let P=[];for await(let I of w)m(),P.push(I);return Buffer.concat(P)})(),k=await g(S).catch(P=>{throw a??P}),x=w.statusCode??0,R=new Headers;for(let[P,I]of Object.entries(w.headers))if(typeof I=="string")R.set(P,I);else if(Array.isArray(I))for(let we of I)R.append(P,we);let T=x!==204&&x!==205&&x!==304;return new Response(T?k:null,{status:x,statusText:w.statusMessage??"",headers:R})}finally{f!==void 0&&clearTimeout(f);}}var Ss;exports.EvolveUploadTimeoutError=void 0;var xs=ze(()=>{Ss=6e5,exports.EvolveUploadTimeoutError=class extends Error{name="EvolveUploadTimeoutError";constructor(e,n){super(`upload to ${e} timed out: no socket activity for ${Math.round(n/1e3)}s`);}};});var cl={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},Un=["no-internet","pinned-context"],$n={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}},dl=["timeoutMs","background","from","checkpointComment","resume"];function q(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Ot(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||E;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}var ke=["e2b","daytona","modal"];function He(t){return Ot(`/api/managed/${t}`)}function Ms(){return `${He("daytona")}/toolbox`}function Ln(){return He("e2b")}function Ds(t){return {"browser-use":{type:"http",url:q("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var O="EVOLVE_API_KEY",Mt="E2B_API_KEY",Dt="DAYTONA_API_KEY",Ut="MODAL_TOKEN_ID",Bn="MODAL_TOKEN_SECRET",Nn="claude",qe=36e5,Us=4,jn=100,W="/home/user";function $s(t,e){return e?e.replace(/\/+$/,"")||"/":t?t==="root"?"/root":`/home/${t}`:W}var E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",z="x-litellm-customer-id",te="x-litellm-tags",fe="run:",Ls=".evolve-sdk/observability/sessions",We=["tag","provider","agent","model","sandboxId","sandbox_id","timestamp","event","events"],Bs=100,Ns=5e3,$t=3,Fn=1e3;var Fs=["off","minimal","low","medium","high","xhigh","max","thinking"],js=2e5,Js=["off","minimal","medium","thinking"],Ks="medium";function ul(t){return t==="none"?{efforts:[],defaultEffort:null}:{efforts:t==="binary"?Js:Fs,defaultEffort:Ks}}function Vs(t,e){return e??J[t]?.defaultReasoningEffort}function Xe(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function Jn(t){if(!(t==="off"||t==="none"||t==="no-thinking"))return !t||t==="thinking"||t==="medium"?"medium":t==="low"||t==="minimal"?"minimal":t==="xhigh"?"max":t}function pl(t){let e=Jn(t);return e?` --variant ${e} --thinking`:""}var J={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",effortSupport:"level",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",defaultReasoningEffort:"high",models:[{alias:"fable",modelId:"claude-fable-5-1",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-5",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-5",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"},{alias:"opus[1m]",modelId:"opus[1m]",description:"Complex reasoning with 1M context window"},{alias:"sonnet[1m]",modelId:"sonnet[1m]",description:"Daily coding with 1M context window"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"},{alias:"openrouter/deepseek/deepseek-v4.1-flash",modelId:"openrouter/deepseek/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via OpenRouter"},{alias:"fireworks/deepseek-v4.1-flash",modelId:"fireworks/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via Fireworks"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},nativeConfig:{format:"json",path:"~/.claude/evolve-user-settings.json",delivery:"settings-flag"},presets:{"no-internet":{configStamp:{permissions:{deny:["WebSearch","WebFetch"]}}},"pinned-context":{configStamp:{autoCompactEnabled:true,autoCompactWindow:js}}},skillsConfig:{targetDir:"~/.claude/skills"},buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:r,nativeConfigPath:s})=>{let o=n?"--continue ":"",d=r?` --effort ${r}`:"",u=s?` --settings ${s}`:"";return `echo "${t}" | claude -p ${o}--model ${e}${d}${u} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",effortSupport:"level",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.6-sol",defaultReasoningEffort:"high",models:[{alias:"gpt-6-astra",modelId:"gpt-6-astra",description:"Newest frontier flagship"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"GPT-5.6 flagship (previous generation)"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Balances intelligence and cost"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"High-volume, cost-sensitive tier"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"GPT-5.5 frontier model (two generations back)"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},nativeConfig:{format:"toml",path:"~/.codex/config.toml",delivery:"base-file"},presets:{"no-internet":{commandFlags:" -c web_search=disabled"},"pinned-context":{commandFlags:` -c model_context_window=${js}`}},skillsConfig:{targetDir:"~/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:r,presetFlags:s})=>{let o=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${o}${s??""} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",effortSupport:"none",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.5-flash",models:[{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest flash the stable gemini CLI serves: coding + agentic planning"},{alias:"gemini-3.5-flash-lite",modelId:"gemini-3.5-flash-lite",description:"Most cost-effective 3.5-class model"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${Ye(t)} --model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",effortSupport:"binary",defaultModel:"qwen3.7-max",defaultReasoningEffort:"thinking",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r})=>{let s=n?"--continue ":"",o=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${o} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",effortSupport:"level",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k3",defaultReasoningEffort:"max",models:[{alias:"kimi-k3",modelId:"moonshot/kimi-k3",description:"Latest flagship: 1M context, always-on thinking",maxContextSize:1048576},{alias:"kimi-k2.7-code",modelId:"moonshot/kimi-k2.7-code",description:"Latest coding-specialized standard model"},{alias:"kimi-k3-raptor",modelId:"kimi-k3-raptor",description:"Evolve-managed Kimi K3 Raptor route for latency-sensitive agent runs",maxContextSize:1048576},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","kimi-k2.7-code":"moonshot/kimi-k2.7-code","kimi-k3-raptor":"kimi-k3-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n,homeDir:r=W})=>{let s=e?"--continue ":"",o=Ye(t),d=`--config-file ${r}/.kimi-code/config.toml`,u=`$(if [ -f ${r}/.kimi-code/mcp.json ]; then printf ' --mcp-config-file ${r}/.kimi-code/mcp.json'; fi)`,l=Xe(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${s}${d}${u}${l} -p ${o} --output-format stream-json; else kimi ${s}-p ${o} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",effortSupport:"level",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-opus-5",defaultReasoningEffort:"high",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5.1",modelId:"openrouter/anthropic/claude-fable-5.1",description:"Anthropic Fable 5.1 via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-5",modelId:"openrouter/anthropic/claude-opus-5",description:"Anthropic Opus 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-5",modelId:"openrouter/anthropic/claude-sonnet-5",description:"Anthropic Sonnet 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-6-astra",modelId:"openrouter/openai/gpt-6-astra",description:"OpenAI GPT-6 Astra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-sol",modelId:"openrouter/openai/gpt-5.6-sol",description:"OpenAI GPT-5.6 Sol via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-terra",modelId:"openrouter/openai/gpt-5.6-terra",description:"OpenAI GPT-5.6 Terra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-luna",modelId:"openrouter/openai/gpt-5.6-luna",description:"OpenAI GPT-5.6 Luna via OpenRouter"},{alias:"openrouter/google/gemini-3.6-flash",modelId:"openrouter/google/gemini-3.6-flash",description:"Gemini 3.6 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3.7-max",modelId:"openrouter/qwen/qwen3.7-max",description:"Qwen 3.7 Max via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k3",modelId:"openrouter/moonshotai/kimi-k3",description:"Kimi K3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3",modelId:"openrouter/z-ai/glm-5.3",description:"Zhipu GLM-5.3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3-flash",modelId:"openrouter/z-ai/glm-5.3-flash",description:"Zhipu GLM-5.3 Flash (OpenRouter id; the Evolve gateway serves it from Fireworks)"},{alias:"openrouter/deepseek/deepseek-v4.1-flash",modelId:"openrouter/deepseek/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via OpenRouter"},{alias:"fireworks/deepseek-v4.1-flash",modelId:"fireworks/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via Fireworks"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{targetDir:"~/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,isExternalGateway:s,reasoningEffort:o})=>{let d=n?"--continue ":"",u=pl(o);if(s)return `OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${d}--model litellm/${e} --format json${u} "${t}" < /dev/null`;let l=gl(e);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${d}--model ${l} --format json${u} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${d}--model litellm/${l} --format json${u} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",effortSupport:"level",defaultModel:"claude-opus-5",defaultReasoningEffort:"high",models:[{alias:"claude-fable-5.1",modelId:"claude-fable-5-1",description:"Factory-managed Claude Fable 5.1"},{alias:"claude-opus-5",modelId:"claude-opus-5",description:"Factory-managed Claude Opus 5"},{alias:"claude-sonnet-5",modelId:"claude-sonnet-5",description:"Factory-managed Claude Sonnet 5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-6-astra",modelId:"gpt-6-astra",description:"Factory-managed GPT-6 Astra"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Factory-managed GPT-5.6 Sol"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Factory-managed GPT-5.6 Terra"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"Factory-managed GPT-5.6 Luna"},{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Factory-managed Gemini 3.6 Flash"},{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Qwen 3.7 Max via the Evolve gateway"},{alias:"kimi-k3",modelId:"kimi-k3",description:"Factory-managed Droid Core Kimi K3"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"},{alias:"openrouter/deepseek/deepseek-v4.1-flash",modelId:"openrouter/deepseek/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via OpenRouter"},{alias:"fireworks/deepseek-v4.1-flash",modelId:"fireworks/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via Fireworks"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"claude-fable-5.1":"claude-fable-5-1","kimi-k3":"moonshot/kimi-k3","glm-5.3":"openrouter/z-ai/glm-5.3","qwen3.7-max":"dashscope/qwen3.7-max"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:t,model:e,isResume:n,sessionId:r,reasoningEffort:s,isDirectMode:o,isExternalGateway:d,homeDir:u=W})=>{let l=!o||d,i=l?`--settings ${u}/.factory/evolve-settings.json `:"",a=l?"custom:Evolve-Gateway-0":e,c=s?` --reasoning-effort ${s}`:"",p=n&&r?`--session-id ${Ye(r)} `:"";return `printf '%s' ${Ye(t)} | droid ${i}exec ${p}--skip-permissions-unsafe --cwd ${u}/workspace --output-format stream-json --model ${Ye(a)}${c}`}}};function K(t){let e=J[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function ve(t,e){if(t.models.some(s=>s.alias===e||s.modelId===e))return true;let n=t.gatewayModelAliases;if(n&&(e in n||Object.values(n).includes(e)))return true;let r=t.directModelAliases;return !!(r&&(e in r||Object.values(r).includes(e)))}function Gs(t,e){return t.models.find(n=>n.alias===e)?.modelId??e}function gl(t){return t.startsWith("openrouter/")||ve(J.opencode,t)?t:`openrouter/${t}`}function Kn(t){return t in J}function N(t,e=W){return t.replace(/^~/,e)}function Ye(t){return `'${t.replace(/'/g,"'\\''")}'`}function ne(t,e=W){let n=K(t);return `${N(n.mcpConfig.settingsDir,e)}/${n.mcpConfig.filename}`}function re(t,e=W){let n=K(t);return N(n.mcpConfig.settingsDir,e)}function se(t){if(t instanceof Error){let e=t.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function Vn(t,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${t}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${t}" cannot specify both command and url`)}function Qe(t){for(let[e,n]of Object.entries(t))Vn(e,n);}function Ze(t){return t.type?t.type:t.command?"stdio":"sse"}function fl(t){let e=Ze(t);return {...t,type:e}}function ml(t){let{type:e,url:n,...r}=t;return Ze(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function hl(t){return {type:Ze(t),...t}}function yl(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function bl(t){let e=Ze(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:o,envVars:d,...u}=t;if(e==="stdio"&&t.command)return {type:"stdio",...u};if(t.url){let l={...u,type:e==="sse"?"sse":"http",url:t.url},i=t.headers??r;return i&&Object.keys(i).length>0&&(l.headers=i),l}return {type:e==="stdio"?"stdio":"http",...u}}async function Gn(t,e,n,r,s){Qe(n);let o=re(e,s),d=ne(e,s);await t.files.makeDir(o);let u={};try{let i=await t.files.read(d);typeof i=="string"&&(u=JSON.parse(i));}catch(i){if(!se(i))throw i}let l=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,r(a)]));await t.files.write(d,JSON.stringify({...u,mcpServers:l},null,2));}async function Lt(t,e,n,r){Qe(n);let s=re("claude",r),o=ne("claude",r),d=Object.fromEntries(Object.entries(n).map(([l,i])=>[l,hl(i)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:d},null,2)),await t.files.makeDir(s);let u={};try{let l=await t.files.read(o);typeof l=="string"&&(u=JSON.parse(l));}catch(l){if(!se(l))throw l}u.enableAllProjectMcpServers=true,await t.files.write(o,JSON.stringify(u,null,2));}async function Bt(t,e,n){await Gn(t,"gemini",e,fl,n);}async function Nt(t,e,n){await Gn(t,"qwen",e,ml,n);}async function jt(t,e,n,r,s){let o=re(e,s),d=ne(e,s);await t.files.makeDir(o);let u={};try{let p=await t.files.read(d);typeof p=="string"&&(u=JSON.parse(p));}catch(p){if(!se(p))throw p}let l=n.split("."),i=u;for(let p=0;p<l.length-1;p++){let g=l[p];(typeof i[g]!="object"||i[g]===null)&&(i[g]={}),i=i[g];}let a=l[l.length-1],c=typeof i[a]=="object"&&i[a]!==null?i[a]:{};i[a]={...c,...r},await t.files.write(d,JSON.stringify(u,null,2));}async function zn(t,e,n){let r=re("qwen",n),s=ne("qwen",n);await t.files.makeDir(r);let o={};try{let i=await t.files.read(s);typeof i=="string"&&(o=JSON.parse(i));}catch(i){if(!se(i))throw i}let d=o.model??{},u=d.generationConfig??{},l=u.extra_body??{};o.model={...d,generationConfig:{...u,extra_body:{...l,enable_thinking:e}}},await t.files.write(s,JSON.stringify(o,null,2));}async function Hn(t,e,n){await Gn(t,"kimi",e,yl,n);}async function Ft(t,e,n){Qe(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let o={};try{let u=await t.files.read(s);typeof u=="string"&&(o=JSON.parse(u));}catch(u){if(!se(u))throw u}let d=Object.fromEntries(Object.entries(n).map(([u,l])=>[u,bl(l)]));await t.files.write(s,JSON.stringify({...o,mcpServers:d},null,2));}async function Jt(t,e,n,r){let s=N(e.settingsPath,r),o=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(o);let d={cloudSessionSync:false,customModels:[{model:e.model,displayName:e.displayName,baseUrl:e.baseUrl,apiKey:`\${${e.apiKeyEnv}}`,provider:e.provider,...e.maxOutputTokens!==void 0&&{maxOutputTokens:e.maxOutputTokens},extraHeaders:n}]};await t.files.write(s,JSON.stringify(d,null,2));}async function qn(t,e,n){Qe(n);let r=`${e}/opencode.json`,s={};try{let d=await t.files.read(r);typeof d=="string"&&(s=JSON.parse(d));}catch(d){if(!se(d))throw d}let o=Object.fromEntries(Object.entries(n).map(([d,u])=>[d,_l(u)]));await t.files.write(r,JSON.stringify({...s,mcp:o},null,2));}function _l(t){let e=Ze(t);if(e==="stdio"&&t.command){let r={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(r.environment=t.env),r}if(t.url){let n={type:"remote",url:t.url};return t.headers&&Object.keys(t.headers).length>0&&(n.headers=t.headers),n}return {type:e==="stdio"?"local":"remote",...t}}function Wn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function zs(t,e,n){let r=t[e];if(r===void 0)return {};let s=Wn(r);if(!s){let o=Array.isArray(r)?"an array":`a ${typeof r}`;throw new Error(`Refusing to rewrite "${e}" in ${n}: expected a TOML table, found ${o}`)}return s}function Yn(t,e){if(t===e)return true;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,d)=>Yn(o,e[d]));let n=Wn(t),r=Wn(e);if(!n||!r)return false;let s=Object.keys(n);return s.length===Object.keys(r).length&&s.every(o=>o in r&&Yn(n[o],r[o]))}async function Hs(t,e){let n="";try{let r=await t.files.read(e);typeof r=="string"&&(n=r);}catch(r){if(!se(r))throw r;return {}}if(!n.trim())return {};try{return smolToml.parse(n)}catch(r){throw new Error(`Failed to parse TOML at ${e}: ${r.message}`)}}async function Xn(t,e,n){await t.files.write(e,smolToml.stringify(n).trimEnd()+`
|
|
15
|
-
`);}function
|
|
16
|
-
`);p.push({sessionUpdate:"error",message:D([h,a.result,a.subtype],a),fatal:true});}return e(p,a,c)}default:return null}};function e(l,i,a){if(!l||l.length===0)return null;let c=i.message,p=ue(i.timestamp),g=typeof c?.model=="string"&&c.model?c.model:void 0,
|
|
14
|
+
`,"utf8"),{size:o}=await promises.stat(t.file.path),d=new URL(t.url),l=(d.protocol==="https:"?https.request:http.request)(d,{method:t.method,headers:{...t.headers,"Content-Type":`multipart/form-data; boundary=${e}`,"Content-Length":String(r.length+o+s.length)}}),i=t.timeoutMs??As,a,c,p=new Promise((_,w)=>{c=w;});p.catch(()=>{});let g=_=>Promise.race([_,p]),m,f=()=>{m!==void 0&&clearTimeout(m),m=setTimeout(()=>{a=new exports.EvolveUploadTimeoutError(t.url,i),l.destroy(a),c(a);},i),m.unref();};l.on("error",_=>c(a??_)),f();let h,y=new Promise((_,w)=>{l.on("response",S=>{h=S,f(),_(S);}),l.on("error",S=>{h===void 0&&w(S);});});y.catch(()=>{});let b=Q.createReadStream(t.file.path);try{let _=(async()=>{await Ja(l,r),f();let P=0;for await(let I of b)await Ja(l,I),f(),P+=I.length,t.onBytes?.(P,o);await new Promise(I=>{l.end(s,I);});})();try{await g(_);}catch(P){if(b.destroy(),h===void 0)throw l.destroy(),a??P}let w=await g(y).catch(P=>{throw a??P}),S=(async()=>{let P=[];for await(let I of w)f(),P.push(I);return Buffer.concat(P)})(),v=await g(S).catch(P=>{throw a??P}),x=w.statusCode??0,R=new Headers;for(let[P,I]of Object.entries(w.headers))if(typeof I=="string")R.set(P,I);else if(Array.isArray(I))for(let ke of I)R.append(P,ke);let E=x!==204&&x!==205&&x!==304;return new Response(E?v:null,{status:x,statusText:w.statusMessage??"",headers:R})}finally{m!==void 0&&clearTimeout(m);}}var As;exports.EvolveUploadTimeoutError=void 0;var Is=ze(()=>{As=6e5,exports.EvolveUploadTimeoutError=class extends Error{name="EvolveUploadTimeoutError";constructor(e,n){super(`upload to ${e} timed out: no socket activity for ${Math.round(n/1e3)}s`);}};});var kl={CLAUDE:"claude",CODEX:"codex",GEMINI:"gemini",QWEN:"qwen",KIMI:"kimi",OPENCODE:"opencode",DROID:"droid"},Bn=["no-internet","pinned-context"],Nn={strict:{coerceTypes:false,removeAdditional:false,useDefaults:false,allErrors:true},loose:{coerceTypes:"array",removeAdditional:false,useDefaults:true,allErrors:true}},vl=["timeoutMs","background","from","checkpointComment","resume"];function q(t=""){let e=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e}${n}`}function Mt(t=""){let e=process.env.EVOLVE_DASHBOARD_URL||T;if(!t)return e;let n=t.startsWith("/")?t:`/${t}`;return `${e.replace(/\/$/,"")}${n}`}var ve=["e2b","daytona","modal"];function qe(t){return Mt(`/api/managed/${t}`)}function Ns(){return `${qe("daytona")}/toolbox`}function jn(){return qe("e2b")}function js(t){return {"browser-use":{type:"http",url:q("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${t}`}}}}var O="EVOLVE_API_KEY",Dt="E2B_API_KEY",Ut="DAYTONA_API_KEY",Lt="MODAL_TOKEN_ID",Jn="MODAL_TOKEN_SECRET",Kn="claude",We=36e5,Js=4,Gn=100,W="/home/user";function Ks(t,e){return e?e.replace(/\/+$/,"")||"/":t?t==="root"?"/root":`/home/${t}`:W}var T=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",H="x-litellm-customer-id",te="x-litellm-tags",me="run:",Gs=".evolve-sdk/observability/sessions",Ye=["tag","provider","agent","model","sandboxId","sandbox_id","timestamp","event","events"],Vs=100,Hs=5e3,$t=3,Vn=1e3;var qs=["off","minimal","low","medium","high","xhigh","max","thinking"],zs=2e5,Ws=["off","minimal","medium","thinking"],Ys="medium";function Sl(t){return t==="none"?{efforts:[],defaultEffort:null}:{efforts:t==="binary"?Ws:qs,defaultEffort:Ys}}function Xs(t,e){return e??J[t]?.defaultReasoningEffort}function Qe(t){return t!=="off"&&t!=="none"&&t!=="minimal"&&t!=="no-thinking"}function Hn(t){if(!(t==="off"||t==="none"||t==="no-thinking"))return !t||t==="thinking"||t==="medium"?"medium":t==="low"||t==="minimal"?"minimal":t==="xhigh"?"max":t}function xl(t){let e=Hn(t);return e?` --variant ${e} --thinking`:""}var J={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",effortSupport:"level",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",defaultReasoningEffort:"high",models:[{alias:"fable",modelId:"claude-fable-5-1",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-5",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-5",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"},{alias:"opus[1m]",modelId:"opus[1m]",description:"Complex reasoning with 1M context window"},{alias:"sonnet[1m]",modelId:"sonnet[1m]",description:"Daily coding with 1M context window"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"},{alias:"openrouter/deepseek/deepseek-v4.1-flash",modelId:"openrouter/deepseek/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via OpenRouter"},{alias:"fireworks/deepseek-v4.1-flash",modelId:"fireworks/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via Fireworks"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:true},nativeConfig:{format:"json",path:"~/.claude/evolve-user-settings.json",delivery:"settings-flag"},presets:{"no-internet":{configStamp:{permissions:{deny:["WebSearch","WebFetch"]}}},"pinned-context":{configStamp:{autoCompactEnabled:true,autoCompactWindow:zs}}},skillsConfig:{targetDir:"~/.claude/skills"},buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:r,nativeConfigPath:s})=>{let o=n?"--continue ":"",d=r?` --effort ${r}`:"",u=s?` --settings ${s}`:"";return `echo "${t}" | claude -p ${o}--model ${e}${d}${u} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",effortSupport:"level",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.6-sol",defaultReasoningEffort:"high",models:[{alias:"gpt-6-astra",modelId:"gpt-6-astra",description:"Newest frontier flagship"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"GPT-5.6 flagship (previous generation)"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Balances intelligence and cost"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"High-volume, cost-sensitive tier"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"GPT-5.5 frontier model (two generations back)"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},nativeConfig:{format:"toml",path:"~/.codex/config.toml",delivery:"base-file"},presets:{"no-internet":{commandFlags:" -c web_search=disabled"},"pinned-context":{commandFlags:` -c model_context_window=${zs}`}},skillsConfig:{targetDir:"~/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:t,model:e,isResume:n,reasoningEffort:r,presetFlags:s})=>{let o=r?` -c model_reasoning_effort="${r}"`:"";return `printf '%s' "${t}" | codex exec --model ${e}${o}${s??""} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",effortSupport:"none",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.5-flash",models:[{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest flash the stable gemini CLI serves: coding + agentic planning"},{alias:"gemini-3.5-flash-lite",modelId:"gemini-3.5-flash-lite",description:"Most cost-effective 3.5-class model"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:t,model:e,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${Xe(t)} --model ${e} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",effortSupport:"binary",defaultModel:"qwen3.7-max",defaultReasoningEffort:"thinking",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r})=>{let s=n?"--continue ":"",o=r||e.startsWith("dashscope/")?e:`dashscope/${e}`;return `qwen "${t}" ${s}--auth-type openai --model ${o} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",effortSupport:"level",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k3",defaultReasoningEffort:"max",models:[{alias:"kimi-k3",modelId:"moonshot/kimi-k3",description:"Latest flagship: 1M context, always-on thinking",maxContextSize:1048576},{alias:"kimi-k2.7-code",modelId:"moonshot/kimi-k2.7-code",description:"Latest coding-specialized standard model"},{alias:"kimi-k3-raptor",modelId:"kimi-k3-raptor",description:"Evolve-managed Kimi K3 Raptor route for latency-sensitive agent runs",maxContextSize:1048576},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","kimi-k2.7-code":"moonshot/kimi-k2.7-code","kimi-k3-raptor":"kimi-k3-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor"},buildCommand:({prompt:t,isResume:e,reasoningEffort:n,homeDir:r=W})=>{let s=e?"--continue ":"",o=Xe(t),d=`--config-file ${r}/.kimi-code/config.toml`,u=`$(if [ -f ${r}/.kimi-code/mcp.json ]; then printf ' --mcp-config-file ${r}/.kimi-code/mcp.json'; fi)`,l=Qe(n)?"":" --no-thinking";return `if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${s}${d}${u}${l} -p ${o} --output-format stream-json; else kimi ${s}-p ${o} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",effortSupport:"level",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-opus-5",defaultReasoningEffort:"high",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5.1",modelId:"openrouter/anthropic/claude-fable-5.1",description:"Anthropic Fable 5.1 via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-5",modelId:"openrouter/anthropic/claude-opus-5",description:"Anthropic Opus 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-5",modelId:"openrouter/anthropic/claude-sonnet-5",description:"Anthropic Sonnet 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-6-astra",modelId:"openrouter/openai/gpt-6-astra",description:"OpenAI GPT-6 Astra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-sol",modelId:"openrouter/openai/gpt-5.6-sol",description:"OpenAI GPT-5.6 Sol via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-terra",modelId:"openrouter/openai/gpt-5.6-terra",description:"OpenAI GPT-5.6 Terra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-luna",modelId:"openrouter/openai/gpt-5.6-luna",description:"OpenAI GPT-5.6 Luna via OpenRouter"},{alias:"openrouter/google/gemini-3.6-flash",modelId:"openrouter/google/gemini-3.6-flash",description:"Gemini 3.6 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3.7-max",modelId:"openrouter/qwen/qwen3.7-max",description:"Qwen 3.7 Max via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k3",modelId:"openrouter/moonshotai/kimi-k3",description:"Kimi K3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3",modelId:"openrouter/z-ai/glm-5.3",description:"Zhipu GLM-5.3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3-flash",modelId:"openrouter/z-ai/glm-5.3-flash",description:"Zhipu GLM-5.3 Flash (OpenRouter id; the Evolve gateway serves it from Fireworks)"},{alias:"openrouter/deepseek/deepseek-v4.1-flash",modelId:"openrouter/deepseek/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via OpenRouter"},{alias:"fireworks/deepseek-v4.1-flash",modelId:"fireworks/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via Fireworks"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{targetDir:"~/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:t,model:e,isResume:n,isDirectMode:r,isExternalGateway:s,reasoningEffort:o})=>{let d=n?"--continue ":"",u=xl(o);if(s)return `OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${d}--model litellm/${e} --format json${u} "${t}" < /dev/null`;let l=Cl(e);return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${d}--model ${l} --format json${u} "${t}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${d}--model litellm/${l} --format json${u} "${t}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",effortSupport:"level",defaultModel:"claude-opus-5",defaultReasoningEffort:"high",models:[{alias:"claude-fable-5.1",modelId:"claude-fable-5-1",description:"Factory-managed Claude Fable 5.1"},{alias:"claude-opus-5",modelId:"claude-opus-5",description:"Factory-managed Claude Opus 5"},{alias:"claude-sonnet-5",modelId:"claude-sonnet-5",description:"Factory-managed Claude Sonnet 5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-6-astra",modelId:"gpt-6-astra",description:"Factory-managed GPT-6 Astra"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Factory-managed GPT-5.6 Sol"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Factory-managed GPT-5.6 Terra"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"Factory-managed GPT-5.6 Luna"},{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Factory-managed Gemini 3.6 Flash"},{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Qwen 3.7 Max via the Evolve gateway"},{alias:"kimi-k3",modelId:"kimi-k3",description:"Factory-managed Droid Core Kimi K3"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"},{alias:"openrouter/deepseek/deepseek-v4.1-flash",modelId:"openrouter/deepseek/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via OpenRouter"},{alias:"fireworks/deepseek-v4.1-flash",modelId:"fireworks/deepseek-v4.1-flash",description:"DeepSeek V4.1 Flash via Fireworks"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.factory/skills"},skipApiKeyEnvInGateway:true,gatewayModelAliases:{"claude-fable-5.1":"claude-fable-5-1","kimi-k3":"moonshot/kimi-k3","glm-5.3":"openrouter/z-ai/glm-5.3","qwen3.7-max":"dashscope/qwen3.7-max"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:t,model:e,isResume:n,sessionId:r,reasoningEffort:s,isDirectMode:o,isExternalGateway:d,homeDir:u=W})=>{let l=!o||d,i=l?`--settings ${u}/.factory/evolve-settings.json `:"",a=l?"custom:Evolve-Gateway-0":e,c=s?` --reasoning-effort ${s}`:"",p=n&&r?`--session-id ${Xe(r)} `:"";return `printf '%s' ${Xe(t)} | droid ${i}exec ${p}--skip-permissions-unsafe --cwd ${u}/workspace --output-format stream-json --model ${Xe(a)}${c}`}}};function K(t){let e=J[t];if(!e)throw new Error(`Unknown agent type: ${t}`);return e}function Se(t,e){if(t.models.some(s=>s.alias===e||s.modelId===e))return true;let n=t.gatewayModelAliases;if(n&&(e in n||Object.values(n).includes(e)))return true;let r=t.directModelAliases;return !!(r&&(e in r||Object.values(r).includes(e)))}function Qs(t,e){return t.models.find(n=>n.alias===e)?.modelId??e}function Cl(t){return t.startsWith("openrouter/")||Se(J.opencode,t)?t:`openrouter/${t}`}function zn(t){return t in J}function B(t,e=W){return t.replace(/^~/,e)}function Xe(t){return `'${t.replace(/'/g,"'\\''")}'`}function ne(t,e=W){let n=K(t);return `${B(n.mcpConfig.settingsDir,e)}/${n.mcpConfig.filename}`}function re(t,e=W){let n=K(t);return B(n.mcpConfig.settingsDir,e)}function se(t){if(t instanceof Error){let e=t.message.toLowerCase();return e.includes("not found")||e.includes("enoent")||e.includes("no such file")||e.includes("does not exist")}return false}function qn(t,e){let n=[e.command,e.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${t}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${t}" cannot specify both command and url`)}function Ze(t){for(let[e,n]of Object.entries(t))qn(e,n);}function et(t){return t.type?t.type:t.command?"stdio":"sse"}function Rl(t){let e=et(t);return {...t,type:e}}function El(t){let{type:e,url:n,...r}=t;return et(t)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function Tl(t){return {type:et(t),...t}}function Pl(t){let{type:e,...n}=t;return n.command?{...n,transport:"stdio"}:n.url&&(e==="http"||e==="sse")?{...n,transport:e}:n}function Al(t){let e=et(t),{type:n,httpHeaders:r,envHttpHeaders:s,bearerTokenEnvVar:o,envVars:d,...u}=t;if(e==="stdio"&&t.command)return {type:"stdio",...u};if(t.url){let l={...u,type:e==="sse"?"sse":"http",url:t.url},i=t.headers??r;return i&&Object.keys(i).length>0&&(l.headers=i),l}return {type:e==="stdio"?"stdio":"http",...u}}async function Wn(t,e,n,r,s){Ze(n);let o=re(e,s),d=ne(e,s);await t.files.makeDir(o);let u={};try{let i=await t.files.read(d);typeof i=="string"&&(u=JSON.parse(i));}catch(i){if(!se(i))throw i}let l=Object.fromEntries(Object.entries(n).map(([i,a])=>[i,r(a)]));await t.files.write(d,JSON.stringify({...u,mcpServers:l},null,2));}async function Ft(t,e,n,r){Ze(n);let s=re("claude",r),o=ne("claude",r),d=Object.fromEntries(Object.entries(n).map(([l,i])=>[l,Tl(i)]));await t.files.write(`${e}/.mcp.json`,JSON.stringify({mcpServers:d},null,2)),await t.files.makeDir(s);let u={};try{let l=await t.files.read(o);typeof l=="string"&&(u=JSON.parse(l));}catch(l){if(!se(l))throw l}u.enableAllProjectMcpServers=true,await t.files.write(o,JSON.stringify(u,null,2));}async function Bt(t,e,n){await Wn(t,"gemini",e,Rl,n);}async function Nt(t,e,n){await Wn(t,"qwen",e,El,n);}async function jt(t,e,n,r,s){let o=re(e,s),d=ne(e,s);await t.files.makeDir(o);let u={};try{let p=await t.files.read(d);typeof p=="string"&&(u=JSON.parse(p));}catch(p){if(!se(p))throw p}let l=n.split("."),i=u;for(let p=0;p<l.length-1;p++){let g=l[p];(typeof i[g]!="object"||i[g]===null)&&(i[g]={}),i=i[g];}let a=l[l.length-1],c=typeof i[a]=="object"&&i[a]!==null?i[a]:{};i[a]={...c,...r},await t.files.write(d,JSON.stringify(u,null,2));}async function Yn(t,e,n){let r=re("qwen",n),s=ne("qwen",n);await t.files.makeDir(r);let o={};try{let i=await t.files.read(s);typeof i=="string"&&(o=JSON.parse(i));}catch(i){if(!se(i))throw i}let d=o.model??{},u=d.generationConfig??{},l=u.extra_body??{};o.model={...d,generationConfig:{...u,extra_body:{...l,enable_thinking:e}}},await t.files.write(s,JSON.stringify(o,null,2));}async function Xn(t,e,n){await Wn(t,"kimi",e,Pl,n);}async function Jt(t,e,n){Ze(n);let r=`${e}/.factory`,s=`${r}/mcp.json`;await t.files.makeDir(r);let o={};try{let u=await t.files.read(s);typeof u=="string"&&(o=JSON.parse(u));}catch(u){if(!se(u))throw u}let d=Object.fromEntries(Object.entries(n).map(([u,l])=>[u,Al(l)]));await t.files.write(s,JSON.stringify({...o,mcpServers:d},null,2));}async function Kt(t,e,n,r){let s=B(e.settingsPath,r),o=s.slice(0,s.lastIndexOf("/"));await t.files.makeDir(o);let d={cloudSessionSync:false,customModels:[{model:e.model,displayName:e.displayName,baseUrl:e.baseUrl,apiKey:`\${${e.apiKeyEnv}}`,provider:e.provider,...e.maxOutputTokens!==void 0&&{maxOutputTokens:e.maxOutputTokens},extraHeaders:n}]};await t.files.write(s,JSON.stringify(d,null,2));}async function Qn(t,e,n){Ze(n);let r=`${e}/opencode.json`,s={};try{let d=await t.files.read(r);typeof d=="string"&&(s=JSON.parse(d));}catch(d){if(!se(d))throw d}let o=Object.fromEntries(Object.entries(n).map(([d,u])=>[d,Il(u)]));await t.files.write(r,JSON.stringify({...s,mcp:o},null,2));}function Il(t){let e=et(t);if(e==="stdio"&&t.command){let r={type:"local",command:t.args?[t.command,...t.args]:[t.command]};return t.env&&Object.keys(t.env).length>0&&(r.environment=t.env),r}if(t.url){let n={type:"remote",url:t.url};return t.headers&&Object.keys(t.headers).length>0&&(n.headers=t.headers),n}return {type:e==="stdio"?"local":"remote",...t}}function Zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Zs(t,e,n){let r=t[e];if(r===void 0)return {};let s=Zn(r);if(!s){let o=Array.isArray(r)?"an array":`a ${typeof r}`;throw new Error(`Refusing to rewrite "${e}" in ${n}: expected a TOML table, found ${o}`)}return s}function er(t,e){if(t===e)return true;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((o,d)=>er(o,e[d]));let n=Zn(t),r=Zn(e);if(!n||!r)return false;let s=Object.keys(n);return s.length===Object.keys(r).length&&s.every(o=>o in r&&er(n[o],r[o]))}async function ei(t,e){let n="";try{let r=await t.files.read(e);typeof r=="string"&&(n=r);}catch(r){if(!se(r))throw r;return {}}if(!n.trim())return {};try{return smolToml.parse(n)}catch(r){throw new Error(`Failed to parse TOML at ${e}: ${r.message}`)}}async function tr(t,e,n){await t.files.write(e,smolToml.stringify(n).trimEnd()+`
|
|
15
|
+
`);}function Dl(t,e){let n={},r=e.type??(e.command?"stdio":"http");if(r==="http"||r==="sse"||!!e.url){if(!e.url)throw new Error(`MCP server "${t}" is missing url for ${r} transport`);n.url=e.url,e.bearerTokenEnvVar&&(n.bearer_token_env_var=e.bearerTokenEnvVar);let o=e.httpHeaders??e.headers;o&&Object.keys(o).length>0&&(n.http_headers=o),e.envHttpHeaders&&Object.keys(e.envHttpHeaders).length>0&&(n.env_http_headers=e.envHttpHeaders);}else n.command=e.command,e.args&&e.args.length>0&&(n.args=e.args),e.cwd&&(n.cwd=e.cwd);return e.env&&Object.keys(e.env).length>0&&(n.env=e.env),e.envVars&&e.envVars.length>0&&(n.env_vars=e.envVars),n}async function Gt(t,e,n){for(let[u,l]of Object.entries(e))qn(u,l);let r=re("codex",n),s=ne("codex",n);await t.files.makeDir(r);let o=await ei(t,s);o.experimental_use_rmcp_client===void 0&&(o.experimental_use_rmcp_client=true);let d=Zs(o,"mcp_servers",s);o.mcp_servers=d;for(let[u,l]of Object.entries(e))d[u]===void 0&&(d[u]=Dl(u,l));await tr(t,s,o);}async function Vt(t,e,n,r={},s){let o=re("codex",s),d=ne("codex",s);await t.files.makeDir(o);let u=await ei(t,d),l={...n?{[H]:n.sessionTagEnv,[te]:n.runTagEnv}:{},...r},i={name:"Evolve Gateway",base_url:e,env_key:"OPENAI_API_KEY",wire_api:"responses",...Object.keys(l).length>0?{env_http_headers:l}:{}},a=Zs(u,"model_providers",d);u.model_provider==="evolve-gateway"&&er(a["evolve-gateway"],i)||(u.model_provider="evolve-gateway",a["evolve-gateway"]=i,u.model_providers=a,await tr(t,d,u));}async function nr(t,e,n,r,s){let o=B(e.configPath,s),d=o.slice(0,o.lastIndexOf("/"));await t.files.makeDir(d);let u={default_model:e.modelName,default_thinking:r.defaultThinking,default_permission_mode:"auto",thinking:{mode:r.defaultThinking?"on":"off",...r.defaultThinking&&r.thinkingEffort?{effort:r.thinkingEffort}:{}},providers:{[e.providerName]:{type:"kimi",base_url:r.baseUrl,api_key:r.apiKey,custom_headers:n}},models:{[e.modelName]:{provider:e.providerName,model:r.model,max_context_size:e.maxContextSize,capabilities:["image_in","thinking"]}}};await tr(t,o,u);}async function rr(t,e,n,r,s){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await Ft(e,n,r,s);break;case "codex":await Gt(e,r,s);break;case "gemini":await Bt(e,r,s);break;case "qwen":await Nt(e,r,s);break;case "kimi":await Xn(e,r,s);break;case "opencode":await Qn(e,n,r);break;case "droid":await Jt(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function ti(t){return !!t&&t.sessionUpdate!=="error"&&t.sessionUpdate!=="usage"}function D(t,e){for(let n of t)if(typeof n=="string"&&n.length>0)return n;try{let n=JSON.stringify(e);if(typeof n=="string"&&n.length>0)return n}catch{}return String(e)}function Ht(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function tt(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,n=Ht(e.input_tokens),r=Ht(e.output_tokens),s=Ht(e.cache_read_input_tokens),o=Ht(e.cache_creation_input_tokens),d={};(n!==void 0||s!==void 0||o!==void 0)&&(d.promptTokens=(n??0)+(s??0)+(o??0)),r!==void 0&&(d.completionTokens=r),s!==void 0&&(d.cachedTokens=s);let u={};for(let[l,i]of Object.entries(e))l==="input_tokens"||l==="output_tokens"||i!=null&&(u[l]=i);return Object.keys(u).length>0&&(d.extra=u),d}function ue(t){if(typeof t=="string"&&t.length>0&&!Number.isNaN(Date.parse(t)))return t;if(typeof t=="number"&&Number.isFinite(t))return new Date(t).toISOString()}function zt(){let t={};return function(i){let a;try{a=JSON.parse(i);}catch{return null}if(a._meta||a._prompt)return null;let c=a.session_id;switch(a.type){case "system":return null;case "assistant":{let p=n(a.message?.content,"assistant")??[],g=tt(a.message?.usage);return g&&p.push({sessionUpdate:"usage",scope:"call",usage:g}),e(p,a,c)}case "user":{let p=a.message?.content;if(typeof p=="string"||Array.isArray(p)&&p.length===1&&p[0].type==="text")return null;let g=a.tool_use_result??a.toolUseResult;return e(n(p,"user",g),a,c)}case "result":{let p=[],g=typeof a.total_cost_usd=="number"&&Number.isFinite(a.total_cost_usd)?a.total_cost_usd:void 0,m=tt(a.usage)??(g!==void 0?{}:null);if(m&&(g!==void 0&&(m.costUsd=g),p.push({sessionUpdate:"usage",scope:"run",usage:m})),a.is_error===true){let h=(Array.isArray(a.errors)?a.errors:[]).filter(y=>typeof y=="string"&&y.length>0).join(`
|
|
16
|
+
`);p.push({sessionUpdate:"error",message:D([h,a.result,a.subtype],a),fatal:true});}return e(p,a,c)}default:return null}};function e(l,i,a){if(!l||l.length===0)return null;let c=i.message,p=ue(i.timestamp),g=typeof c?.model=="string"&&c.model?c.model:void 0,m=typeof c?.id=="string"&&c.id?c.id:void 0,f=typeof i.parent_tool_use_id=="string"&&i.parent_tool_use_id?i.parent_tool_use_id:void 0,h={};for(let y of ["stop_reason","stop_sequence","requestId"]){let b=c?.[y];b!=null&&(h[y]=b);}return l.map(y=>({sessionId:a,update:y,...p!==void 0?{timestamp:p}:{},...g!==void 0?{model:g}:{},...m!==void 0?{messageId:m}:{},...f!==void 0?{parentToolCallId:f}:{},...Object.keys(h).length>0?{extra:h}:{}}))}function n(l,i,a){if(typeof l=="string")return i==="user"?null:[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}];if(!l||!Array.isArray(l))return null;let c=[];for(let p of l){let g=null;switch(p.type){case "text":case "text_delta":if(i==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"text",text:p.text}};break;case "image":if(i==="user")break;g={sessionUpdate:"agent_message_chunk",content:{type:"image",data:p.source?.type==="base64"?p.source.data:"",mimeType:p.source?.type==="base64"?p.source.media_type:"",uri:p.source?.type==="url"?p.source.url:void 0}};break;case "thinking":case "thinking_delta":g={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:p.thinking}};break;case "tool_use":case "server_tool_use":case "mcp_tool_use":{if(t[p.id]=p,p.name==="TodoWrite")Array.isArray(p.input?.todos)&&(g={sessionUpdate:"plan",entries:u(p.input)});else {let m=r(p);g={sessionUpdate:"tool_call",toolCallId:p.id,status:"pending",...m,toolName:p.name};}break}case "tool_result":case "tool_search_tool_result":case "web_fetch_tool_result":case "web_search_tool_result":case "code_execution_tool_result":case "bash_code_execution_tool_result":case "text_editor_code_execution_tool_result":case "mcp_tool_result":{let m=t[p.tool_use_id];if(!m||(delete t[p.tool_use_id],m.name==="TodoWrite"))break;g={sessionUpdate:"tool_call_update",toolCallId:p.tool_use_id,status:"is_error"in p&&p.is_error?"failed":"completed",...s(p,m),...a!=null?{rawOutput:a}:{}};break}}g&&c.push(g);}return c.length>0?c:null}function r(l){let i=l.name,a=l.input||{};switch(i){case "Task":return {title:a.description||"Task",kind:"think",content:a.prompt?[{type:"content",content:{type:"text",text:a.prompt}}]:[],rawInput:a};case "NotebookRead":return {title:a.notebook_path?`Read Notebook ${a.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:a.notebook_path?[{path:a.notebook_path}]:[],rawInput:a};case "NotebookEdit":return {title:a.notebook_path?`Edit Notebook ${a.notebook_path}`:"Edit Notebook",kind:"edit",content:a.new_source?[{type:"content",content:{type:"text",text:a.new_source}}]:[],locations:a.notebook_path?[{path:a.notebook_path}]:[],rawInput:a};case "Bash":return {title:a.command?"`"+a.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:a.description?[{type:"content",content:{type:"text",text:a.description}}]:[],rawInput:a};case "BashOutput":return {title:"Tail Logs",kind:"execute",content:[],rawInput:a};case "KillShell":return {title:"Kill Process",kind:"execute",content:[],rawInput:a};case "Read":{let c="";return a.limit?c=" ("+((a.offset??0)+1)+" - "+((a.offset??0)+a.limit)+")":a.offset&&(c=" (from line "+(a.offset+1)+")"),{title:"Read "+(a.file_path??"File")+c,kind:"read",content:[],locations:a.file_path?[{path:a.file_path,line:a.offset??0}]:[],rawInput:a}}case "LS":return {title:a.path?`List \`${a.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:a};case "Edit":{let c=a.file_path;return {title:c?`Edit \`${c}\``:"Edit",kind:"edit",content:c?[{type:"diff",path:c,oldText:a.old_string??null,newText:a.new_string??""}]:[],locations:c?[{path:c}]:[],rawInput:a}}case "Write":return {title:a.file_path?`Write ${a.file_path}`:"Write",kind:"edit",content:a.file_path?[{type:"diff",path:a.file_path,oldText:null,newText:a.content??""}]:[],locations:a.file_path?[{path:a.file_path}]:[],rawInput:a};case "Glob":{let c="Find";return a.path&&(c+=` \`${a.path}\``),a.pattern&&(c+=` \`${a.pattern}\``),{title:c,kind:"search",content:[],locations:a.path?[{path:a.path}]:[],rawInput:a}}case "Grep":{let c="grep";return a["-i"]&&(c+=" -i"),a["-n"]&&(c+=" -n"),a["-A"]!==void 0&&(c+=` -A ${a["-A"]}`),a["-B"]!==void 0&&(c+=` -B ${a["-B"]}`),a["-C"]!==void 0&&(c+=` -C ${a["-C"]}`),a.output_mode==="files_with_matches"?c+=" -l":a.output_mode==="count"&&(c+=" -c"),a.head_limit!==void 0&&(c+=` | head -${a.head_limit}`),a.glob&&(c+=` --include="${a.glob}"`),a.type&&(c+=` --type=${a.type}`),a.multiline&&(c+=" -P"),c+=` "${a.pattern??""}"`,a.path&&(c+=` ${a.path}`),{title:c,kind:"search",content:[],rawInput:a}}case "WebFetch":return {title:a.url?`Fetch ${a.url}`:"Fetch",kind:"fetch",content:a.prompt?[{type:"content",content:{type:"text",text:a.prompt}}]:[],rawInput:a};case "WebSearch":{let c=`"${a.query??""}"`;return a.allowed_domains?.length>0&&(c+=` (allowed: ${a.allowed_domains.join(", ")})`),a.blocked_domains?.length>0&&(c+=` (blocked: ${a.blocked_domains.join(", ")})`),{title:c,kind:"fetch",content:[],rawInput:a}}case "TodoWrite":return {title:Array.isArray(a.todos)?`Update TODOs: ${a.todos.map(c=>c.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:a};case "ExitPlanMode":return {title:"Ready to code?",kind:"switch_mode",content:a.plan?[{type:"content",content:{type:"text",text:a.plan}}]:[],rawInput:a};default:if(i?.startsWith("mcp__")){let c=i.split("__"),p=c[1]||"mcp",g=c.slice(2).join("__")||i;return {title:`${p}: ${g}`,kind:"other",content:[],rawInput:a}}return {title:i||"Unknown Tool",kind:"other",content:[],rawInput:a}}}function s(l,i){return i?.name==="ExitPlanMode"?{title:"Exited Plan Mode"}:o(l.content)}function o(l){return Array.isArray(l)&&l.length>0?{content:l.map(i=>({type:"content",content:d(i)}))}:typeof l=="string"&&l.length>0?{content:[{type:"content",content:{type:"text",text:l}}]}:{}}function d(l){if(l.type==="text")return {type:"text",text:l.text};if(l.type==="image"){if(l.data&&l.mimeType)return {type:"image",data:l.data,mimeType:l.mimeType};if(l.source?.type==="base64")return {type:"image",data:l.source.data||"",mimeType:l.source.media_type||""};if(l.source?.type==="url")return {type:"image",data:"",mimeType:"",uri:l.source.url}}return l}function u(l){return l.todos.map(i=>({content:i.content,status:i.status||"pending",priority:"medium"}))}}function qt(){let e;return function(a){let c;try{c=JSON.parse(a);}catch{return null}if(c._meta||c._prompt)return null;let p=[];switch(c.type){case "thread.started":return typeof c.thread_id=="string"&&c.thread_id&&(e=c.thread_id),null;case "turn.started":return null;case "turn.completed":{let g=n(c.usage);if(!g)return null;p.push({update:{sessionUpdate:"usage",scope:"run",usage:g}});break}case "error":{let g=D([c.message],c);p.push({update:{sessionUpdate:"error",message:g,fatal:false}});break}case "turn.failed":{let g=D([c.error?.message],c.error??c);p.push({update:{sessionUpdate:"error",message:g,fatal:true}});break}case "item.started":{let g=c.item;if(!g)return null;let m=r(g);m&&p.push({update:m});break}case "item.updated":{let g=c.item;if(!g)return null;let m=s(g);m&&p.push({update:m});break}case "item.completed":{let g=c.item;if(!g)return null;let m=o(g);m&&p.push({update:m});break}default:return null}return p.length===0?null:e===void 0?p:p.map(g=>({sessionId:e,...g}))};function n(i){if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i,c=y=>typeof y=="number"&&Number.isFinite(y)?y:void 0,p={},g=c(a.input_tokens),m=c(a.output_tokens),f=c(a.cached_input_tokens);g!==void 0&&(p.promptTokens=g),m!==void 0&&(p.completionTokens=m),f!==void 0&&(p.cachedTokens=f);let h={};for(let[y,b]of Object.entries(a))y==="input_tokens"||y==="output_tokens"||y==="cached_input_tokens"||b!=null&&(h[y]=b);return Object.keys(h).length>0&&(p.extra=h),p}function r(i){let a=i.id;switch(i.type){case "mcp_tool_call":return {type:"mcp_tool_call",name:`${i.server}:${i.tool}`},{sessionUpdate:"tool_call",toolCallId:a,title:`${i.server}: ${i.tool}`,toolName:`mcp__${i.server}__${i.tool}`,kind:"other",status:"in_progress",rawInput:i.arguments,content:[]};case "command_execution":return {type:"command_execution",name:i.command},{sessionUpdate:"tool_call",toolCallId:a,title:i.command?`\`${i.command}\``:"Execute Command",toolName:"command_execution",kind:"execute",status:"in_progress",rawInput:{command:i.command},content:[]};case "web_search":return {type:"web_search",name:i.query},{sessionUpdate:"tool_call",toolCallId:a,title:`Search: ${i.query??""}`,toolName:"web_search",kind:"fetch",status:"in_progress",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(i.items)};default:return null}}function s(i){return i.type==="todo_list"?{sessionUpdate:"plan",entries:l(i.items)}:null}function o(i){let a=i.id;switch(i.type){case "error":return {sessionUpdate:"error",message:D([i.message],i),fatal:false};case "reasoning":return {sessionUpdate:"agent_thought_chunk",content:{type:"text",text:i.text??i.summary?.join(`
|
|
17
17
|
`)??i.content?.join(`
|
|
18
|
-
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:i.text??""}};case "mcp_tool_call":{let p=d(i.result),g=i.status==="failed"||i.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:a,status:g,content:p,rawOutput:i}}case "command_execution":{let p=i.aggregated_output?[{type:"content",content:{type:"text",text:i.aggregated_output}}]:[],g=i.status==="completed"||i.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:a,status:g,content:p,rawOutput:i}}case "file_change":{let p=i.changes??[],g=p.map(m=>({path:m.path})),f=p.length===1?`${p[0].kind==="add"?"Create":"Edit"} ${p[0].path}`:`Edit ${p.length} files`;return {sessionUpdate:"tool_call",toolCallId:a,title:f,toolName:"file_change",kind:"edit",status:i.status==="completed"?"completed":"failed",rawInput:{changes:p},content:p.map(m=>({type:"diff",path:m.path,oldText:m.kind==="add"?null:"",newText:""})),locations:g}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:a,title:`Search: ${i.query??""}`,toolName:"web_search",kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(i.items)};default:return null}}function d(i){return i?.content?Array.isArray(i.content)?i.content.map(a=>({type:"content",content:u(a)})):typeof i.content=="string"?[{type:"content",content:{type:"text",text:i.content}}]:[]:[]}function u(i){return i.type==="text"?{type:"text",text:i.text??""}:i.type==="image"?{type:"image",data:i.data??"",mimeType:i.mime_type??i.mimeType??"",uri:i.uri}:i}function l(i){if(!Array.isArray(i))return [];let a=false;return i.map(c=>{let p;return c.completed?p="completed":a?p="pending":(p="in_progress",a=true),{content:c.text??"",status:p,priority:"medium"}})}}var Sl={applypatch:"edit",apply_patch:"edit",create:"edit",edit:"edit",grep:"search",glob:"search",ls:"search",read:"read",write:"edit",execute:"execute",execute_cli:"execute",fetchurl:"fetch",fetch_url:"fetch",webfetch:"fetch",web_fetch:"fetch",websearch:"fetch",web_search:"fetch",skill:"execute",task:"think",todowrite:"other",todo_write:"other"},xl=new Set(["assistant_text_complete","thinking_text_complete","droid_working_state_changed","permission_resolved","settings_updated","session_title_updated","mcp_status_changed","session_token_usage_changed","mission_state_changed","mission_features_changed","mission_progress_entry","mission_heartbeat","mission_worker_started","mission_worker_completed","mcp_auth_required","mcp_auth_completed","structured_output"]);function qt(){let t=new Map,e,n,r=false,s="",o;return function(u){let l;try{l=JSON.parse(u);}catch{return null}if(!Qs(l))return null;let i=Cl(l);if(i.sessionId&&(e=i.sessionId),i.errorText)return [er(e,i.errorText,true)];if(i.resultText)return s=i.resultText,r=true,[Se(e,i.resultText)];if(i.handled)return null;let c=Rl(l)??l,p=Xs(c);p&&(e=p);let g=[],f=C(c,"type");switch(f){case "system":{let h=C(c,"model");return h&&(n=h),null}case "message":{let h=C(c,"role"),y=C(c,"text")||nr(c.content);if(!y)break;h==="assistant"&&(r=true,s=y,g.push(Se(e,y)));break}case "completion":{let h=C(c,"finalText")||C(c,"result");h&&(!r||h!==s)&&(r=true,s=h,g.push(Se(e,h)));let y=et(c.usage);y&&g.push({sessionId:e,update:{sessionUpdate:"usage",scope:"run",usage:y}});break}case "assistant_text_delta":{let h=C(c,"textDelta")||C(c,"text");h&&(r=true,s+=h,g.push(Se(e,h)));break}case "thinking_text_delta":{let h=C(c,"textDelta")||C(c,"text");if(h){let y=Ws(c,h,o);y&&(o=y.signature,g.push({sessionId:e,update:y.event}));}break}case "reasoning":{let h=C(c,"text");if(h){let y=Ws(c,h,o);y&&(o=y.signature,g.push({sessionId:e,update:y.event}));}break}case "assistant":{let h=C(c,"text")||nr(U(c.message)?.content);h&&(r=true,s=h,g.push(Se(e,h)));break}case "tool_call":case "tool_call_delta":{let h=U(c.toolUse)??U(c.tool_use)??c,y=Ys(h,t);y&&g.push({sessionId:e,update:y});break}case "tool_result":{let h=El(c,t);h&&g.push({sessionId:e,update:h});break}case "tool_progress_update":case "tool_progress":{let h=Pl(c);h&&g.push({sessionId:e,update:h});break}case "create_message":{for(let h of Tl(c,t)){if(h.sessionUpdate==="agent_message_chunk"){let y=h.content.type==="text"?h.content.text:"";if(r&&y===s)continue;r=true,s=y;}g.push({sessionId:e,update:h});}break}case "result":{if(c.is_error===true||c.subtype==="failure"){g.push(er(e,D([ie(c.result),ie(c.error),ie(c.subtype)],c),true));break}let h=ie(c.result??c.text??c.error);h&&(r=true,s=h,g.push(Se(e,h)));break}case "error":{g.push(er(e,D([ie(c.message),ie(c.error)],c),false));break}default:if(f&&!xl.has(f))return null}if(g.length>0&&f!=="reasoning"&&f!=="thinking_text_delta"&&(o=void 0),g.length===0)return null;let m=ue(c.timestamp);return g.map(h=>({...h,...m!==void 0?{timestamp:m}:{},...n!==void 0?{model:n}:{}}))}}function Ws(t,e,n){let r=tr(t,"id")||tr(t,"messageId"),s=tr(t,"blockIndex"),o=`${C(t,"type")}:${r}:${s}:${e}`;return o===n?null:{signature:o,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function Cl(t){if(t.type!=="response")return {handled:false};let e=U(t.result),n=U(t.error),r=Xs(e??t);if(n)return {handled:true,sessionId:r,errorText:ie(n.message??n)};let s=e?C(e,"finalText")||C(e,"result"):"";return {handled:true,sessionId:r,resultText:s}}function Rl(t){return t.method!=="droid.session_notification"?null:U(U(t.params)?.notification)}function Tl(t,e){let n=U(t.message);if(!n)return [];let r=[],s=n.content;if(Array.isArray(s))for(let o of s){let d=U(o);if(d&&d.type==="tool_use"){let u=Ys(d,e);u&&r.push(u);}}if(n.role==="assistant"){let o=nr(s);o&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}});}return r}function Ys(t,e){let n=C(t,"id")||C(t,"toolUseId")||C(t,"tool_use_id"),r=C(t,"name")||C(t,"toolName")||C(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let s=U(t.input)??U(t.toolInput)??U(t.arguments)??U(t.parameters)??{};if(Zs(r)==="todowrite"){let i=Al(s);if(i)return i}let{title:o,kind:d,content:u,locations:l}=Il(r,s);return {sessionUpdate:"tool_call",toolCallId:n,title:o,toolName:r,kind:d,status:"pending",rawInput:s,content:u,locations:l}}function El(t,e){let n=C(t,"toolUseId")||C(t,"tool_use_id")||C(t,"tool_id")||C(t,"id")||C(t,"toolId");if(!n)return null;let r=C(t,"toolName")||C(t,"tool_name")||e.get(n);return e.delete(n),{sessionUpdate:"tool_call_update",toolCallId:n,status:t.isError===true||t.is_error===true?"failed":"completed",title:r,content:rr(t.content??t.result??t.value??t.error)}}function Pl(t){let e=C(t,"toolUseId")||C(t,"tool_use_id")||C(t,"tool_id")||C(t,"id")||C(t,"toolId");if(!e)return null;let n=U(t.update),r=ie(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?rr(r):void 0}}function Al(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let s=U(r);if(!s)return [];let o=C(s,"content"),d=Ol(C(s,"status")),u=Ml(C(s,"priority"));return o?[{content:o,status:d,priority:u}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function Il(t,e){let n=Sl[Zs(t)]||"other",r=C(e,"path")||C(e,"filePath")||C(e,"file_path")||C(e,"absolute_path"),s=C(e,"command"),o=C(e,"url"),d=r||s||o;return {title:d?`${t} ${d}`:t,kind:n,content:Object.keys(e).length>0?rr(e):[],locations:r?[{path:r}]:[]}}function Xs(t){if(t)return C(t,"session_id")||C(t,"sessionId")}function Se(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function er(t,e,n){return {sessionId:t,update:{sessionUpdate:"error",message:e,fatal:n}}}function nr(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=U(e);return n?C(n,"text")||C(n,"content"):""}).filter(Boolean).join(""):""}function rr(t){let e=ie(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function ie(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function Qs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U(t){return Qs(t)?t:null}function C(t,e){let n=t[e];return typeof n=="string"?n:""}function tr(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function Zs(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Ol(t){return t==="in_progress"||t==="completed"?t:"pending"}function Ml(t){return t==="high"||t==="low"?t:"medium"}var Dl={read_file:"read",read_many_files:"read",write_file:"edit",replace:"edit",edit_file:"edit",run_shell_command:"execute",shell:"execute",glob:"search",grep:"search",search_file_content:"search",list_directory:"search",brave_web_search:"fetch",web_search:"fetch",google_web_search:"fetch",web_fetch:"fetch",delegate_to_agent:"think",write_todos:"other",save_memory:"other",activate_skill:"other"};function Wt(){let t,e;return function(i){let a;try{a=JSON.parse(i);}catch{return null}if(a._meta||a._prompt)return null;let c=(typeof a.session_id=="string"&&a.session_id?a.session_id:void 0)??e,p=[];switch(a.type){case "init":return typeof a.model=="string"&&a.model&&(t=a.model),typeof a.session_id=="string"&&a.session_id&&(e=a.session_id),null;case "result":{let f=n(a.stats);if(f&&p.push({sessionId:c,update:{sessionUpdate:"usage",scope:"run",usage:f}}),a.status!=="error")break;p.push({sessionId:c,update:{sessionUpdate:"error",message:D([a.error?.message,a.error?.type,'gemini ended the run with result status "error" and no error text'],a.error??a),fatal:true}});break}case "message":{let f=r(a);f&&p.push({sessionId:c,update:f});break}case "tool_use":{let f=s(a);f&&p.push({sessionId:c,update:f});break}case "tool_result":{let f=o(a);f&&p.push({sessionId:c,update:f});break}case "error":{let f=d(a);f&&p.push({sessionId:c,update:f});break}default:return null}if(p.length===0)return null;let g=ue(a.timestamp);return p.map(f=>({...f,...g!==void 0?{timestamp:g}:{},...t!==void 0?{model:t}:{}}))};function n(l){if(!l||typeof l!="object"||Array.isArray(l))return null;let i=l,a=h=>typeof h=="number"&&Number.isFinite(h)?h:void 0,c={},p=a(i.input_tokens),g=a(i.output_tokens),f=a(i.cached);p!==void 0&&(c.promptTokens=p),g!==void 0&&(c.completionTokens=g),f!==void 0&&(c.cachedTokens=f);let m={};for(let[h,y]of Object.entries(i))h==="input_tokens"||h==="output_tokens"||h==="cached"||y!=null&&(m[h]=y);return Object.keys(m).length>0&&(c.extra=m),c}function r(l){let i=l.role,a=l.content;return a?i==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}:i==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:a}}:null:null}function s(l){let i=l.tool_id,a=l.tool_name,c=l.parameters||{},{title:p,kind:g,content:f,locations:m}=u(a,c);return {sessionUpdate:"tool_call",toolCallId:i,title:p,toolName:a,kind:g,status:"pending",rawInput:c,content:f,locations:m}}function o(l){let i=l.tool_id,a=l.status,c=l.output,p=l.error,g=[];return c&&typeof c=="string"&&c.length>0&&g.push({type:"content",content:{type:"text",text:c}}),p?.message&&!c&&g.push({type:"content",content:{type:"text",text:p.message}}),{sessionUpdate:"tool_call_update",toolCallId:i,status:a==="success"?"completed":"failed",content:g}}function d(l){return {sessionUpdate:"error",message:D([l.message],l),fatal:false}}function u(l,i){let a=Dl[l]||"other",c=[],p=[],g=l;switch(l){case "read_file":g=`Read ${i.absolute_path||i.file_path||"file"}`,(i.absolute_path||i.file_path)&&p.push({path:i.absolute_path||i.file_path});break;case "write_file":g=`Write ${i.file_path||"file"}`,i.file_path&&(p.push({path:i.file_path}),c.push({type:"diff",path:i.file_path,oldText:null,newText:i.content||""}));break;case "edit_file":g=`Edit ${i.file_path||"file"}`,i.file_path&&p.push({path:i.file_path});break;case "replace":g=`Edit ${i.file_path||"file"}`,i.file_path&&(p.push({path:i.file_path}),(i.old_string!==void 0||i.new_string!==void 0)&&c.push({type:"diff",path:i.file_path,oldText:i.old_string||"",newText:i.new_string||""}));break;case "run_shell_command":case "shell":g=i.command?`\`${i.command}\``:"Run command",i.description&&c.push({type:"content",content:{type:"text",text:i.description}});break;case "brave_web_search":case "web_search":case "google_web_search":g=i.query?`"${i.query}"`:"Web search";break;case "web_fetch":g=i.prompt?`Fetch: ${i.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":g=`Find ${i.pattern||"files"}`,i.dir_path&&p.push({path:i.dir_path});break;case "grep":case "search_file_content":g=`grep "${i.pattern||i.query||""}"`;break;case "list_directory":g=`List ${i.dir_path||i.path||"directory"}`,(i.dir_path||i.path)&&p.push({path:i.dir_path||i.path});break;case "read_many_files":g=`Read ${i.include?.length||"multiple"} files`,Array.isArray(i.include)&&i.include.forEach(f=>p.push({path:f}));break;case "delegate_to_agent":g=i.agent_name?`Agent: ${i.agent_name}`:"Delegate to agent";break;case "write_todos":g="Update todos";break;case "save_memory":g=i.fact?`Remember: "${i.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":g=i.name?`Activate skill: ${i.name}`:"Activate skill";break;default:g=l;}return {title:g,kind:a,content:c,locations:p}}}var Ul={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function ei(t){return t==="TodoList"||t==="SetTodoList"}function ir(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function ni(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function or(t){if(!t||typeof t!="object")return null;if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {type:"content",content:{type:"text",text:t.text}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=ni(e);return n?{type:"content",content:{type:"image",data:n.data,mimeType:n.mimeType}}:{type:"content",content:{type:"image",data:"",mimeType:"",uri:e}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{type:"content",content:{type:"text",text:`[video] ${t.video_url.url}`}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{type:"content",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}:null}function sr(t){let e=[];if(typeof t=="string")return t.length>0&&e.push({type:"content",content:{type:"text",text:t}}),e;if(Array.isArray(t)){for(let n of t){if(typeof n=="string"&&n.length>0){e.push({type:"content",content:{type:"text",text:n}});continue}let r=or(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=or(t);n&&e.push(n);}return e}function $l(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&ir(e.content.text))}function Ll(t){if(!t||typeof t!="object")return null;if(t.type==="think"&&typeof t.think=="string"&&t.think.length>0)return {update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t.think}}};if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.text}}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=ni(e);return n?{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:n.data,mimeType:n.mimeType}}}:{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:"",mimeType:"",uri:e}}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[video] ${t.video_url.url}`}}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}}:null}function Bl(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function ti(t){if(!t||typeof t!="object")return [];let e=t.todos;return Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object")return null;let r=n.title;if(typeof r!="string"||r.length===0)return null;let s=n.status;return {content:r,status:Bl(s),priority:"medium"}}).filter(n=>n!==null):[]}function ar(){let t=new Set,e=0;function n(u,l){return typeof u=="string"&&u.length>0?u:(e+=1,`kimi_${l.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(l){let i;try{i=JSON.parse(l);}catch{return null}if(!i||typeof i!="object")return null;let a=i.role;return "_meta"in i||"_prompt"in i?null:a==="meta"?i.type!=="turn.step.retrying"?null:[{update:{sessionUpdate:"error",message:D([i.error_message,i.error_name],i),fatal:false}}]:a==="assistant"?r(i):a==="tool"?s(i):typeof i.type=="string"&&"payload"in i?o(i):null};function r(u){let l=[],i=u.content,a=u.tool_calls;if(typeof i=="string"&&i.length>0)l.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}}});else if(Array.isArray(i))for(let c of i){let p=Ll(c);p&&l.push(p);}if(Array.isArray(a))for(let c of a){if(!c||typeof c!="object")continue;let p=c.function;if(!p)continue;let g=p.name??"",f=n(c.id,g),m;try{m=p.arguments?JSON.parse(p.arguments):{};}catch{m=p.arguments;}if(ei(g)){let w=ti(m);w.length>0&&l.push({update:{sessionUpdate:"plan",entries:w}}),t.add(f);continue}let{title:h,kind:y,toolContent:b,locations:_}=d(g,typeof m=="object"&&m!==null?m:{});l.push({update:{sessionUpdate:"tool_call",toolCallId:f,title:h,toolName:g,kind:y,status:"pending",rawInput:m,content:b,locations:_}});}return l.length>0?l:null}function s(u){let l=u.tool_call_id;if(typeof l!="string"||l.length===0)return null;if(t.has(l))return t.delete(l),null;let i=u.content,a=[],c=false;if(typeof i=="string")c=ir(i),i.length>0&&a.push({type:"content",content:{type:"text",text:i}});else if(Array.isArray(i))for(let p of i){let g=or(p);g&&(g.type==="content"&&g.content.type==="text"&&ir(g.content.text)&&(c=true),a.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:l,status:c?"failed":"completed",content:a}}]}function o(u){let l=u.type,i=u.payload??{},a=[];switch(l){case "TextPart":{let c=i.text;typeof c=="string"&&c.length>0&&a.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}});break}case "ThinkPart":{let c=i.think;typeof c=="string"&&c.length>0&&a.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c}}});break}case "ToolCall":{let c=i.function?.name??"",p=n(i.id,c),g=i.function;if(!g)break;let f;try{f=g.arguments?JSON.parse(g.arguments):{};}catch{f=g.arguments;}if(ei(c)){let _=ti(f);_.length>0&&a.push({update:{sessionUpdate:"plan",entries:_}}),t.add(p);break}let{title:m,kind:h,toolContent:y,locations:b}=d(c,typeof f=="object"&&f!==null?f:{});a.push({update:{sessionUpdate:"tool_call",toolCallId:p,title:m,toolName:c,kind:h,status:"pending",rawInput:f,content:y,locations:b}});break}case "ToolResult":{let c=i.tool_call_id;if(typeof c!="string"||c.length===0)break;if(t.has(c)){t.delete(c);break}let p=i.return_value??i.content,g=[],f=i.is_error===true;if(p&&typeof p=="object"&&!Array.isArray(p)){let m=p;f=f||m.type==="ToolError"||m.is_error===true,g.push(...sr(m.output)),g.length===0&&typeof m.message=="string"&&m.message.length>0&&g.push({type:"content",content:{type:"text",text:m.message}}),g.length===0&&g.push(...sr(p));}else g.push(...sr(p));f=f||$l(g),a.push({update:{sessionUpdate:"tool_call_update",toolCallId:c,status:f?"failed":"completed",content:g}});break}default:return null}return a.length>0?a:null}function d(u,l){let i=Ul[u]||"other",a=[],c=[],p=u;switch(u){case "Read":case "ReadFile":{let g=l.path??l.file_path;p=`Read ${g||"file"}`,g&&c.push({path:g});break}case "ReadMediaFile":{let g=l.path??l.file_path;p=`Read media ${g||"file"}`,g&&c.push({path:g});break}case "Write":case "WriteFile":{let g=l.path??l.file_path;p=`Write ${g||"file"}`,g&&(c.push({path:g}),typeof l.content=="string"&&a.push({type:"diff",path:g,oldText:null,newText:l.content}));break}case "Edit":case "StrReplaceFile":{let g=l.path??l.file_path;p=`Edit ${g||"file"}`,g&&c.push({path:g});break}case "Bash":case "Shell":p=l.command?`\`${l.command}\``:"Run command";break;case "Glob":p=`Find ${l.pattern||"files"}`,l.path&&c.push({path:l.path});break;case "Grep":p=`grep "${l.pattern||""}"`,l.path&&c.push({path:l.path});break;case "WebSearch":case "SearchWeb":p=l.query?`"${l.query}"`:"Web search";break;case "FetchURL":p=l.url?`Fetch ${l.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":p=l.description||"Subagent task";break;case "Think":p=l.thought||"Thinking";break;case "CreateSubagent":p=l.name?`Subagent: ${l.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":p="Update todos";break;default:p=u;}return {title:p,kind:i,toolContent:a,locations:c}}}var Nl={read:"read",write:"edit",edit:"edit",multiedit:"edit",apply_patch:"edit",bash:"execute",glob:"search",grep:"search",list:"search",codesearch:"search",lsp:"search",webfetch:"fetch",websearch:"fetch",task:"think",batch:"think",plan_enter:"switch_mode",plan_exit:"switch_mode",todoread:"other",todowrite:"other",skill:"other",question:"other"};function jl(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function Fl(t){if(typeof t!="string")return "pending";switch(t.toLowerCase()){case "in_progress":case "in-progress":case "running":return "in_progress";case "completed":case "done":case "cancelled":return "completed";default:return "pending"}}function Jl(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function ri(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return null;let n=e.content;return typeof n!="string"||n.length===0?null:{content:n,status:Fl(e.status),priority:Jl(e.priority)}}).filter(e=>e!==null):[]}function Kl(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let u=jl(r);return u?{type:"content",content:{type:"image",data:u.data,mimeType:u.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function Vl(t,e){if(t==="error")return typeof e.error=="string"?e.error:null;if(typeof e.output=="string")return e.output;if(e.output===void 0||e.output===null)return null;try{return JSON.stringify(e.output)}catch{return String(e.output)}}function Gl(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function lr(){return function(l){let i;try{i=JSON.parse(l);}catch{return null}if(!i||typeof i!="object")return null;let a=i.sessionID,c=[];switch(i.type){case "step_start":return null;case "step_finish":{let g=t(i.part);if(!g)return null;c.push({sessionUpdate:"usage",scope:"call",usage:g});break}case "user":{let g=e(i);g&&c.push(g);break}case "text":{let g=n(i);g&&c.push(g);break}case "reasoning":{let g=r(i);g&&c.push(g);break}case "tool_use":{c.push(...s(i));break}case "error":{let g=o(i);g&&c.push(g);break}default:return null}if(c.length===0)return null;let p=ue(i.timestamp);return c.map(g=>({sessionId:a,update:g,...p!==void 0?{timestamp:p}:{}}))};function t(u){if(!u||typeof u!="object")return null;let l=u.tokens;if(!l||typeof l!="object")return null;let i=l,a=typeof i.cache=="object"&&i.cache?i.cache:{},c=w=>typeof w=="number"&&Number.isFinite(w)?w:void 0,p=c(i.input),g=c(i.output),f=c(a.read),m=c(a.write),h=c(i.reasoning),y=c(u.cost),b={};(p!==void 0||f!==void 0)&&(b.promptTokens=(p??0)+(f??0)),g!==void 0&&(b.completionTokens=g),f!==void 0&&(b.cachedTokens=f),y!==void 0&&y>0&&(b.costUsd=y);let _={};return h&&(_.reasoning_tokens=h),m&&(_.cache_write_tokens=m),Object.keys(_).length>0&&(b.extra=_),b}function e(u){let i=(Array.isArray(u.parts)?u.parts:[]).filter(a=>a&&typeof a=="object"&&a.type==="text"&&typeof a.text=="string"&&a.text).map(a=>a.text).join(`
|
|
19
|
-
`);return i.length===0?null:{sessionUpdate:"user_message_chunk",content:{type:"text",text:i}}}function n(u){let l=u.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}function r(u){let l=u.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l}}}function s(u){let l=u.part;if(!l)return [];let i=typeof l.callID=="string"?l.callID:"";if(i.length===0)return [];let a=typeof l.tool=="string"?l.tool:"",c=a.toLowerCase(),p=typeof l.state=="object"&&l.state?l.state:{},g=typeof p.input=="object"&&p.input?p.input:{},
|
|
20
|
-
`),s=
|
|
21
|
-
`).filter(u=>u.length>0).map(u=>{let[l,i]=u.split(" ");return {sha:l,name:i}});if(s.length===0||!s[0].sha)throw new j(`No matching ref ${JSON.stringify(n)} found in ${Ce(t)}`);let o=s[0];return (s.find(u=>u.name===`${o.name}^{}`)??o).sha}async function Mc(t,e={}){let n=wr(t);if(n.kind!=="git")return {ref:n.raw};let r=await vr(n,e),s;return n.viaSkillsSh?s=`skills.sh/${n.org}/${n.repo}${n.skillName?`/${n.skillName}`:""}@${r}`:n.subdir!==void 0||n.raw.includes("://")?s=`https://${n.host}/${n.org}/${n.repo}/tree/${r}${n.subdir?`/${n.subdir}`:""}`:s=`${n.org}/${n.repo}@${r}`,{ref:s,gitUrl:Ce(n),gitCommit:r}}async function yr(t){let e=[],n=async s=>{let o=s===""?t:X.join(t,s),d=await promises.readdir(o,{withFileTypes:true});for(let u of d){let l=s===""?u.name:`${s}/${u.name}`;u.isDirectory()?await n(l):u.isFile()&&e.push(l);}};await n(""),e.sort();let r=crypto.createHash("sha256");for(let s of e){let o=crypto.createHash("sha256").update(await promises.readFile(X.join(t,s))).digest("hex");r.update(s),r.update("\0"),r.update(o),r.update("\0");}return `sha256:${r.digest("hex")}`}async function tt(t){try{return (await promises.stat(t)).isFile()}catch{return false}}async function Sr(t){try{return (await promises.stat(t)).isDirectory()}catch{return false}}async function bi(t,e){if(!await Sr(t))throw new j(`Skill path does not exist or is not a directory: ${e}`);if(await tt(X.join(t,ae)))return [t];let r=(await promises.readdir(t,{withFileTypes:true})).filter(d=>d.isDirectory()&&!d.name.startsWith(".")).map(d=>d.name).sort(),s=[],o=[];for(let d of r)await tt(X.join(t,d,ae))?o.push(X.join(t,d)):s.push(d);if(s.length>0)throw new j(`Skill root ${e} contains child directories without ${ae}: ${s.join(", ")}`);if(o.length===0)throw new j(`Skill path ${e} must be a skill directory containing ${ae}, or a root whose immediate child directories each contain ${ae}.`);return o}async function Dc(t){let e=new Map;await tt(X.join(t,ae))&&e.set(X.basename(t),t);for(let n of _r){let r=X.join(t,n);if(!await Sr(r))continue;let s=await promises.readdir(r,{withFileTypes:true});for(let o of s.sort((d,u)=>d.name<u.name?-1:1)){if(!o.isDirectory()||o.name.startsWith("."))continue;let d=X.join(r,o.name);await tt(X.join(d,ae))&&e.set(o.name,d);}}return Array.from(e,([n,r])=>({dir:r,name:n}))}function Uc(t){return t.cacheDir??process.env.EVOLVE_SKILLS_CACHE??Tc}async function $c(t,e,n){let r=X.join(Uc(n),t.host,t.org,t.repo,e),s=X.join(r,t.repo),o=X.join(r,".evolve-complete");if(await tt(o)&&await Sr(s))return s;await promises.mkdir(X.dirname(r),{recursive:true});let d=await promises.mkdtemp(`${r}.tmp-`),u=X.join(d,t.repo),l=n.checkoutTimeoutMs??12e4,i={cwd:u,timeoutMs:l,gitEnv:n.gitEnv};try{await promises.mkdir(u),await oe(["init","--quiet"],i),await oe(["remote","add","origin",kr(t)],i),t.subdir?(await oe(["sparse-checkout","init","--cone"],i),await oe(["sparse-checkout","set",t.subdir],i)):(await oe(["sparse-checkout","init","--cone"],i),await oe(["sparse-checkout","set",..._r],i)),await oe(["fetch","--quiet","--depth=1","origin",e],i),await oe(["checkout","--quiet","FETCH_HEAD"],i),await promises.rm(X.join(u,".git"),{recursive:!0,force:!0}),await promises.writeFile(X.join(d,".evolve-complete"),""),await promises.rm(r,{recursive:!0,force:!0});try{await promises.rename(d,r);}catch{await promises.rm(d,{recursive:!0,force:!0});}return s}catch(a){throw await promises.rm(d,{recursive:true,force:true}),a}}async function _i(t,e){let n=0,r=0,s=async o=>{let d=await promises.readdir(o,{withFileTypes:true});for(let u of d){let l=X.join(o,u.name);if(u.isDirectory())await s(l);else if(u.isFile()&&(n+=1,r+=(await promises.stat(l)).size,n>mr||r>hr))throw new j(`Skill ${e} exceeds the size ceiling (${mr} files / ${hr} bytes) \u2014 a skill is instructions, not a dataset.`)}};await s(t);}async function xr(t,e={}){let n=new Map;for(let r of t){let s=wr(r);if(s.kind==="upload")throw new j(`Skill reference ${JSON.stringify(s.raw)} is a platform upload handle; only the hosted platform can resolve it. Use a skills.sh/git reference or a local folder here.`);if(s.kind==="name")throw new j(`Skill reference ${JSON.stringify(s.raw)} is a platform skill name \u2014 a moving pointer only the hosted platform can resolve (server-side, at job create). Use a skills.sh/git reference or a local folder here.`);if(s.kind==="local"){let l=await bi(s.path,s.raw);for(let i of l)await _i(i,s.raw),n.set(X.basename(i),{name:X.basename(i),dir:i,source:s.raw,digest:await yr(i)});continue}let o=await vr(s,e),d=await $c(s,o,e),u;if(s.subdir)u=(await bi(X.join(d,s.subdir),`${s.raw} (${s.subdir})`)).map(i=>({dir:i,name:X.basename(i)}));else if(u=await Dc(d),u.length===0)throw new j(`No skills found in ${Ce(s)}@${o.slice(0,12)}: expected ${ae} at the repo root or under ${_r.join(", ")}.`);if(s.skillName){let l=u.filter(i=>i.name===s.skillName);if(l.length===0)throw new j(`Skill ${JSON.stringify(s.skillName)} not found in ${Ce(s)}@${o.slice(0,12)}. Available: ${u.map(i=>i.name).sort().join(", ")||"(none)"}`);u=l;}for(let{dir:l,name:i}of u)await _i(l,s.raw),n.set(i,{name:i,dir:l,source:s.raw,gitUrl:Ce(s),gitCommit:o,digest:await yr(l)});}return Array.from(n.values()).sort((r,s)=>r.name<s.name?-1:r.name>s.name?1:0)}function en(t){return `'${t.replace(/'/g,"'\\''")}'`}async function Cr(t,e,n){if(e.length===0)return;let{tarGzipDirectory:r}=await Promise.resolve().then(()=>(gr(),pr));await t.files.makeDir(n);for(let s of e){let o=await r(s.dir),d=`${n}/.evolve-skill-${s.name}.tgz`,u=`${n}/${s.name}`;await t.files.write(d,o),await t.commands.run(`mkdir -p ${en(u)} && tar -xzf ${en(d)} -C ${en(u)} && rm -f ${en(d)}`,{timeoutMs:6e4});}}function Y(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function Re(t){return JSON.stringify(Lc__default.default(t,{target:"jsonSchema7"}),null,2)}function Te(t){return JSON.stringify(t,null,2)}function wi(t,e=false){let n={};function r(s,o){for(let d of Q__namespace.readdirSync(s)){let u=X__namespace.join(s,d),l=o?`${o}/${d}`:d;Q__namespace.statSync(u).isDirectory()?e&&r(u,l):n[l]=Q__namespace.readFileSync(u);}}return r(t,""),n}function ki(t,e){let n=X__namespace.resolve(t),r=n.endsWith(X__namespace.sep)?n:n+X__namespace.sep;for(let[s,o]of Object.entries(e)){let d=X__namespace.resolve(n,s);if(!d.startsWith(r))throw new Error(`Unsafe file path escapes target directory: ${s}`);let u=X__namespace.dirname(d);Q__namespace.mkdirSync(u,{recursive:true});let l;o instanceof ArrayBuffer||o instanceof Uint8Array?l=Buffer.from(o):l=o,Q__namespace.writeFileSync(d,l);}}var A=class extends Error{field;constructor(e,n){super(n),this.name="EvolveConfigError",this.field=e;}};function Rr(t){return typeof t=="string"&&t.trim()!==""}function Ee(t){return t==null?String(t):JSON.stringify(t)}function nt(t){if(!t)return;if(t.type!==void 0&&!Kn(t.type))throw new A("type",`Evolve agent config: unknown agent type ${Ee(t.type)}. Valid types: ${Object.keys(J).join(", ")}.`);let e=t.type??Nn;if(t.model!==void 0&&!Rr(t.model))throw new A("model",`Evolve agent config: "model" is empty (${Ee(t.model)}). Pass a model id such as "${K(e).defaultModel}", or omit model entirely to use ${e}'s default.`);if(t.config!==void 0){if(!Ri(e))throw new A("config",`Evolve agent config: agent "${e}" does not support a native config. Agents with native-config support: ${Ti().join(", ")}.`);let n=t.config;if(typeof n=="string"){if(!Rr(n))throw new A("config",`Evolve agent config: "config" is an empty path (${Ee(n)}). Pass a local settings file path or an inline JSON object.`)}else if(!rn(n))throw new A("config",`Evolve agent config: "config" must be a local file path or a JSON object, received ${Ee(n)}.`)}t.preset!==void 0&&Tr(e,t.preset);}function Tr(t,e){if(!Un.includes(e))throw new A("preset",`Evolve agent config: unknown preset ${Ee(e)}. Valid presets: ${Un.join(", ")}.`);let n=Ci(e);if(!n.includes(t))throw new A("preset",`Evolve agent config: agent "${t}" cannot guarantee preset "${e}". Agents that can: ${n.join(", ")}.`)}function xi(t){let e=J[t]?.presets;return e?Object.keys(e):[]}function Ci(t){return Object.keys(J).filter(e=>xi(e).includes(t))}function sn(t,e){let n={...t};for(let[r,s]of Object.entries(e)){let o=n[r];if(rn(o)&&rn(s))n[r]=sn(o,s);else if(Array.isArray(o)&&Array.isArray(s)){let d=[...o];for(let u of s)d.some(l=>Pe(l)===Pe(u))||d.push(u);n[r]=d;}else n[r]=s;}return n}function rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ri(t){return J[t]?.nativeConfig!==void 0}function Ti(){return Object.keys(J).filter(Ri)}function Nc(t,e){if(e===void 0)return;let n=J[t]?.nativeConfig;if(!n)throw new A("config",`Evolve agent config: agent "${t}" does not support a native config. Agents with native-config support: ${Ti().join(", ")}.`);let r;if(typeof e=="string"){let s=e.replace(/^~/,process.env.HOME||"");if(!Q__namespace.existsSync(s))throw new A("config",`Agent config file not found: ${s}`);let o=Q__namespace.readFileSync(s,"utf-8");try{r=n.format==="toml"?smolToml.parse(o):JSON.parse(o);}catch(d){throw new A("config",`Invalid ${t} config file ${e}: ${d.message}`)}}else {let s;try{s=JSON.parse(JSON.stringify(e));}catch(o){throw new A("config",`Invalid inline ${t} config: not JSON-serializable: ${o.message}`)}if(JSON.stringify(s)!==JSON.stringify(e))throw new A("config",`Invalid inline ${t} config: expected a JSON object that can be represented without conversion`);r=s;}if(!rn(r))throw new A("config",`Invalid ${t} config: expected a ${n.format==="toml"?"TOML table":"JSON object"}.`);if(n.format==="toml"){let s;try{s=smolToml.parse(smolToml.stringify(r));}catch(o){throw new A("config",`Invalid ${t} config for TOML conversion: ${o.message}`)}if(Pe(s)!==Pe(r))throw new A("config",`Invalid ${t} config: the document cannot be represented losslessly as TOML (TOML has no null and no mixed-type arrays)`)}return r}function Pe(t){return Array.isArray(t)?`[${t.map(Pe).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Pe(r)}`).join(",")}}`:JSON.stringify(t)??"null"}function Er(t){if(!t||!Rr(t.prompt))throw new A("prompt",`run() requires a non-empty "prompt" string, received ${Ee(t?.prompt)}.`)}function Pr(t){if(t){for(let e of We)if(e in t)throw new A(`observability.${e}`,`Evolve observability metadata: "${e}" is reserved for session identity and would split this run across two dashboard sessions. Reserved keys: ${We.join(", ")}. Use a different key, or set the session tag with .withSessionTagPrefix().`)}}function on(t){if(t.externalGateway){if(t.providerApiKey||t.providerBaseUrl||t.oauthToken)throw new Error("externalGateway cannot be combined with providerApiKey/providerBaseUrl/oauthToken (direct mode)");if(t.apiKey)throw new Error("externalGateway cannot be combined with apiKey (Evolve gateway mode)")}}function jc(t){let e=t.replace(/^~/,process.env.HOME||"");if(!Q__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return Q__namespace.readFileSync(e,"utf-8")}function Si(t,e,n){if(!e.providerEnvMap||!n)return;let r=n.indexOf("/");if(r<=0)return;let s=n.slice(0,r);if(!(e.providerEnvMap[s]||!ve(e,n)))throw new A("model",`Model "${n}" is served through the Evolve gateway only: the ${t} agent holds no ${s} key in direct mode. Set ${O} (or apiKey) to run it through the gateway, or pick a model whose route has a direct-mode key (${Object.keys(e.providerEnvMap).join(", ")}).`)}function an(t){let e=t?.type??Nn,n=K(e),r=Nc(e,t?.config);t?.preset!==void 0&&Tr(e,t.preset);let s={...r!==void 0?{config:r}:{},...t?.preset!==void 0?{preset:t.preset}:{}};if(t?.externalGateway){on(t);let{apiKey:l,baseUrl:i,revoke:a}=t.externalGateway;if(!l||!i||typeof a!="function")throw new Error("externalGateway requires apiKey, baseUrl, and a revoke() function");return {type:e,apiKey:l,baseUrl:i,isDirectMode:true,externalGateway:{revoke:a},model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize,...s}}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,maxContextSize:t.maxContextSize,...s}}if(t?.providerApiKey){Si(e,n,t.model);let l=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,i=t.providerBaseUrl??l??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:i,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize,...s}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize,...s};let o=process.env[O];if(o)return {type:e,apiKey:o,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s};if(n.providerEnvMap){let i=(t?.model??n.defaultModel)?.split("/")[0],a=i?n.providerEnvMap[i]:void 0,c=a?process.env[a.keyEnv]:void 0;if(c){let g=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:c,baseUrl:g,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}}let d=process.env[n.apiKeyEnv];if(d){Si(e,n,t?.model);let i=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:i,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}if(n.oauthEnv){let l=process.env[n.oauthEnv];if(l){if(n.oauthFileName){let i=jc(l);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:i,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}return {type:e,apiKey:l,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}}let u=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)${u}, or ${O} / ${n.apiKeyEnv} env var.`)}function Kc(t){return `e2b_${Buffer.from(t,"utf8").toString("hex")}`}var Mi=new WeakSet;function Mr(t){return Mi.add(t),t}function Ie(t){return Mi.has(t)}function Ii(t,e){return new Error(`${O} is set but ${t} failed to load.
|
|
22
|
-
Try installing: ${e}`)}function
|
|
23
|
-
Try reinstalling: npm install @evolvingmachines/evolve`):d}let e=process.env[
|
|
24
|
-
Try installing: npm install @evolvingmachines/daytona`):d}let n=process.env[
|
|
25
|
-
Try installing: npm install @evolvingmachines/modal`):d}let s=process.env[O];if(s)return
|
|
18
|
+
`)??""}};case "agent_message":return {sessionUpdate:"agent_message_chunk",content:{type:"text",text:i.text??""}};case "mcp_tool_call":{let p=d(i.result),g=i.status==="failed"||i.error?"failed":"completed";return {sessionUpdate:"tool_call_update",toolCallId:a,status:g,content:p,rawOutput:i}}case "command_execution":{let p=i.aggregated_output?[{type:"content",content:{type:"text",text:i.aggregated_output}}]:[],g=i.status==="completed"||i.exit_code===0?"completed":"failed";return {sessionUpdate:"tool_call_update",toolCallId:a,status:g,content:p,rawOutput:i}}case "file_change":{let p=i.changes??[],g=p.map(f=>({path:f.path})),m=p.length===1?`${p[0].kind==="add"?"Create":"Edit"} ${p[0].path}`:`Edit ${p.length} files`;return {sessionUpdate:"tool_call",toolCallId:a,title:m,toolName:"file_change",kind:"edit",status:i.status==="completed"?"completed":"failed",rawInput:{changes:p},content:p.map(f=>({type:"diff",path:f.path,oldText:f.kind==="add"?null:"",newText:""})),locations:g}}case "web_search":return {sessionUpdate:"tool_call",toolCallId:a,title:`Search: ${i.query??""}`,toolName:"web_search",kind:"fetch",status:"completed",content:[]};case "todo_list":return {sessionUpdate:"plan",entries:l(i.items)};default:return null}}function d(i){return i?.content?Array.isArray(i.content)?i.content.map(a=>({type:"content",content:u(a)})):typeof i.content=="string"?[{type:"content",content:{type:"text",text:i.content}}]:[]:[]}function u(i){return i.type==="text"?{type:"text",text:i.text??""}:i.type==="image"?{type:"image",data:i.data??"",mimeType:i.mime_type??i.mimeType??"",uri:i.uri}:i}function l(i){if(!Array.isArray(i))return [];let a=false;return i.map(c=>{let p;return c.completed?p="completed":a?p="pending":(p="in_progress",a=true),{content:c.text??"",status:p,priority:"medium"}})}}var Ul={applypatch:"edit",apply_patch:"edit",create:"edit",edit:"edit",grep:"search",glob:"search",ls:"search",read:"read",write:"edit",execute:"execute",execute_cli:"execute",fetchurl:"fetch",fetch_url:"fetch",webfetch:"fetch",web_fetch:"fetch",websearch:"fetch",web_search:"fetch",skill:"execute",task:"think",todowrite:"other",todo_write:"other"},Ll=new Set(["assistant_text_complete","thinking_text_complete","droid_working_state_changed","permission_resolved","settings_updated","session_title_updated","mcp_status_changed","session_token_usage_changed","mission_state_changed","mission_features_changed","mission_progress_entry","mission_heartbeat","mission_worker_started","mission_worker_completed","mcp_auth_required","mcp_auth_completed","structured_output"]);function Wt(){let t=new Map,e,n,r=false,s="",o;return function(u){let l;try{l=JSON.parse(u);}catch{return null}if(!ii(l))return null;let i=$l(l);if(i.sessionId&&(e=i.sessionId),i.errorText)return [sr(e,i.errorText,true)];if(i.resultText)return s=i.resultText,r=true,[xe(e,i.resultText)];if(i.handled)return null;let c=Fl(l)??l,p=si(c);p&&(e=p);let g=[],m=C(c,"type");switch(m){case "system":{let h=C(c,"model");return h&&(n=h),null}case "message":{let h=C(c,"role"),y=C(c,"text")||or(c.content);if(!y)break;h==="assistant"&&(r=true,s=y,g.push(xe(e,y)));break}case "completion":{let h=C(c,"finalText")||C(c,"result");h&&(!r||h!==s)&&(r=true,s=h,g.push(xe(e,h)));let y=tt(c.usage);y&&g.push({sessionId:e,update:{sessionUpdate:"usage",scope:"run",usage:y}});break}case "assistant_text_delta":{let h=C(c,"textDelta")||C(c,"text");h&&(r=true,s+=h,g.push(xe(e,h)));break}case "thinking_text_delta":{let h=C(c,"textDelta")||C(c,"text");if(h){let y=ni(c,h,o);y&&(o=y.signature,g.push({sessionId:e,update:y.event}));}break}case "reasoning":{let h=C(c,"text");if(h){let y=ni(c,h,o);y&&(o=y.signature,g.push({sessionId:e,update:y.event}));}break}case "assistant":{let h=C(c,"text")||or(U(c.message)?.content);h&&(r=true,s=h,g.push(xe(e,h)));break}case "tool_call":case "tool_call_delta":{let h=U(c.toolUse)??U(c.tool_use)??c,y=ri(h,t);y&&g.push({sessionId:e,update:y});break}case "tool_result":{let h=Nl(c,t);h&&g.push({sessionId:e,update:h});break}case "tool_progress_update":case "tool_progress":{let h=jl(c);h&&g.push({sessionId:e,update:h});break}case "create_message":{for(let h of Bl(c,t)){if(h.sessionUpdate==="agent_message_chunk"){let y=h.content.type==="text"?h.content.text:"";if(r&&y===s)continue;r=true,s=y;}g.push({sessionId:e,update:h});}break}case "result":{if(c.is_error===true||c.subtype==="failure"){g.push(sr(e,D([ie(c.result),ie(c.error),ie(c.subtype)],c),true));break}let h=ie(c.result??c.text??c.error);h&&(r=true,s=h,g.push(xe(e,h)));break}case "error":{g.push(sr(e,D([ie(c.message),ie(c.error)],c),false));break}default:if(m&&!Ll.has(m))return null}if(g.length>0&&m!=="reasoning"&&m!=="thinking_text_delta"&&(o=void 0),g.length===0)return null;let f=ue(c.timestamp);return g.map(h=>({...h,...f!==void 0?{timestamp:f}:{},...n!==void 0?{model:n}:{}}))}}function ni(t,e,n){let r=ir(t,"id")||ir(t,"messageId"),s=ir(t,"blockIndex"),o=`${C(t,"type")}:${r}:${s}:${e}`;return o===n?null:{signature:o,event:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e}}}}function $l(t){if(t.type!=="response")return {handled:false};let e=U(t.result),n=U(t.error),r=si(e??t);if(n)return {handled:true,sessionId:r,errorText:ie(n.message??n)};let s=e?C(e,"finalText")||C(e,"result"):"";return {handled:true,sessionId:r,resultText:s}}function Fl(t){return t.method!=="droid.session_notification"?null:U(U(t.params)?.notification)}function Bl(t,e){let n=U(t.message);if(!n)return [];let r=[],s=n.content;if(Array.isArray(s))for(let o of s){let d=U(o);if(d&&d.type==="tool_use"){let u=ri(d,e);u&&r.push(u);}}if(n.role==="assistant"){let o=or(s);o&&r.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:o}});}return r}function ri(t,e){let n=C(t,"id")||C(t,"toolUseId")||C(t,"tool_use_id"),r=C(t,"name")||C(t,"toolName")||C(t,"tool_name")||"Tool";if(!n)return null;e.set(n,r);let s=U(t.input)??U(t.toolInput)??U(t.arguments)??U(t.parameters)??{};if(oi(r)==="todowrite"){let i=Jl(s);if(i)return i}let{title:o,kind:d,content:u,locations:l}=Kl(r,s);return {sessionUpdate:"tool_call",toolCallId:n,title:o,toolName:r,kind:d,status:"pending",rawInput:s,content:u,locations:l}}function Nl(t,e){let n=C(t,"toolUseId")||C(t,"tool_use_id")||C(t,"tool_id")||C(t,"id")||C(t,"toolId");if(!n)return null;let r=C(t,"toolName")||C(t,"tool_name")||e.get(n);return e.delete(n),{sessionUpdate:"tool_call_update",toolCallId:n,status:t.isError===true||t.is_error===true?"failed":"completed",title:r,content:ar(t.content??t.result??t.value??t.error)}}function jl(t){let e=C(t,"toolUseId")||C(t,"tool_use_id")||C(t,"tool_id")||C(t,"id")||C(t,"toolId");if(!e)return null;let n=U(t.update),r=ie(t.content??n?.text??n?.status??n?.details);return {sessionUpdate:"tool_call_update",toolCallId:e,status:"in_progress",content:r?ar(r):void 0}}function Jl(t){let e=t.todos;if(!Array.isArray(e))return null;let n=e.flatMap(r=>{let s=U(r);if(!s)return [];let o=C(s,"content"),d=Gl(C(s,"status")),u=Vl(C(s,"priority"));return o?[{content:o,status:d,priority:u}]:[]});return n.length>0?{sessionUpdate:"plan",entries:n}:null}function Kl(t,e){let n=Ul[oi(t)]||"other",r=C(e,"path")||C(e,"filePath")||C(e,"file_path")||C(e,"absolute_path"),s=C(e,"command"),o=C(e,"url"),d=r||s||o;return {title:d?`${t} ${d}`:t,kind:n,content:Object.keys(e).length>0?ar(e):[],locations:r?[{path:r}]:[]}}function si(t){if(t)return C(t,"session_id")||C(t,"sessionId")}function xe(t,e){return {sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e}}}}function sr(t,e,n){return {sessionId:t,update:{sessionUpdate:"error",message:e,fatal:n}}}function or(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{let n=U(e);return n?C(n,"text")||C(n,"content"):""}).filter(Boolean).join(""):""}function ar(t){let e=ie(t);return e?[{type:"content",content:{type:"text",text:e}}]:[]}function ie(t){if(typeof t=="string")return t;if(t==null)return "";try{return JSON.stringify(t)}catch{return String(t)}}function ii(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function U(t){return ii(t)?t:null}function C(t,e){let n=t[e];return typeof n=="string"?n:""}function ir(t,e){let n=t[e];return typeof n=="string"||typeof n=="number"||typeof n=="boolean"?String(n):""}function oi(t){return t.replace(/[-_\s]/g,"").toLowerCase()}function Gl(t){return t==="in_progress"||t==="completed"?t:"pending"}function Vl(t){return t==="high"||t==="low"?t:"medium"}var Hl={read_file:"read",read_many_files:"read",write_file:"edit",replace:"edit",edit_file:"edit",run_shell_command:"execute",shell:"execute",glob:"search",grep:"search",search_file_content:"search",list_directory:"search",brave_web_search:"fetch",web_search:"fetch",google_web_search:"fetch",web_fetch:"fetch",delegate_to_agent:"think",write_todos:"other",save_memory:"other",activate_skill:"other"};function Yt(){let t,e;return function(i){let a;try{a=JSON.parse(i);}catch{return null}if(a._meta||a._prompt)return null;let c=(typeof a.session_id=="string"&&a.session_id?a.session_id:void 0)??e,p=[];switch(a.type){case "init":return typeof a.model=="string"&&a.model&&(t=a.model),typeof a.session_id=="string"&&a.session_id&&(e=a.session_id),null;case "result":{let m=n(a.stats);if(m&&p.push({sessionId:c,update:{sessionUpdate:"usage",scope:"run",usage:m}}),a.status!=="error")break;p.push({sessionId:c,update:{sessionUpdate:"error",message:D([a.error?.message,a.error?.type,'gemini ended the run with result status "error" and no error text'],a.error??a),fatal:true}});break}case "message":{let m=r(a);m&&p.push({sessionId:c,update:m});break}case "tool_use":{let m=s(a);m&&p.push({sessionId:c,update:m});break}case "tool_result":{let m=o(a);m&&p.push({sessionId:c,update:m});break}case "error":{let m=d(a);m&&p.push({sessionId:c,update:m});break}default:return null}if(p.length===0)return null;let g=ue(a.timestamp);return p.map(m=>({...m,...g!==void 0?{timestamp:g}:{},...t!==void 0?{model:t}:{}}))};function n(l){if(!l||typeof l!="object"||Array.isArray(l))return null;let i=l,a=h=>typeof h=="number"&&Number.isFinite(h)?h:void 0,c={},p=a(i.input_tokens),g=a(i.output_tokens),m=a(i.cached);p!==void 0&&(c.promptTokens=p),g!==void 0&&(c.completionTokens=g),m!==void 0&&(c.cachedTokens=m);let f={};for(let[h,y]of Object.entries(i))h==="input_tokens"||h==="output_tokens"||h==="cached"||y!=null&&(f[h]=y);return Object.keys(f).length>0&&(c.extra=f),c}function r(l){let i=l.role,a=l.content;return a?i==="assistant"?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a}}:i==="user"?{sessionUpdate:"user_message_chunk",content:{type:"text",text:a}}:null:null}function s(l){let i=l.tool_id,a=l.tool_name,c=l.parameters||{},{title:p,kind:g,content:m,locations:f}=u(a,c);return {sessionUpdate:"tool_call",toolCallId:i,title:p,toolName:a,kind:g,status:"pending",rawInput:c,content:m,locations:f}}function o(l){let i=l.tool_id,a=l.status,c=l.output,p=l.error,g=[];return c&&typeof c=="string"&&c.length>0&&g.push({type:"content",content:{type:"text",text:c}}),p?.message&&!c&&g.push({type:"content",content:{type:"text",text:p.message}}),{sessionUpdate:"tool_call_update",toolCallId:i,status:a==="success"?"completed":"failed",content:g}}function d(l){return {sessionUpdate:"error",message:D([l.message],l),fatal:false}}function u(l,i){let a=Hl[l]||"other",c=[],p=[],g=l;switch(l){case "read_file":g=`Read ${i.absolute_path||i.file_path||"file"}`,(i.absolute_path||i.file_path)&&p.push({path:i.absolute_path||i.file_path});break;case "write_file":g=`Write ${i.file_path||"file"}`,i.file_path&&(p.push({path:i.file_path}),c.push({type:"diff",path:i.file_path,oldText:null,newText:i.content||""}));break;case "edit_file":g=`Edit ${i.file_path||"file"}`,i.file_path&&p.push({path:i.file_path});break;case "replace":g=`Edit ${i.file_path||"file"}`,i.file_path&&(p.push({path:i.file_path}),(i.old_string!==void 0||i.new_string!==void 0)&&c.push({type:"diff",path:i.file_path,oldText:i.old_string||"",newText:i.new_string||""}));break;case "run_shell_command":case "shell":g=i.command?`\`${i.command}\``:"Run command",i.description&&c.push({type:"content",content:{type:"text",text:i.description}});break;case "brave_web_search":case "web_search":case "google_web_search":g=i.query?`"${i.query}"`:"Web search";break;case "web_fetch":g=i.prompt?`Fetch: ${i.prompt.substring(0,50)}...`:"Web fetch";break;case "glob":g=`Find ${i.pattern||"files"}`,i.dir_path&&p.push({path:i.dir_path});break;case "grep":case "search_file_content":g=`grep "${i.pattern||i.query||""}"`;break;case "list_directory":g=`List ${i.dir_path||i.path||"directory"}`,(i.dir_path||i.path)&&p.push({path:i.dir_path||i.path});break;case "read_many_files":g=`Read ${i.include?.length||"multiple"} files`,Array.isArray(i.include)&&i.include.forEach(m=>p.push({path:m}));break;case "delegate_to_agent":g=i.agent_name?`Agent: ${i.agent_name}`:"Delegate to agent";break;case "write_todos":g="Update todos";break;case "save_memory":g=i.fact?`Remember: "${i.fact.substring(0,40)}..."`:"Save memory";break;case "activate_skill":g=i.name?`Activate skill: ${i.name}`:"Activate skill";break;default:g=l;}return {title:g,kind:a,content:c,locations:p}}}var zl={Read:"read",ReadFile:"read",ReadMediaFile:"read",Write:"edit",WriteFile:"edit",Edit:"edit",StrReplaceFile:"edit",Bash:"execute",Shell:"execute",Glob:"search",Grep:"search",WebSearch:"fetch",SearchWeb:"fetch",FetchURL:"fetch",Agent:"think",AgentSwarm:"think",Task:"think",Think:"think",CreateSubagent:"think",TodoList:"other",SetTodoList:"other"};function ai(t){return t==="TodoList"||t==="SetTodoList"}function cr(t){return /<system>\s*ERROR:/i.test(t)||t.includes("<error>")||t.includes("ToolError")}function ci(t){let e=/^data:([^;,]+)((?:;[^,]*)*),(.+)$/i.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function dr(t){if(!t||typeof t!="object")return null;if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {type:"content",content:{type:"text",text:t.text}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=ci(e);return n?{type:"content",content:{type:"image",data:n.data,mimeType:n.mimeType}}:{type:"content",content:{type:"image",data:"",mimeType:"",uri:e}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{type:"content",content:{type:"text",text:`[video] ${t.video_url.url}`}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{type:"content",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}:null}function lr(t){let e=[];if(typeof t=="string")return t.length>0&&e.push({type:"content",content:{type:"text",text:t}}),e;if(Array.isArray(t)){for(let n of t){if(typeof n=="string"&&n.length>0){e.push({type:"content",content:{type:"text",text:n}});continue}let r=dr(n);r&&e.push(r);}return e}if(t&&typeof t=="object"){let n=dr(t);n&&e.push(n);}return e}function ql(t){return t.some(e=>e.type==="content"&&e.content.type==="text"&&cr(e.content.text))}function Wl(t){if(!t||typeof t!="object")return null;if(t.type==="think"&&typeof t.think=="string"&&t.think.length>0)return {update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t.think}}};if(t.type==="text"&&typeof t.text=="string"&&t.text.length>0)return {update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.text}}};if(t.type==="image_url"&&typeof t.image_url?.url=="string"){let e=t.image_url.url,n=ci(e);return n?{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:n.data,mimeType:n.mimeType}}}:{update:{sessionUpdate:"agent_message_chunk",content:{type:"image",data:"",mimeType:"",uri:e}}}}return t.type==="video_url"&&typeof t.video_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[video] ${t.video_url.url}`}}}:t.type==="audio_url"&&typeof t.audio_url?.url=="string"?{update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[audio] ${t.audio_url.url}`}}}:null}function Yl(t){return t==="in_progress"?"in_progress":t==="done"||t==="completed"?"completed":"pending"}function li(t){if(!t||typeof t!="object")return [];let e=t.todos;return Array.isArray(e)?e.map(n=>{if(!n||typeof n!="object")return null;let r=n.title;if(typeof r!="string"||r.length===0)return null;let s=n.status;return {content:r,status:Yl(s),priority:"medium"}}).filter(n=>n!==null):[]}function ur(){let t=new Set,e=0;function n(u,l){return typeof u=="string"&&u.length>0?u:(e+=1,`kimi_${l.replace(/[^a-zA-Z0-9_]/g,"_")||"tool"}_${e}`)}return function(l){let i;try{i=JSON.parse(l);}catch{return null}if(!i||typeof i!="object")return null;let a=i.role;return "_meta"in i||"_prompt"in i?null:a==="meta"?i.type!=="turn.step.retrying"?null:[{update:{sessionUpdate:"error",message:D([i.error_message,i.error_name],i),fatal:false}}]:a==="assistant"?r(i):a==="tool"?s(i):typeof i.type=="string"&&"payload"in i?o(i):null};function r(u){let l=[],i=u.content,a=u.tool_calls;if(typeof i=="string"&&i.length>0)l.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}}});else if(Array.isArray(i))for(let c of i){let p=Wl(c);p&&l.push(p);}if(Array.isArray(a))for(let c of a){if(!c||typeof c!="object")continue;let p=c.function;if(!p)continue;let g=p.name??"",m=n(c.id,g),f;try{f=p.arguments?JSON.parse(p.arguments):{};}catch{f=p.arguments;}if(ai(g)){let w=li(f);w.length>0&&l.push({update:{sessionUpdate:"plan",entries:w}}),t.add(m);continue}let{title:h,kind:y,toolContent:b,locations:_}=d(g,typeof f=="object"&&f!==null?f:{});l.push({update:{sessionUpdate:"tool_call",toolCallId:m,title:h,toolName:g,kind:y,status:"pending",rawInput:f,content:b,locations:_}});}return l.length>0?l:null}function s(u){let l=u.tool_call_id;if(typeof l!="string"||l.length===0)return null;if(t.has(l))return t.delete(l),null;let i=u.content,a=[],c=false;if(typeof i=="string")c=cr(i),i.length>0&&a.push({type:"content",content:{type:"text",text:i}});else if(Array.isArray(i))for(let p of i){let g=dr(p);g&&(g.type==="content"&&g.content.type==="text"&&cr(g.content.text)&&(c=true),a.push(g));}return [{update:{sessionUpdate:"tool_call_update",toolCallId:l,status:c?"failed":"completed",content:a}}]}function o(u){let l=u.type,i=u.payload??{},a=[];switch(l){case "TextPart":{let c=i.text;typeof c=="string"&&c.length>0&&a.push({update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}});break}case "ThinkPart":{let c=i.think;typeof c=="string"&&c.length>0&&a.push({update:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c}}});break}case "ToolCall":{let c=i.function?.name??"",p=n(i.id,c),g=i.function;if(!g)break;let m;try{m=g.arguments?JSON.parse(g.arguments):{};}catch{m=g.arguments;}if(ai(c)){let _=li(m);_.length>0&&a.push({update:{sessionUpdate:"plan",entries:_}}),t.add(p);break}let{title:f,kind:h,toolContent:y,locations:b}=d(c,typeof m=="object"&&m!==null?m:{});a.push({update:{sessionUpdate:"tool_call",toolCallId:p,title:f,toolName:c,kind:h,status:"pending",rawInput:m,content:y,locations:b}});break}case "ToolResult":{let c=i.tool_call_id;if(typeof c!="string"||c.length===0)break;if(t.has(c)){t.delete(c);break}let p=i.return_value??i.content,g=[],m=i.is_error===true;if(p&&typeof p=="object"&&!Array.isArray(p)){let f=p;m=m||f.type==="ToolError"||f.is_error===true,g.push(...lr(f.output)),g.length===0&&typeof f.message=="string"&&f.message.length>0&&g.push({type:"content",content:{type:"text",text:f.message}}),g.length===0&&g.push(...lr(p));}else g.push(...lr(p));m=m||ql(g),a.push({update:{sessionUpdate:"tool_call_update",toolCallId:c,status:m?"failed":"completed",content:g}});break}default:return null}return a.length>0?a:null}function d(u,l){let i=zl[u]||"other",a=[],c=[],p=u;switch(u){case "Read":case "ReadFile":{let g=l.path??l.file_path;p=`Read ${g||"file"}`,g&&c.push({path:g});break}case "ReadMediaFile":{let g=l.path??l.file_path;p=`Read media ${g||"file"}`,g&&c.push({path:g});break}case "Write":case "WriteFile":{let g=l.path??l.file_path;p=`Write ${g||"file"}`,g&&(c.push({path:g}),typeof l.content=="string"&&a.push({type:"diff",path:g,oldText:null,newText:l.content}));break}case "Edit":case "StrReplaceFile":{let g=l.path??l.file_path;p=`Edit ${g||"file"}`,g&&c.push({path:g});break}case "Bash":case "Shell":p=l.command?`\`${l.command}\``:"Run command";break;case "Glob":p=`Find ${l.pattern||"files"}`,l.path&&c.push({path:l.path});break;case "Grep":p=`grep "${l.pattern||""}"`,l.path&&c.push({path:l.path});break;case "WebSearch":case "SearchWeb":p=l.query?`"${l.query}"`:"Web search";break;case "FetchURL":p=l.url?`Fetch ${l.url}`:"Web fetch";break;case "Agent":case "AgentSwarm":case "Task":p=l.description||"Subagent task";break;case "Think":p=l.thought||"Thinking";break;case "CreateSubagent":p=l.name?`Subagent: ${l.name}`:"Create subagent";break;case "TodoList":case "SetTodoList":p="Update todos";break;default:p=u;}return {title:p,kind:i,toolContent:a,locations:c}}}var Xl={read:"read",write:"edit",edit:"edit",multiedit:"edit",apply_patch:"edit",bash:"execute",glob:"search",grep:"search",list:"search",codesearch:"search",lsp:"search",webfetch:"fetch",websearch:"fetch",task:"think",batch:"think",plan_enter:"switch_mode",plan_exit:"switch_mode",todoread:"other",todowrite:"other",skill:"other",question:"other"};function Ql(t){let e=/^data:([^;,]+)?((?:;[^,]+)*),(.*)$/s.exec(t);if(!e)return null;let n=e[1]||"",r=e[2]||"",s=e[3]||"";return /;base64/i.test(r)?{mimeType:n,data:s}:null}function Zl(t){if(typeof t!="string")return "pending";switch(t.toLowerCase()){case "in_progress":case "in-progress":case "running":return "in_progress";case "completed":case "done":case "cancelled":return "completed";default:return "pending"}}function ec(t){return t==="high"||t==="medium"||t==="low"?t:"medium"}function di(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return null;let n=e.content;return typeof n!="string"||n.length===0?null:{content:n,status:Zl(e.status),priority:ec(e.priority)}}).filter(e=>e!==null):[]}function tc(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.mime=="string"?e.mime:"",r=typeof e.url=="string"?e.url:"";if(n.startsWith("image/")){if(r.length>0){let u=Ql(r);return u?{type:"content",content:{type:"image",data:u.data,mimeType:u.mimeType||n}}:{type:"content",content:{type:"image",data:"",mimeType:n,uri:r}}}return null}return {type:"content",content:{type:"text",text:`[attachment] ${(typeof e.filename=="string"?e.filename:"")||"attachment"} (${n||"file"})`}}}function nc(t,e){if(t==="error")return typeof e.error=="string"?e.error:null;if(typeof e.output=="string")return e.output;if(e.output===void 0||e.output===null)return null;try{return JSON.stringify(e.output)}catch{return String(e.output)}}function rc(t,e){return t==="error"?"failed":t==="running"?"in_progress":t==="pending"?"pending":typeof e=="number"&&e!==0?"failed":"completed"}function pr(){return function(l){let i;try{i=JSON.parse(l);}catch{return null}if(!i||typeof i!="object")return null;let a=i.sessionID,c=[];switch(i.type){case "step_start":return null;case "step_finish":{let g=t(i.part);if(!g)return null;c.push({sessionUpdate:"usage",scope:"call",usage:g});break}case "user":{let g=e(i);g&&c.push(g);break}case "text":{let g=n(i);g&&c.push(g);break}case "reasoning":{let g=r(i);g&&c.push(g);break}case "tool_use":{c.push(...s(i));break}case "error":{let g=o(i);g&&c.push(g);break}default:return null}if(c.length===0)return null;let p=ue(i.timestamp);return c.map(g=>({sessionId:a,update:g,...p!==void 0?{timestamp:p}:{}}))};function t(u){if(!u||typeof u!="object")return null;let l=u.tokens;if(!l||typeof l!="object")return null;let i=l,a=typeof i.cache=="object"&&i.cache?i.cache:{},c=w=>typeof w=="number"&&Number.isFinite(w)?w:void 0,p=c(i.input),g=c(i.output),m=c(a.read),f=c(a.write),h=c(i.reasoning),y=c(u.cost),b={};(p!==void 0||m!==void 0)&&(b.promptTokens=(p??0)+(m??0)),g!==void 0&&(b.completionTokens=g),m!==void 0&&(b.cachedTokens=m),y!==void 0&&y>0&&(b.costUsd=y);let _={};return h&&(_.reasoning_tokens=h),f&&(_.cache_write_tokens=f),Object.keys(_).length>0&&(b.extra=_),b}function e(u){let i=(Array.isArray(u.parts)?u.parts:[]).filter(a=>a&&typeof a=="object"&&a.type==="text"&&typeof a.text=="string"&&a.text).map(a=>a.text).join(`
|
|
19
|
+
`);return i.length===0?null:{sessionUpdate:"user_message_chunk",content:{type:"text",text:i}}}function n(u){let l=u.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:l}}}function r(u){let l=u.part?.text;return typeof l!="string"||l.length===0?null:{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:l}}}function s(u){let l=u.part;if(!l)return [];let i=typeof l.callID=="string"?l.callID:"";if(i.length===0)return [];let a=typeof l.tool=="string"?l.tool:"",c=a.toLowerCase(),p=typeof l.state=="object"&&l.state?l.state:{},g=typeof p.input=="object"&&p.input?p.input:{},m=p.status,f=p.title??p.metadata?.description??c,h=p.metadata?.exit,{kind:y,content:b,locations:_}=d(c,g),w=[];if(w.push({sessionUpdate:"tool_call",toolCallId:i,title:f,toolName:a,kind:y,status:"pending",rawInput:g,content:b,locations:_}),c==="todowrite"){let R=di(g.todos);if(R.length===0&&typeof p.output=="string")try{R=di(JSON.parse(p.output));}catch{}R.length>0&&w.push({sessionUpdate:"plan",entries:R});}let S=rc(m,h);if(S==="pending")return w;let v=nc(m,p),x=[];if(typeof v=="string"&&v.length>0&&x.push({type:"content",content:{type:"text",text:v}}),Array.isArray(p.attachments))for(let R of p.attachments){let E=tc(R);E&&x.push(E);}return w.push({sessionUpdate:"tool_call_update",toolCallId:i,status:S,content:x,rawOutput:p}),w}function o(u){return {sessionUpdate:"error",message:D([u.error?.data?.message,u.error?.message,u.error?.name],u.error??u),fatal:false}}function d(u,l){let i=Xl[u]||"other",a=[],c=[];switch(u){case "read":{let p=l.filePath??l.path;if(p){let g=l.offset;c.push({path:p,line:typeof g=="number"&&Number.isFinite(g)?Math.max(0,g-1):void 0});}break}case "write":{let p=l.filePath??l.path;p&&(c.push({path:p}),typeof l.content=="string"&&a.push({type:"diff",path:p,oldText:null,newText:l.content}));break}case "edit":case "multiedit":{let p=l.filePath??l.path;p&&(c.push({path:p}),u==="edit"&&(l.oldString!==void 0||l.newString!==void 0)&&a.push({type:"diff",path:p,oldText:l.oldString??"",newText:l.newString??""}));break}case "apply_patch":break;case "bash":{let p=l.command;p&&l.description?a.push({type:"content",content:{type:"text",text:l.description}}):p&&a.push({type:"content",content:{type:"text",text:p}});break}case "glob":case "list":{let p=l.path;p&&c.push({path:p});break}case "grep":{let p=l.path;p&&c.push({path:p});break}case "codesearch":case "websearch":{let p=l.query;p&&a.push({type:"content",content:{type:"text",text:p}});break}case "webfetch":{let p=l.url;p&&a.push({type:"content",content:{type:"text",text:p}});break}case "task":{let p=l.description;p&&a.push({type:"content",content:{type:"text",text:p}});break}}return {kind:i,content:a,locations:c}}}var sc={Read:"read",read_file:"read",Write:"edit",Edit:"edit",write_file:"edit",edit_file:"edit",Bash:"execute",BashOutput:"execute",KillShell:"execute",shell:"execute",run_shell_command:"execute",WebFetch:"fetch",WebSearch:"fetch",brave_web_search:"fetch",Glob:"search",Grep:"search",LS:"search",list_directory:"search",Task:"think",TodoWrite:"other",ExitPlanMode:"switch_mode"};function Xt(){let t=new Map,e=new Map;return function(c){let p;try{p=JSON.parse(c);}catch{return null}if(!p||typeof p!="object")return null;let g=p;if("_meta"in g||"_prompt"in g)return null;let m=g.session_id||void 0,f=[];switch(g.type){case "assistant":{let v=g;f.push(...r(v));let x=n(v.message?.usage);x&&f.push({sessionUpdate:"usage",scope:"call",usage:x});break}case "stream_event":{f.push(...s(g));break}case "user":{f.push(...o(g));break}case "system":return null;case "result":{let v=n(g.usage);if(v&&f.push({sessionUpdate:"usage",scope:"run",usage:v}),g.is_error!==true)break;let x=g.error;f.push({sessionUpdate:"error",message:D([x?.message,g.subtype],g.error??g),fatal:true});break}default:return null}if(f.length===0)return null;let h=g.message,y=typeof h?.model=="string"&&h.model?h.model:void 0,b=typeof h?.id=="string"&&h.id?h.id:void 0,_=typeof g.parent_tool_use_id=="string"&&g.parent_tool_use_id?g.parent_tool_use_id:void 0,w=h?.stop_reason,S=w!=null?{stop_reason:w}:void 0;return f.map(v=>({sessionId:m,update:v,...y!==void 0?{model:y}:{},...b!==void 0?{messageId:b}:{},..._!==void 0?{parentToolCallId:_}:{},...S!==void 0?{extra:S}:{}}))};function n(a){if(!a||typeof a!="object"||Array.isArray(a))return null;let c=a,p=b=>typeof b=="number"&&Number.isFinite(b)?b:void 0,g={},m=p(c.input_tokens),f=p(c.output_tokens),h=p(c.cache_read_input_tokens);m!==void 0&&(g.promptTokens=m),f!==void 0&&(g.completionTokens=f),h!==void 0&&(g.cachedTokens=h);let y={};for(let[b,_]of Object.entries(c))b==="input_tokens"||b==="output_tokens"||b==="cache_read_input_tokens"||_!=null&&(y[b]=_);return Object.keys(y).length>0&&(g.extra=y),g}function r(a){let c=[],p=a.message?.content;if(!Array.isArray(p))return c;for(let g of p){let m=d(g);c.push(...m);}return c}function s(a){let c=[],p=a.event;if(!p)return c;switch(p.type){case "content_block_start":{let g=p.index??0,m=p.content_block;m&&(t.set(g,m),m.type==="tool_use"&&e.set(g,""));break}case "content_block_delta":{let g=p.index??0,m=p.delta,f=t.get(g);if(m?.type==="text_delta"&&m.text)c.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:m.text}});else if(m?.type==="thinking_delta"&&m.thinking)c.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:m.thinking}});else if(m?.type==="input_json_delta"&&m.partial_json&&f?.type==="tool_use"){let h=e.get(g)||"";e.set(g,h+m.partial_json);}break}case "content_block_stop":{let g=p.index??0,m=t.get(g);if(m&&!(m.type==="text"&&m.text)){if(!(m.type==="thinking"&&m.thinking)){if(m.type==="tool_use"){let f=m,h=e.get(g)||"";e.delete(g);let y=f.input;if(h)try{y=JSON.parse(h);}catch{}let b={...f,input:y},_=u(b);_&&c.push(_);}else if(m.type==="tool_result"){let f=l(m);f&&c.push(f);}}}t.delete(g);break}}return c}function o(a){let c=a.message?.content,p=[];if(typeof c=="string")return p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:c}}),p;if(Array.isArray(c)){for(let g of c)if(g.type==="text")p.push({sessionUpdate:"user_message_chunk",content:{type:"text",text:g.text}});else if(g.type==="tool_result"){let m=l(g);m&&p.push(m);}}return p}function d(a){switch(a.type){case "text":return a.text?[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:a.text}}]:[];case "thinking":return a.thinking?[{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:a.thinking}}]:[];case "tool_use":{let c=u(a);return c?[c]:[]}case "tool_result":{let c=l(a);return c?[c]:[]}}}function u(a){let c=a.id,p=a.name,g=a.input;if(p==="TodoWrite"&&Array.isArray(g?.todos))return {sessionUpdate:"plan",entries:g.todos.map(b=>({content:b.content,status:b.status||"pending",priority:"medium"}))};let{title:m,kind:f,content:h,locations:y}=i(p,g||{});return {sessionUpdate:"tool_call",toolCallId:c,title:m,toolName:p,kind:f,status:"pending",rawInput:g,content:h,locations:y}}function l(a){let c=a.tool_use_id,p=a.is_error??false,g=a.content,m=[];if(typeof g=="string"&&g.length>0)m.push({type:"content",content:{type:"text",text:g}});else if(Array.isArray(g))for(let f of g)f.type==="text"&&m.push({type:"content",content:{type:"text",text:f.text}});return {sessionUpdate:"tool_call_update",toolCallId:c,status:p?"failed":"completed",content:m}}function i(a,c){let p=sc[a]||"other",g=[],m=[],f=a;switch(a){case "Read":case "read_file":f=`Read ${c.file_path||c.absolute_path||"file"}`,(c.file_path||c.absolute_path)&&m.push({path:c.file_path||c.absolute_path});break;case "Write":case "write_file":f=`Write ${c.file_path||"file"}`,c.file_path&&(m.push({path:c.file_path}),g.push({type:"diff",path:c.file_path,oldText:null,newText:c.content||""}));break;case "Edit":case "edit_file":f=`Edit ${c.file_path||"file"}`,c.file_path&&m.push({path:c.file_path});break;case "Bash":case "shell":case "run_shell_command":f=c.command?`\`${c.command}\``:"Run command",c.description&&g.push({type:"content",content:{type:"text",text:c.description}});break;case "WebFetch":f=c.url?`Fetch ${c.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":f=c.query?`"${c.query}"`:"Web search";break;case "Glob":f=`Find ${c.pattern||"files"}`,c.path&&m.push({path:c.path});break;case "Grep":f=`grep "${c.pattern||""}"`;break;case "LS":case "list_directory":f=`List ${c.path||"directory"}`,c.path&&m.push({path:c.path});break;case "Task":f=c.description||"Subagent task";break;case "TodoWrite":f="Update todos";break;case "ExitPlanMode":f="Exit plan mode";break;default:f=a;}return {title:f,kind:p,content:g,locations:m}}}function ui(t){return Xt()(t)}function fe(t){switch(t){case "claude":return zt();case "codex":return qt();case "gemini":return Yt();case "qwen":return Xt();case "kimi":return ur();case "opencode":return pr();case "droid":return Wt();default:return ()=>null}}function ic(t,e){let n=e.trim();return n?fe(t)(n):null}function oc(t,e){let n=[],r=e.split(`
|
|
20
|
+
`),s=fe(t);for(let o of r){let d=o.trim();if(!d)continue;let u=s(d);u&&n.push(...u);}return n}var Fc=util.promisify(child_process.execFile),ae="SKILL.md",Bc=X.join(os$1.homedir(),".cache","evolve","skills"),Sr=["skills","skills/.curated","skills/.experimental","skills/.system",".claude/skills"],Nc=/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)(?:@(.+))?$/,jc=/^[0-9a-f]{40}$/,_r=2e3,wr=64*1024*1024,z=class extends Error{constructor(e){super(e),this.name="SkillRefError";}},N=class extends Error{constructor(e){super(e),this.name="SkillResolveError";}};function Jc(t){return t==="~"?os$1.homedir():t.startsWith("~/")?X.join(os$1.homedir(),t.slice(2)):t}function Kc(t){let e=t.indexOf("@");if(e===-1)return {base:t};let n=t.slice(e+1);if(!n)throw new z(`Empty @ref in skill reference segment: ${JSON.stringify(t)}`);return {base:t.slice(0,e),gitRef:n}}var Gc=/^[A-Za-z0-9._-]+$/;function en(t,e,n){if(!Gc.test(t))throw new z(`Cannot parse skill reference ${JSON.stringify(n)}: ${e} ${JSON.stringify(t)} may only contain letters, digits, ".", "_" and "-".`);return t}function xr(t){let e=String(t??"").trim();if(!e)throw new z("Skill reference cannot be empty.");if(e.startsWith("upload:")){let o=e.slice(7);if(!o)throw new z(`Skill upload reference ${JSON.stringify(e)} names no upload id.`);return {kind:"upload",id:o,raw:e}}if(e.startsWith("name:")){let o=e.slice(5);if(!o)throw new z(`Skill name reference ${JSON.stringify(e)} names no skill.`);return en(o,"skill name",e),{kind:"name",name:o,raw:e}}if(e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.startsWith("~"))return {kind:"local",path:Jc(e),raw:e};let n=e.match(/^(?:https?:\/\/)?(?:www\.)?skills\.sh\/(.+)$/);if(n){let d=n[1].replace(/\/+$/,"").split("/").filter(Boolean);if(d.length<2||d.length>3)throw new z(`Cannot parse skill reference ${JSON.stringify(e)}: expected skills.sh/<owner>/<repo> or skills.sh/<owner>/<repo>/<skill>, optionally @ref.`);let{base:u,gitRef:l}=Kc(d[d.length-1]);d[d.length-1]=u;let[i,a,c]=d;return en(i,"owner",e),en(a,"repo",e),c!==void 0&&en(c,"skill name",e),{kind:"git",host:"github.com",org:i,repo:a,...l?{gitRef:l}:{},...c?{skillName:c}:{},viaSkillsSh:true,raw:e}}let r=e.match(/^https?:\/\/([^/]+)\/(.+)$/);if(r){let o=r[1],d=r[2].replace(/\/+$/,"").split("/").filter(Boolean);if(d.length<2)throw new z(`Git URL must have at least org/name in the path: ${JSON.stringify(e)}`);let u=d[0],l=d[1].replace(/\.git$/,""),i,a;return d.length>=4&&d[2]==="tree"&&(i=d[3],d.length>4&&(a=d.slice(4).join("/"))),{kind:"git",host:o,org:u,repo:l,...i?{gitRef:i}:{},...a?{subdir:a}:{},viaSkillsSh:false,raw:e}}let s=e.match(Nc);if(s)return {kind:"git",host:"github.com",org:s[1],repo:s[2],...s[3]?{gitRef:s[3]}:{},viaSkillsSh:false,raw:e};throw new z(`Cannot parse skill reference ${JSON.stringify(e)}. Expected skills.sh/<owner>/<repo>[/<skill>], org/repo[@ref], an https git URL, or a local folder path (prefix relative paths with './').`)}function Cr(t){return `https://${t.host}/${t.org}/${t.repo}.git`}function Re(t){return `https://${t.host}/${t.org}/${t.repo}`}async function oe(t,e){try{let{stdout:n}=await Fc("git",t,{cwd:e.cwd,timeout:e.timeoutMs,env:e.gitEnv??process.env,maxBuffer:16777216});return n}catch(n){let r=n,s=(r.stderr||r.message||"").trim();throw new N(`git ${t[0]} failed${r.killed?" (timed out)":""}: ${s}`)}}async function Rr(t,e={}){if(t.gitRef&&jc.test(t.gitRef))return t.gitRef;let n=t.gitRef??"HEAD",s=(await oe(["ls-remote",Cr(t),n,`${n}^{}`],{timeoutMs:e.lsRemoteTimeoutMs??3e4,gitEnv:e.gitEnv})).trim().split(`
|
|
21
|
+
`).filter(u=>u.length>0).map(u=>{let[l,i]=u.split(" ");return {sha:l,name:i}});if(s.length===0||!s[0].sha)throw new N(`No matching ref ${JSON.stringify(n)} found in ${Re(t)}`);let o=s[0];return (s.find(u=>u.name===`${o.name}^{}`)??o).sha}async function Vc(t,e={}){let n=xr(t);if(n.kind!=="git")return {ref:n.raw};let r=await Rr(n,e),s;return n.viaSkillsSh?s=`skills.sh/${n.org}/${n.repo}${n.skillName?`/${n.skillName}`:""}@${r}`:n.subdir!==void 0||n.raw.includes("://")?s=`https://${n.host}/${n.org}/${n.repo}/tree/${r}${n.subdir?`/${n.subdir}`:""}`:s=`${n.org}/${n.repo}@${r}`,{ref:s,gitUrl:Re(n),gitCommit:r}}async function kr(t){let e=[],n=async s=>{let o=s===""?t:X.join(t,s),d=await promises.readdir(o,{withFileTypes:true});for(let u of d){let l=s===""?u.name:`${s}/${u.name}`;u.isDirectory()?await n(l):u.isFile()&&e.push(l);}};await n(""),e.sort();let r=crypto.createHash("sha256");for(let s of e){let o=crypto.createHash("sha256").update(await promises.readFile(X.join(t,s))).digest("hex");r.update(s),r.update("\0"),r.update(o),r.update("\0");}return `sha256:${r.digest("hex")}`}async function nt(t){try{return (await promises.stat(t)).isFile()}catch{return false}}async function Er(t){try{return (await promises.stat(t)).isDirectory()}catch{return false}}async function Ci(t,e){if(!await Er(t))throw new N(`Skill path does not exist or is not a directory: ${e}`);if(await nt(X.join(t,ae)))return [t];let r=(await promises.readdir(t,{withFileTypes:true})).filter(d=>d.isDirectory()&&!d.name.startsWith(".")).map(d=>d.name).sort(),s=[],o=[];for(let d of r)await nt(X.join(t,d,ae))?o.push(X.join(t,d)):s.push(d);if(s.length>0)throw new N(`Skill root ${e} contains child directories without ${ae}: ${s.join(", ")}`);if(o.length===0)throw new N(`Skill path ${e} must be a skill directory containing ${ae}, or a root whose immediate child directories each contain ${ae}.`);return o}async function Hc(t){let e=new Map;await nt(X.join(t,ae))&&e.set(X.basename(t),t);for(let n of Sr){let r=X.join(t,n);if(!await Er(r))continue;let s=await promises.readdir(r,{withFileTypes:true});for(let o of s.sort((d,u)=>d.name<u.name?-1:1)){if(!o.isDirectory()||o.name.startsWith("."))continue;let d=X.join(r,o.name);await nt(X.join(d,ae))&&e.set(o.name,d);}}return Array.from(e,([n,r])=>({dir:r,name:n}))}function zc(t){return t.cacheDir??process.env.EVOLVE_SKILLS_CACHE??Bc}async function qc(t,e,n){let r=X.join(zc(n),t.host,t.org,t.repo,e),s=X.join(r,t.repo),o=X.join(r,".evolve-complete");if(await nt(o)&&await Er(s))return s;await promises.mkdir(X.dirname(r),{recursive:true});let d=await promises.mkdtemp(`${r}.tmp-`),u=X.join(d,t.repo),l=n.checkoutTimeoutMs??12e4,i={cwd:u,timeoutMs:l,gitEnv:n.gitEnv};try{await promises.mkdir(u),await oe(["init","--quiet"],i),await oe(["remote","add","origin",Cr(t)],i),t.subdir?(await oe(["sparse-checkout","init","--cone"],i),await oe(["sparse-checkout","set",t.subdir],i)):(await oe(["sparse-checkout","init","--cone"],i),await oe(["sparse-checkout","set",...Sr],i)),await oe(["fetch","--quiet","--depth=1","origin",e],i),await oe(["checkout","--quiet","FETCH_HEAD"],i),await promises.rm(X.join(u,".git"),{recursive:!0,force:!0}),await promises.writeFile(X.join(d,".evolve-complete"),""),await promises.rm(r,{recursive:!0,force:!0});try{await promises.rename(d,r);}catch{await promises.rm(d,{recursive:!0,force:!0});}return s}catch(a){throw await promises.rm(d,{recursive:true,force:true}),a}}async function Ri(t,e){let n=0,r=0,s=async o=>{let d=await promises.readdir(o,{withFileTypes:true});for(let u of d){let l=X.join(o,u.name);if(u.isDirectory())await s(l);else if(u.isFile()&&(n+=1,r+=(await promises.stat(l)).size,n>_r||r>wr))throw new N(`Skill ${e} exceeds the size ceiling (${_r} files / ${wr} bytes) \u2014 a skill is instructions, not a dataset.`)}};await s(t);}async function Tr(t,e={}){let n=new Map;for(let r of t){let s=xr(r);if(s.kind==="upload")throw new N(`Skill reference ${JSON.stringify(s.raw)} is a platform upload handle; only the hosted platform can resolve it. Use a skills.sh/git reference or a local folder here.`);if(s.kind==="name")throw new N(`Skill reference ${JSON.stringify(s.raw)} is a platform skill name \u2014 a moving pointer only the hosted platform can resolve (server-side, at job create). Use a skills.sh/git reference or a local folder here.`);if(s.kind==="local"){let l=await Ci(s.path,s.raw);for(let i of l)await Ri(i,s.raw),n.set(X.basename(i),{name:X.basename(i),dir:i,source:s.raw,digest:await kr(i)});continue}let o=await Rr(s,e),d=await qc(s,o,e),u;if(s.subdir)u=(await Ci(X.join(d,s.subdir),`${s.raw} (${s.subdir})`)).map(i=>({dir:i,name:X.basename(i)}));else if(u=await Hc(d),u.length===0)throw new N(`No skills found in ${Re(s)}@${o.slice(0,12)}: expected ${ae} at the repo root or under ${Sr.join(", ")}.`);if(s.skillName){let l=u.filter(i=>i.name===s.skillName);if(l.length===0)throw new N(`Skill ${JSON.stringify(s.skillName)} not found in ${Re(s)}@${o.slice(0,12)}. Available: ${u.map(i=>i.name).sort().join(", ")||"(none)"}`);u=l;}for(let{dir:l,name:i}of u)await Ri(l,s.raw),n.set(i,{name:i,dir:l,source:s.raw,gitUrl:Re(s),gitCommit:o,digest:await kr(l)});}return Array.from(n.values()).sort((r,s)=>r.name<s.name?-1:r.name>s.name?1:0)}function tn(t){return `'${t.replace(/'/g,"'\\''")}'`}async function Pr(t,e,n){if(e.length===0)return;let{tarGzipDirectory:r}=await Promise.resolve().then(()=>(yr(),hr));await t.files.makeDir(n);for(let s of e){let o=await r(s.dir),d=`${n}/.evolve-skill-${s.name}.tgz`,u=`${n}/${s.name}`;await t.files.write(d,o),await t.commands.run(`mkdir -p ${tn(u)} && tar -xzf ${tn(d)} -C ${tn(u)} && rm -f ${tn(d)}`,{timeoutMs:6e4});}}function Y(t){return t!==null&&typeof t=="object"&&"safeParse"in t&&typeof t.safeParse=="function"}function Ee(t){return JSON.stringify(Wc__default.default(t,{target:"jsonSchema7"}),null,2)}function Te(t){return JSON.stringify(t,null,2)}function Ei(t,e=false){let n={};function r(s,o){for(let d of Q__namespace.readdirSync(s)){let u=X__namespace.join(s,d),l=o?`${o}/${d}`:d;Q__namespace.statSync(u).isDirectory()?e&&r(u,l):n[l]=Q__namespace.readFileSync(u);}}return r(t,""),n}function Ti(t,e){let n=X__namespace.resolve(t),r=n.endsWith(X__namespace.sep)?n:n+X__namespace.sep;for(let[s,o]of Object.entries(e)){let d=X__namespace.resolve(n,s);if(!d.startsWith(r))throw new Error(`Unsafe file path escapes target directory: ${s}`);let u=X__namespace.dirname(d);Q__namespace.mkdirSync(u,{recursive:true});let l;o instanceof ArrayBuffer||o instanceof Uint8Array?l=Buffer.from(o):l=o,Q__namespace.writeFileSync(d,l);}}var A=class extends Error{field;constructor(e,n){super(n),this.name="EvolveConfigError",this.field=e;}};function Ar(t){return typeof t=="string"&&t.trim()!==""}function Pe(t){return t==null?String(t):JSON.stringify(t)}function rt(t){if(!t)return;if(t.type!==void 0&&!zn(t.type))throw new A("type",`Evolve agent config: unknown agent type ${Pe(t.type)}. Valid types: ${Object.keys(J).join(", ")}.`);let e=t.type??Kn;if(t.model!==void 0&&!Ar(t.model))throw new A("model",`Evolve agent config: "model" is empty (${Pe(t.model)}). Pass a model id such as "${K(e).defaultModel}", or omit model entirely to use ${e}'s default.`);if(t.config!==void 0){if(!Mi(e))throw new A("config",`Evolve agent config: agent "${e}" does not support a native config. Agents with native-config support: ${Di().join(", ")}.`);let n=t.config;if(typeof n=="string"){if(!Ar(n))throw new A("config",`Evolve agent config: "config" is an empty path (${Pe(n)}). Pass a local settings file path or an inline JSON object.`)}else if(!sn(n))throw new A("config",`Evolve agent config: "config" must be a local file path or a JSON object, received ${Pe(n)}.`)}t.preset!==void 0&&Ir(e,t.preset);}function Ir(t,e){if(!Bn.includes(e))throw new A("preset",`Evolve agent config: unknown preset ${Pe(e)}. Valid presets: ${Bn.join(", ")}.`);let n=Oi(e);if(!n.includes(t))throw new A("preset",`Evolve agent config: agent "${t}" cannot guarantee preset "${e}". Agents that can: ${n.join(", ")}.`)}function Ii(t){let e=J[t]?.presets;return e?Object.keys(e):[]}function Oi(t){return Object.keys(J).filter(e=>Ii(e).includes(t))}function on(t,e){let n={...t};for(let[r,s]of Object.entries(e)){let o=n[r];if(sn(o)&&sn(s))n[r]=on(o,s);else if(Array.isArray(o)&&Array.isArray(s)){let d=[...o];for(let u of s)d.some(l=>Ae(l)===Ae(u))||d.push(u);n[r]=d;}else n[r]=s;}return n}function sn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mi(t){return J[t]?.nativeConfig!==void 0}function Di(){return Object.keys(J).filter(Mi)}function Xc(t,e){if(e===void 0)return;let n=J[t]?.nativeConfig;if(!n)throw new A("config",`Evolve agent config: agent "${t}" does not support a native config. Agents with native-config support: ${Di().join(", ")}.`);let r;if(typeof e=="string"){let s=e.replace(/^~/,process.env.HOME||"");if(!Q__namespace.existsSync(s))throw new A("config",`Agent config file not found: ${s}`);let o=Q__namespace.readFileSync(s,"utf-8");try{r=n.format==="toml"?smolToml.parse(o):JSON.parse(o);}catch(d){throw new A("config",`Invalid ${t} config file ${e}: ${d.message}`)}}else {let s;try{s=JSON.parse(JSON.stringify(e));}catch(o){throw new A("config",`Invalid inline ${t} config: not JSON-serializable: ${o.message}`)}if(JSON.stringify(s)!==JSON.stringify(e))throw new A("config",`Invalid inline ${t} config: expected a JSON object that can be represented without conversion`);r=s;}if(!sn(r))throw new A("config",`Invalid ${t} config: expected a ${n.format==="toml"?"TOML table":"JSON object"}.`);if(n.format==="toml"){let s;try{s=smolToml.parse(smolToml.stringify(r));}catch(o){throw new A("config",`Invalid ${t} config for TOML conversion: ${o.message}`)}if(Ae(s)!==Ae(r))throw new A("config",`Invalid ${t} config: the document cannot be represented losslessly as TOML (TOML has no null and no mixed-type arrays)`)}return r}function Ae(t){return Array.isArray(t)?`[${t.map(Ae).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Ae(r)}`).join(",")}}`:JSON.stringify(t)??"null"}function Or(t){if(!t||!Ar(t.prompt))throw new A("prompt",`run() requires a non-empty "prompt" string, received ${Pe(t?.prompt)}.`)}function Mr(t){if(t){for(let e of Ye)if(e in t)throw new A(`observability.${e}`,`Evolve observability metadata: "${e}" is reserved for session identity and would split this run across two dashboard sessions. Reserved keys: ${Ye.join(", ")}. Use a different key, or set the session tag with .withSessionTagPrefix().`)}}function an(t){if(t.externalGateway){if(t.providerApiKey||t.providerBaseUrl||t.oauthToken)throw new Error("externalGateway cannot be combined with providerApiKey/providerBaseUrl/oauthToken (direct mode)");if(t.apiKey)throw new Error("externalGateway cannot be combined with apiKey (Evolve gateway mode)")}}function Qc(t){let e=t.replace(/^~/,process.env.HOME||"");if(!Q__namespace.existsSync(e))throw new Error(`OAuth file not found: ${e}`);return Q__namespace.readFileSync(e,"utf-8")}function Ai(t,e,n){if(!e.providerEnvMap||!n)return;let r=n.indexOf("/");if(r<=0)return;let s=n.slice(0,r);if(!(e.providerEnvMap[s]||!Se(e,n)))throw new A("model",`Model "${n}" is served through the Evolve gateway only: the ${t} agent holds no ${s} key in direct mode. Set ${O} (or apiKey) to run it through the gateway, or pick a model whose route has a direct-mode key (${Object.keys(e.providerEnvMap).join(", ")}).`)}function ln(t){let e=t?.type??Kn,n=K(e),r=Xc(e,t?.config);t?.preset!==void 0&&Ir(e,t.preset);let s={...r!==void 0?{config:r}:{},...t?.preset!==void 0?{preset:t.preset}:{}};if(t?.externalGateway){an(t);let{apiKey:l,baseUrl:i,revoke:a}=t.externalGateway;if(!l||!i||typeof a!="function")throw new Error("externalGateway requires apiKey, baseUrl, and a revoke() function");return {type:e,apiKey:l,baseUrl:i,isDirectMode:true,externalGateway:{revoke:a},model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize,...s}}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,maxContextSize:t.maxContextSize,...s}}if(t?.providerApiKey){Ai(e,n,t.model);let l=n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0,i=t.providerBaseUrl??l??n.defaultBaseUrl;return {type:e,apiKey:t.providerApiKey,baseUrl:i,isDirectMode:true,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize,...s}}if(t?.apiKey)return {type:e,apiKey:t.apiKey,isDirectMode:false,model:t.model,reasoningEffort:t.reasoningEffort,maxContextSize:t.maxContextSize,...s};let o=process.env[O];if(o)return {type:e,apiKey:o,isDirectMode:false,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s};if(n.providerEnvMap){let i=(t?.model??n.defaultModel)?.split("/")[0],a=i?n.providerEnvMap[i]:void 0,c=a?process.env[a.keyEnv]:void 0;if(c){let g=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:c,baseUrl:g,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}}let d=process.env[n.apiKeyEnv];if(d){Ai(e,n,t?.model);let i=(n.baseUrlEnv?process.env[n.baseUrlEnv]:void 0)??n.defaultBaseUrl;return {type:e,apiKey:d,baseUrl:i,isDirectMode:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}if(n.oauthEnv){let l=process.env[n.oauthEnv];if(l){if(n.oauthFileName){let i=Qc(l);return {type:e,apiKey:"__oauth_file__",isDirectMode:true,isOAuth:true,oauthFileContent:i,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}return {type:e,apiKey:l,isDirectMode:true,isOAuth:true,model:t?.model,reasoningEffort:t?.reasoningEffort,maxContextSize:t?.maxContextSize,...s}}}let u=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)${u}, or ${O} / ${n.apiKeyEnv} env var.`)}function td(t){return `e2b_${Buffer.from(t,"utf8").toString("hex")}`}var Ni=new WeakSet;function $r(t){return Ni.add(t),t}function Oe(t){return Ni.has(t)}function Fi(t,e){return new Error(`${O} is set but ${t} failed to load.
|
|
22
|
+
Try installing: ${e}`)}function Bi(t){return t.message?.includes("Cannot find module")||t.message?.includes("MODULE_NOT_FOUND")}function Fr(t,e){if(!e||e.timeoutMs===void 0&&e.resources===void 0)return t;let n=t.create.bind(t);return t.create=(r={})=>n({...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.resources!==void 0?{resources:e.resources}:{},...r}),t}async function it(t,e="e2b",n){let r=t||process.env[O];if(!r)throw new Error(`${O} is required for Evolve-managed sandbox features`);if(!ve.includes(e))throw new Error(`Unknown managed sandbox provider "${e}". Supported: ${ve.join(", ")}`);if(e==="daytona")try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return Fr($r(s({apiKey:r,apiUrl:qe("daytona"),managedToolboxUrl:Ns()})),n)}catch(s){let o=s;throw Bi(o)?Fi("@evolvingmachines/daytona","npm install @evolvingmachines/daytona"):o}if(e==="modal"){let{ManagedModalProvider:s}=await Promise.resolve().then(()=>($i(),Li));return Fr($r(new s({apiKey:r,baseUrl:qe("modal")})),n)}try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return Fr($r(s({apiKey:td(r),apiUrl:jn()})),n)}catch(s){let o=s;throw Bi(o)?Fi("@evolvingmachines/e2b","npm install @evolvingmachines/evolve"):o}}function nd(t="e2b",e){let n=typeof e=="string"?{apiKey:e}:e??{},{apiKey:r,...s}=n;return it(r,t,s)}async function un(){let t=process.env[Dt];if(t)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===jn()&&delete process.env.E2B_API_URL,o({apiKey:t})}catch(o){let d=o;throw d.message?.includes("Cannot find module")||d.message?.includes("MODULE_NOT_FOUND")?new Error(`${Dt} is set but @evolvingmachines/e2b failed to load.
|
|
23
|
+
Try reinstalling: npm install @evolvingmachines/evolve`):d}let e=process.env[Ut];if(e)try{let{createDaytonaProvider:o}=await import('@evolvingmachines/daytona');return o({apiKey:e})}catch(o){let d=o;throw d.message?.includes("Cannot find module")||d.message?.includes("MODULE_NOT_FOUND")?new Error(`${Ut} is set but @evolvingmachines/daytona failed to load.
|
|
24
|
+
Try installing: npm install @evolvingmachines/daytona`):d}let n=process.env[Lt],r=process.env[Jn];if(n&&r)try{let{createModalProvider:o}=await import('@evolvingmachines/modal');return o({tokenId:n,tokenSecret:r})}catch(o){let d=o;throw d.message?.includes("Cannot find module")||d.message?.includes("MODULE_NOT_FOUND")?new Error(`${Lt} is set but @evolvingmachines/modal failed to load.
|
|
25
|
+
Try installing: npm install @evolvingmachines/modal`):d}let s=process.env[O];if(s)return it(s);throw new Error(`No sandbox provider configured. Either:
|
|
26
26
|
1. Set ${O} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
27
|
-
2. Set ${
|
|
28
|
-
3. Set ${
|
|
29
|
-
4. Set ${
|
|
30
|
-
5. Pass sandbox explicitly: .withSandbox(provider)`)}function
|
|
27
|
+
2. Set ${Dt} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
28
|
+
3. Set ${Ut} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
29
|
+
4. Set ${Lt} and ${Jn} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
30
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function rd(t){return new Promise(e=>setTimeout(e,t))}async function G(t,e,n=0){let r=sd(e),s=e?.onItemRetry,o=null,d=0,u=r.backoffMs;for(;d<r.maxAttempts;){if(d++,o=await t(d),!r.retryOn(o))return o;if(d>=r.maxAttempts)break;if(s){let l=o.error??"Unknown error";s(n,d,l);}await rd(u),u*=r.backoffMultiplier;}return o}function sd(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var ji=`## FILESYSTEM INSTRUCTIONS:
|
|
31
31
|
|
|
32
32
|
You are running in a sandbox environment.
|
|
33
33
|
|
|
@@ -60,7 +60,7 @@ Examples:
|
|
|
60
60
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
61
61
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
62
62
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
63
|
-
`;var
|
|
63
|
+
`;var Ji=`## FILESYSTEM INSTRUCTIONS:
|
|
64
64
|
|
|
65
65
|
You are running in a sandbox environment.
|
|
66
66
|
|
|
@@ -94,9 +94,9 @@ Examples:
|
|
|
94
94
|
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
95
95
|
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
96
96
|
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
97
|
-
`;var
|
|
97
|
+
`;var Ki=`## SYSTEM PROMPT
|
|
98
98
|
|
|
99
|
-
{{systemPrompt}}`;var
|
|
99
|
+
{{systemPrompt}}`;var Gi=`## STRUCTURED OUTPUT
|
|
100
100
|
|
|
101
101
|
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
102
102
|
|
|
@@ -114,13 +114,13 @@ You are free to:
|
|
|
114
114
|
But your final \`output/result.json\` MUST conform to the schema above.
|
|
115
115
|
|
|
116
116
|
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
117
|
-
### Never just state results as text.`;var
|
|
117
|
+
### Never just state results as text.`;var Vi=`## BROWSER AUTOMATION
|
|
118
118
|
|
|
119
119
|
Actionbook is preconfigured for remote browser automation in this environment. When browser automation is needed, start sessions with \`actionbook browser start --session s1\`, then use normal Actionbook browser commands. Do not override the configured browser mode or browser endpoint unless the user explicitly asks.
|
|
120
|
-
`;var
|
|
120
|
+
`;var Hi=`## Browser Automation
|
|
121
121
|
|
|
122
122
|
The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
|
|
123
|
-
`;var
|
|
123
|
+
`;var zi=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
124
124
|
|
|
125
125
|
You are a judge. {{candidateCount}} AI workers attempted the same task independently. Your job is to analyze their solution attempts and pick the best one based on the evaluation criteria below.
|
|
126
126
|
|
|
@@ -150,7 +150,7 @@ You must judge their work based on:
|
|
|
150
150
|
5. Pick the best candidate (0-indexed)
|
|
151
151
|
|
|
152
152
|
**IMPORTANT:** Be thorough. Do not skip steps. Your judgment must be evidence-based \u2014 cite specific files, outputs, or discrepancies to justify your decision.
|
|
153
|
-
`;var
|
|
153
|
+
`;var qi=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
154
154
|
|
|
155
155
|
You are a quality verifier. An AI worker produced output for a task. Your job is to verify whether the output meets the specified quality criteria.
|
|
156
156
|
|
|
@@ -183,14 +183,14 @@ The output must satisfy:
|
|
|
183
183
|
**IMPORTANT:** Be thorough and fair. Cite specific evidence. If the output generally achieves the goal with minor issues, consider passing. Only fail if there are significant problems that violate the criteria.
|
|
184
184
|
|
|
185
185
|
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
186
|
-
`;var
|
|
186
|
+
`;var Wi=`### CONTEXT STRUCTURE
|
|
187
187
|
|
|
188
188
|
\`\`\`
|
|
189
189
|
{{fileTree}}
|
|
190
190
|
\`\`\`
|
|
191
191
|
|
|
192
192
|
Examine all files within each item folder before producing your output.
|
|
193
|
-
`;var
|
|
193
|
+
`;var Yi="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var Xi="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var Qi=`{{originalPrompt}}
|
|
194
194
|
|
|
195
195
|
## IMPORTANT: Previous Attempt Failed Verification
|
|
196
196
|
|
|
@@ -199,28 +199,28 @@ Your previous attempt did not pass quality verification. Please address this fee
|
|
|
199
199
|
{{feedback}}
|
|
200
200
|
|
|
201
201
|
Make sure your output addresses all the feedback points above.
|
|
202
|
-
`;var
|
|
202
|
+
`;var Zi=ji,eo=Ji,to=Ki,no=Gi,Br=Vi,ro=Hi,Nr=zi,so=Yi,jr=qi,io=Xi,oo=Wi,Jr=Qi;function le(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:n)}function Kr(t){let e=t.mode==="swe"?eo:Zi,n=le(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
|
|
203
203
|
|
|
204
204
|
|
|
205
205
|
${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
|
|
206
206
|
|
|
207
207
|
|
|
208
|
-
${le(
|
|
208
|
+
${le(to,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=Y(t.schema)?Ee(t.schema):Te(t.schema);n+=`
|
|
209
209
|
|
|
210
210
|
|
|
211
|
-
${le(
|
|
212
|
-
(empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,s=Object.keys(t).some(l=>l.startsWith("worker_task/input/")),o=[];e.forEach((l,i)=>{let a=i===e.length-1,c=a?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",p=a?" ":"\u2502 ";if(l==="worker_task"){o.push({line:`${c}${l}/`,comment:"task given to worker"});let g=[];n&&g.push({name:"system_prompt.txt",comment:"worker system prompt"}),g.push({name:"user_prompt.txt",comment:"worker task prompt"}),r&&g.push({name:"schema.json",comment:"expected output schema"}),s&&g.push({name:"input/",comment:"worker input files"}),g.forEach((f
|
|
213
|
-
`)}var
|
|
211
|
+
${le(no,{schema:r}).trim()}`;}return n}function pn(t){let e=[...new Set(Object.keys(t).map(l=>l.split("/")[0]))].sort((l,i)=>l==="worker_task"?-1:i==="worker_task"?1:l.localeCompare(i));if(!e.length)return `context/
|
|
212
|
+
(empty)`;let n="worker_task/system_prompt.txt"in t,r="worker_task/schema.json"in t,s=Object.keys(t).some(l=>l.startsWith("worker_task/input/")),o=[];e.forEach((l,i)=>{let a=i===e.length-1,c=a?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",p=a?" ":"\u2502 ";if(l==="worker_task"){o.push({line:`${c}${l}/`,comment:"task given to worker"});let g=[];n&&g.push({name:"system_prompt.txt",comment:"worker system prompt"}),g.push({name:"user_prompt.txt",comment:"worker task prompt"}),r&&g.push({name:"schema.json",comment:"expected output schema"}),s&&g.push({name:"input/",comment:"worker input files"}),g.forEach((m,f)=>{let y=f===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";o.push({line:`${p}${y}${m.name}`,comment:m.comment});});}else if(l.startsWith("candidate_")){let g=l.replace("candidate_","");o.push({line:`${c}${l}/`,comment:`worker ${g} solution`});}else if(l==="worker_output")o.push({line:`${c}${l}/`,comment:"output to verify"});else if(l.startsWith("item_")){let g=l.replace("item_","");o.push({line:`${c}${l}/`,comment:`input ${g}`});}else o.push({line:`${c}${l}/`,comment:""});});let d=Math.max(...o.map(l=>l.line.length)),u=["context/"];for(let l of o)if(l.comment){let i=" ".repeat(d-l.line.length+3);u.push(`${l.line}${i}# ${l.comment}`);}else u.push(l.line);return u.join(`
|
|
213
|
+
`)}var ao=X.join(os$1.homedir(),Gs),kd=/^[A-Za-z0-9_-]{1,32}$/,ot=class{tag;timestamp;provider;agent;model;reasoningEffort;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;warnedKeys=new Set;localQueue=Promise.resolve();dirReady=promises.mkdir(ao,{recursive:true}).catch(()=>{});eventBuffer=[];dashboardQueue=Promise.resolve();flushTimer;constructor(e){this.validateConfig(e),this.provider=e.provider,this.agent=e.agent,this.model=e.model,this.reasoningEffort=e.reasoningEffort,this.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=Mt(),this.observability=e.observability,this.tag=e.tag||`${e.tagPrefix||"evolve"}-${crypto.randomBytes(8).toString("hex")}`,this.timestamp=new Date().toISOString();let n=this.timestamp.replace(/[:.]/g,"-"),r=`${this.tag}_${this.provider}_${this.sandboxId}_${this.agent}_${n}.jsonl`;this.localFilePath=X.join(ao,r),this.parser=fe(e.agent);}getTag(){return this.tag}getTimestamp(){return this.timestamp}writePrompt(e){this.isClosed||this.write({_prompt:{text:e}});}writeEventParsed(e,n){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey&&n))for(let r of n)this.bufferForDashboard(r);}writeEvent(e){if(!this.isClosed&&(this.writeLocalLine(e),this.apiKey)){let n=this.parser(e);if(n)for(let r of n)this.bufferForDashboard(r);}}async flush(){await this.localQueue,await this.dashboardQueue,this.apiKey&&this.eventBuffer.length>0&&(this.flushDashboard(),await this.dashboardQueue);}async close(){this.isClosed||(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.write({_sessionEnd:{timestamp:new Date().toISOString()}}),this.isClosed=true,await this.flush());}writeLocalLine(e){this.metaWritten||this.writeMeta();let n=e.endsWith(`
|
|
214
214
|
`)?e:e+`
|
|
215
215
|
`;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)+`
|
|
216
216
|
`;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.annotations()}},n=JSON.stringify(e)+`
|
|
217
|
-
`;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>=Bs){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Ns));}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.annotations(),events:e};for(let r=1;r<=$t;r++)try{let s=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(s.ok)return;if(s.status===429||s.status===401||s.status>=500){if(r===$t){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Fn*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===$t?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(Fn*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Ot();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.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))}annotations(){if(!this.observability)return {};let e={};for(let[n,r]of Object.entries(this.observability))if(r!==void 0){if(We.includes(n)){this.warnedKeys.has(n)||(this.warnedKeys.add(n),console.warn(`[SessionLogger] observability key "${n}" is reserved for session identity \u2014 ignoring it.`));continue}e[n]=r;}return e}};function ot(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function at(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed integrations");return e}async function lt(t){return await t.text().catch(()=>"")}function Fr(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function cd(t){let e=Array.from(new Set((t??[]).map(n=>n.trim()).filter(Boolean)));if(e.length===0)throw new Error("withIntegrations() requires at least one app");return e}async function no(t){let e=await fetch(`${ot(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${at(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Fr(t.userId),apps:cd(t.apps),tools:t.tools,accounts:t.accounts,keys:t.keys,authConfigs:t.authConfigs,sessionTag:t.sessionTag}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integrations session create failed (${e.status}): ${await lt(e)}`);let n=await e.json();if(!n.mcp?.url)throw new Error("Managed integrations response missing mcp.url");return {url:n.mcp.url,headers:n.mcp.headers??{}}}async function dd(t){let e=await fetch(`${ot(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${at(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Fr(t.userId),app:t.app,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration connect failed (${e.status}): ${await lt(e)}`);return await e.json()}async function ud(t){let e=Array.from(new Set((t.userIds??[]).map(d=>Fr(d))));if(e.length===0)throw new Error("Integration accounts.list() requires at least one userId");let n=new URLSearchParams({userIds:e.join(",")});t.app&&n.set("app",t.app),t.statuses?.length&&n.set("statuses",t.statuses.join(","));let r={Authorization:`Bearer ${at(t.apiKey)}`,accept:"application/json"},s=await fetch(`${ot(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Managed integration status failed (${s.status}): ${await lt(s)}`);return ((await s.json()).accounts??[]).map(d=>({userId:String(d.userId??""),app:String(d.app??""),appName:typeof d.appName=="string"?d.appName:void 0,appIcon:typeof d.appIcon=="string"?d.appIcon:void 0,accountLabel:typeof d.accountLabel=="string"?d.accountLabel:void 0,status:String(d.status??""),accountId:typeof d.accountId=="string"?d.accountId:void 0,updatedAt:typeof d.updatedAt=="string"?d.updatedAt:void 0}))}async function pd(t){let e=await fetch(`${ot(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${at(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account update failed (${e.status}): ${await lt(e)}`);return await e.json()}async function gd(t){let e=await fetch(`${ot(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${at(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account delete failed (${e.status}): ${await lt(e)}`);return await e.json()}var ro={auth:dd,accounts:{list:ud,update:pd,delete:gd}};util.promisify(child_process.exec);var Hr=util.promisify(child_process.execFile),oo=Symbol.for("evolve:awsSdkCache"),ao=Symbol.for("evolve:s3ClientCache");var xd=3600,Cd=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Rd(t){if(t.startsWith("s3://")){let s=t.slice(5),o=s.indexOf("/");return o===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,o),prefix:s.slice(o+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,r=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:r.join("/")};if(r.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:r[0],prefix:r.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function pn(t,e,n,r){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:r}}let s=t?.bucket||"",o=t?.prefix||"",d=t?.endpoint;if(t?.url){let u=Rd(t.url);s=s||u.bucket,o=o||u.prefix,d=d||u.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:o,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:d,credentials:t?.credentials,mode:"byok"}}function Jr(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 Td(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 ct(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function Ed(t,e){let n=K(t),r=Td(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(u=>Jr(u)):[Jr(n.mcpConfig.settingsDir)],o=[...Cd.map(u=>`--exclude=${ct(u)}`),`--exclude=${ct(r+"/temp")}`,...(n.checkpointExcludes??[]).map(u=>`--exclude=${ct(Jr(u))}`)].join(" "),d=[ct(r+"/"),...s.map(u=>ct(u+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${o} ${d}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function Me(){let t=globalThis[oo];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,s]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[oo]={s3:r,presigner:s},{s3:r,presigner:s}}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 ut(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[ao];if(r?.key===n)return r.client;let{s3:s}=await Me(),o=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[ao]={client:o,key:n},o}async function yo(t,e,n){let{s3:r,presigner:s}=await Me(),o=await ut(t),d=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(o,d,{expiresIn:xd})}async function lo(t,e){let{s3:n}=await Me(),r=await ut(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let o=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||o==="NotFound"||o==="NoSuchKey")return false;throw s}}async function bo(t,e){let{s3:n}=await Me(),o=await(await(await ut(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!o)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(o)}async function Pd(t,e,n){let{s3:r}=await Me();await(await ut(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function _o(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function wo(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Ad(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function ko(t,e,n,r){let s=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:r})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${o}`)}return s.json()}async function Id(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${r}`)}return n.json()}async function Od(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${r}`)}return n.json()}async function qr(t,e,n,r,s){let o=new Date().toISOString(),d=Ed(n,r),u=await t.commands.run(d,{timeoutMs:12e4});if(u.exitCode!==0)throw new Error(`Checkpoint tar failed: ${u.stderr}`);let l=u.stdout.trim().split(`
|
|
218
|
-
`).pop()?.trim();if(!l||l.length!==64)throw new Error(`Invalid checkpoint hash: ${l}`);let i=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}),a=parseInt(i.stdout.trim(),10),c=Number.isNaN(a)?void 0:a,p;try{if(e.mode==="byok"){let g=
|
|
219
|
-
`).pop()?.trim();if(l!==s)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${l})`);let i=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(i.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${i.stderr}`);return o}function
|
|
220
|
-
`)){if(!s||s.startsWith("total "))continue;let o=s[0];if(o!=="-"&&o!=="d"&&o!=="l")throw new Error(`Archive contains unsupported entry type: "${o}"`);let d=s.match(/\d{2}:\d{2}\s+(.+)/)??s.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!d)throw new
|
|
221
|
-
${n}`)}function
|
|
222
|
-
`}],directories:[
|
|
223
|
-
`}],directories:[
|
|
217
|
+
`;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>=Vs){this.flushDashboard();return}!this.flushTimer&&!this.isClosed&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushDashboard();},Hs));}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,reasoningEffort:this.reasoningEffort!==void 0&&kd.test(this.reasoningEffort)?this.reasoningEffort:null,sandboxId:this.sandboxId,timestamp:this.timestamp,...this.annotations(),events:e};for(let r=1;r<=$t;r++)try{let s=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(s.ok)return;if(s.status===429||s.status===401||s.status>=500){if(r===$t){console.debug(`[SessionLogger] Dashboard ${s.status} after ${r} retries, requeueing`),this.requeueEvents(e);return}await this.delay(Vn*r);continue}console.debug(`[SessionLogger] Dashboard ${s.status}, dropping events`);return}catch(s){r===$t?(console.debug("[SessionLogger] Dashboard sync failed after retries, requeueing:",s),this.requeueEvents(e)):await this.delay(Vn*r);}}requeueEvents(e){this.eventBuffer.unshift(...e);}validateConfig(e){let n=Mt();if(e.apiKey&&!n.startsWith("https://")&&!n.includes("localhost")&&!n.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))}annotations(){if(!this.observability)return {};let e={};for(let[n,r]of Object.entries(this.observability))if(r!==void 0){if(Ye.includes(n)){this.warnedKeys.has(n)||(this.warnedKeys.add(n),console.warn(`[SessionLogger] observability key "${n}" is reserved for session identity \u2014 ignoring it.`));continue}e[n]=r;}return e}};function at(t){return (t||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,"")}function lt(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed integrations");return e}async function ct(t){return await t.text().catch(()=>"")}function Gr(t){let e=t?.trim();if(!e)throw new Error('Integration userId is required; use "root" for dashboard-owned accounts');return e}function vd(t){let e=Array.from(new Set((t??[]).map(n=>n.trim()).filter(Boolean)));if(e.length===0)throw new Error("withIntegrations() requires at least one app");return e}async function co(t){let e=await fetch(`${at(t.dashboardUrl)}/api/integration-sessions`,{method:"POST",headers:{Authorization:`Bearer ${lt(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Gr(t.userId),apps:vd(t.apps),tools:t.tools,accounts:t.accounts,keys:t.keys,authConfigs:t.authConfigs,sessionTag:t.sessionTag}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integrations session create failed (${e.status}): ${await ct(e)}`);let n=await e.json();if(!n.mcp?.url)throw new Error("Managed integrations response missing mcp.url");return {url:n.mcp.url,headers:n.mcp.headers??{}}}async function Sd(t){let e=await fetch(`${at(t.dashboardUrl)}/api/integrations/connect`,{method:"POST",headers:{Authorization:`Bearer ${lt(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({userId:Gr(t.userId),app:t.app,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration connect failed (${e.status}): ${await ct(e)}`);return await e.json()}async function xd(t){let e=Array.from(new Set((t.userIds??[]).map(d=>Gr(d))));if(e.length===0)throw new Error("Integration accounts.list() requires at least one userId");let n=new URLSearchParams({userIds:e.join(",")});t.app&&n.set("app",t.app),t.statuses?.length&&n.set("statuses",t.statuses.join(","));let r={Authorization:`Bearer ${lt(t.apiKey)}`,accept:"application/json"},s=await fetch(`${at(t.dashboardUrl)}/api/integrations/status?${n}`,{headers:r,signal:AbortSignal.timeout(3e4)});if(!s.ok)throw new Error(`Managed integration status failed (${s.status}): ${await ct(s)}`);return ((await s.json()).accounts??[]).map(d=>({userId:String(d.userId??""),app:String(d.app??""),appName:typeof d.appName=="string"?d.appName:void 0,appIcon:typeof d.appIcon=="string"?d.appIcon:void 0,accountLabel:typeof d.accountLabel=="string"?d.accountLabel:void 0,status:String(d.status??""),accountId:typeof d.accountId=="string"?d.accountId:void 0,updatedAt:typeof d.updatedAt=="string"?d.updatedAt:void 0}))}async function Cd(t){let e=await fetch(`${at(t.dashboardUrl)}/api/integrations/accounts/update`,{method:"POST",headers:{Authorization:`Bearer ${lt(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId,accountLabel:t.accountLabel}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account update failed (${e.status}): ${await ct(e)}`);return await e.json()}async function Rd(t){let e=await fetch(`${at(t.dashboardUrl)}/api/integrations/disconnect`,{method:"POST",headers:{Authorization:`Bearer ${lt(t.apiKey)}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({accountId:t.accountId}),signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new Error(`Managed integration account delete failed (${e.status}): ${await ct(e)}`);return await e.json()}var uo={auth:Sd,accounts:{list:xd,update:Cd,delete:Rd}};util.promisify(child_process.exec);var Yr=util.promisify(child_process.execFile),mo=Symbol.for("evolve:awsSdkCache"),fo=Symbol.for("evolve:s3ClientCache");var $d=3600,Fd=["node_modules","__pycache__","*.pyc",".cache",".npm",".pip",".venv","venv"];function Bd(t){if(t.startsWith("s3://")){let s=t.slice(5),o=s.indexOf("/");return o===-1?{bucket:s,prefix:""}:{bucket:s.slice(0,o),prefix:s.slice(o+1).replace(/\/+$/,"")}}let e=new URL(t),n=e.hostname,r=e.pathname.split("/").filter(Boolean);if(n.includes(".s3.")&&n.endsWith(".amazonaws.com"))return {bucket:n.split(".s3.")[0],prefix:r.join("/")};if(r.length===0)throw new Error(`Invalid storage URL: no bucket in path. Expected https://endpoint/bucket/prefix, got ${t}`);return {bucket:r[0],prefix:r.slice(1).join("/"),endpoint:`${e.protocol}//${e.host}`}}function mn(t,e,n,r){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:r}}let s=t?.bucket||"",o=t?.prefix||"",d=t?.endpoint;if(t?.url){let u=Bd(t.url);s=s||u.bucket,o=o||u.prefix,d=d||u.endpoint;}if(!s)throw new Error("Storage bucket is required. Provide url (s3://bucket/prefix) or explicit bucket name.");return {bucket:s,prefix:o,region:t?.region||process.env.AWS_REGION||"us-east-1",endpoint:d,credentials:t?.credentials,mode:"byok"}}function Vr(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 Nd(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 dt(t){return "'"+t.replace(/'/g,"'\\''")+"'"}function jd(t,e){let n=K(t),r=Nd(e),s=n.checkpointDirs?.length?n.checkpointDirs.map(u=>Vr(u)):[Vr(n.mcpConfig.settingsDir)],o=[...Fd.map(u=>`--exclude=${dt(u)}`),`--exclude=${dt(r+"/temp")}`,...(n.checkpointExcludes??[]).map(u=>`--exclude=${dt(Vr(u))}`)].join(" "),d=[dt(r+"/"),...s.map(u=>dt(u+"/"))].join(" ");return [`tar -czf /tmp/evolve-ckpt.tar.gz -C /home/user ${o} ${d}`,"sha256sum /tmp/evolve-ckpt.tar.gz | awk '{print $1}'"].join(" && ")}async function De(){let t=globalThis[mo];if(t)return t;let e="@aws-sdk/client-s3",n="@aws-sdk/s3-request-presigner";try{let[r,s]=await Promise.all([Function("m","return import(m)")(e),Function("m","return import(m)")(n)]);return globalThis[mo]={s3:r,presigner:s},{s3:r,presigner:s}}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 pt(t){let e=t.credentials?`${t.credentials.accessKeyId}:${t.credentials.secretAccessKey.slice(-4)}`:"env",n=`${t.bucket}:${t.region}:${t.endpoint||""}:${e}`,r=globalThis[fo];if(r?.key===n)return r.client;let{s3:s}=await De(),o=new s.S3Client({region:t.region,...t.endpoint&&{endpoint:t.endpoint,forcePathStyle:true},...t.credentials&&{credentials:t.credentials}});return globalThis[fo]={client:o,key:n},o}async function xo(t,e,n){let{s3:r,presigner:s}=await De(),o=await pt(t),d=n==="put"?new r.PutObjectCommand({Bucket:t.bucket,Key:e,ContentType:"application/gzip"}):new r.GetObjectCommand({Bucket:t.bucket,Key:e});return s.getSignedUrl(o,d,{expiresIn:$d})}async function ho(t,e){let{s3:n}=await De(),r=await pt(t);try{return await r.send(new n.HeadObjectCommand({Bucket:t.bucket,Key:e})),!0}catch(s){let o=s?.name||s?.message||"";if(s?.$metadata?.httpStatusCode===404||o==="NotFound"||o==="NoSuchKey")return false;throw s}}async function Co(t,e){let{s3:n}=await De(),o=await(await(await pt(t)).send(new n.GetObjectCommand({Bucket:t.bucket,Key:e}))).Body?.transformToString();if(!o)throw new Error(`Empty response from S3 key: ${e}`);return JSON.parse(o)}async function Jd(t,e,n){let{s3:r}=await De();await(await pt(t)).send(new r.PutObjectCommand({Bucket:t.bucket,Key:e,Body:JSON.stringify(n,null,2),ContentType:"application/json"}));}function Ro(t,e){return `${t.prefix?`${t.prefix}/`:""}data/${e}/archive.tar.gz`}function Eo(t,e){return `${t.prefix?`${t.prefix}/`:""}checkpoints/${e}.json`}function Kd(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return `ckpt_${t}_${e}`}async function To(t,e,n,r){let s=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:r})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Gateway presign failed (${s.status}): ${o}`)}return s.json()}async function Gd(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 r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint create failed (${n.status}): ${r}`)}return n.json()}async function Vd(t,e){let n=await fetch(`${t.gatewayUrl}/api/checkpoints/${encodeURIComponent(e)}`,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!n.ok){if(n.status===404)throw new Error(`Checkpoint ${e} not found`);let r=await n.text().catch(()=>"");throw new Error(`Gateway checkpoint get failed (${n.status}): ${r}`)}return n.json()}async function Xr(t,e,n,r,s){let o=new Date().toISOString(),d=jd(n,r),u=await t.commands.run(d,{timeoutMs:12e4});if(u.exitCode!==0)throw new Error(`Checkpoint tar failed: ${u.stderr}`);let l=u.stdout.trim().split(`
|
|
218
|
+
`).pop()?.trim();if(!l||l.length!==64)throw new Error(`Invalid checkpoint hash: ${l}`);let i=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}),a=parseInt(i.stdout.trim(),10),c=Number.isNaN(a)?void 0:a,p;try{if(e.mode==="byok"){let g=Ro(e,l);if(!await ho(e,g)){let h=await xo(e,g,"put"),y=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${h}"`,{timeoutMs:3e5});if(y.exitCode!==0)throw new Error(`Checkpoint upload failed: ${y.stderr}`);if(!await ho(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}p=Kd();let f={id:p,hash:l,tag:s.tag,timestamp:o,sizeBytes:c,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment,sandboxId:t.sandboxId};await Jd(e,Eo(e,p),f);}else {let g=await To(e,s.tag,l,"put");if(!g.alreadyExists){let f=await t.commands.run(`curl -sf -X PUT -H "Content-Type: application/gzip" --upload-file /tmp/evolve-ckpt.tar.gz "${g.url}"`,{timeoutMs:3e5});if(f.exitCode!==0)throw new Error(`Checkpoint upload failed: ${f.stderr}`)}p=(await Gd(e,{tag:s.tag,hash:l,sizeBytes:c??0,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment})).id;}}finally{await t.commands.run("rm -f /tmp/evolve-ckpt.tar.gz",{timeoutMs:1e4});}return {id:p,hash:l,tag:s.tag,timestamp:o,sizeBytes:c,agentType:n,model:s.model,workspaceMode:s.workspaceMode,parentId:s.parentId,comment:s.comment}}async function Po(t,e,n){let r=await Zr(e,n),s=r.hash,o={agentType:r.agentType,workspaceMode:r.workspaceMode},d=await Mo(e,r),u=await t.commands.run(`curl -sf -o /tmp/evolve-restore.tar.gz "${d}" && sha256sum /tmp/evolve-restore.tar.gz | awk '{print $1}'`,{timeoutMs:3e5});if(u.exitCode!==0)throw new Error(`Checkpoint download failed: ${u.stderr}`);let l=u.stdout.trim().split(`
|
|
219
|
+
`).pop()?.trim();if(l!==s)throw await t.commands.run("rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:1e4}),new Error(`Checkpoint integrity check failed (expected ${s}, got ${l})`);let i=await t.commands.run("tar -xzf /tmp/evolve-restore.tar.gz -C /home/user && rm -f /tmp/evolve-restore.tar.gz",{timeoutMs:12e4});if(i.exitCode!==0)throw new Error(`Checkpoint extraction failed: ${i.stderr}`);return o}function Ao(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||T,s=!t.url&&!t.bucket&&!!n;return mn(t,s,r,n)}async function Io(t,e){let{s3:n}=await De(),r=await pt(t),o=`${t.prefix?`${t.prefix}/`:""}checkpoints/`,d=[],u;do{let p={Bucket:t.bucket,Prefix:o,...u&&{ContinuationToken:u}},g=await r.send(new n.ListObjectsV2Command(p));if(g.Contents)for(let m of g.Contents)m.Key?.endsWith(".json")&&m.LastModified&&d.push({key:m.Key,lastModified:m.LastModified});u=g.IsTruncated?g.NextContinuationToken:void 0;}while(u);if(d.length===0)return [];d.sort((p,g)=>{let m=g.lastModified.getTime()-p.lastModified.getTime();return m!==0?m:g.key<p.key?-1:g.key>p.key?1:0});let i=!!e?.tag?d:e?.limit?d.slice(0,e.limit):d,c=(await Promise.all(i.map(async p=>{try{return await Co(t,p.key)}catch{return null}}))).filter(p=>p!==null);return e?.tag&&(c=c.filter(p=>p.tag===e.tag)),e?.limit&&c.length>e.limit&&(c=c.slice(0,e.limit)),c}async function Oo(t,e){let n=new URLSearchParams;e?.limit&&n.set("limit",String(e.limit)),e?.tag&&n.set("tag",e.tag);let r=`${t.gatewayUrl}/api/checkpoints${n.toString()?`?${n}`:""}`,s=await fetch(r,{method:"GET",headers:{Authorization:`Bearer ${t.gatewayApiKey}`}});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Gateway list checkpoints failed (${s.status}): ${o}`)}return s.json()}function Hd(t){return t&&t>0?Math.min(t,500):100}async function Qr(t,e){return t.mode==="byok"?(await Io(t,{limit:1,tag:e?.tag}))[0]??null:(await Oo(t,{limit:1,tag:e?.tag}))[0]??null}async function Zr(t,e){if(t.mode==="byok"){let n=Eo(t,e);try{return await Co(t,n)}catch(r){throw zd(r)?new Error(`Checkpoint ${e} not found`):r}}else return await Vd(t,e)}async function yo(t,e,n){if(e==="latest"){let r=await Qr(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function Mo(t,e){if(t.mode==="byok")return xo(t,Ro(t,e.hash),"get");{let n=await To(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function Do(t){return !(!t||X.isAbsolute(t)||t.startsWith("-")||X.normalize(t).startsWith("..")||t.includes("\0"))}function bo(t,e){let n=X.resolve(t,e),r=X.resolve(t),s=X.relative(r,n);if(s.startsWith("..")||X.isAbsolute(s))throw new Error(`Path traversal detected: "${e}" resolves outside target directory`)}function zd(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Hr(t){let e=t.filter(n=>!Do(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var Uo=10*1024*1024,_o=false;async function Lo(){if(!_o)try{await Yr("tar",["--version"]),_o=!0;}catch{throw new Error("The 'tar' command is not available on this system. Storage download/extract requires tar (available on macOS, Linux, and Windows with Git Bash or WSL).")}}async function wo(t,e){let n=await Zr(t,e),r=await Mo(t,n),s=e.replace(/[^a-zA-Z0-9_-]/g,"_"),o=X.join(os$1.tmpdir(),`evolve-dl-${s}-${Date.now()}.tar.gz`),d=await fetch(r);if(!d.ok)throw new Error(`Checkpoint download failed (${d.status})`);if(!d.body)throw new Error("Checkpoint download returned empty body");let u=crypto.createHash("sha256"),l=Q.createWriteStream(o);try{let a=d.body.getReader();await new Promise((c,p)=>{l.on("error",p),l.on("finish",c);async function g(){for(;;){let{done:m,value:f}=await a.read();if(m){l.end();break}u.update(f),l.write(f)||await new Promise(h=>l.once("drain",h));}}g().catch(p);});}catch(a){throw l.destroy(),await promises.unlink(o).catch(()=>{}),a}let i=u.digest("hex");if(i!==n.hash)throw await promises.unlink(o).catch(()=>{}),new Error(`Checkpoint integrity check failed (expected ${n.hash}, got ${i})`);return {tmpPath:o,metadata:n}}var Wr=class extends Error{constructor(n){super(`Could not read a file path out of this 'tar -tvzf' line: ${JSON.stringify(n)}. The listing is produced by the tar on THIS machine, so an unrecognised layout means an unsupported tar variant (busybox, a very old BSD tar) rather than a corrupt archive. Refusing to return a partial file list.`);this.line=n;this.name="TarListingParseError";}},qd={LC_ALL:"C",LANG:"C"};function Wd(t){let e=[],n=[],r=[];for(let s of t.trim().split(`
|
|
220
|
+
`)){if(!s||s.startsWith("total "))continue;let o=s[0];if(o!=="-"&&o!=="d"&&o!=="l")throw new Error(`Archive contains unsupported entry type: "${o}"`);let d=s.match(/\d{2}:\d{2}\s+(.+)/)??s.match(/[A-Z][a-z]{2}\s+\d{1,2}\s+\d{4}\s+(.+)/);if(!d)throw new Wr(s);let u=d[1];if(o==="l"){let l=u.indexOf(" -> ");l!==-1&&(u=u.slice(0,l)),e.push(u);}else o==="d"?n.push(u.replace(/\/$/,"")):r.push(u);}return {filePaths:r,dirPaths:n,symlinkPaths:[...new Set(e)]}}async function ko(t){await Lo();let{stdout:e}=await Yr("tar",["-tvzf",t],{maxBuffer:Uo,env:{...process.env,...qd}}),{filePaths:n,dirPaths:r,symlinkPaths:s}=Wd(e);return Hr(r),Hr(s),Hr(n)}async function zr(t,e,n){await Lo(),await promises.mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await Yr("tar",r,{maxBuffer:Uo});}function Yd(t){let e="^",n=0;for(;n<t.length;){let r=t[n];r==="*"&&t[n+1]==="*"?t[n+2]==="/"?(e+="(?:.*/)?",n+=3):(e+=".*",n+=2):r==="*"?(e+="[^/]*",n++):r==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(r)?(e+="\\"+r,n++):(e+=r,n++);}return e+="$",new RegExp(e)}function es(t,e){let n=Ao(t,e);return $o(n)}function Xd(t){let e=Ao(t||{});return $o(e)}function $o(t){return {async listCheckpoints(e){let n=Hd(e?.limit);return t.mode==="byok"?Io(t,{limit:n,tag:e?.tag}):Oo(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return Zr(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,s=n?.to||process.cwd(),o=await yo(t,e),{tmpPath:d,metadata:u}=await wo(t,o);try{if(r)return await promises.mkdir(s,{recursive:!0}),await ko(d),await zr(d,s),s;{await promises.mkdir(s,{recursive:!0});let l=X.join(s,`checkpoint-${u.id}.tar.gz`);return await promises.copyFile(d,l),l}}finally{await promises.unlink(d).catch(()=>{});}},async downloadFiles(e,n){let r=await yo(t,e),{tmpPath:s}=await wo(t,r),o;try{let d=await ko(s),u;if(n?.files){let i=n.files.filter(c=>!Do(c));if(i.length>0)throw new Error(`Unsafe file path requested: ${i[0]}`);let a=new Set(n.files);u=d.filter(c=>a.has(c));}else if(n?.glob){let i=n.glob.map(Yd);u=d.filter(a=>i.some(c=>c.test(a)));}else u=d;if(u.length===0)return {};o=X.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`);try{await zr(s,o,u);}catch(i){let a=i?.message??"";if(!a.includes("E2BIG")&&!a.includes("Argument list too long")&&!a.includes("ENAMETOOLONG"))throw i;await promises.rm(o,{recursive:!0,force:!0}).catch(()=>{}),o=X.join(os$1.tmpdir(),`evolve-extract-${Date.now()}`),await zr(s,o);}let l={};return await Promise.all(u.map(async i=>{bo(o,i),l[i]=await promises.readFile(X.join(o,i));})),n?.to&&(await promises.mkdir(n.to,{recursive:!0}),await Promise.all(Object.entries(l).map(async([i,a])=>{bo(n.to,i);let c=X.join(n.to,i);await promises.mkdir(X.dirname(c),{recursive:!0}),await promises.writeFile(c,a);}))),l}finally{o&&await promises.rm(o,{recursive:true,force:true}).catch(()=>{}),await promises.unlink(s).catch(()=>{});}}}}function ce(t){return `'${t.replace(/'/g,"'\\''")}'`}function fn(t){return typeof t=="string"&&t.length>0}function Ue(t,e,n){let r=t[e];if(!fn(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function Qd(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
|
|
221
|
+
${n}`)}function Zd(t,e){switch(t){case "droid":{let n=Ue(e,"marketplace",t),r=Ue(e,"plugin",t);return [`droid plugin marketplace add ${ce(n)}`,`droid plugin install ${ce(r)} --scope user`]}case "claude":{let n=Ue(e,"marketplace",t),r=Ue(e,"plugin",t);return [`claude plugin marketplace add ${ce(n)} --scope user`,`claude plugin install ${ce(r)} --scope user`]}case "gemini":{let n=Ue(e,"source",t),r=e,s=[`gemini extensions install ${ce(n)}`];return fn(r.ref)&&s.push(`--ref ${ce(r.ref)}`),r.autoUpdate===true&&s.push("--auto-update"),r.preRelease===true&&s.push("--pre-release"),s.push("--consent"),r.skipSettings===true&&s.push("--skip-settings"),[s.join(" ")]}case "codex":{if("plugin"in e)throw new Error("withPlugins() for codex registers marketplaces only; codex has no plugin install command");let n=Ue(e,"marketplace",t),r=e,s=[`codex plugin marketplace add ${ce(n)}`];if(fn(r.ref)&&s.push(`--ref ${ce(r.ref)}`),Array.isArray(r.sparse))for(let o of r.sparse){if(!fn(o))throw new Error("withPlugins() for codex requires sparse entries to be non-empty strings");s.push(`--sparse ${ce(o)}`);}return [s.join(" ")]}default:throw new Error(`withPlugins() is not supported for ${t}`)}}async function Fo(t,e,n){if(n?.length)for(let r of n){let s=Zd(t,r);for(let o of s){let d=await e.commands.run(o,{timeoutMs:12e4});if(d.exitCode!==0)throw Qd(o,d)}}}var Jo="/home/user/.agent-browser",Bo=`${Jo}/config.json`,Ko="/home/user/.actionbook",tu=`${Ko}/config.toml`;function No(t){return t==="actionbook"||t==="agent-browser"}function nu(t){return t.remote===true}function jo(t){if(t==null)return;if(typeof t!="string")throw new Error("browser profile must be a string");let e=t.trim();if(!e)throw new Error("browser profile cannot be empty");return e}function Go(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(No(t))return {provider:t,managed:false};throw new Error("Unsupported browser configuration")}if(t.provider===void 0)return {provider:"agent-browser",managed:t.remote!==false,profile:jo(t.profile)};if(No(t.provider))return {provider:t.provider,managed:nu(t),profile:jo(t.profile)};throw new Error("Unsupported browser configuration")}function ts(t,e){return t==="actionbook"?{envs:{},files:[{path:tu,data:smolToml.stringify({version:1,browser:{mode:"cloud",cdp_endpoint:e.cdpUrl}}).trimEnd()+`
|
|
222
|
+
`}],directories:[Ko]}:{envs:{AGENT_BROWSER_CONFIG:Bo},files:[{path:Bo,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
|
|
223
|
+
`}],directories:[Jo]}}function Vo(t){return (t?.dashboardUrl||T).replace(/\/$/,"")}async function Ho(t){return await t.text().catch(()=>"")}async function zo(t,e,n={}){let r=await fetch(`${Vo(t)}/api/browser-sessions`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"content-type":"application/json",accept:"application/json"},body:JSON.stringify({sessionTag:e,options:{remote:true},browserAuth:n.browserCredentials===true,...t.profile?{profile:t.profile}:{}}),signal:AbortSignal.timeout(3e4)});if(!r.ok)throw new Error(`Managed browser session create failed (${r.status}): ${await Ho(r)}`);let s=await r.json();if(!s.id||!s.sessionId||!s.cdpUrl||!s.liveUrl)throw new Error("Managed browser session response missing id, sessionId, cdpUrl, or liveUrl");return {id:s.id,sessionId:s.sessionId,sessionTag:s.sessionTag,cdpUrl:s.cdpUrl,liveUrl:s.liveUrl,browserAuthGrantToken:s.browserAuthGrantToken}}async function qo(t,e){let n=await fetch(`${Vo(t)}/api/browser-sessions/${encodeURIComponent(e.id)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!n.ok&&n.status!==404)throw new Error(`Managed browser session stop failed (${n.status}): ${await Ho(n)}`)}var iu="RSA-OAEP-256",ns="browser-login";function ou(t){return (t||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,"")}function au(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser credentials require EVOLVE_API_KEY or an explicit apiKey");return e}async function lu(t){return await t.text().catch(()=>"")}async function gt(t,e,n={}){let r=await fetch(`${ou(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${au(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser credentials request failed (${r.status}): ${await lu(r)}`);return await r.json()}async function cu(t,e){let n=await gt(t,"/api/browser-credentials/public-key"),r=crypto.publicEncrypt({key:n.publicKey,padding:crypto.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(e,"utf8"));return {algorithm:iu,keyId:n.id,ciphertext:r.toString("base64url")}}var hn=class{constructor(e={}){this.config=e;}toMetadata(e){let{account_label:n,...r}=e;return {...r,accountLabel:n}}async list(e={}){let n=new URLSearchParams;e.website&&n.set("website",e.website),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let r=n.toString()?`?${n.toString()}`:"",s=await gt(this.config,`/api/browser-credentials${r}`);return {credentials:s.credentials.map(o=>this.toMetadata(o)),total:s.total,count:s.count,offset:s.offset,hasMore:s.has_more??s.offset+s.count<s.total}}async create(e){let n=await cu(this.config,e.password),r=await gt(this.config,"/api/browser-credentials",{method:"POST",body:JSON.stringify({website:e.website,account_label:e.accountLabel,email:e.email,encryptedPassword:n})});return {status:r.status,credential:this.toMetadata(r.credential)}}async delete(e){let n="id"in e?e:{website:e.website,account_label:e.accountLabel};return await gt(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function rs(t={}){return new hn(t)}async function Wo(t){return (await gt({apiKey:t.apiKey,dashboardUrl:t.dashboardUrl},"/api/browser-login/mcp-config",{method:"POST",body:JSON.stringify({browserSessionId:t.browserSessionId,sessionTag:t.sessionTag,grantToken:t.grantToken,allow:du(t.config)})})).server}function du(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var ss="x-evolve-provider-runtime-binding";function uu(t){return (t||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,"")}async function pu(t){return await t.text().catch(()=>"")}var mt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ProviderRuntimeTokenRequestError";}};function Yo(t){return t instanceof mt&&t.status===404}async function is(t,e,n={}){let r=await fetch(`${uu(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new mt(r.status,`Provider runtime token request failed (${r.status}): ${await pu(r)}`);return await r.json()}function gu(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return e.enabled===true&&(e.provider==="anthropic"||e.provider==="openai"||e.provider==="gemini"||e.provider==="dashscope"||e.provider==="kimi"||e.provider==="openrouter"||e.provider==="droid")&&(e.credentialMode==="provider_key"||e.credentialMode==="evolve_key")&&typeof e.token=="string"&&e.token.length>0&&typeof e.bindingSecret=="string"&&e.bindingSecret.length>0&&typeof e.baseUrl=="string"&&e.baseUrl.length>0&&typeof e.expiresAt=="string"&&e.expiresAt.length>0}async function Xo(t,e){let n=await is(t,"/api/provider-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!gu(n))throw new mt(502,"Provider runtime token response was invalid");return n}async function Qo(t,e){return (await is(t,"/api/provider-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function Zo(t,e){return (await is(t,"/api/provider-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}function os(t){return t.delivery==="direct"}var bn=18181,L="/tmp/evolve-managed-secrets",ft=`${L}/proxy.py`,Fe=`${L}/config.json`,he=`${L}/ca.crt`,yn=`${L}/ca.key`,Le=`${L}/ca-bundle.crt`,na=["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","http_proxy","https_proxy","all_proxy","NO_PROXY","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"];function ra(){return [...na]}var sa=String.raw`#!/usr/bin/env python3
|
|
224
224
|
import base64
|
|
225
225
|
import json
|
|
226
226
|
import os
|
|
@@ -636,34 +636,34 @@ def serve():
|
|
|
636
636
|
if __name__ == "__main__":
|
|
637
637
|
register_channel()
|
|
638
638
|
serve()
|
|
639
|
-
`;function
|
|
640
|
-
`).map(a=>a.trim()).filter(Boolean);if(o.length>0)throw new Error(`Artifact roots are not collectable: ${o.join("; ")}`);let d;try{d=await t.commands.run(`set -o pipefail 2>/dev/null; find -- ${r.map(
|
|
641
|
-
`)}var hu=262144,yu=128e3,bu=new Set(["low","medium","high","xhigh","max"]);function ca(t){if(t)return bu.has(t)?t:void 0}function bn(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var yt=class{agentConfig;options;sandbox;hasRun=false;workingDir;homeDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;providerRuntimeToken;managedSecretRuntimeToken;managedSecretProxy;credentialsSealed=false;skills;resolvedSkillsList;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(nt(e),Pr(n.observability),n.managedSecrets){if(e.isDirectMode)throw new Error("managed secrets are available only in gateway mode with EVOLVE_API_KEY");if(n.sandboxId)throw new Error("managed secrets cannot be used with an existing sandbox; grants are sandbox-scoped.");if(n.sandboxProvider&&!Ie(n.sandboxProvider))throw new Error("managed secrets require an Evolve-managed sandbox provider")}if(this.agentConfig=e,this.options=n,n.sandboxId&&n.sandboxCreateOptions?.user)throw new Error("sandbox user cannot be enforced when attaching to an existing sandbox; create a fresh sandbox with the user instead");if(this.homeDir=$s(n.sandboxCreateOptions?.user,n.sandboxCreateOptions?.homeDir),this.homeDir!==W){if(n.storage)throw new Error("Checkpoint storage requires the default /home/user sandbox home directory; remove sandbox user/homeDir or storage");if(n.managedBrowser||n.browserCredentials)throw new Error("Managed browser features require the default /home/user sandbox home directory")}if(this.workingDir=n.workingDirectory||n.sandboxCreateOptions?.workingDirectory||`${this.homeDir}/workspace`,this.sandboxState=n.sandboxId?"ready":"stopped",n.workspaceMode==="task"&&[n.context,n.files,n.systemPrompt,n.browserPrompt,n.schema].some(Boolean))throw new Error('workspaceMode "task" cannot be combined with context, files, systemPrompt, browserPrompt, or schema; the task owns the working directory');if(this.skills=n.skills,this.storage=n.storage,n.schema)if(Y(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 r=this.createAjvValidator();this.compiledValidator=r.compile(this.jsonSchema);}catch(r){throw new Error(`Invalid JSON Schema: ${r.message}`)}}this.registry=K(e.type),this.sessionTag=la(n.sessionTagPrefix||"evolve");}browserRuntimeInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl,sessionId:this.managedBrowserSession.sessionId,sessionTag:this.managedBrowserSession.sessionTag}}browserResponseInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl}}emitLifecycle(e,n){let r=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...r?{browser:r}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,r,s){let o=++this.nextOperationId;return this.activeOperationId=o,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),o}finalizeOperation(e,n,r,s="idle",o="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=o,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,o){let d=n==="run"?"run_background_complete":"command_background_complete",u=n==="run"?"run_background_failed":"command_background_failed",l=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async i=>{if(this.interruptedOperations.delete(e)||i.exitCode===130){this.finalizeOperation(e,s,l,"interrupted");return}n==="run"&&o&&await this.writeDroidSessionState(o);let c=i.exitCode===0?d:u,p=i.exitCode===0?"idle":"error";this.finalizeOperation(e,s,c,p);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,u,"error");});}createAjvValidator(){let n={...$n[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 uu__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot create or attach another 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");let r=false;try{if(this.options.sandboxId)(this.options.mcpServers||this.options.integrations||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser||this.options.browserCredentials)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, integrations, plugins, context, files, systemPrompt, managed browser setup, and browser credentials"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,await this.loadDroidSessionState(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {await this.ensureManagedBrowserSession(e),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let s=this.buildEnvironmentVariables();this.sandbox=await n.create(this.buildSandboxCreateOptions(s)),r=!0,await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(s){throw r&&this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}return this.sandbox}resolveKimiMaxContextSize(){if(typeof this.agentConfig.maxContextSize=="number")return this.agentConfig.maxContextSize;let e=this.agentConfig.model||this.registry.defaultModel;return ve(this.registry,e)||ve(this.registry,this.resolveCommandModel(e))?this.registry.models.find(s=>s.alias===e||s.modelId===e)?.maxContextSize??this.registry.spendTrackingTomlProvider?.maxContextSize??hu:yu}reasoningEffort(){return Vs(this.agentConfig.type,this.agentConfig.reasoningEffort)}buildKimiDirectModelEnvs(){let e=Xe(this.reasoningEffort()),n=ca(this.reasoningEffort()),r={KIMI_MODEL_NAME:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),KIMI_MODEL_API_KEY:this.agentConfig.apiKey,KIMI_MODEL_PROVIDER_TYPE:"kimi",KIMI_MODEL_MAX_CONTEXT_SIZE:String(this.resolveKimiMaxContextSize()),KIMI_MODEL_DEFAULT_THINKING:e?"true":"false",KIMI_MODEL_THINKING_MODE:e?"on":"off"};return n&&(r.KIMI_MODEL_THINKING_EFFORT=n),this.agentConfig.baseUrl&&(r.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl),r}buildEnvironmentVariables(){let e={},n=this.validatedUserSecretsForEnvironment();if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode)Object.assign(e,this.buildKimiDirectModelEnvs());else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){if(!(!this.agentConfig.isDirectMode&&ht(this.agentConfig.type))){if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let r of Object.values(this.registry.providerEnvMap))e[r.keyEnv]=this.agentConfig.apiKey;else {let r=this.agentConfig.model?.split("/")[0],s=r?this.registry.providerEnvMap?.[r]:void 0,o=s?s.keyEnv:this.registry.apiKeyEnv,d=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:o;e[d]=this.agentConfig.apiKey;}}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let r=q(this.registry.gatewayPath),s=this.requireActiveProviderRuntimeToken();if(this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[z]:this.sessionTag,...this.providerRuntimeHeaderUpdates()}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=s?.baseUrl??r),s&&(this.shouldExposeProviderRuntimeTokenEnv()&&(e[this.registry.apiKeyEnv]=s.token),this.agentConfig.type==="gemini"&&(e.GEMINI_DEFAULT_AUTH_TYPE=os),this.registry.spendTrackingEnvs&&(e[yn]=s.bindingSecret)),!s){if(ht(this.agentConfig.type))throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);e[O]=this.agentConfig.apiKey;}}if(this.agentConfig.externalGateway&&this.registry.gatewayConfigEnv&&(e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.externalGateway&&this.agentConfig.type==="gemini"&&(e.GEMINI_CLI_TRUST_WORKSPACE="true"),this.agentConfig.type==="claude"&&(e.IS_SANDBOX="1"),this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,Qr(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.managedSecretRuntimeToken&&Object.assign(e,na(this.managedSecretRuntimeToken)),n&&Object.assign(e,n),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";e[r]=as(e[r],{[z]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},s);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildSandboxCreateOptions(e){return {...this.options.sandboxCreateOptions,envs:e,workingDirectory:this.workingDir}}validatedUserSecretsForEnvironment(){let e={...this.options.sandboxCreateOptions?.envs,...this.options.secrets};if(Object.keys(e).length===0)return;let n=new Set;this.agentConfig.isDirectMode||(n.add(O),n.add(yn),this.agentConfig.type==="gemini"&&n.add("GEMINI_DEFAULT_AUTH_TYPE"));let r=o=>{o&&n.add(o);};r(this.registry.apiKeyEnv),r(this.registry.baseUrlEnv);for(let o of Object.values(this.registry.providerEnvMap??{}))r(o.keyEnv);if(this.managedSecretRuntimeToken)for(let o of Yo())n.add(o);for(let o of this.managedSecretRuntimeToken?.env??[])r(o.envName);let s={};for(let[o,d]of Object.entries(e)){if(n.has(o))throw new Error(`${o} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);o!==this.registry.gatewayConfigEnv&&(s[o]=d);}return s}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await jo(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async ensureProviderRuntimeToken(){let e=ht(this.agentConfig.type);if(this.agentConfig.isDirectMode||!e||!this.options.providerRouting||this.providerRuntimeToken)return;let n;try{n=await Vo(this.options.providerRouting,{provider:e,sessionTag:this.sessionTag});}catch(r){throw Ko(r)?new Error(`${e} runtime token endpoint is required in gateway mode: ${r.message}`):r}this.providerRuntimeToken=n,this.providerRuntimeToken&&this.sandbox?.sandboxId&&await this.bindProviderRuntimeToken(this.sandbox.sandboxId);}directSandboxProviderDeclaration(){let e=this.options.sandboxProvider;if(!e||Ie(e))return;let n=e.providerType;return ke.includes(n)?n:void 0}async bindProviderRuntimeToken(e){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let n=this.directSandboxProviderDeclaration();if(!await Go(this.options.providerRouting,{token:this.providerRuntimeToken.token,sandboxId:e,...n?{directSandboxProvider:n}:{}}))throw new Error("Failed to bind provider runtime token to sandbox")}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=Qr(this.options.managedBrowser.provider,this.managedBrowserSession);for(let r of n.directories)await e.files.makeDir(r);for(let r of n.files)await e.files.write(r.path,r.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await Fo(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}async closeProviderRuntimeToken(e=false){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let n=this.providerRuntimeToken,r;for(let o=0;o<3;o++)try{if(!await zo(this.options.providerRouting,{token:n.token}))throw new Error("Dashboard returned ok=false");this.providerRuntimeToken=void 0;return}catch(d){r=d,o<2&&await new Promise(u=>setTimeout(u,100*(o+1)));}let s=`Provider runtime token cleanup failed: ${r.message}`;if(e)throw new Error(s);console.warn(`[Evolve] ${s}`),this.providerRuntimeToken=void 0;}async ensureManagedSecretRuntimeToken(){this.managedSecretRuntimeToken||!this.options.managedSecrets||(this.managedSecretRuntimeToken=await Qo({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{sessionTag:this.sessionTag,secrets:this.options.managedSecrets.secrets}));}async bindManagedSecretRuntimeToken(e){if(!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;if(!await Zo({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:this.managedSecretRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind managed secret runtime token to sandbox")}async setupManagedSecretEgress(e){if(!this.managedSecretRuntimeToken||!is(this.managedSecretRuntimeToken))return;if(await e.files.makeDir($),await e.commands.run(`umask 077 && mkdir -p ${$}/certs && chmod 700 ${$} ${$}/certs`,{timeoutMs:5e3}),await e.files.write(ft,Xo),await e.files.write(Le,ra(this.managedSecretRuntimeToken)),await e.commands.run(`chmod 700 ${ft} && chmod 600 ${Le}`,{timeoutMs:5e3}),await e.commands.run(sa(),{timeoutMs:3e4}),this.managedSecretProxy=await e.commands.spawn(ia(),{timeoutMs:3e4}),(await e.commands.run(`python3 - <<'PY'
|
|
639
|
+
`;function mu(t){return (t||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,"")}function fu(t){let e=t.apiKey||process.env.EVOLVE_API_KEY;if(!e)throw new Error("EVOLVE_API_KEY is required for managed secrets");return e}async function hu(t){return await t.text().catch(()=>"")}async function $e(t,e,n={}){let r=await fetch(`${mu(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${fu(t)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Managed secrets request failed (${r.status}): ${await hu(r)}`);return await r.json()}function yu(t){let e=n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[];return {id:String(t.id??""),name:String(t.name??""),...typeof t.label=="string"?{label:t.label}:{},...t.delivery==="brokered"||t.delivery==="direct"?{delivery:t.delivery}:{},allowedHosts:e(t.allowed_hosts??t.allowedHosts),allowedPathPrefixes:e(t.allowed_path_prefixes??t.allowedPathPrefixes),allowedMethods:e(t.allowed_methods??t.allowedMethods),createdAt:String(t.created_at??t.createdAt??""),updatedAt:String(t.updated_at??t.updatedAt??""),lastUsedAt:typeof(t.last_used_at??t.lastUsedAt)=="string"?t.last_used_at??t.lastUsedAt:null}}function as(t={}){return {async list(){return (await $e(t,"/api/managed-secrets")).secrets??[]},async set(e){let n={name:e.name,value:e.value,delivery:e.delivery,...e.label!==void 0?{label:e.label}:{},...e.allowedHosts!==void 0?{allowed_hosts:e.allowedHosts}:{},...e.allowedPathPrefixes!==void 0?{allowed_path_prefixes:e.allowedPathPrefixes}:{},...e.allowedMethods!==void 0?{allowed_methods:e.allowedMethods}:{}},r=await $e(t,"/api/managed-secrets",{method:"POST",body:JSON.stringify(n)});return {status:r.status,secret:yu(r.secret??{})}},async delete(e){let n=await $e(t,"/api/managed-secrets",{method:"DELETE",body:JSON.stringify({name:e.name,...e.label!==void 0?{label:e.label}:{}})});return {ok:n.ok,name:n.name,label:n.label}}}}function bu(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function ea(t){try{return new URL(t).protocol==="https:"}catch{return false}}function _u(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return typeof e.token=="string"&&e.token.startsWith("evrt_")&&typeof e.bindingSecret=="string"&&e.bindingSecret.startsWith("evrb_")&&typeof e.egressUrl=="string"&&ea(e.egressUrl)&&typeof e.channelUrl=="string"&&ea(e.channelUrl)&&typeof e.expiresAt=="string"&&Array.isArray(e.env)&&e.env.every(n=>{if(!n||typeof n!="object"||Array.isArray(n))return false;let r=n;return typeof r.name!="string"||typeof r.envName!="string"||!bu(r.allowedHosts)?false:r.delivery==="direct"?typeof r.value=="string"&&r.value.length>0:(r.delivery===void 0||r.delivery==="brokered")&&typeof r.placeholder=="string"&&r.placeholder.startsWith("evsec_")&&r.value===void 0})}async function ia(t,e){let n=await $e(t,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!_u(n))throw new Error("Invalid managed secret runtime token response");return n}async function oa(t,e){return (await $e(t,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function aa(t,e){return (await $e(t,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}var wu=/^[A-Za-z0-9._-]{1,80}$/;function ku(t){if(!Array.isArray(t)||t.length===0)throw new Error("withManagedSecrets() requires at least one secret");return t.map((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`managedSecrets[${n}] must be an object with a name`);let r=ta(e.name,`managedSecrets[${n}].name`),s;if(e.label!==void 0){if(typeof e.label!="string"||!wu.test(e.label.trim()))throw new Error(`managedSecrets[${n}].label may contain only letters, numbers, dots, underscores, and hyphens (at most 80 characters)`);s=e.label.trim();}let o=e.as===void 0?void 0:ta(e.as,`managedSecrets[${n}].as`);return {name:r,...s!==void 0?{label:s}:{},...o!==void 0?{as:o}:{}}})}function ta(t,e){if(typeof t!="string"||!t.trim())throw new Error(`${e} is required`);let n=t.trim().toUpperCase();if(!/^[A-Z_][A-Z0-9_]{0,127}$/.test(n))throw new Error(`${e} must be a valid environment variable name`);if(n.startsWith("EVOLVE_"))throw new Error(`${e} cannot use the reserved EVOLVE_ prefix`);return n}function vu(t){let e=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...na]),n=r=>{r&&e.add(r);};n(t.apiKeyEnv),n(t.baseUrlEnv),n(t.customHeadersEnv),n(t.gatewayConfigEnv),t.spendTrackingEnvs&&(n(t.spendTrackingEnvs.sessionTagEnv),n(t.spendTrackingEnvs.runTagEnv));for(let r of Object.values(t.providerEnvMap??{}))n(r.keyEnv);return e}function la(t,e){if(!t)return;let n=ku(t),r=vu(e),s=new Set;for(let o of n){let d=o.as||o.name;if(r.has(d))throw new Error(`${d} is reserved for Evolve-managed sandbox services and cannot be used as a managed secret env var`);if(s.has(d))throw new Error(`duplicate managed secret env var: ${d}`);s.add(d);}return n}function ls(t){return t.env.some(e=>!os(e))}function ca(t){let e={};for(let s of t.env)os(s)?e[s.envName]=s.value:e[s.envName]=s.placeholder;if(!ls(t))return e;let n=`http://127.0.0.1:${bn}`;e.HTTPS_PROXY=n,e.https_proxy=n,e.NODE_EXTRA_CA_CERTS=he,e.SSL_CERT_FILE=Le,e.REQUESTS_CA_BUNDLE=Le,e.CURL_CA_BUNDLE=Le,e.GIT_SSL_CAINFO=Le;let r=new URL(t.egressUrl).hostname;return e.NO_PROXY=`localhost,127.0.0.1,::1,${r}`,e.no_proxy=e.NO_PROXY,e}function da(t){let e=t.env.filter(r=>!os(r)),n=Array.from(new Set(e.flatMap(r=>r.allowedHosts)));return JSON.stringify({egress_url:t.egressUrl,channel_url:t.channelUrl,token:t.token,binding:t.bindingSecret,hosts:n,placeholders:e.map(r=>r.placeholder),base_dir:L,ca_cert:he,ca_key:yn,port:bn,max_body_bytes:10*1024*1024},null,2)}function ua(){return ["umask 077",`mkdir -p ${L}/certs`,`chmod 700 ${L} ${L}/certs`,`chmod 700 ${ft} 2>/dev/null || true`,`chmod 600 ${Fe} 2>/dev/null || true`,`if [ ! -f ${yn} ]; then openssl genrsa -out ${yn} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${he} ]; then openssl req -x509 -new -nodes -key ${yn} -sha256 -days 30 -subj "/CN=Evolve Managed Secrets" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ${he} >/dev/null 2>&1; fi`,`SYSTEM_CA_BUNDLE=""; for p in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem; do if [ -f "$p" ]; then SYSTEM_CA_BUNDLE="$p"; break; fi; done; if [ -n "$SYSTEM_CA_BUNDLE" ]; then cat "$SYSTEM_CA_BUNDLE" ${he} > ${Le}; else cp ${he} ${Le}; fi`,`if command -v update-ca-certificates >/dev/null 2>&1; then cp ${he} /usr/local/share/ca-certificates/evolve-managed-secrets.crt 2>/dev/null && update-ca-certificates >/dev/null 2>&1 || true; fi`].join(" && ")}function pa(){return `umask 077 && exec python3 ${ft} ${Fe}`}function ga(){return `rm -f ${Fe}`}function ht(t){return `'${t.replaceAll("'",`'"'"'`)}'`}function Su(t){let e=t.trim();if(e==="")return [];let n=Buffer.from(e,"base64"),r=[],s=0;for(let o=0;o<n.length;o++)n[o]===0&&(r.push(n.toString("utf8",s,o)),s=o+1);return s<n.length&&r.push(n.toString("utf8",s,n.length)),r}async function ma(t,e,n){if(n.length===0)throw new Error("collectArtifacts() requires at least one path.");let r=n.map(a=>{if(!a||a.includes("\0"))throw new Error(`Invalid artifact path: ${JSON.stringify(a)}`);let c=X.posix.normalize(a);if(!X.posix.isAbsolute(c)&&(c===".."||c.startsWith("../")))throw new Error(`Artifact path escapes the working directory: ${a}`);return X.posix.isAbsolute(c)?c:X.posix.join(e,c)}),o=(await t.commands.run(r.map(a=>`if [ ! -e ${ht(a)} ]; then echo MISSING ${ht(a)}; elif [ ! -r ${ht(a)} ]; then echo UNREADABLE ${ht(a)}; fi`).join("; "),{cwd:e,timeoutMs:15e3})).stdout.split(`
|
|
640
|
+
`).map(a=>a.trim()).filter(Boolean);if(o.length>0)throw new Error(`Artifact roots are not collectable: ${o.join("; ")}`);let d;try{d=await t.commands.run(`set -o pipefail 2>/dev/null; find -- ${r.map(ht).join(" ")} -type f -printf '%p\\0%s\\0' | base64 -w0`,{cwd:e,timeoutMs:3e4});}catch(a){throw new Error(`Artifact listing failed: ${a.message}`)}if(d.exitCode!==0)throw new Error(`Artifact listing failed (exit ${d.exitCode}): ${(d.stderr||"").slice(0,500)}`);let u=Su(d.stdout);if(u.length%2!==0)throw new Error("Sandbox returned malformed artifact metadata.");let l=new Map;for(let a=0;a<u.length;a+=2){let c=u[a],p=Number(u[a+1]);if(!Number.isSafeInteger(p)||p<0)throw new Error(`Sandbox returned an invalid artifact size: ${c}`);l.has(c)||l.set(c,p);}let i={};for(let a of [...l.keys()].sort()){let c=r.some(m=>a===m||a.startsWith(`${m.replace(/\/$/,"")}/`));if(!X.posix.isAbsolute(a)||!c)throw new Error(`Sandbox returned an invalid artifact path: ${a}`);let p=X.posix.relative(e,a),g=p&&p!==".."&&!p.startsWith("../")?p:a;i[g]=await t.files.read(a);}return i}var _n="EVOLVE_PROVIDER_RUNTIME_BINDING",cs="gemini-api-key";function yt(t){switch(t){case "claude":return "anthropic";case "codex":return "openai";case "gemini":return "gemini";case "qwen":return "dashscope";case "kimi":return "kimi";case "opencode":return "openrouter";case "droid":return "droid";default:return null}}function Tu(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function fa(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function ds(t,e,n="newline"){let r=new Map;if(t){let s=n==="comma"?t.split(/,(?=\s*[^,:]+:)/):t.split(/\r?\n/);for(let o of s){let d=o.trim();if(!d)continue;let u=d.indexOf(":");if(u<=0)continue;let l=d.slice(0,u).trim(),i=d.slice(u+1).trim();r.set(l.toLowerCase(),`${l}: ${i}`);}}for(let[s,o]of Object.entries(e)){let d=s.toLowerCase();if(d===te&&r.has(d)&&n==="newline"){let u=r.get(d),l=u.slice(u.indexOf(":")+1).trim();r.set(d,`${s}: ${l},${o}`);}else r.set(d,`${s}: ${o}`);}return Array.from(r.values()).join(n==="comma"?", ":`
|
|
641
|
+
`)}var Pu=262144,Au=128e3,Iu=new Set(["low","medium","high","xhigh","max"]);function ha(t){if(t)return Iu.has(t)?t:void 0}function wn(t){let e=t.replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}var bt=class{agentConfig;options;sandbox;hasRun=false;workingDir;homeDir;lastRunTimestamp;registry;sessionTag;previousSessionTag;sessionLogger;activeCommand;activeProcessId=null;activeOperationId=null;activeOperationKind=null;nextOperationId=0;interruptedOperations=new Set;sandboxState;agentState="idle";droidSessionId;managedBrowserSession;providerRuntimeToken;managedSecretRuntimeToken;managedSecretProxy;credentialsSealed=false;skills;resolvedSkillsList;storage;lastCheckpointId;zodSchema;jsonSchema;schemaOptions;compiledValidator;constructor(e,n={}){if(rt(e),Mr(n.observability),n.managedSecrets){if(e.isDirectMode)throw new Error("managed secrets are available only in gateway mode with EVOLVE_API_KEY");if(n.sandboxId)throw new Error("managed secrets cannot be used with an existing sandbox; grants are sandbox-scoped.");if(n.sandboxProvider&&!Oe(n.sandboxProvider))throw new Error("managed secrets require an Evolve-managed sandbox provider")}if(this.agentConfig=e,this.options=n,n.sandboxId&&n.sandboxCreateOptions?.user)throw new Error("sandbox user cannot be enforced when attaching to an existing sandbox; create a fresh sandbox with the user instead");if(this.homeDir=Ks(n.sandboxCreateOptions?.user,n.sandboxCreateOptions?.homeDir),this.homeDir!==W){if(n.storage)throw new Error("Checkpoint storage requires the default /home/user sandbox home directory; remove sandbox user/homeDir or storage");if(n.managedBrowser||n.browserCredentials)throw new Error("Managed browser features require the default /home/user sandbox home directory")}if(this.workingDir=n.workingDirectory||n.sandboxCreateOptions?.workingDirectory||`${this.homeDir}/workspace`,this.sandboxState=n.sandboxId?"ready":"stopped",n.workspaceMode==="task"&&[n.context,n.files,n.systemPrompt,n.browserPrompt,n.schema].some(Boolean))throw new Error('workspaceMode "task" cannot be combined with context, files, systemPrompt, browserPrompt, or schema; the task owns the working directory');if(this.skills=n.skills,this.storage=n.storage,n.schema)if(Y(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 r=this.createAjvValidator();this.compiledValidator=r.compile(this.jsonSchema);}catch(r){throw new Error(`Invalid JSON Schema: ${r.message}`)}}this.registry=K(e.type),this.sessionTag=fa(n.sessionTagPrefix||"evolve");}browserRuntimeInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl,sessionId:this.managedBrowserSession.sessionId,sessionTag:this.managedBrowserSession.sessionTag}}browserResponseInfo(){if(this.managedBrowserSession)return {liveUrl:this.managedBrowserSession.liveUrl}}emitLifecycle(e,n){let r=this.browserRuntimeInfo();e?.onLifecycle?.({sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,timestamp:new Date().toISOString(),reason:n,...r?{browser:r}:{}});}invalidateActiveOperation(){this.activeCommand=void 0,this.activeProcessId=null,this.activeOperationId=null,this.activeOperationKind=null;}beginOperation(e,n,r,s){let o=++this.nextOperationId;return this.activeOperationId=o,this.activeOperationKind=e,this.activeCommand=n,this.activeProcessId=n.processId,this.sandboxState="running",this.agentState="running",this.emitLifecycle(r,s),o}finalizeOperation(e,n,r,s="idle",o="ready"){return this.activeOperationId!==e?false:(this.invalidateActiveOperation(),this.sandboxState=o,this.agentState=s,this.emitLifecycle(n,r),true)}watchBackgroundOperation(e,n,r,s,o){let d=n==="run"?"run_background_complete":"command_background_complete",u=n==="run"?"run_background_failed":"command_background_failed",l=n==="run"?"run_interrupted":"command_interrupted";r.wait().then(async i=>{if(this.interruptedOperations.delete(e)||i.exitCode===130){this.finalizeOperation(e,s,l,"interrupted");return}n==="run"&&o&&await this.writeDroidSessionState(o);let c=i.exitCode===0?d:u,p=i.exitCode===0?"idle":"error";this.finalizeOperation(e,s,c,p);}).catch(()=>{this.interruptedOperations.delete(e),this.finalizeOperation(e,s,u,"error");});}createAjvValidator(){let n={...Nn[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 xu__default.default({...n,strict:false})}async getSandbox(e){if(this.sandbox)return this.sandbox;if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot create or attach another 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");let r=false;try{if(this.options.sandboxId)(this.options.mcpServers||this.options.integrations||this.options.plugins||this.options.context||this.options.files||this.options.systemPrompt||this.options.managedBrowser||this.options.browserCredentials)&&console.warn("[Evolve] Connecting to existing sandbox - ignoring mcpServers, integrations, plugins, context, files, systemPrompt, managed browser setup, and browser credentials"),this.sandbox=await n.connect(this.options.sandboxId),this.hasRun=!0,await this.loadDroidSessionState(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_connected");else {await this.ensureManagedBrowserSession(e),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let s=this.buildEnvironmentVariables();this.sandbox=await n.create(this.buildSandboxCreateOptions(s)),r=!0,await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox),await this.setupManagedBrowser(this.sandbox),await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox),await this.setupWorkspace(this.sandbox),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_ready");}}catch(s){throw r&&this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(e,"sandbox_error"),s}return this.sandbox}resolveKimiMaxContextSize(){if(typeof this.agentConfig.maxContextSize=="number")return this.agentConfig.maxContextSize;let e=this.agentConfig.model||this.registry.defaultModel;return Se(this.registry,e)||Se(this.registry,this.resolveCommandModel(e))?this.registry.models.find(s=>s.alias===e||s.modelId===e)?.maxContextSize??this.registry.spendTrackingTomlProvider?.maxContextSize??Pu:Au}reasoningEffort(){return Xs(this.agentConfig.type,this.agentConfig.reasoningEffort)}buildKimiDirectModelEnvs(){let e=Qe(this.reasoningEffort()),n=ha(this.reasoningEffort()),r={KIMI_MODEL_NAME:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),KIMI_MODEL_API_KEY:this.agentConfig.apiKey,KIMI_MODEL_PROVIDER_TYPE:"kimi",KIMI_MODEL_MAX_CONTEXT_SIZE:String(this.resolveKimiMaxContextSize()),KIMI_MODEL_DEFAULT_THINKING:e?"true":"false",KIMI_MODEL_THINKING_MODE:e?"on":"off"};return n&&(r.KIMI_MODEL_THINKING_EFFORT=n),this.agentConfig.baseUrl&&(r.KIMI_MODEL_BASE_URL=this.agentConfig.baseUrl),r}buildEnvironmentVariables(){let e={},n=this.validatedUserSecretsForEnvironment();if(this.agentConfig.type==="kimi"&&this.agentConfig.isDirectMode)Object.assign(e,this.buildKimiDirectModelEnvs());else if(this.agentConfig.oauthFileContent)this.registry.oauthActivationEnv&&(e[this.registry.oauthActivationEnv.key]=this.registry.oauthActivationEnv.value);else if(!(this.agentConfig.type==="kimi"&&!this.agentConfig.isDirectMode)){if(!(!this.agentConfig.isDirectMode&&yt(this.agentConfig.type))){if(!(this.registry.skipApiKeyEnvInGateway&&!this.agentConfig.isDirectMode))if(this.registry.providerEnvMap&&!this.agentConfig.isDirectMode)for(let r of Object.values(this.registry.providerEnvMap))e[r.keyEnv]=this.agentConfig.apiKey;else {let r=this.agentConfig.model?.split("/")[0],s=r?this.registry.providerEnvMap?.[r]:void 0,o=s?s.keyEnv:this.registry.apiKeyEnv,d=this.agentConfig.isOAuth&&this.registry.oauthEnv?this.registry.oauthEnv:o;e[d]=this.agentConfig.apiKey;}}}if(this.agentConfig.isDirectMode&&!this.agentConfig.isOAuth&&this.agentConfig.type!=="kimi")this.agentConfig.baseUrl&&this.registry.baseUrlEnv&&(e[this.registry.baseUrlEnv]=this.agentConfig.baseUrl);else if(!this.agentConfig.isDirectMode){let r=q(this.registry.gatewayPath),s=this.requireActiveProviderRuntimeToken();if(this.registry.gatewayConfigEnv?e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({[H]:this.sessionTag,...this.providerRuntimeHeaderUpdates()}):this.registry.baseUrlEnv&&this.agentConfig.type!=="kimi"&&(e[this.registry.baseUrlEnv]=s?.baseUrl??r),s&&(this.shouldExposeProviderRuntimeTokenEnv()&&(e[this.registry.apiKeyEnv]=s.token),this.agentConfig.type==="gemini"&&(e.GEMINI_DEFAULT_AUTH_TYPE=cs),this.registry.spendTrackingEnvs&&(e[_n]=s.bindingSecret)),!s){if(yt(this.agentConfig.type))throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);e[O]=this.agentConfig.apiKey;}}if(this.agentConfig.externalGateway&&this.registry.gatewayConfigEnv&&(e[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.externalGateway&&this.agentConfig.type==="gemini"&&(e.GEMINI_CLI_TRUST_WORKSPACE="true"),this.agentConfig.type==="claude"&&(e.IS_SANDBOX="1"),this.managedBrowserSession&&this.options.managedBrowser&&Object.assign(e,ts(this.options.managedBrowser.provider,this.managedBrowserSession).envs),this.managedSecretRuntimeToken&&Object.assign(e,ca(this.managedSecretRuntimeToken)),n&&Object.assign(e,n),!this.agentConfig.isDirectMode&&this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";e[r]=ds(e[r],{[H]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},s);}return !this.agentConfig.isDirectMode&&this.registry.spendTrackingEnvs&&(e[this.registry.spendTrackingEnvs.sessionTagEnv]=this.sessionTag),e}buildSandboxCreateOptions(e){return {...this.options.sandboxCreateOptions,envs:e,workingDirectory:this.workingDir}}validatedUserSecretsForEnvironment(){let e={...this.options.sandboxCreateOptions?.envs,...this.options.secrets};if(Object.keys(e).length===0)return;let n=new Set;this.agentConfig.isDirectMode||(n.add(O),n.add(_n),this.agentConfig.type==="gemini"&&n.add("GEMINI_DEFAULT_AUTH_TYPE"));let r=o=>{o&&n.add(o);};r(this.registry.apiKeyEnv),r(this.registry.baseUrlEnv);for(let o of Object.values(this.registry.providerEnvMap??{}))r(o.keyEnv);if(this.managedSecretRuntimeToken)for(let o of ra())n.add(o);for(let o of this.managedSecretRuntimeToken?.env??[])r(o.envName);let s={};for(let[o,d]of Object.entries(e)){if(n.has(o))throw new Error(`${o} is reserved for Evolve-managed sandbox services and cannot be set with secrets`);o!==this.registry.gatewayConfigEnv&&(s[o]=d);}return s}async ensureManagedBrowserSession(e){this.managedBrowserSession||!this.options.managedBrowser||(this.managedBrowserSession=await zo(this.options.managedBrowser,this.sessionTag,{browserCredentials:this.options.browserCredentials!==void 0}),this.emitLifecycle(e,"browser_ready"));}async ensureProviderRuntimeToken(){let e=yt(this.agentConfig.type);if(this.agentConfig.isDirectMode||!e||!this.options.providerRouting||this.providerRuntimeToken)return;let n;try{n=await Xo(this.options.providerRouting,{provider:e,sessionTag:this.sessionTag});}catch(r){throw Yo(r)?new Error(`${e} runtime token endpoint is required in gateway mode: ${r.message}`):r}this.providerRuntimeToken=n,this.providerRuntimeToken&&this.sandbox?.sandboxId&&await this.bindProviderRuntimeToken(this.sandbox.sandboxId);}directSandboxProviderDeclaration(){let e=this.options.sandboxProvider;if(!e||Oe(e))return;let n=e.providerType;return ve.includes(n)?n:void 0}async bindProviderRuntimeToken(e){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let n=this.directSandboxProviderDeclaration();if(!await Qo(this.options.providerRouting,{token:this.providerRuntimeToken.token,sandboxId:e,...n?{directSandboxProvider:n}:{}}))throw new Error("Failed to bind provider runtime token to sandbox")}async setupManagedBrowser(e){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let n=ts(this.options.managedBrowser.provider,this.managedBrowserSession);for(let r of n.directories)await e.files.makeDir(r);for(let r of n.files)await e.files.write(r.path,r.data);}async closeManagedBrowserSession(){if(!this.managedBrowserSession||!this.options.managedBrowser)return;let e=this.managedBrowserSession;this.managedBrowserSession=void 0;try{await qo(this.options.managedBrowser,e);}catch(n){console.warn(`[Evolve] Managed browser cleanup failed: ${n.message}`);}}async closeProviderRuntimeToken(e=false){if(!this.providerRuntimeToken||!this.options.providerRouting)return;let n=this.providerRuntimeToken,r;for(let o=0;o<3;o++)try{if(!await Zo(this.options.providerRouting,{token:n.token}))throw new Error("Dashboard returned ok=false");this.providerRuntimeToken=void 0;return}catch(d){r=d,o<2&&await new Promise(u=>setTimeout(u,100*(o+1)));}let s=`Provider runtime token cleanup failed: ${r.message}`;if(e)throw new Error(s);console.warn(`[Evolve] ${s}`),this.providerRuntimeToken=void 0;}async ensureManagedSecretRuntimeToken(){this.managedSecretRuntimeToken||!this.options.managedSecrets||(this.managedSecretRuntimeToken=await ia({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{sessionTag:this.sessionTag,secrets:this.options.managedSecrets.secrets}));}async bindManagedSecretRuntimeToken(e){if(!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;if(!await oa({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:this.managedSecretRuntimeToken.token,sandboxId:e}))throw new Error("Failed to bind managed secret runtime token to sandbox")}async setupManagedSecretEgress(e){if(!this.managedSecretRuntimeToken||!ls(this.managedSecretRuntimeToken))return;if(await e.files.makeDir(L),await e.commands.run(`umask 077 && mkdir -p ${L}/certs && chmod 700 ${L} ${L}/certs`,{timeoutMs:5e3}),await e.files.write(ft,sa),await e.files.write(Fe,da(this.managedSecretRuntimeToken)),await e.commands.run(`chmod 700 ${ft} && chmod 600 ${Fe}`,{timeoutMs:5e3}),await e.commands.run(ua(),{timeoutMs:3e4}),this.managedSecretProxy=await e.commands.spawn(pa(),{timeoutMs:3e4}),(await e.commands.run(`python3 - <<'PY'
|
|
642
642
|
import socket, sys, time
|
|
643
643
|
for _ in range(50):
|
|
644
644
|
try:
|
|
645
|
-
s = socket.create_connection(("127.0.0.1", ${
|
|
645
|
+
s = socket.create_connection(("127.0.0.1", ${bn}), timeout=0.2)
|
|
646
646
|
s.close()
|
|
647
647
|
sys.exit(0)
|
|
648
648
|
except OSError:
|
|
649
649
|
time.sleep(0.1)
|
|
650
650
|
sys.exit(1)
|
|
651
|
-
PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy failed to start");await e.commands.run(oa(),{timeoutMs:5e3});}async closeManagedSecretRuntimeToken(){let e=this.managedSecretProxy;if(this.managedSecretProxy=void 0,e&&await e.kill().catch(()=>false),!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;let n=this.managedSecretRuntimeToken,r;try{for(let s=0;s<3;s++)try{if(!await ea({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:n.token}))throw new Error("Dashboard returned ok=false");return}catch(o){r=o,s<2&&await new Promise(d=>setTimeout(d,100*(s+1)));}console.warn(`[Evolve] Managed secret runtime token cleanup failed: ${r.message}`);}finally{this.managedSecretRuntimeToken=void 0;}}buildGatewayConfigJson(e){let n=this.requireActiveProviderRuntimeToken(),r=this.agentConfig.externalGateway?this.agentConfig.baseUrl??bn(q(this.registry.gatewayPath)):n?.baseUrl??bn(q(this.registry.gatewayPath)),s=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),o={},d=this.options.secrets?.[this.registry.gatewayConfigEnv];if(d)try{o=JSON.parse(d);}catch{}let u=o.provider??{},l=u.litellm??{},i=l.options??{},a=l.models??{},c=a[s]??{},p=c.headers??{},g=this.agentConfig.type==="opencode"?Jn(this.reasoningEffort()):void 0,f=c.variants??{},m=g?f[g]??{}:void 0;return o.provider={...u,litellm:{...l,npm:"@ai-sdk/openai-compatible",options:{...i,baseURL:r,apiKey:n?.token??this.agentConfig.apiKey},models:{...a,[s]:{...c,name:s,headers:{...p,...e},...g?{variants:{...f,[g]:{...m,reasoningEffort:g}}}:{}}}}},JSON.stringify(o)}activeProviderRuntimeToken(){let e=ht(this.agentConfig.type);return e&&this.providerRuntimeToken?.provider===e?this.providerRuntimeToken:void 0}requireActiveProviderRuntimeToken(){let e=ht(this.agentConfig.type),n=this.activeProviderRuntimeToken();if(!this.agentConfig.isDirectMode&&e&&!n)throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);return n}ensureSessionLogger(e){if(this.sessionLogger)return;let n=this.options.sandboxProvider;this.sessionLogger=new it({provider:n?.name||n?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,sandboxId:e.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}async flushSessionLoggerWithTimeout(e=2e3){this.sessionLogger&&await Promise.race([this.sessionLogger.flush(),new Promise(n=>setTimeout(n,e))]);}requiresPreRunDashboardIngest(){return !!(this.activeProviderRuntimeToken()||this.managedSecretRuntimeToken)}providerRuntimeHeaderUpdates(){let e=this.activeProviderRuntimeToken();return e?{[ts]:e.bindingSecret}:{}}shouldExposeProviderRuntimeTokenEnv(){return this.agentConfig.type!=="kimi"&&!this.registry.gatewayConfigEnv}buildProviderRuntimeProcessEnvs(){if(this.agentConfig.externalGateway){if(this.agentConfig.type==="kimi")return this.buildKimiDirectModelEnvs();let r={[this.registry.apiKeyEnv]:this.agentConfig.apiKey};return this.registry.baseUrlEnv&&this.agentConfig.baseUrl&&(r[this.registry.baseUrlEnv]=this.agentConfig.baseUrl),this.registry.gatewayConfigEnv&&(r[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.type==="gemini"&&(r.GEMINI_CLI_TRUST_WORKSPACE="true"),r}let e=this.activeProviderRuntimeToken();if(!e)return {};let n={};if(this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.apiKeyEnv]=e.token),this.agentConfig.type==="gemini"&&(n.GEMINI_DEFAULT_AUTH_TYPE=os),this.registry.baseUrlEnv&&this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.baseUrlEnv]=e.baseUrl),this.registry.spendTrackingEnvs&&(n[yn]=e.bindingSecret),this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";n[r]=as(this.options.secrets?.[r],this.providerRuntimeHeaderUpdates(),s);}return n}buildRunEnvs(e){if(this.agentConfig.externalGateway)return this.buildProviderRuntimeProcessEnvs();if(this.agentConfig.isDirectMode)return;let n=this.buildProviderRuntimeProcessEnvs(),r=this.registry.customHeadersEnv;if(r){let o=this.options.secrets?.[r],d=this.registry.customHeadersFormat||"newline";return n[r]=as(o,{[z]:this.sessionTag,[te]:`${fe}${e}`,...this.providerRuntimeHeaderUpdates()},d),n}let s=this.registry.spendTrackingEnvs;return s?{...n,[s.sessionTagEnv]:this.sessionTag,[s.runTagEnv]:`${fe}${e}`}:this.registry.gatewayConfigEnv?{...n,[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[z]:this.sessionTag,[te]:`${fe}${e}`,...this.providerRuntimeHeaderUpdates()})}:Object.keys(n).length>0?n:void 0}async writeCodexGatewayProviderConfig(e){if(this.agentConfig.type==="codex"){if(this.agentConfig.externalGateway){await Vt(e,this.agentConfig.baseUrl||q(),void 0,void 0,this.homeDir);return}this.agentConfig.isDirectMode||!this.registry.spendTrackingEnvs||await Vt(e,this.activeProviderRuntimeToken()?.baseUrl||this.agentConfig.baseUrl||q(),this.registry.spendTrackingEnvs,this.activeProviderRuntimeToken()?{[ts]:yn}:void 0,this.homeDir);}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(o=>typeof o.sessionId=="string"&&o.sessionId.length>0)?.sessionId;if(r){this.droidSessionId=r;return}let s=this.extractDroidSessionId(e);s&&(this.droidSessionId=s);}extractDroidSessionId(e){try{return this.findDroidSessionId(JSON.parse(e))}catch{return}}findDroidSessionId(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,r=n.sessionId??n.session_id;return typeof r=="string"&&r.length>0?r:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}droidSessionStatePath(){return `${this.homeDir}/.factory/evolve-session.json`}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(this.droidSessionStatePath());if(typeof n!="string")return;let r=JSON.parse(n);typeof r.sessionId=="string"&&r.sessionId.length>0&&(this.droidSessionId=r.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir(`${this.homeDir}/.factory`),await e.files.write(this.droidSessionStatePath(),JSON.stringify({sessionId:this.droidSessionId},null,2)));}resolveCommandModel(e){return (this.agentConfig.isDirectMode?this.registry.directModelAliases:this.registry.gatewayModelAliases)?.[e]??e}droidSettingsModel(){let e=this.agentConfig.model||this.registry.defaultModel;return this.agentConfig.externalGateway?Gs(this.registry,e):this.resolveCommandModel(e)}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=N(this.registry.mcpConfig.settingsDir,this.homeDir);await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.agentConfig.type==="gemini"&&(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&await this.writeGeminiGatewayAuthSettings(e),this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async writeGeminiGatewayAuthSettings(e){let n=N(this.registry.mcpConfig.settingsDir,this.homeDir),r=`${n}/${this.registry.mcpConfig.filename}`;await e.files.makeDir(n);let s={};try{let u=await e.files.read(r);typeof u=="string"&&u.trim()&&(s=JSON.parse(u));}catch(u){let l=u.message||"";if(!/not found|no such file|does not exist/i.test(l))throw u}let o=typeof s.security=="object"&&s.security!==null?s.security:{},d=typeof o.auth=="object"&&o.auth!==null?o.auth:{};s.security={...o,auth:{...d,selectedType:os}},await e.files.write(r,JSON.stringify(s,null,2));}async setupAgentPlugins(e){await Io(this.agentConfig.type,e,this.options.plugins);}assertProviderRuntimeDoesNotExposeGatewayKey(e){if(!this.activeProviderRuntimeToken())return;let n=this.agentConfig.apiKey;for(let[r,s]of Object.entries(e))for(let o of Object.values(s.headers||{}))if(o.includes(n))throw new Error(`MCP server "${r}" would expose the Evolve API key inside the sandbox. Use managed agent-browser or remove this gateway-authenticated MCP server.`)}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge";if(r!=="task"){let o=r==="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 ${o}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let d=jr({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),u=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(u,d);}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.integrations){let o=await no({...this.options.integrations,sessionTag:this.sessionTag});s={...s,integrations:{type:"http",url:o.url,headers:o.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let o=await Jo({apiKey:this.options.browserCredentials.apiKey,dashboardUrl:this.options.browserCredentials.dashboardUrl,browserSessionId:this.managedBrowserSession.id,sessionTag:this.managedBrowserSession.sessionTag,grantToken:this.managedBrowserSession.browserAuthGrantToken,config:this.options.browserCredentials.config});s={...s,[Zr]:o};}await this.writeNativeAgentConfig(e),Object.keys(s).length>0&&(this.assertProviderRuntimeDoesNotExposeGatewayKey(s),await Zn(this.agentConfig.type,e,this.workingDir,s,this.homeDir)),await this.writeCodexGatewayProviderConfig(e),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await jt(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[z]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.skills?.length&&await this.setupSkills(e);}async writeNativeAgentConfig(e){let n=this.effectiveNativeConfigDocument();if(!n)return;let r=this.registry.nativeConfig;if(!r)throw new Error(`Agent "${this.agentConfig.type}" has a config but no nativeConfig registry knowledge`);let s=N(r.path,this.homeDir),o=s.substring(0,s.lastIndexOf("/")),d=r.format==="toml"?smolToml.stringify(n):JSON.stringify(n,null,2);await e.commands.run(`mkdir -p ${o}`,{timeoutMs:3e4}),await e.files.write(s,d),await e.commands.run(`chmod 600 ${s}`,{timeoutMs:3e4});}effectiveNativeConfigDocument(){let e=this.agentConfig.config,n=this.agentConfig.preset,r=n?this.registry.presets?.[n]?.configStamp:void 0;return r?sn(e??{},r):e}presetCommandFlags(){let e=this.agentConfig.preset;return e?this.registry.presets?.[e]?.commandFlags:void 0}nativeConfigFlagPath(){let e=this.registry.nativeConfig;if(!(!e||e.delivery!=="settings-flag"||!this.effectiveNativeConfigDocument()))return N(e.path,this.homeDir)}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,r=N(n.targetDir,this.homeDir),s=await xr(this.skills);this.resolvedSkillsList=s,await Cr(e,s,r);}resolvedSkills(){return this.resolvedSkillsList??[]}async uploadContextFiles(e,n){let r=Object.entries(n).map(([o,d])=>({path:`${this.workingDir}/context/${o}`,data:d}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([o,d])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:d}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e,n){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:mu(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:n??this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.reasoningEffort(),nativeConfigPath:this.nativeConfigFlagPath(),presetFlags:this.presetCommandFlags(),isDirectMode:this.agentConfig.isDirectMode,isExternalGateway:!!this.agentConfig.externalGateway,skills:this.skills,homeDir:this.homeDir})}async writeKimiPerRunConfig(e,n){if(this.agentConfig.isDirectMode||!this.registry.spendTrackingTomlProvider)return;let r=this.requireActiveProviderRuntimeToken();await Qn(e,{...this.registry.spendTrackingTomlProvider,maxContextSize:this.resolveKimiMaxContextSize()},{[z]:this.sessionTag,[te]:`${fe}${n}`,...this.providerRuntimeHeaderUpdates()},{baseUrl:bn(r?.baseUrl??q(this.registry.gatewayPath)),apiKey:r?.token??this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:Xe(this.reasoningEffort()),thinkingEffort:ca(this.reasoningEffort())},this.homeDir);}async run(e,n){if(this.credentialsSealed)throw new Error("Agent credentials are sealed; this Evolve instance cannot run the agent again");Er(e);let{prompt:r,timeoutMs:s=qe,background:o=false,checkpointComment:d,resume:u}=e,{from:l}=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(l&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(l==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let k=await Wr(this.storage);if(!k)throw new Error('No checkpoints found for from: "latest".');l=k.id;}if(l){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");await this.ensureManagedBrowserSession(n),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let k=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create(this.buildSandboxCreateOptions(k)),await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox);let x=await vo(this.sandbox,this.storage,l);if(await this.setupManagedBrowser(this.sandbox),x.agentType&&x.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${x.agentType}, current: ${this.agentConfig.type})`);let R=this.options.workspaceMode||"knowledge";if(x.workspaceMode&&x.workspaceMode!==R)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${x.workspaceMode}, current: ${R})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let T=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!T}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=l,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(x){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),x}}let i=await this.getSandbox(n);await this.ensureProviderRuntimeToken(),await this.loadDroidSessionState(i),this.lastRunTimestamp=Date.now(),this.ensureSessionLogger(i),this.sessionLogger?.writePrompt(r),this.requiresPreRunDashboardIngest()&&await this.flushSessionLoggerWithTimeout();let a=this.buildCommand(r,u),c=crypto.randomUUID(),p=this.buildRunEnvs(c);if(await this.writeCodexGatewayProviderConfig(i),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await jt(i,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[z]:this.sessionTag,[te]:`${fe}${c}`,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.agentConfig.type==="qwen"&&await zn(i,Xe(this.reasoningEffort()),this.homeDir),await this.writeKimiPerRunConfig(i,c),(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&this.registry.droidGatewaySettings){let k=!!this.agentConfig.externalGateway,x=k?void 0:this.requireActiveProviderRuntimeToken();await Jt(i,{...this.registry.droidGatewaySettings,model:this.droidSettingsModel(),baseUrl:k?this.agentConfig.baseUrl??q():bn(x?.baseUrl??q()),apiKeyEnv:this.registry.apiKeyEnv},k?{}:{[z]:this.sessionTag,[te]:`${fe}${c}`,...this.providerRuntimeHeaderUpdates()},this.homeDir);}let g="",f=me(this.agentConfig.type),m=k=>{g+=k;let x=g.split(`
|
|
652
|
-
`);g=x.pop()??"";for(let R of x){if(!R.trim())continue;let
|
|
653
|
-
`),
|
|
654
|
-
`),
|
|
655
|
-
`).filter(Boolean),u=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,l=[],i=`${r}/`;for(let f of d){let[m,h]=f.split("|");if(!m||!h)continue;let y=parseInt(h,10);u>0&&y<u||l.push(m);}let a={},c=await Promise.all(l.map(async f=>{try{let m=await n.files.read(f);return {relativePath:f.startsWith(i)?f.slice(i.length):f.split("/").pop()||f,content:m}}catch{return null}}));for(let f of c)f&&(a[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return {files:a,data:null};let p=a["result.json"];if(!p)return {files:a,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof p=="string"?p:new TextDecoder().decode(p);try{let f=JSON.parse(g);if(this.zodSchema){let m=this.zodSchema.safeParse(f);return m.success?{files:a,data:m.data}:{files:a,data:null,error:`Schema validation failed: ${m.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(f))return {files:a,data:f};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:a,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:a,data:null}}catch(f){return {files:a,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await qr(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=n.id,n}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,r=this.activeOperationKind,s=false;try{this.activeCommand?s=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(s=await this.sandbox.commands.kill(this.activeProcessId));}catch{s=false;}if(!s)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let o=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,o),s}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(r){n=r;}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession();}if(n)throw n;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=false,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed");}async getHost(e){return (await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return !this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=la(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let n=this.agentConfig.apiKey;if(!n)throw new Error("Cost tracking requires an API key.");let r=process.env.EVOLVE_DASHBOARD_URL||E,s=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${o}`)}return s}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,n){return {...e,asOf:e.asOf??n.asOf,isComplete:e.isComplete??n.isComplete,truncated:e.truncated??n.truncated}}normalizeSessionCost(e){let n={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),s=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(s)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let d=new URLSearchParams({tag:n,runId:e.runId}),l=await(await this.fetchSpend(d)).json();return this.normalizeRunCost(l,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,o=r.runs[s];if(!o)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return o}};function _u(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function wu(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return e}async function ku(t){return await t.text().catch(()=>"")}async function da(t,e,n={}){let r=await fetch(`${_u(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${wu(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await ku(r)}`);return r.status===204?{}:await r.json()}var _n=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await da(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await da(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function ls(t={}){return new _n(t)}var bt=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(nt(e),on(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(Y(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=ro;static browserCredentials=es;static browserProfiles=ls;static managedSecrets=ss;async initializeAgent(){let e=an(this.config.agent),n=K(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let r=ta(this.config.managedSecrets,n);if(r&&this.config.sandbox&&!Ie(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let s=this.config.sandbox??(r?await st(e.apiKey):await Ur()),o={},d,u,l=this.config.skills,i;if(this.config.browser){let p=Lo(this.config.browser);if(i=p,p.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');o=Ds(e.apiKey);}if((p.provider==="actionbook"||p.provider==="agent-browser")&&p.managed){if(e.isDirectMode)throw new Error(`Managed browser provider "${p.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);d=p.provider==="actionbook"?$r:Yi,u={provider:p.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,...p.profile?{profile:p.profile}:{}};}if(p.profile&&!p.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!i||i.provider!=="agent-browser"||!i.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let a=this.config.storage!==void 0?pn(this.config.storage,!e.isDirectMode,E,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:s,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:r?{secrets:r,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...o,...this.config.mcpServers},browserPrompt:d,managedBrowser:u,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||E},storage:a};this.agent=new yt(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,s=this.listenerCount("lifecycle")>0;return {onStdout:e?o=>this.emit("stdout",o):void 0,onStderr:n?o=>this.emit("stderr",o):void 0,onContent:r?o=>this.emit("content",o):void 0,onLifecycle:s?o=>this.emit("lifecycle",o):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let n=this.status();this.emit("lifecycle",{sandboxId:n.sandboxId,sandbox:n.sandbox,agent:n.agent,timestamp:new Date().toISOString(),reason:e,...n.browser?{browser:n.browser}:{}});}async run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o,resume:d}){if(s&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let u=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o,resume:d},u)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.executeCommand(e,n,r)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return (await this.agent.getSandbox(e)).sandboxId}async updateNetwork(e){if(!this.agent)throw new Error("No sandbox yet. Call prepareSandbox(), run() or executeCommand() before updateNetwork().");let n=await this.agent.getSandbox(this.createStreamCallbacks());if(typeof n.updateNetwork!="function")throw new Error(`The ${this.config.sandbox?.providerType??"configured"} sandbox provider cannot change network policy after start. Create the sandbox with the policy it needs for its whole lifetime, or use a provider that supports runtime changes.`);await n.updateNetwork(e);}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials();}isSealed(){return this.agent?.isSealed()??false}resolvedSkills(){return this.agent?.resolvedSkills()??[]}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async uploadFileFromPath(e,n){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,n)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=an(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:E,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Xr(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return Xr(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var Ne=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e;}async use(e){await this.acquire();try{return await e()}finally{this.release();}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++;}};var ye=Symbol.for("evolve.SwarmResult"),je=class t extends Array{get success(){return this.filter(e=>e.status==="success")}get filtered(){return this.filter(e=>e.status==="filtered")}get error(){return this.filter(e=>e.status==="error")}static from(e){let n=new t;return n.push(...e),n}};var cs=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Us;if(n>jn)throw new Error(`concurrency=${n} exceeds max ${jn}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:n,timeoutMs:e.timeoutMs??qe,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations},this.semaphore=new Ne(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:s,verify:o}=e,d=e.retry??this.config.retry,u=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs;if(s&&o)throw new Error("map() cannot use both bestOf and verify options simultaneously");let i=await Promise.all(n.map((a,c)=>s?this.executeMapItemWithBestOf(a,r,c,u,e,l,d):o?this.executeMapItemWithVerify(a,r,c,u,e,l,d):d?V(p=>this.executeMapItem(a,r,c,u,e,l,p),d,c):this.executeMapItem(a,r,c,u,e,l)));return je.from(i)}async filter(e){let{items:n,prompt:r,condition:s,verify:o}=e,d=e.retry??this.config.retry,u=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,i=await Promise.all(n.map((c,p)=>o?this.executeFilterItemWithVerify(c,r,p,u,e,l,d):d?V(g=>this.executeFilterItem(c,r,p,u,e,l,g),d,p):this.executeFilterItem(c,r,p,u,e,l))),a=[];for(let c of i)if(c.status==="error")a.push(c);else if(c.data!==null)try{s(c.data)?a.push(c):a.push({...c,status:"filtered"});}catch(p){a.push({...c,status:"error",data:null,error:`Condition function threw: ${p.message}`});}return je.from(a)}async reduce(e){let{items:n,prompt:r,verify:s}=e,o=e.retry??this.config.retry,d=this.generateOperationId(),u=e.timeoutMs??this.config.timeoutMs,l=[],i=[];n.forEach((w,S)=>{l.push(this.getFiles(w)),i.push(this.getIndex(w,S));});let a={};l.forEach((w,S)=>{Object.entries(w).forEach(([k,x])=>{a[`item_${i[S]}/${k}`]=x;});});let c=dn(a),p=le(Zi,{fileTree:c}),g=e.systemPrompt?`${p}
|
|
651
|
+
PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy failed to start");await e.commands.run(ga(),{timeoutMs:5e3});}async closeManagedSecretRuntimeToken(){let e=this.managedSecretProxy;if(this.managedSecretProxy=void 0,e&&await e.kill().catch(()=>false),!this.managedSecretRuntimeToken||!this.options.managedSecrets)return;let n=this.managedSecretRuntimeToken,r;try{for(let s=0;s<3;s++)try{if(!await aa({apiKey:this.options.managedSecrets.apiKey,dashboardUrl:this.options.managedSecrets.dashboardUrl},{token:n.token}))throw new Error("Dashboard returned ok=false");return}catch(o){r=o,s<2&&await new Promise(d=>setTimeout(d,100*(s+1)));}console.warn(`[Evolve] Managed secret runtime token cleanup failed: ${r.message}`);}finally{this.managedSecretRuntimeToken=void 0;}}buildGatewayConfigJson(e){let n=this.requireActiveProviderRuntimeToken(),r=this.agentConfig.externalGateway?this.agentConfig.baseUrl??wn(q(this.registry.gatewayPath)):n?.baseUrl??wn(q(this.registry.gatewayPath)),s=this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),o={},d=this.options.secrets?.[this.registry.gatewayConfigEnv];if(d)try{o=JSON.parse(d);}catch{}let u=o.provider??{},l=u.litellm??{},i=l.options??{},a=l.models??{},c=a[s]??{},p=c.headers??{},g=this.agentConfig.type==="opencode"?Hn(this.reasoningEffort()):void 0,m=c.variants??{},f=g?m[g]??{}:void 0;return o.provider={...u,litellm:{...l,npm:"@ai-sdk/openai-compatible",options:{...i,baseURL:r,apiKey:n?.token??this.agentConfig.apiKey},models:{...a,[s]:{...c,name:s,headers:{...p,...e},...g?{variants:{...m,[g]:{...f,reasoningEffort:g}}}:{}}}}},JSON.stringify(o)}activeProviderRuntimeToken(){let e=yt(this.agentConfig.type);return e&&this.providerRuntimeToken?.provider===e?this.providerRuntimeToken:void 0}requireActiveProviderRuntimeToken(){let e=yt(this.agentConfig.type),n=this.activeProviderRuntimeToken();if(!this.agentConfig.isDirectMode&&e&&!n)throw new Error(`${this.agentConfig.type} gateway mode requires a Dashboard runtime token before sandbox setup`);return n}ensureSessionLogger(e){if(this.sessionLogger)return;let n=this.options.sandboxProvider;this.sessionLogger=new ot({provider:n?.name||n?.providerType||"unknown",agent:this.agentConfig.type,model:this.agentConfig.model||this.registry.defaultModel,reasoningEffort:this.reasoningEffort(),sandboxId:e.sandboxId,tag:this.sessionTag,apiKey:this.agentConfig.isDirectMode?void 0:this.agentConfig.apiKey,observability:{...this.options.observability,...this.managedBrowserSession&&this.options.managedBrowser?{browser_provider:this.options.managedBrowser.provider,browser_session_id:this.managedBrowserSession.id,dashboard_session_id:this.managedBrowserSession.sessionId,browser_session_tag:this.managedBrowserSession.sessionTag,browser_live_url:this.managedBrowserSession.liveUrl}:{}}});}async flushSessionLoggerWithTimeout(e=2e3){this.sessionLogger&&await Promise.race([this.sessionLogger.flush(),new Promise(n=>setTimeout(n,e))]);}requiresPreRunDashboardIngest(){return !!(this.activeProviderRuntimeToken()||this.managedSecretRuntimeToken)}providerRuntimeHeaderUpdates(){let e=this.activeProviderRuntimeToken();return e?{[ss]:e.bindingSecret}:{}}shouldExposeProviderRuntimeTokenEnv(){return this.agentConfig.type!=="kimi"&&!this.registry.gatewayConfigEnv}buildProviderRuntimeProcessEnvs(){if(this.agentConfig.externalGateway){if(this.agentConfig.type==="kimi")return this.buildKimiDirectModelEnvs();let r={[this.registry.apiKeyEnv]:this.agentConfig.apiKey};return this.registry.baseUrlEnv&&this.agentConfig.baseUrl&&(r[this.registry.baseUrlEnv]=this.agentConfig.baseUrl),this.registry.gatewayConfigEnv&&(r[this.registry.gatewayConfigEnv]=this.buildGatewayConfigJson({})),this.agentConfig.type==="gemini"&&(r.GEMINI_CLI_TRUST_WORKSPACE="true"),r}let e=this.activeProviderRuntimeToken();if(!e)return {};let n={};if(this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.apiKeyEnv]=e.token),this.agentConfig.type==="gemini"&&(n.GEMINI_DEFAULT_AUTH_TYPE=cs),this.registry.baseUrlEnv&&this.shouldExposeProviderRuntimeTokenEnv()&&(n[this.registry.baseUrlEnv]=e.baseUrl),this.registry.spendTrackingEnvs&&(n[_n]=e.bindingSecret),this.registry.customHeadersEnv){let r=this.registry.customHeadersEnv,s=this.registry.customHeadersFormat||"newline";n[r]=ds(this.options.secrets?.[r],this.providerRuntimeHeaderUpdates(),s);}return n}buildRunEnvs(e){if(this.agentConfig.externalGateway)return this.buildProviderRuntimeProcessEnvs();if(this.agentConfig.isDirectMode)return;let n=this.buildProviderRuntimeProcessEnvs(),r=this.registry.customHeadersEnv;if(r){let o=this.options.secrets?.[r],d=this.registry.customHeadersFormat||"newline";return n[r]=ds(o,{[H]:this.sessionTag,[te]:`${me}${e}`,...this.providerRuntimeHeaderUpdates()},d),n}let s=this.registry.spendTrackingEnvs;return s?{...n,[s.sessionTagEnv]:this.sessionTag,[s.runTagEnv]:`${me}${e}`}:this.registry.gatewayConfigEnv?{...n,[this.registry.gatewayConfigEnv]:this.buildGatewayConfigJson({[H]:this.sessionTag,[te]:`${me}${e}`,...this.providerRuntimeHeaderUpdates()})}:Object.keys(n).length>0?n:void 0}async writeCodexGatewayProviderConfig(e){if(this.agentConfig.type==="codex"){if(this.agentConfig.externalGateway){await Vt(e,this.agentConfig.baseUrl||q(),void 0,void 0,this.homeDir);return}this.agentConfig.isDirectMode||!this.registry.spendTrackingEnvs||await Vt(e,this.activeProviderRuntimeToken()?.baseUrl||this.agentConfig.baseUrl||q(),this.registry.spendTrackingEnvs,this.activeProviderRuntimeToken()?{[ss]:_n}:void 0,this.homeDir);}}captureDroidSession(e,n){if(this.agentConfig.type!=="droid")return;let r=n?.find(o=>typeof o.sessionId=="string"&&o.sessionId.length>0)?.sessionId;if(r){this.droidSessionId=r;return}let s=this.extractDroidSessionId(e);s&&(this.droidSessionId=s);}extractDroidSessionId(e){try{return this.findDroidSessionId(JSON.parse(e))}catch{return}}findDroidSessionId(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,r=n.sessionId??n.session_id;return typeof r=="string"&&r.length>0?r:this.findDroidSessionId(n.result)??this.findDroidSessionId(n.params)??this.findDroidSessionId(n.notification)}droidSessionStatePath(){return `${this.homeDir}/.factory/evolve-session.json`}async loadDroidSessionState(e){if(!(this.agentConfig.type!=="droid"||this.droidSessionId))try{let n=await e.files.read(this.droidSessionStatePath());if(typeof n!="string")return;let r=JSON.parse(n);typeof r.sessionId=="string"&&r.sessionId.length>0&&(this.droidSessionId=r.sessionId);}catch{}}async writeDroidSessionState(e){this.agentConfig.type!=="droid"||!this.droidSessionId||(await e.files.makeDir(`${this.homeDir}/.factory`),await e.files.write(this.droidSessionStatePath(),JSON.stringify({sessionId:this.droidSessionId},null,2)));}resolveCommandModel(e){return (this.agentConfig.isDirectMode?this.registry.directModelAliases:this.registry.gatewayModelAliases)?.[e]??e}droidSettingsModel(){let e=this.agentConfig.model||this.registry.defaultModel;return this.agentConfig.externalGateway?Qs(this.registry,e):this.resolveCommandModel(e)}async setupAgentAuth(e){if(this.agentConfig.oauthFileContent&&this.registry.oauthFileName){let n=B(this.registry.mcpConfig.settingsDir,this.homeDir);await e.files.makeDir(n),await e.files.write(`${n}/${this.registry.oauthFileName}`,this.agentConfig.oauthFileContent);return}this.agentConfig.type==="gemini"&&(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&await this.writeGeminiGatewayAuthSettings(e),this.registry.setupCommand&&await e.commands.run(this.registry.setupCommand,{timeoutMs:3e4});}async writeGeminiGatewayAuthSettings(e){let n=B(this.registry.mcpConfig.settingsDir,this.homeDir),r=`${n}/${this.registry.mcpConfig.filename}`;await e.files.makeDir(n);let s={};try{let u=await e.files.read(r);typeof u=="string"&&u.trim()&&(s=JSON.parse(u));}catch(u){let l=u.message||"";if(!/not found|no such file|does not exist/i.test(l))throw u}let o=typeof s.security=="object"&&s.security!==null?s.security:{},d=typeof o.auth=="object"&&o.auth!==null?o.auth:{};s.security={...o,auth:{...d,selectedType:cs}},await e.files.write(r,JSON.stringify(s,null,2));}async setupAgentPlugins(e){await Fo(this.agentConfig.type,e,this.options.plugins);}assertProviderRuntimeDoesNotExposeGatewayKey(e){if(!this.activeProviderRuntimeToken())return;let n=this.agentConfig.apiKey;for(let[r,s]of Object.entries(e))for(let o of Object.values(s.headers||{}))if(o.includes(n))throw new Error(`MCP server "${r}" would expose the Evolve API key inside the sandbox. Use managed agent-browser or remove this gateway-authenticated MCP server.`)}async setupWorkspace(e,n){let r=this.options.workspaceMode||"knowledge";if(r!=="task"){let o=r==="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 ${o}`,{timeoutMs:3e4}),!n?.skipSystemPrompt){let d=Kr({workingDir:this.workingDir,systemPrompt:this.options.systemPrompt,browserPrompt:this.options.browserPrompt,schema:this.zodSchema||this.jsonSchema,mode:r}),u=`${this.workingDir}/${this.registry.systemPromptFile}`;await e.files.write(u,d);}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.integrations){let o=await co({...this.options.integrations,sessionTag:this.sessionTag});s={...s,integrations:{type:"http",url:o.url,headers:o.headers}};}if(this.options.browserCredentials){if(!this.options.managedBrowser||this.options.managedBrowser.provider!=="agent-browser")throw new Error("Browser credentials require managed remote agent-browser.");if(!this.managedBrowserSession?.id||!this.managedBrowserSession.sessionTag||!this.managedBrowserSession.browserAuthGrantToken)throw new Error("Managed browser session is missing browser credential grant data.");let o=await Wo({apiKey:this.options.browserCredentials.apiKey,dashboardUrl:this.options.browserCredentials.dashboardUrl,browserSessionId:this.managedBrowserSession.id,sessionTag:this.managedBrowserSession.sessionTag,grantToken:this.managedBrowserSession.browserAuthGrantToken,config:this.options.browserCredentials.config});s={...s,[ns]:o};}await this.writeNativeAgentConfig(e),Object.keys(s).length>0&&(this.assertProviderRuntimeDoesNotExposeGatewayKey(s),await rr(this.agentConfig.type,e,this.workingDir,s,this.homeDir)),await this.writeCodexGatewayProviderConfig(e),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await jt(e,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[H]:this.sessionTag,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.skills?.length&&await this.setupSkills(e);}async writeNativeAgentConfig(e){let n=this.effectiveNativeConfigDocument();if(!n)return;let r=this.registry.nativeConfig;if(!r)throw new Error(`Agent "${this.agentConfig.type}" has a config but no nativeConfig registry knowledge`);let s=B(r.path,this.homeDir),o=s.substring(0,s.lastIndexOf("/")),d=r.format==="toml"?smolToml.stringify(n):JSON.stringify(n,null,2);await e.commands.run(`mkdir -p ${o}`,{timeoutMs:3e4}),await e.files.write(s,d),await e.commands.run(`chmod 600 ${s}`,{timeoutMs:3e4});}effectiveNativeConfigDocument(){let e=this.agentConfig.config,n=this.agentConfig.preset,r=n?this.registry.presets?.[n]?.configStamp:void 0;return r?on(e??{},r):e}presetCommandFlags(){let e=this.agentConfig.preset;return e?this.registry.presets?.[e]?.commandFlags:void 0}nativeConfigFlagPath(){let e=this.registry.nativeConfig;if(!(!e||e.delivery!=="settings-flag"||!this.effectiveNativeConfigDocument()))return B(e.path,this.homeDir)}async setupSkills(e){if(!this.skills?.length)return;let{skillsConfig:n}=this.registry,r=B(n.targetDir,this.homeDir),s=await Tr(this.skills);this.resolvedSkillsList=s,await Pr(e,s,r);}resolvedSkills(){return this.resolvedSkillsList??[]}async uploadContextFiles(e,n){let r=Object.entries(n).map(([o,d])=>({path:`${this.workingDir}/context/${o}`,data:d}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}async uploadWorkspaceFiles(e,n){let r=Object.entries(n).map(([o,d])=>({path:o.startsWith("/")?o:`${this.workingDir}/${o}`,data:d}));if(r.length===0)return;let s=new Set(r.map(o=>o.path.substring(0,o.path.lastIndexOf("/"))).filter(Boolean));s.size>0&&await e.commands.run(`mkdir -p ${Array.from(s).join(" ")}`,{timeoutMs:3e4}),await e.files.writeBatch(r);}buildCommand(e,n){return this.registry.buildCommand({prompt:this.agentConfig.type==="droid"?e:Tu(e),model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),isResume:n??this.hasRun,sessionId:this.agentConfig.type==="droid"?this.droidSessionId:void 0,reasoningEffort:this.reasoningEffort(),nativeConfigPath:this.nativeConfigFlagPath(),presetFlags:this.presetCommandFlags(),isDirectMode:this.agentConfig.isDirectMode,isExternalGateway:!!this.agentConfig.externalGateway,skills:this.skills,homeDir:this.homeDir})}async writeKimiPerRunConfig(e,n){if(this.agentConfig.isDirectMode||!this.registry.spendTrackingTomlProvider)return;let r=this.requireActiveProviderRuntimeToken();await nr(e,{...this.registry.spendTrackingTomlProvider,maxContextSize:this.resolveKimiMaxContextSize()},{[H]:this.sessionTag,[te]:`${me}${n}`,...this.providerRuntimeHeaderUpdates()},{baseUrl:wn(r?.baseUrl??q(this.registry.gatewayPath)),apiKey:r?.token??this.agentConfig.apiKey,model:this.resolveCommandModel(this.agentConfig.model||this.registry.defaultModel),defaultThinking:Qe(this.reasoningEffort()),thinkingEffort:ha(this.reasoningEffort())},this.homeDir);}async run(e,n){if(this.credentialsSealed)throw new Error("Agent credentials are sealed; this Evolve instance cannot run the agent again");Or(e);let{prompt:r,timeoutMs:s=We,background:o=false,checkpointComment:d,resume:u}=e,{from:l}=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(l&&(this.sandbox||this.options.sandboxId))throw new Error("Cannot restore into existing sandbox. Call kill() first, or create a new Evolve instance.");if(l==="latest"){if(!this.storage)throw new Error('Storage not configured. Call .withStorage() before using from: "latest".');let v=await Qr(this.storage);if(!v)throw new Error('No checkpoints found for from: "latest".');l=v.id;}if(l){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");await this.ensureManagedBrowserSession(n),await this.ensureProviderRuntimeToken(),await this.ensureManagedSecretRuntimeToken();let v=this.buildEnvironmentVariables();this.sandboxState="booting",this.emitLifecycle(n,"sandbox_boot");try{this.sandbox=await this.options.sandboxProvider.create(this.buildSandboxCreateOptions(v)),await this.bindProviderRuntimeToken(this.sandbox.sandboxId),await this.bindManagedSecretRuntimeToken(this.sandbox.sandboxId),await this.setupManagedSecretEgress(this.sandbox);let x=await Po(this.sandbox,this.storage,l);if(await this.setupManagedBrowser(this.sandbox),x.agentType&&x.agentType!==this.agentConfig.type)throw new Error(`Cannot restore checkpoint: agent type mismatch (checkpoint: ${x.agentType}, current: ${this.agentConfig.type})`);let R=this.options.workspaceMode||"knowledge";if(x.workspaceMode&&x.workspaceMode!==R)throw new Error(`Cannot restore checkpoint: workspace mode mismatch (checkpoint: ${x.workspaceMode}, current: ${R})`);await this.setupAgentAuth(this.sandbox),await this.setupAgentPlugins(this.sandbox);let E=!!(this.options.systemPrompt||this.options.browserPrompt||this.zodSchema||this.jsonSchema);await this.setupWorkspace(this.sandbox,{skipSystemPrompt:!E}),await this.loadDroidSessionState(this.sandbox),this.hasRun=!0,this.lastCheckpointId=l,this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(n,"sandbox_ready");}catch(x){throw this.sandbox&&(await this.sandbox.kill().catch(()=>{}),this.sandbox=void 0),await this.closeManagedBrowserSession().catch(()=>{}),await this.closeProviderRuntimeToken().catch(()=>{}),await this.closeManagedSecretRuntimeToken().catch(()=>{}),this.sandboxState="error",this.agentState="error",this.emitLifecycle(n,"sandbox_error"),x}}let i=await this.getSandbox(n);await this.ensureProviderRuntimeToken(),await this.loadDroidSessionState(i),this.lastRunTimestamp=Date.now(),this.ensureSessionLogger(i),this.sessionLogger?.writePrompt(r),this.requiresPreRunDashboardIngest()&&await this.flushSessionLoggerWithTimeout();let a=this.buildCommand(r,u),c=crypto.randomUUID(),p=this.buildRunEnvs(c);if(await this.writeCodexGatewayProviderConfig(i),!this.agentConfig.isDirectMode&&this.registry.spendTrackingJsonConfig&&await jt(i,this.agentConfig.type,this.registry.spendTrackingJsonConfig.headersPath,{[H]:this.sessionTag,[te]:`${me}${c}`,...this.providerRuntimeHeaderUpdates()},this.homeDir),this.agentConfig.type==="qwen"&&await Yn(i,Qe(this.reasoningEffort()),this.homeDir),await this.writeKimiPerRunConfig(i,c),(!this.agentConfig.isDirectMode||this.agentConfig.externalGateway)&&this.registry.droidGatewaySettings){let v=!!this.agentConfig.externalGateway,x=v?void 0:this.requireActiveProviderRuntimeToken();await Kt(i,{...this.registry.droidGatewaySettings,model:this.droidSettingsModel(),baseUrl:v?this.agentConfig.baseUrl??q():wn(x?.baseUrl??q()),apiKeyEnv:this.registry.apiKeyEnv},v?{}:{[H]:this.sessionTag,[te]:`${me}${c}`,...this.providerRuntimeHeaderUpdates()},this.homeDir);}let g="",m=fe(this.agentConfig.type),f=v=>{g+=v;let x=g.split(`
|
|
652
|
+
`);g=x.pop()??"";for(let R of x){if(!R.trim())continue;let E=m(R);if(this.captureDroidSession(R,E),this.sessionLogger?.writeEventParsed(R,E),n?.onStdout?.(R+`
|
|
653
|
+
`),E&&n?.onContent)for(let P of E)n.onContent(P);}},h=v=>{n?.onStderr?.(v);},y=await i.commands.spawn(a,{cwd:this.workingDir,timeoutMs:s,envs:p,onStdout:f,onStderr:h}),b=this.beginOperation("run",y,n,"run_start");if(this.hasRun=true,o)return this.watchBackgroundOperation(b,"run",y,n,i),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:c,exitCode:0,stdout:`Background process started with ID ${y.processId}`,stderr:""};let _;try{_=await y.wait();}catch(v){throw this.interruptedOperations.delete(b),this.finalizeOperation(b,n,"run_failed","error"),v}if(this.interruptedOperations.delete(b)||_.exitCode===130?this.finalizeOperation(b,n,"run_interrupted","interrupted"):_.exitCode===0?this.finalizeOperation(b,n,"run_complete","idle"):this.finalizeOperation(b,n,"run_failed","error"),g.trim()){let v=m(g);if(this.captureDroidSession(g,v),this.sessionLogger?.writeEventParsed(g,v),n?.onStdout?.(g+`
|
|
654
|
+
`),v&&n?.onContent)for(let x of v)n.onContent(x);}await this.writeDroidSessionState(i),this.sessionLogger&&!o&&await this.flushSessionLoggerWithTimeout();let S;if(this.storage&&!o&&_.exitCode===0)try{S=await Xr(i,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:d,parentId:this.lastCheckpointId}),this.lastCheckpointId=S.id;}catch(v){console.warn(`[Evolve] Auto-checkpoint failed: ${v.message}`);}return {sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:c,exitCode:_.exitCode,stdout:_.stdout,stderr:_.stderr,checkpoint:S}}async executeCommand(e,n={},r){let{timeoutMs:s=We,background:o=false}=n;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let d=await this.getSandbox(r);this.credentialsSealed||await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.requiresPreRunDashboardIngest()&&(this.ensureSessionLogger(d),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let u="",l="",i=h=>{u+=h,r?.onStdout?.(h);},a=h=>{l+=h,r?.onStderr?.(h);},c=this.credentialsSealed?{}:this.buildProviderRuntimeProcessEnvs(),p=await d.commands.spawn(e,{cwd:this.workingDir,timeoutMs:s,envs:Object.keys(c).length>0?c:void 0,onStdout:i,onStderr:a}),g=this.beginOperation("command",p,r,"command_start");if(o)return this.watchBackgroundOperation(g,"command",p,r),{sandboxId:d.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${p.processId}`,stderr:""};let m;try{m=await p.wait();}catch(h){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,r,"command_failed","error"),h}return this.interruptedOperations.delete(g)||m.exitCode===130?this.finalizeOperation(g,r,"command_interrupted","interrupted"):m.exitCode===0?this.finalizeOperation(g,r,"command_complete","idle"):this.finalizeOperation(g,r,"command_failed","error"),{sandboxId:d.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:m.exitCode,stdout:u||m.stdout||"",stderr:l||m.stderr||""}}async sealCredentials(){if(this.credentialsSealed)return;if(!this.sandbox)throw new Error("No active sandbox. Call run() or executeCommand() first.");if(this.activeCommand)throw new Error("Cannot seal credentials while a process is running.");if(this.agentConfig.isDirectMode&&!this.agentConfig.externalGateway)throw new Error("Credential sealing requires gateway mode; direct provider credentials cannot be revoked by Evolve");if([this.options.secrets&&Object.keys(this.options.secrets).length>0,this.options.sandboxCreateOptions?.envs&&Object.keys(this.options.sandboxCreateOptions.envs).length>0,this.options.managedSecrets,this.options.integrations,this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0,this.options.managedBrowser,this.options.browserCredentials].some(Boolean))throw new Error("Credential sealing requires a credential-minimal sandbox: omit secrets, managed secrets, integrations, MCP servers, and browser credentials");if(this.agentConfig.externalGateway){await this.agentConfig.externalGateway.revoke(),this.credentialsSealed=true;return}if(!this.providerRuntimeToken||!this.options.providerRouting)throw new Error("Cannot seal credentials: no active provider runtime token to revoke. Without a gateway-issued runtime token the sandbox may hold credentials Evolve cannot revoke, so sealing would be a false guarantee.");await this.closeProviderRuntimeToken(true),this.credentialsSealed=true;}isSealed(){return this.credentialsSealed}async collectArtifacts(e){if(!this.credentialsSealed)throw new Error("Call sealCredentials() before collecting artifacts.");if(!this.sandbox)throw new Error("No active sandbox.");if(this.activeCommand)throw new Error("Cannot collect artifacts while a process is running.");return ma(this.sandbox,this.workingDir,e)}async uploadContext(e){let n=await this.getSandbox();await this.uploadContextFiles(n,e);}async uploadFiles(e){let n=await this.getSandbox();await this.uploadWorkspaceFiles(n,e);}async uploadFileFromPath(e,n){let r=await this.getSandbox(),s=e.startsWith("/")?e:`${this.workingDir}/${e}`,o=s.substring(0,s.lastIndexOf("/"));if(o&&await r.commands.run(`mkdir -p ${o}`,{timeoutMs:3e4}),r.files.writeFromPath){await r.files.writeFromPath(s,n);return}let{readFile:d}=await import('fs/promises');await r.files.write(s,await d(n));}async getOutputFiles(e=false){let n=await this.getSandbox(),r=`${this.workingDir}/output`,s=e?"":"-maxdepth 1",d=(await n.commands.run(`find ${r} ${s} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
655
|
+
`).filter(Boolean),u=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,l=[],i=`${r}/`;for(let m of d){let[f,h]=m.split("|");if(!f||!h)continue;let y=parseInt(h,10);u>0&&y<u||l.push(f);}let a={},c=await Promise.all(l.map(async m=>{try{let f=await n.files.read(m);return {relativePath:m.startsWith(i)?m.slice(i.length):m.split("/").pop()||m,content:f}}catch{return null}}));for(let m of c)m&&(a[m.relativePath]=m.content);if(!this.zodSchema&&!this.jsonSchema)return {files:a,data:null};let p=a["result.json"];if(!p)return {files:a,data:null,error:"Schema provided but agent did not create output/result.json"};let g=typeof p=="string"?p:new TextDecoder().decode(p);try{let m=JSON.parse(g);if(this.zodSchema){let f=this.zodSchema.safeParse(m);return f.success?{files:a,data:f.data}:{files:a,data:null,error:`Schema validation failed: ${f.error.message}`,rawData:g}}if(this.compiledValidator){if(this.compiledValidator(m))return {files:a,data:m};{let h=this.compiledValidator.errors?.map(y=>`${y.instancePath} ${y.message}`).join(", ")||"Unknown validation error";return {files:a,data:null,error:`Schema validation failed: ${h}`,rawData:g}}}return {files:a,data:null}}catch(m){return {files:a,data:null,error:`Failed to parse result.json: ${m.message}`,rawData:g}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let n=await Xr(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=n.id,n}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=true,this.lastCheckpointId=void 0;}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"));}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"));}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return false;let n=this.activeOperationId,r=this.activeOperationKind,s=false;try{this.activeCommand?s=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(s=await this.sandbox.commands.kill(this.activeProcessId));}catch{s=false;}if(!s)return this.sandboxState="running",this.agentState="running",false;n!==null&&this.interruptedOperations.add(n),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let o=r==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,o),s}status(){let e=this.browserRuntimeInfo();return {sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let n;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0);}catch(r){n=r;}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession();}if(n)throw n;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=false,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed");}async getHost(e){return (await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return !this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush();}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=fa(this.options.sessionTagPrefix||"evolve");}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let n=this.agentConfig.apiKey;if(!n)throw new Error("Cost tracking requires an API key.");let r=process.env.EVOLVE_DASHBOARD_URL||T,s=await fetch(`${r}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(1e4)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Spend query failed (${s.status}): ${o}`)}return s}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,n){return {...e,asOf:e.asOf??n.asOf,isComplete:e.isComplete??n.isComplete,truncated:e.truncated??n.truncated}}normalizeSessionCost(e){let n={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return {...e,runs:e.runs.map(r=>this.normalizeRunCost(r,n))}}async getSessionCost(){let e=this.resolveSpendTag(),n=new URLSearchParams({tag:e}),s=await(await this.fetchSpend(n)).json();return this.normalizeSessionCost(s)}async getRunCost(e){let n=this.resolveSpendTag();if("runId"in e){let d=new URLSearchParams({tag:n,runId:e.runId}),l=await(await this.fetchSpend(d)).json();return this.normalizeRunCost(l,{asOf:new Date().toISOString(),isComplete:false,truncated:false})}let r=await this.getSessionCost(),s=e.index>0?e.index-1:r.runs.length+e.index,o=r.runs[s];if(!o)throw new Error(`Run index ${e.index} out of range. Session has ${r.runs.length} run(s).`);return o}};function Ou(t){return (t||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,"")}function Mu(t){let e=t||process.env.EVOLVE_API_KEY;if(!e)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return e}async function Du(t){return await t.text().catch(()=>"")}async function ya(t,e,n={}){let r=await fetch(`${Ou(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${Mu(t?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await Du(r)}`);return r.status===204?{}:await r.json()}var kn=class{constructor(e={}){this.config=e;}toMetadata(e){return {id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return {profiles:(await ya(this.config,"/api/browser-profiles")).profiles.map(n=>this.toMetadata(n))}}async delete(e){return await ya(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function us(t={}){return new kn(t)}var _t=class extends events.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=false;constructor(){super();}on(e,n){return super.on(e,n)}off(e,n){return super.off(e,n)}emit(e,...n){return super.emit(e,...n)}withAgent(e){return e&&(rt(e),an(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:true}){return e===false?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let n=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...n],this}withSkills(e){return this.config.skills=e,this}withSchema(e,n){return this.config.schema=e,n&&(Y(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=n),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=uo;static browserCredentials=rs;static browserProfiles=us;static managedSecrets=as;async initializeAgent(){let e=ln(this.config.agent),n=K(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let r=la(this.config.managedSecrets,n);if(r&&this.config.sandbox&&!Oe(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let s=this.config.sandbox??(r?await it(e.apiKey):await un()),o={},d,u,l=this.config.skills,i;if(this.config.browser){let p=Go(this.config.browser);if(i=p,p.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');o=js(e.apiKey);}if((p.provider==="actionbook"||p.provider==="agent-browser")&&p.managed){if(e.isDirectMode)throw new Error(`Managed browser provider "${p.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);d=p.provider==="actionbook"?Br:ro,u={provider:p.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||T,...p.profile?{profile:p.profile}:{}};}if(p.profile&&!p.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!i||i.provider!=="agent-browser"||!i.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let a=this.config.storage!==void 0?mn(this.config.storage,!e.isDirectMode,T,e.isDirectMode?void 0:e.apiKey):void 0,c={sandboxProvider:s,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:r?{secrets:r,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||T}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...o,...this.config.mcpServers},browserPrompt:d,managedBrowser:u,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||T,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:l,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||T}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||T},storage:a};this.agent=new bt(e,c);}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,n=this.listenerCount("stderr")>0,r=this.listenerCount("content")>0,s=this.listenerCount("lifecycle")>0;return {onStdout:e?o=>this.emit("stdout",o):void 0,onStderr:n?o=>this.emit("stderr",o):void 0,onContent:r?o=>this.emit("content",o):void 0,onLifecycle:s?o=>this.emit("lifecycle",o):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let n=this.status();this.emit("lifecycle",{sandboxId:n.sandboxId,sandbox:n.sandbox,agent:n.agent,timestamp:new Date().toISOString(),reason:e,...n.browser?{browser:n.browser}:{}});}async run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o,resume:d}){if(s&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let u=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:n,background:r,from:s,checkpointComment:o,resume:d},u)}async executeCommand(e,n={}){this.agent||await this.initializeAgent();let r=this.createStreamCallbacks();return this.agent.executeCommand(e,n,r)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return (await this.agent.getSandbox(e)).sandboxId}async updateNetwork(e){if(!this.agent)throw new Error("No sandbox yet. Call prepareSandbox(), run() or executeCommand() before updateNetwork().");let n=await this.agent.getSandbox(this.createStreamCallbacks());if(typeof n.updateNetwork!="function")throw new Error(`The ${this.config.sandbox?.providerType??"configured"} sandbox provider cannot change network policy after start. Create the sandbox with the policy it needs for its whole lifetime, or use a provider that supports runtime changes.`);await n.updateNetwork(e);}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials();}isSealed(){return this.agent?.isSealed()??false}resolvedSkills(){return this.agent?.resolvedSkills()??[]}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}async interrupt(){if(!this.agent)return false;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async uploadFileFromPath(e,n){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,n)}async getOutputFiles(e=false){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=ln(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:T,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0;}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return es(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return es(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=true),this.config.sandboxId=e;}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"));}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"));}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=false,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0);}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability();}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}};var Ne=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e;}async use(e){await this.acquire();try{return await e()}finally{this.release();}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++;}};var ye=Symbol.for("evolve.SwarmResult"),je=class t extends Array{get success(){return this.filter(e=>e.status==="success")}get filtered(){return this.filter(e=>e.status==="filtered")}get error(){return this.filter(e=>e.status==="error")}static from(e){let n=new t;return n.push(...e),n}};var ps=class t{config;semaphore;constructor(e={}){let n=e.concurrency??Js;if(n>Gn)throw new Error(`concurrency=${n} exceeds max ${Gn}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:e.agent,sandbox:e.sandbox,tag:e.tag??"swarm",concurrency:n,timeoutMs:e.timeoutMs??We,workspaceMode:e.workspaceMode??"knowledge",retry:e.retry,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations},this.semaphore=new Ne(this.config.concurrency);}async map(e){let{items:n,prompt:r,bestOf:s,verify:o}=e,d=e.retry??this.config.retry,u=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs;if(s&&o)throw new Error("map() cannot use both bestOf and verify options simultaneously");let i=await Promise.all(n.map((a,c)=>s?this.executeMapItemWithBestOf(a,r,c,u,e,l,d):o?this.executeMapItemWithVerify(a,r,c,u,e,l,d):d?G(p=>this.executeMapItem(a,r,c,u,e,l,p),d,c):this.executeMapItem(a,r,c,u,e,l)));return je.from(i)}async filter(e){let{items:n,prompt:r,condition:s,verify:o}=e,d=e.retry??this.config.retry,u=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,i=await Promise.all(n.map((c,p)=>o?this.executeFilterItemWithVerify(c,r,p,u,e,l,d):d?G(g=>this.executeFilterItem(c,r,p,u,e,l,g),d,p):this.executeFilterItem(c,r,p,u,e,l))),a=[];for(let c of i)if(c.status==="error")a.push(c);else if(c.data!==null)try{s(c.data)?a.push(c):a.push({...c,status:"filtered"});}catch(p){a.push({...c,status:"error",data:null,error:`Condition function threw: ${p.message}`});}return je.from(a)}async reduce(e){let{items:n,prompt:r,verify:s}=e,o=e.retry??this.config.retry,d=this.generateOperationId(),u=e.timeoutMs??this.config.timeoutMs,l=[],i=[];n.forEach((w,S)=>{l.push(this.getFiles(w)),i.push(this.getIndex(w,S));});let a={};l.forEach((w,S)=>{Object.entries(w).forEach(([v,x])=>{a[`item_${i[S]}/${v}`]=x;});});let c=pn(a),p=le(oo,{fileTree:c}),g=e.systemPrompt?`${p}
|
|
656
656
|
|
|
657
|
-
${e.systemPrompt}`:p,f=(w,S,k)=>({operationId:d,operation:"reduce",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:i,errorRetry:S,verifyRetry:k,...this.pipelineContextToMeta(e._pipelineContext)}),m=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,b=async(w,S,k,x)=>{let R=await this.semaphore.use(()=>this.execute(a,w,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:m,skills:h,integrations:y,tagPrefix:S,timeoutMs:u,observability:{swarmName:this.config.tag,operationName:e.name,operationId:d,operation:"reduce",role:"worker",errorRetry:k,verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),T=f(R,k,x&&x>1?x-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:T,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:T}},_=`${this.config.tag}-reduce`;return s?this.runWithVerification((w,S,k)=>b(w,S,void 0,k),{originalPrompt:r,inputFiles:a,verifyConfig:s,timeoutMs:u,systemPrompt:g,schema:e.schema,mcpServers:m,skills:h,integrations:y,operationId:d,baseTag:_,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?V(w=>{let S=w>1?w-1:void 0,k=S?`${_}-er${S}`:_;return b(r,k,S)},o):b(r,_)}async bestOf(e){let{item:n,prompt:r,config:s}=e,o=e.retry??this.config.retry,d=s.n??s.taskAgents?.length;if(d===void 0)throw new Error("bestOf requires n or taskAgents");if(d<2)throw new Error("bestOf requires n >= 2");let u=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,i=this.getFiles(n),a=s.mcpServers??this.config.mcpServers,c=s.judgeMcpServers??s.mcpServers??this.config.mcpServers,p=s.skills??this.config.skills,g=s.judgeSkills??s.skills??this.config.skills,f=s.integrations??this.config.integrations,m=s.judgeIntegrations??s.integrations??this.config.integrations,h=await Promise.all(Array.from({length:d},async(S,k)=>{let x=o?await V(R=>this.executeBestOfCandidate({inputFiles:i,prompt:r,candidateIndex:k,operationId:u,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:a,skills:p,integrations:f,timeoutMs:l,attempt:R}),o,k):await this.executeBestOfCandidate({inputFiles:i,prompt:r,candidateIndex:k,operationId:u,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:a,skills:p,integrations:f,timeoutMs:l});return s.onCandidateComplete?.(0,k,x.status==="success"?"success":"error"),x})),y=o?await V(S=>this.executeBestOfJudge({inputFiles:i,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:u,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:c,skills:g,integrations:m,attempt:S}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:i,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:u,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:c,skills:g,integrations:m}),b=h.findIndex(S=>S.status==="success"),_=y.decision?.winner??(b>=0?b:0);s.onJudgeComplete?.(0,_,y.decision?.reasoning??"Judge failed to provide reasoning");let w={operationId:u,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:d};return {winner:h[_]??h[0],winnerIndex:_,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:w,candidates:h}}async execute(e,n,r){let s=null,o="",d=r.tagPrefix,u={},l=null,i,a,c={...this.config.agent,...r.agent};try{s=new bt().withAgent(c).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&s.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&s.withSystemPrompt(r.systemPrompt),r.mcpServers&&s.withMcpServers(r.mcpServers),r.skills?.length&&s.withSkills(r.skills),r.integrations&&s.withIntegrations(r.integrations),r.observability&&s.withObservability(r.observability),Object.keys(e).length>0&&s.withContext(e);let p=await s.run({prompt:n,timeoutMs:r.timeoutMs});o=p.sandboxId,d=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),u=g.files;}catch{}p.exitCode!==0?i=`Agent exited with code ${p.exitCode}`:r.schema?g?(l=g.data,g.error&&(i=g.error),g.rawData&&(a=g.rawData)):i="Failed to read output files from sandbox":l=u;}catch(p){if(i=p.message,s){d=s.getSessionTag()??r.tagPrefix;try{u=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:u,data:l,tag:d,sandboxId:o,error:i,rawData:a}}async executeMapItem(e,n,r,s,o,d,u=1){let l=this.getFiles(e),i=u>1?`${this.config.tag}-map-${r}-er${u-1}`:`${this.config.tag}-map-${r}`,a=this.evaluatePrompt(n,l,r);if(a instanceof Error)return this.buildErrorResult(`Prompt function threw: ${a.message}`,{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let c=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=await this.semaphore.use(()=>this.execute(l,a,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:c,skills:p,integrations:g,tagPrefix:i,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:u>1?u-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),m={operationId:s,operation:"map",tag:f.tag,sandboxId:f.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:u>1?u-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(f,m)}async executeMapItemWithVerify(e,n,r,s,o,d,u){let l=this.getFiles(e),i=`${this.config.tag}-map-${r}`,a=o.verify,c=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=this.evaluatePrompt(n,l,r);if(f instanceof Error)return this.buildErrorResult(`Prompt function threw: ${f.message}`,{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let m=async(h,y,b)=>{let _=await this.semaphore.use(()=>this.execute(l,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:c,skills:p,integrations:g,tagPrefix:y,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),w={operationId:s,operation:"map",tag:_.tag,sandboxId:_.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(_,w)};return this.runWithVerification(m,{originalPrompt:f,inputFiles:l,verifyConfig:a,timeoutMs:d,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:c,skills:p,integrations:g,operationId:s,baseTag:i,retry:u,itemIndex:r,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,o,d,u){let l=this.getFiles(e),i=`${this.config.tag}-map-${r}`,a=this.evaluatePrompt(n,l,r);if(a instanceof Error)return this.buildErrorResult(`Prompt function threw: ${a.message}`,{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let c=o.bestOf,p=c.n??c.taskAgents?.length;if(p===void 0||p<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let g=o.mcpServers??this.config.mcpServers,f=c.mcpServers??g,m=c.judgeMcpServers??c.mcpServers??g,h=o.skills??this.config.skills,y=c.skills??h,b=c.judgeSkills??c.skills??h,_=o.integrations??this.config.integrations,w=c.integrations??_,S=c.judgeIntegrations??c.integrations??_,k=await Promise.all(Array.from({length:p},async(we,At)=>{let Os=u?await V(al=>this.executeBestOfCandidate({inputFiles:l,prompt:a,candidateIndex:At,operationId:s,config:c,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:w,timeoutMs:d,parentIndex:r,attempt:al,_pipelineContext:o._pipelineContext}),u,At):await this.executeBestOfCandidate({inputFiles:l,prompt:a,candidateIndex:At,operationId:s,config:c,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:y,integrations:w,timeoutMs:d,parentIndex:r,_pipelineContext:o._pipelineContext});return c.onCandidateComplete?.(r,At,Os.status==="success"?"success":"error"),Os})),x=u?await V(we=>this.executeBestOfJudge({inputFiles:l,taskPrompt:a,candidates:k,config:c,timeoutMs:d,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:b,integrations:S,parentIndex:r,attempt:we,_pipelineContext:o._pipelineContext}),{...u,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:a,candidates:k,config:c,timeoutMs:d,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:b,integrations:S,parentIndex:r,_pipelineContext:o._pipelineContext}),R=k.findIndex(we=>we.status==="success"),T=x.decision?.winner??(R>=0?R:0),P=k[T]??k[0];c.onJudgeComplete?.(r,T,x.decision?.reasoning??"Judge failed to provide reasoning");let I={operationId:s,operation:"bestof-judge",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:p,...this.pipelineContextToMeta(o._pipelineContext)};return {...P,meta:{...P.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:r,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:T,judgeReasoning:x.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:I,candidates:k}}}async executeFilterItem(e,n,r,s,o,d,u=1){let l=this.getFiles(e),i=u>1?`${this.config.tag}-filter-${r}-er${u-1}`:`${this.config.tag}-filter-${r}`,a=o.mcpServers??this.config.mcpServers,c=o.skills??this.config.skills,p=o.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(l,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:a,skills:c,integrations:p,tagPrefix:i,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:u>1?u-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:u>1?u-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(g,f,l)}async executeFilterItemWithVerify(e,n,r,s,o,d,u){let l=this.getFiles(e),i=`${this.config.tag}-filter-${r}`,a=o.verify,c=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,f=async(m,h,y)=>{let b=await this.semaphore.use(()=>this.execute(l,m,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:c,skills:p,integrations:g,tagPrefix:h,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),_={operationId:s,operation:"filter",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(b,_,l)};return this.runWithVerification(f,{originalPrompt:n,inputFiles:l,verifyConfig:a,timeoutMs:d,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:c,skills:p,integrations:g,operationId:s,baseTag:i,retry:u,itemIndex:r,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:o,config:d,timeoutMs:u,parentIndex:l,attempt:i=1,_pipelineContext:a}=e,c=l!==void 0?`${this.config.tag}-map-${l}-bestof-cand-${s}`:`${this.config.tag}-bestof-cand-${s}`,p=i>1?`${c}-er${i-1}`:c,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:d.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:p,timeoutMs:u,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:l,role:"candidate",candidateIndex:s,errorRetry:i>1?i-1:void 0,...this.pipelineContextToObservability(a)}})),f={operationId:o,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:s,errorRetry:i>1?i-1:void 0,candidateIndex:s,...this.pipelineContextToMeta(a)};return this.buildResult(g,f)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((r,s)=>{r.status==="error"&&(n[`candidate_${s}/_failed.txt`]=`STATUS: FAILED
|
|
657
|
+
${e.systemPrompt}`:p,m=(w,S,v)=>({operationId:d,operation:"reduce",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:e.name,inputCount:n.length,inputIndices:i,errorRetry:S,verifyRetry:v,...this.pipelineContextToMeta(e._pipelineContext)}),f=e.mcpServers??this.config.mcpServers,h=e.skills??this.config.skills,y=e.integrations??this.config.integrations,b=async(w,S,v,x)=>{let R=await this.semaphore.use(()=>this.execute(a,w,{systemPrompt:g,schema:e.schema,schemaOptions:e.schemaOptions,agent:e.agent,mcpServers:f,skills:h,integrations:y,tagPrefix:S,timeoutMs:u,observability:{swarmName:this.config.tag,operationName:e.name,operationId:d,operation:"reduce",role:"worker",errorRetry:v,verifyRetry:x&&x>1?x-1:void 0,...this.pipelineContextToObservability(e._pipelineContext)}})),E=m(R,v,x&&x>1?x-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:E,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:E}},_=`${this.config.tag}-reduce`;return s?this.runWithVerification((w,S,v)=>b(w,S,void 0,v),{originalPrompt:r,inputFiles:a,verifyConfig:s,timeoutMs:u,systemPrompt:g,schema:e.schema,mcpServers:f,skills:h,integrations:y,operationId:d,baseTag:_,retry:o,operation:"reduce",_pipelineContext:e._pipelineContext}):o?G(w=>{let S=w>1?w-1:void 0,v=S?`${_}-er${S}`:_;return b(r,v,S)},o):b(r,_)}async bestOf(e){let{item:n,prompt:r,config:s}=e,o=e.retry??this.config.retry,d=s.n??s.taskAgents?.length;if(d===void 0)throw new Error("bestOf requires n or taskAgents");if(d<2)throw new Error("bestOf requires n >= 2");let u=this.generateOperationId(),l=e.timeoutMs??this.config.timeoutMs,i=this.getFiles(n),a=s.mcpServers??this.config.mcpServers,c=s.judgeMcpServers??s.mcpServers??this.config.mcpServers,p=s.skills??this.config.skills,g=s.judgeSkills??s.skills??this.config.skills,m=s.integrations??this.config.integrations,f=s.judgeIntegrations??s.integrations??this.config.integrations,h=await Promise.all(Array.from({length:d},async(S,v)=>{let x=o?await G(R=>this.executeBestOfCandidate({inputFiles:i,prompt:r,candidateIndex:v,operationId:u,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:a,skills:p,integrations:m,timeoutMs:l,attempt:R}),o,v):await this.executeBestOfCandidate({inputFiles:i,prompt:r,candidateIndex:v,operationId:u,config:s,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:a,skills:p,integrations:m,timeoutMs:l});return s.onCandidateComplete?.(0,v,x.status==="success"?"success":"error"),x})),y=o?await G(S=>this.executeBestOfJudge({inputFiles:i,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:u,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:c,skills:g,integrations:f,attempt:S}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:i,taskPrompt:r,candidates:h,config:s,timeoutMs:l,operationId:u,systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,mcpServers:c,skills:g,integrations:f}),b=h.findIndex(S=>S.status==="success"),_=y.decision?.winner??(b>=0?b:0);s.onJudgeComplete?.(0,_,y.decision?.reasoning??"Judge failed to provide reasoning");let w={operationId:u,operation:"bestof-judge",tag:y.tag,sandboxId:y.sandboxId,swarmName:this.config.tag,operationName:e.name,candidateCount:d};return {winner:h[_]??h[0],winnerIndex:_,judgeReasoning:y.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:w,candidates:h}}async execute(e,n,r){let s=null,o="",d=r.tagPrefix,u={},l=null,i,a,c={...this.config.agent,...r.agent};try{s=new _t().withAgent(c).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&s.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&s.withSystemPrompt(r.systemPrompt),r.mcpServers&&s.withMcpServers(r.mcpServers),r.skills?.length&&s.withSkills(r.skills),r.integrations&&s.withIntegrations(r.integrations),r.observability&&s.withObservability(r.observability),Object.keys(e).length>0&&s.withContext(e);let p=await s.run({prompt:n,timeoutMs:r.timeoutMs});o=p.sandboxId,d=s.getSessionTag()??r.tagPrefix;let g=null;try{g=await s.getOutputFiles(!0),u=g.files;}catch{}p.exitCode!==0?i=`Agent exited with code ${p.exitCode}`:r.schema?g?(l=g.data,g.error&&(i=g.error),g.rawData&&(a=g.rawData)):i="Failed to read output files from sandbox":l=u;}catch(p){if(i=p.message,s){d=s.getSessionTag()??r.tagPrefix;try{u=(await s.getOutputFiles(!0)).files;}catch{}}}finally{s&&await s.kill().catch(()=>{});}return {files:u,data:l,tag:d,sandboxId:o,error:i,rawData:a}}async executeMapItem(e,n,r,s,o,d,u=1){let l=this.getFiles(e),i=u>1?`${this.config.tag}-map-${r}-er${u-1}`:`${this.config.tag}-map-${r}`,a=this.evaluatePrompt(n,l,r);if(a instanceof Error)return this.buildErrorResult(`Prompt function threw: ${a.message}`,{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let c=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,m=await this.semaphore.use(()=>this.execute(l,a,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:c,skills:p,integrations:g,tagPrefix:i,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",errorRetry:u>1?u-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),f={operationId:s,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:u>1?u-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(m,f)}async executeMapItemWithVerify(e,n,r,s,o,d,u){let l=this.getFiles(e),i=`${this.config.tag}-map-${r}`,a=o.verify,c=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,m=this.evaluatePrompt(n,l,r);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let f=async(h,y,b)=>{let _=await this.semaphore.use(()=>this.execute(l,h,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:c,skills:p,integrations:g,tagPrefix:y,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"map",itemIndex:r,role:"worker",verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),w={operationId:s,operation:"map",tag:_.tag,sandboxId:_.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:b&&b>1?b-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(_,w)};return this.runWithVerification(f,{originalPrompt:m,inputFiles:l,verifyConfig:a,timeoutMs:d,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:c,skills:p,integrations:g,operationId:s,baseTag:i,retry:u,itemIndex:r,operation:"map",_pipelineContext:o._pipelineContext})}async executeMapItemWithBestOf(e,n,r,s,o,d,u){let l=this.getFiles(e),i=`${this.config.tag}-map-${r}`,a=this.evaluatePrompt(n,l,r);if(a instanceof Error)return this.buildErrorResult(`Prompt function threw: ${a.message}`,{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let c=o.bestOf,p=c.n??c.taskAgents?.length;if(p===void 0||p<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:s,operation:"map",tag:i,sandboxId:"",itemIndex:r});let g=o.mcpServers??this.config.mcpServers,m=c.mcpServers??g,f=c.judgeMcpServers??c.mcpServers??g,h=o.skills??this.config.skills,y=c.skills??h,b=c.judgeSkills??c.skills??h,_=o.integrations??this.config.integrations,w=c.integrations??_,S=c.judgeIntegrations??c.integrations??_,v=await Promise.all(Array.from({length:p},async(ke,It)=>{let Bs=u?await G(_l=>this.executeBestOfCandidate({inputFiles:l,prompt:a,candidateIndex:It,operationId:s,config:c,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:y,integrations:w,timeoutMs:d,parentIndex:r,attempt:_l,_pipelineContext:o._pipelineContext}),u,It):await this.executeBestOfCandidate({inputFiles:l,prompt:a,candidateIndex:It,operationId:s,config:c,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:m,skills:y,integrations:w,timeoutMs:d,parentIndex:r,_pipelineContext:o._pipelineContext});return c.onCandidateComplete?.(r,It,Bs.status==="success"?"success":"error"),Bs})),x=u?await G(ke=>this.executeBestOfJudge({inputFiles:l,taskPrompt:a,candidates:v,config:c,timeoutMs:d,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:b,integrations:S,parentIndex:r,attempt:ke,_pipelineContext:o._pipelineContext}),{...u,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:a,candidates:v,config:c,timeoutMs:d,operationId:s,systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,mcpServers:f,skills:b,integrations:S,parentIndex:r,_pipelineContext:o._pipelineContext}),R=v.findIndex(ke=>ke.status==="success"),E=x.decision?.winner??(R>=0?R:0),P=v[E]??v[0];c.onJudgeComplete?.(r,E,x.decision?.reasoning??"Judge failed to provide reasoning");let I={operationId:s,operation:"bestof-judge",tag:x.tag,sandboxId:x.sandboxId,swarmName:this.config.tag,operationName:o.name,candidateCount:p,...this.pipelineContextToMeta(o._pipelineContext)};return {...P,meta:{...P.meta,operation:"map",swarmName:this.config.tag,operationName:o.name,itemIndex:r,...this.pipelineContextToMeta(o._pipelineContext)},bestOf:{winnerIndex:E,judgeReasoning:x.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:I,candidates:v}}}async executeFilterItem(e,n,r,s,o,d,u=1){let l=this.getFiles(e),i=u>1?`${this.config.tag}-filter-${r}-er${u-1}`:`${this.config.tag}-filter-${r}`,a=o.mcpServers??this.config.mcpServers,c=o.skills??this.config.skills,p=o.integrations??this.config.integrations,g=await this.semaphore.use(()=>this.execute(l,n,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:a,skills:c,integrations:p,tagPrefix:i,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",errorRetry:u>1?u-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),m={operationId:s,operation:"filter",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,errorRetry:u>1?u-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(g,m,l)}async executeFilterItemWithVerify(e,n,r,s,o,d,u){let l=this.getFiles(e),i=`${this.config.tag}-filter-${r}`,a=o.verify,c=o.mcpServers??this.config.mcpServers,p=o.skills??this.config.skills,g=o.integrations??this.config.integrations,m=async(f,h,y)=>{let b=await this.semaphore.use(()=>this.execute(l,f,{systemPrompt:o.systemPrompt,schema:o.schema,schemaOptions:o.schemaOptions,agent:o.agent,mcpServers:c,skills:p,integrations:g,tagPrefix:h,timeoutMs:d,observability:{swarmName:this.config.tag,operationName:o.name,operationId:s,operation:"filter",itemIndex:r,role:"worker",verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToObservability(o._pipelineContext)}})),_={operationId:s,operation:"filter",tag:b.tag,sandboxId:b.sandboxId,swarmName:this.config.tag,operationName:o.name,itemIndex:r,verifyRetry:y&&y>1?y-1:void 0,...this.pipelineContextToMeta(o._pipelineContext)};return this.buildResult(b,_,l)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:l,verifyConfig:a,timeoutMs:d,systemPrompt:o.systemPrompt,schema:o.schema,mcpServers:c,skills:p,integrations:g,operationId:s,baseTag:i,retry:u,itemIndex:r,operation:"filter",_pipelineContext:o._pipelineContext})}async executeBestOfCandidate(e){let{inputFiles:n,prompt:r,candidateIndex:s,operationId:o,config:d,timeoutMs:u,parentIndex:l,attempt:i=1,_pipelineContext:a}=e,c=l!==void 0?`${this.config.tag}-map-${l}-bestof-cand-${s}`:`${this.config.tag}-bestof-cand-${s}`,p=i>1?`${c}-er${i-1}`:c,g=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:e.systemPrompt,schema:e.schema,schemaOptions:e.schemaOptions,agent:d.taskAgents?.[s],mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:p,timeoutMs:u,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:l,role:"candidate",candidateIndex:s,errorRetry:i>1?i-1:void 0,...this.pipelineContextToObservability(a)}})),m={operationId:o,operation:"bestof-cand",tag:g.tag,sandboxId:g.sandboxId,swarmName:this.config.tag,itemIndex:s,errorRetry:i>1?i-1:void 0,candidateIndex:s,...this.pipelineContextToMeta(a)};return this.buildResult(g,m)}buildJudgeContext(e){let n=this.buildEvaluatorContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,systemPrompt:e.systemPrompt,schema:e.schema});return e.candidates.forEach((r,s)=>{r.status==="error"&&(n[`candidate_${s}/_failed.txt`]=`STATUS: FAILED
|
|
658
658
|
|
|
659
|
-
Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([o,d])=>{n[`candidate_${s}/${o}`]=d;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:o,parentIndex:d,attempt:u=1,_pipelineContext:l}=e,i=d!==void 0?`${this.config.tag}-map-${d}-bestof-judge`:`${this.config.tag}-bestof-judge`,a=u>1?`${i}-er${u-1}`:i,c=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),p=dn(c),g=le(Lr,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:p}),f=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),m=await this.semaphore.use(()=>this.execute(c,Xi,{systemPrompt:g,schema:f,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:a,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:d,role:"judge",errorRetry:u>1?u-1:void 0,...this.pipelineContextToObservability(l)}})),h=null;if(m.data&&!m.error)h=m.data;else if(m.rawData)try{let y=JSON.parse(m.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${m.error}`);}return {status:h?"success":"error",decision:h,tag:m.tag,sandboxId:m.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(([r,s])=>{n[`worker_output/${r}`]=s;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:s,workerTag:o,retryAttempt:d=1,operation:u,itemIndex:l,attemptIndex:i,_pipelineContext:a}=e,c=d>1?`${o}-verifier-er${d-1}`:`${o}-verifier`,p=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,f=n.verifierIntegrations??e.integrations,m=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=dn(m),y=le(Br,{criteria:n.criteria,fileTree:h}),b=await this.semaphore.use(()=>this.execute(m,Qi,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:p,skills:g,integrations:f,tagPrefix:c,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:u,itemIndex:l,role:"verifier",verifyRetry:i&&i>1?i-1:void 0,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(a)}})),_=null;if(b.data&&!b.error)_=b.data;else if(b.rawData)try{let w=JSON.parse(b.rawData);_={passed:!!w.passed,reasoning:w.reasoning??"Verification completed",feedback:w.feedback};}catch{console.warn(`Verify validation failed: ${b.error}`);}return {status:_?"success":"error",decision:_,tag:b.tag,sandboxId:b.sandboxId,error:_?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return le(Nr,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:s,verifyConfig:o,timeoutMs:d,operationId:u,baseTag:l,retry:i,itemIndex:a=0,operation:c,_pipelineContext:p}=n,g=o.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,f=r,m=null,h=0;for(;h<g;){h++;let b=h>1?`${l}-vr${h-1}`:l,_=i?await V(k=>e(f,k>1?`${b}-er${k-1}`:b,h),i,a):await e(f,b,h);if(o.onWorkerComplete?.(a,h,_.status==="error"?"error":"success"),_.status==="error")return _;m=_;let w=i?await V(k=>this.executeVerify({inputFiles:s,outputFiles:_.files,taskPrompt:f,config:o,timeoutMs:d,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:u,workerTag:b,retryAttempt:k,operation:c,itemIndex:a,attemptIndex:h,_pipelineContext:p}),{...i,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:_.files,taskPrompt:f,config:o,timeoutMs:d,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:u,workerTag:b,operation:c,itemIndex:a,attemptIndex:h,_pipelineContext:p}),S={operationId:u,operation:"verify",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)};if(o.onVerifierComplete?.(a,h,w.decision?.passed??false,w.decision?.feedback),w.decision?.passed)return {..._,verify:{passed:true,reasoning:w.decision.reasoning,verifyMeta:S,attempts:h}};if(h<g){let k=w.decision?.feedback??w.decision?.reasoning??"Output did not meet criteria";f=t.buildRetryPromptWithFeedback(r,k);}}let y=h>1?`${l}-vr${h-1}`:l;return {...m,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:u,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)},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,r){if(typeof e=="string")return e;try{return e(n,r)}catch(s){return s}}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"]=Y(e.schema)?Re(e.schema):Te(e.schema)),Object.entries(e.inputFiles).forEach(([r,s])=>{n[`worker_task/input/${r}`]=s;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&ye in e&&e[ye]===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,r){let s=r??e.files;return e.error?{[ye]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[ye]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[ye]:true,status:"error",data:null,files:{},meta:n,error:e}}};var wn=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}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 kn(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),r=[],s=e,o=Date.now();for(let u=0;u<this.steps.length;u++){let l=this.steps[u],i=l.config.name,a=Date.now();this.events.onStepStart?.({type:l.type,index:u,name:i,itemCount:s.length});let c={pipelineRunId:n,pipelineStepIndex:u};try{let p=await this.executeStep(l,s,u,i,c),g=Date.now()-a;if(r.push({type:l.type,index:u,durationMs:g,results:p.output}),this.events.onStepComplete?.({type:l.type,index:u,name:i,durationMs:g,successCount:p.successCount,errorCount:p.errorCount,filteredCount:p.filteredCount}),l.type==="reduce")return {pipelineRunId:n,steps:r,output:p.output,totalDurationMs:Date.now()-o};s=p.nextItems;}catch(p){throw this.events.onStepError?.({type:l.type,index:u,name:i,error:p instanceof Error?p:new Error(String(p))}),p}}let d=r[r.length-1];return {pipelineRunId:n,steps:r,output:d?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,r,s,o){if(e.type==="map"){let l=e.config,i=await this.swarm.map({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s),bestOf:this.wrapBestOf(l.bestOf,r,s)});return {output:[...i],nextItems:i.success,successCount:i.success.length,errorCount:i.error.length,filteredCount:0}}if(e.type==="filter"){let l=e.config,i=await this.swarm.filter({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s)}),a=l.emit??"success",c=a==="success"?i.success:a==="filtered"?i.filtered:[...i.success,...i.filtered];return {output:[...i],nextItems:c,successCount:i.success.length,errorCount:i.error.length,filteredCount:i.filtered.length}}let d=e.config,u=await this.swarm.reduce({items:n,...d,_pipelineContext:o,retry:this.wrapRetry(d.retry,r,s),verify:this.wrapVerify(d.verify,r,s)});return {output:u,nextItems:[],successCount:u.status==="success"?1:0,errorCount:u.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,o,d)=>{e.onItemRetry?.(s,o,d),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,error:d});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,o,d)=>{e.onWorkerComplete?.(s,o,d),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,status:d});},onVerifierComplete:(s,o,d,u)=>{e.onVerifierComplete?.(s,o,d,u),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,passed:d,feedback:u});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,o,d)=>{e.onCandidateComplete?.(s,o,d),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:o,status:d});},onJudgeComplete:(s,o,d)=>{e.onJudgeComplete?.(s,o,d),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:o,reasoning:d});}}}},kn=class t extends wn{constructor(e,n,r){super(e,n,r);}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]: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")}};var ua=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","BUDGET","INDETERMINATE","CANCELLED"],pa=["e2b","daytona","modal"],ga=["my","shared"],fa=["queued","running","completed","failed"],ma=["queued","running","completed"];function Fe(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.provisional!="boolean")return null;let n=r=>typeof r=="number"&&Number.isFinite(r)?r:null;return {provisional:e.provisional,spent_usd:n(e.spent_usd),input_tokens:n(e.input_tokens),cached_input_tokens:n(e.cached_input_tokens),cache_write_tokens:n(e.cache_write_tokens),output_tokens:n(e.output_tokens),as_of:typeof e.as_of=="string"?e.as_of:null}}function ha(t){let e=t.stats?.evals??{},n=[];for(let r of Object.keys(e).sort()){let s=e[r]?.pass_at_k??{},o=[];for(let d of Object.keys(s)){let u=Number(d),l=s[d];!Number.isFinite(u)||typeof l!="number"||!Number.isFinite(l)||o.push({k:u,value:l});}o.length!==0&&(o.sort((d,u)=>d.k-u.k),n.push({evals_key:r,points:o}));}return n}var vn=["dataset_flag","job_dataset_record","task_hash","none"],Sn=["hash_mismatch","task_not_in_dataset","no_dataset_named","dataset_ambiguous","no_hash_match","no_task_digest"],xn=1e9;function Cn(t){let e=t.data?.update;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(n.sessionUpdate!=="usage"||n.source!=="gateway")return null;let r=n.usage;return !r||typeof r!="object"||Array.isArray(r)?null:n}function _t(t,e,n){if(t!=null){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${n} storedAt is not a list of date-time strings`);if(t.length!==e)throw new Error(`${n} storedAt has ${t.length} entries for ${e} events (one per event, index-aligned)`);return t}}var ya=["trace-parsed","verifier","trace-stdout","trace-stderr","trace-atif","trajectory","agent-home"],ba=["trace-stdout","trace-stderr","agent-home"],ds=["missing_authorization","invalid_api_key","read_only_key","credential_service_unavailable","rate_limited","insufficient_credits","quota_exceeded","invalid_json","invalid_input","invalid_limit","invalid_status","invalid_visibility","invalid_cursor","invalid_after","invalid_format","invalid_ids","invalid_multipart","idempotency_key_reused","dataset_not_found","dataset_version_not_found","dataset_name_taken","dataset_in_use","dataset_not_owned","dataset_import_in_progress","upstream_not_watchable","no_active_version","version_not_ready","version_not_activatable","unknown_task_names","no_tasks","task_not_found","task_failed_to_build","upload_session_not_found","upload_offset_mismatch","upload_chunk_digest_mismatch","upload_incomplete","upload_archive_digest_mismatch","upload_session_failed","too_many_concurrent_upload_chunks","agent_not_found","agent_name_taken","agent_name_reserved","agent_invalid_name","agent_source_required","agent_source_conflict","agent_invalid_env","agent_too_large","agent_limit_reached","skill_not_found","skill_name_not_found","skill_ref_invalid","skill_unresolvable","skill_invalid","skill_in_use","skill_too_large","skill_limit_reached","too_many_concurrent_skill_uploads","secret_not_found","secret_ambiguous","secret_brokered_unsupported","secret_exists","secret_not_attached","agent_version_not_found","agent_version_unresolvable","agent_kwarg_unsupported","agent_config_unsupported","agent_config_key_refused","agent_preset_unsupported","provider_unsupported","job_not_found","job_not_terminal","no_failed_trials","trial_not_found","trial_not_settled","concurrent_update","regrade_source_ineligible","no_regradable_trials","invalid_rubric","analysis_already_running","analysis_not_found","analysis_not_terminal","check_not_found","check_not_terminal","no_checkable_tasks","too_many_concurrent_check_uploads","no_analyzable_trials","not_a_job_dir","invalid_trial","trial_too_large","upload_too_large","job_uploaded","job_already_uploaded","too_many_concurrent_job_uploads","job_import_not_found","import_not_found","import_too_large","too_many_concurrent_imports","invalid_archive","unpinned_git_ref","hub_package_not_found","hub_unreachable","package_not_retained","package_corrupt","package_missing","too_many_concurrent_package_downloads","org_not_found","org_slug_taken","org_forbidden","org_personal_immutable","org_last_owner","org_in_use","org_member_not_found","invite_not_found","invite_invalid","internal_error"];function Rn(t){return typeof t=="string"&&ds.includes(t)}var _a=["level","binary","none"];var Au=6e5,Iu=5e3;function wa(t,e,n){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be a positive number`);return r}function Ou(t){let e=t?.apiKey||process.env[O];if(!e)throw new Error(`sessions() requires an API key. Set ${O} or pass { apiKey } in config.`);let n=t?.dashboardUrl||E;async function r(i,a){let c=await fetch(`${n}${i}`,{...a,headers:{Authorization:`Bearer ${e}`,...a?.headers}});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`Dashboard API error (${c.status}): ${p||c.statusText}`)}return c}function s(i){return {id:i.id,tag:i.tag,agent:i.agent,model:i.model||null,provider:i.provider,sandboxId:i.sandboxId||null,state:i.isEnded?"ended":"live",runtimeStatus:i.runtimeStatus||"unknown",cost:typeof i.cost=="number"?i.cost:null,usage:Fe(i.usage),createdAt:i.createdAt,endedAt:i.endedAt||null,stepCount:i.stepCount||0,toolStats:i.toolStats||null}}function o(i,a){if(i.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(i.status||"unknown")})`);if(typeof i.replayUrl!="string"||typeof i.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:i.sessionId||a,status:"ready",replayUrl:i.replayUrl,downloadUrl:i.downloadUrl,suggestedStartSeconds:typeof i.suggestedStartSeconds=="number"?i.suggestedStartSeconds:void 0,sizeBytes:typeof i.sizeBytes=="number"?i.sizeBytes:void 0,readyAt:typeof i.readyAt=="string"?i.readyAt:void 0}}let d=i=>new Promise(a=>setTimeout(a,i));function u(i){if(i==null)return [];if(!Array.isArray(i))throw new Error("Session transcript response gatewayCalls is not a list");return i.map((a,c)=>{let p=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!p||Cn({data:p})===null)throw new Error(`Session transcript response gatewayCalls[${c}] is not a gateway usage event`);return p})}async function l(i,a){let c=new URLSearchParams;a?.since!=null&&c.set("since",String(a.since));let p=c.toString(),f=await(await r(`/api/sessions/${encodeURIComponent(i)}/events${p?`?${p}`:""}`)).json(),m=f.session;if(!m||typeof m!="object"||Array.isArray(m))throw new Error("Session transcript response missing session");let h=f.events||[];return {session:s(m),events:h,total:typeof f.total=="number"?f.total:(a?.since??0)+h.length,gatewayCalls:u(f.gatewayCalls),storedAt:_t(f.storedAt,h.length,"Session transcript response")}}return {async list(i){let a=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(i?.limit??20,200)),paginated:"true"});if(i?.cursor&&a.set("cursor",i.cursor),i?.state&&i.state!=="all"&&a.set("state",i.state),i?.agent&&a.set("agent",i.agent),i?.tagPrefix&&a.set("tagPrefix",i.tagPrefix),i?.sort){let g={newest:"desc",oldest:"asc",cost:"desc"};a.set("sortDirection",g[i.sort]),i.sort==="cost"?a.set("sortField","cost"):a.set("sortField","timestamp");}let p=await(await r(`/api/sessions?${a}`)).json();return {items:(p.items||[]).map(s),nextCursor:p.nextCursor||null,hasMore:!!p.hasMore}},async get(i){let c=await(await r(`/api/sessions/${encodeURIComponent(i)}`)).json();return s(c)},async events(i,a){return (await l(i,a)).events},transcript:l,async download(i,a){let g=(await(await r(`/api/sessions/${encodeURIComponent(i)}`)).json()).tag||i,f=await fetch(`${n}/api/sessions/${encodeURIComponent(i)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!f.ok){let b=await f.text().catch(()=>"");throw new Error(`Download failed (${f.status}): ${b||f.statusText}`)}let m=a?.to||process.cwd();await promises.mkdir(m,{recursive:true});let h=X.join(m,`${g}.jsonl`);if(!f.body)throw new Error("Download response has no body");let y=stream.Readable.fromWeb(f.body);return await promises$1.pipeline(y,Q.createWriteStream(h)),h},async browserReplay(i,a){let c=wa("timeoutMs",a?.timeoutMs,Au),p=wa("intervalMs",a?.intervalMs,Iu),g=Date.now()+c,f=`/api/sessions/${encodeURIComponent(i)}/browser-replay`;for(;;){let m=g-Date.now();if(m<=0)throw new Error(`Browser replay timed out after ${c}ms`);let h;try{h=await fetch(`${n}${f}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,m))});}catch(b){let _=b.name;throw _==="AbortError"||_==="TimeoutError"?new Error(`Browser replay timed out after ${c}ms`):b}let y={};if(h.ok)y=await h.json();else {let b=await h.text().catch(()=>"");throw new Error(`Dashboard API error (${h.status}): ${b||h.statusText}`)}if(y.status==="ready")return o(y,i);if(y.status==="failed"){let b=typeof y.error=="string"?y.error:"unknown error";throw new Error(`Browser replay failed: ${b}`)}if(Date.now()>=g)throw new Error(`Browser replay timed out after ${c}ms`);await d(Math.min(p,Math.max(0,g-Date.now())));}}}}ms();us();function Ju(t,e,n){return t==="measured"&&e===0&&n.every(r=>(r??null)===null)}function Ku(t,e,n){return typeof t!="number"||!Number.isFinite(t)?{lane:"unmeasured"}:e==="measured"?Ju(e,t,n)?{lane:"unmeasured"}:{lane:"measured",usd:t}:e==="measured_provisional"?{lane:"floor",usd:t}:{lane:"unmeasured"}}function hs(t){let e=t.agent_result;return Ku(e?.cost_usd,t.spend_source,[e?.n_input_tokens,e?.n_cache_tokens,e?.n_output_tokens])}var ys={stdoutFile:"stdout.log",harborCopies:[]},Pn={claude:{stdoutFile:"claude-code.txt",harborCopies:[{sandboxRoot:"/root/.claude",agentDir:"sessions"}]},codex:{stdoutFile:"codex.txt",harborCopies:[{sandboxRoot:"/root/.codex/sessions",agentDir:"sessions"}]},gemini:{stdoutFile:"gemini-cli.txt",harborCopies:[]},qwen:{stdoutFile:"qwen-code.txt",harborCopies:[{sandboxRoot:"/root/.qwen/projects",agentDir:"qwen-sessions"}]},kimi:{stdoutFile:"kimi-code.txt",harborCopies:[]},opencode:{stdoutFile:"opencode.txt",harborCopies:[{sandboxRoot:"/root/.local/share/opencode",agentDir:"opencode/xdg-data/opencode"}]},droid:{stdoutFile:"droid.txt",harborCopies:[]}},Vu={"claude-code":"claude",codex:"codex","gemini-cli":"gemini","qwen-coder":"qwen","kimi-code":"kimi",opencode:"opencode"};function bs(t){let e=t in Pn?t:Vu[t];return e===void 0?ys:Pn[e]}var Gu="/logs/agent",zu="agent-home.json";function _s(t){let e=Ea(Gu,t);if(e!==null)return e;let n=t.replace(/^\/+/,"");if(n===zu)return n;let r=/^(?:root|home\/[^/]+)\/(.+)$/.exec(n);return r!==null?r[1]:`sessions/${n}`}function Ea(t,e){return e.startsWith(`${t}/`)?e.slice(t.length+1):null}function ws(t,e){let n=_s(e),r=e.replace(/^\/+/,"");t.has(n)&&(n=r);for(let s=2;t.has(n);s++)n=`${r}.${s}`;return t.add(n),n}function ks(t,e){for(let n of t.harborCopies){let r=Ea(n.sandboxRoot,e);if(r!==null)return `${n.agentDir}/${r}`}return null}function Hu(t,e){let n=new Set,r={};for(let s of Object.keys(e).sort()){r[`agent/${ws(n,s)}`]=e[s];let o=ks(t,s);o!==null&&!n.has(o)&&(n.add(o),r[`agent/${o}`]=e[s]);}return Object.fromEntries(Object.keys(r).sort().map(s=>[s,r[s]]))}function En(t){return JSON.stringify(t,null,2)+`
|
|
660
|
-
`}function
|
|
659
|
+
Error: ${r.error??"Unknown error"}`),Object.entries(r.files).forEach(([o,d])=>{n[`candidate_${s}/${o}`]=d;});}),n}async executeBestOfJudge(e){let{candidates:n,config:r,timeoutMs:s,operationId:o,parentIndex:d,attempt:u=1,_pipelineContext:l}=e,i=d!==void 0?`${this.config.tag}-map-${d}-bestof-judge`:`${this.config.tag}-bestof-judge`,a=u>1?`${i}-er${u-1}`:i,c=this.buildJudgeContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,candidates:n,systemPrompt:e.systemPrompt,schema:e.schema}),p=pn(c),g=le(Nr,{candidateCount:String(n.length),criteria:r.judgeCriteria,fileTree:p}),m=zod.z.object({winner:zod.z.number().min(0).max(n.length-1),reasoning:zod.z.string()}),f=await this.semaphore.use(()=>this.execute(c,so,{systemPrompt:g,schema:m,agent:r.judgeAgent,mcpServers:e.mcpServers,skills:e.skills,integrations:e.integrations,tagPrefix:a,timeoutMs:s,observability:{swarmName:this.config.tag,operationId:o,operation:"map",itemIndex:d,role:"judge",errorRetry:u>1?u-1:void 0,...this.pipelineContextToObservability(l)}})),h=null;if(f.data&&!f.error)h=f.data;else if(f.rawData)try{let y=JSON.parse(f.rawData);console.warn(`Judge returned invalid winner ${y.winner}, defaulting to candidate 0`),h={winner:0,reasoning:y.reasoning??"Judge failed to provide reasoning"};}catch{console.warn(`Judge validation failed: ${f.error}`);}return {status:h?"success":"error",decision:h,tag:f.tag,sandboxId:f.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(([r,s])=>{n[`worker_output/${r}`]=s;}),n}async executeVerify(e){let{config:n,timeoutMs:r,operationId:s,workerTag:o,retryAttempt:d=1,operation:u,itemIndex:l,attemptIndex:i,_pipelineContext:a}=e,c=d>1?`${o}-verifier-er${d-1}`:`${o}-verifier`,p=n.verifierMcpServers??e.mcpServers,g=n.verifierSkills??e.skills,m=n.verifierIntegrations??e.integrations,f=this.buildVerifyContext({inputFiles:e.inputFiles,taskPrompt:e.taskPrompt,outputFiles:e.outputFiles,systemPrompt:e.systemPrompt,schema:e.schema}),h=pn(f),y=le(jr,{criteria:n.criteria,fileTree:h}),b=await this.semaphore.use(()=>this.execute(f,io,{systemPrompt:y,schema:t.VerifyDecisionSchema,agent:n.verifierAgent,mcpServers:p,skills:g,integrations:m,tagPrefix:c,timeoutMs:r,observability:{swarmName:this.config.tag,operationId:s,operation:u,itemIndex:l,role:"verifier",verifyRetry:i&&i>1?i-1:void 0,errorRetry:d>1?d-1:void 0,...this.pipelineContextToObservability(a)}})),_=null;if(b.data&&!b.error)_=b.data;else if(b.rawData)try{let w=JSON.parse(b.rawData);_={passed:!!w.passed,reasoning:w.reasoning??"Verification completed",feedback:w.feedback};}catch{console.warn(`Verify validation failed: ${b.error}`);}return {status:_?"success":"error",decision:_,tag:b.tag,sandboxId:b.sandboxId,error:_?void 0:"Verifier failed to produce valid decision"}}static buildRetryPromptWithFeedback(e,n){return le(Jr,{originalPrompt:e,feedback:n})}async runWithVerification(e,n){let{originalPrompt:r,inputFiles:s,verifyConfig:o,timeoutMs:d,operationId:u,baseTag:l,retry:i,itemIndex:a=0,operation:c,_pipelineContext:p}=n,g=o.maxAttempts??t.DEFAULT_VERIFY_MAX_ATTEMPTS,m=r,f=null,h=0;for(;h<g;){h++;let b=h>1?`${l}-vr${h-1}`:l,_=i?await G(v=>e(m,v>1?`${b}-er${v-1}`:b,h),i,a):await e(m,b,h);if(o.onWorkerComplete?.(a,h,_.status==="error"?"error":"success"),_.status==="error")return _;f=_;let w=i?await G(v=>this.executeVerify({inputFiles:s,outputFiles:_.files,taskPrompt:m,config:o,timeoutMs:d,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:u,workerTag:b,retryAttempt:v,operation:c,itemIndex:a,attemptIndex:h,_pipelineContext:p}),{...i,retryOn:void 0}):await this.executeVerify({inputFiles:s,outputFiles:_.files,taskPrompt:m,config:o,timeoutMs:d,systemPrompt:n.systemPrompt,schema:n.schema,mcpServers:n.mcpServers,skills:n.skills,integrations:n.integrations,operationId:u,workerTag:b,operation:c,itemIndex:a,attemptIndex:h,_pipelineContext:p}),S={operationId:u,operation:"verify",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)};if(o.onVerifierComplete?.(a,h,w.decision?.passed??false,w.decision?.feedback),w.decision?.passed)return {..._,verify:{passed:true,reasoning:w.decision.reasoning,verifyMeta:S,attempts:h}};if(h<g){let v=w.decision?.feedback??w.decision?.reasoning??"Output did not meet criteria";m=t.buildRetryPromptWithFeedback(r,v);}}let y=h>1?`${l}-vr${h-1}`:l;return {...f,status:"error",verify:{passed:false,reasoning:"Max verification retries exceeded",verifyMeta:{operationId:u,operation:"verify",tag:`${y}-verifier`,sandboxId:"",swarmName:this.config.tag,attempts:h,...this.pipelineContextToMeta(p)},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,r){if(typeof e=="string")return e;try{return e(n,r)}catch(s){return s}}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"]=Y(e.schema)?Ee(e.schema):Te(e.schema)),Object.entries(e.inputFiles).forEach(([r,s])=>{n[`worker_task/input/${r}`]=s;}),n}isSwarmResult(e){return typeof e=="object"&&e!==null&&ye in e&&e[ye]===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,r){let s=r??e.files;return e.error?{[ye]:true,status:"error",data:null,files:s,meta:n,error:e.error,rawData:e.rawData}:{[ye]:true,status:"success",data:e.data,files:s,meta:n}}buildErrorResult(e,n){return {[ye]:true,status:"error",data:null,files:{},meta:n,error:e}}};var vn=class t{swarm;steps;events;constructor(e,n=[],r={}){this.swarm=e,this.steps=n,this.events=r;}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 Sn(this.swarm,[...this.steps,{type:"reduce",config:e}],this.events)}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]:n})}return new t(this.swarm,this.steps,{...this.events,...e})}async run(e){let n=crypto.randomBytes(8).toString("hex"),r=[],s=e,o=Date.now();for(let u=0;u<this.steps.length;u++){let l=this.steps[u],i=l.config.name,a=Date.now();this.events.onStepStart?.({type:l.type,index:u,name:i,itemCount:s.length});let c={pipelineRunId:n,pipelineStepIndex:u};try{let p=await this.executeStep(l,s,u,i,c),g=Date.now()-a;if(r.push({type:l.type,index:u,durationMs:g,results:p.output}),this.events.onStepComplete?.({type:l.type,index:u,name:i,durationMs:g,successCount:p.successCount,errorCount:p.errorCount,filteredCount:p.filteredCount}),l.type==="reduce")return {pipelineRunId:n,steps:r,output:p.output,totalDurationMs:Date.now()-o};s=p.nextItems;}catch(p){throw this.events.onStepError?.({type:l.type,index:u,name:i,error:p instanceof Error?p:new Error(String(p))}),p}}let d=r[r.length-1];return {pipelineRunId:n,steps:r,output:d?.results??[],totalDurationMs:Date.now()-o}}async executeStep(e,n,r,s,o){if(e.type==="map"){let l=e.config,i=await this.swarm.map({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s),bestOf:this.wrapBestOf(l.bestOf,r,s)});return {output:[...i],nextItems:i.success,successCount:i.success.length,errorCount:i.error.length,filteredCount:0}}if(e.type==="filter"){let l=e.config,i=await this.swarm.filter({items:n,...l,_pipelineContext:o,retry:this.wrapRetry(l.retry,r,s),verify:this.wrapVerify(l.verify,r,s)}),a=l.emit??"success",c=a==="success"?i.success:a==="filtered"?i.filtered:[...i.success,...i.filtered];return {output:[...i],nextItems:c,successCount:i.success.length,errorCount:i.error.length,filteredCount:i.filtered.length}}let d=e.config,u=await this.swarm.reduce({items:n,...d,_pipelineContext:o,retry:this.wrapRetry(d.retry,r,s),verify:this.wrapVerify(d.verify,r,s)});return {output:u,nextItems:[],successCount:u.status==="success"?1:0,errorCount:u.status==="error"?1:0,filteredCount:0}}wrapRetry(e,n,r){if(e)return {...e,onItemRetry:(s,o,d)=>{e.onItemRetry?.(s,o,d),this.events.onItemRetry?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,error:d});}}}wrapVerify(e,n,r){if(e)return {...e,onWorkerComplete:(s,o,d)=>{e.onWorkerComplete?.(s,o,d),this.events.onWorkerComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,status:d});},onVerifierComplete:(s,o,d,u)=>{e.onVerifierComplete?.(s,o,d,u),this.events.onVerifierComplete?.({stepIndex:n,stepName:r,itemIndex:s,attempt:o,passed:d,feedback:u});}}}wrapBestOf(e,n,r){if(e)return {...e,onCandidateComplete:(s,o,d)=>{e.onCandidateComplete?.(s,o,d),this.events.onCandidateComplete?.({stepIndex:n,stepName:r,itemIndex:s,candidateIndex:o,status:d});},onJudgeComplete:(s,o,d)=>{e.onJudgeComplete?.(s,o,d),this.events.onJudgeComplete?.({stepIndex:n,stepName:r,itemIndex:s,winnerIndex:o,reasoning:d});}}}},Sn=class t extends vn{constructor(e,n,r){super(e,n,r);}on(e,n){if(typeof e=="string"){let r=`on${e.charAt(0).toUpperCase()}${e.slice(1)}`;return new t(this.swarm,this.steps,{...this.events,[r]: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")}};var gs=class extends Error{feature;provider;reason;constructor(e,n,r){super(`${n} does not support ${e}${r?`: ${r}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=e,this.provider=n,this.reason=r;}},ms=class extends Error{path;provider;constructor(e,n){super(`${n}: no such file or directory: ${e}`),this.name="SandboxPathNotFoundError",this.path=e,this.provider=n;}},fs=class extends Error{sandboxId;provider;state;constructor(e,n,r){super(`${n} sandbox ${e} is not running (${r}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=e,this.provider=n,this.state=r;}};function hs(t,e){return !!t&&typeof t=="object"&&t.name===e}function Fu(t){return hs(t,"SandboxFeatureUnsupportedError")}function Bu(t){return hs(t,"SandboxPathNotFoundError")}function Nu(t){return hs(t,"SandboxNotRunningError")}var ba=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","BUDGET","INDETERMINATE","CANCELLED"],_a=["e2b","daytona","modal"],wa=["my","shared"],ka=["queued","running","completed","failed"],va=["queued","running","completed"];function Je(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.provisional!="boolean")return null;let n=r=>typeof r=="number"&&Number.isFinite(r)?r:null;return {provisional:e.provisional,spent_usd:n(e.spent_usd),input_tokens:n(e.input_tokens),cached_input_tokens:n(e.cached_input_tokens),cache_write_tokens:n(e.cache_write_tokens),output_tokens:n(e.output_tokens),as_of:typeof e.as_of=="string"?e.as_of:null}}function Sa(t){let e=t.stats?.evals??{},n=[];for(let r of Object.keys(e).sort()){let s=e[r]?.pass_at_k??{},o=[];for(let d of Object.keys(s)){let u=Number(d),l=s[d];!Number.isFinite(u)||typeof l!="number"||!Number.isFinite(l)||o.push({k:u,value:l});}o.length!==0&&(o.sort((d,u)=>d.k-u.k),n.push({evals_key:r,points:o}));}return n}var xn=["dataset_flag","job_dataset_record","task_hash","none"],Cn=["hash_mismatch","task_not_in_dataset","no_dataset_named","dataset_ambiguous","no_hash_match","no_task_digest"],Rn=1e9;function En(t){let e=t.data?.update;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(n.sessionUpdate!=="usage"||n.source!=="gateway")return null;let r=n.usage;return !r||typeof r!="object"||Array.isArray(r)?null:n}function wt(t,e,n){if(t!=null){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${n} storedAt is not a list of date-time strings`);if(t.length!==e)throw new Error(`${n} storedAt has ${t.length} entries for ${e} events (one per event, index-aligned)`);return t}}var xa=["trace-parsed","verifier","trace-stdout","trace-stderr","trace-atif","trajectory","agent-home","filesystem"],Ca=["agent","verifier","setup","system","metrics"],Ra=["trace-stdout","trace-stderr","agent-home"],ys=["missing_authorization","invalid_api_key","read_only_key","credential_service_unavailable","rate_limited","insufficient_credits","quota_exceeded","invalid_json","invalid_input","invalid_limit","invalid_status","invalid_visibility","invalid_cursor","invalid_after","invalid_format","invalid_ids","invalid_multipart","idempotency_key_reused","dataset_not_found","dataset_version_not_found","dataset_name_taken","dataset_in_use","dataset_not_owned","dataset_import_in_progress","upstream_not_watchable","no_active_version","version_not_ready","version_not_activatable","unknown_task_names","no_tasks","task_not_found","task_failed_to_build","upload_session_not_found","upload_offset_mismatch","upload_chunk_digest_mismatch","upload_incomplete","upload_archive_digest_mismatch","upload_session_failed","too_many_concurrent_upload_chunks","agent_not_found","agent_name_taken","agent_name_reserved","agent_invalid_name","agent_source_required","agent_source_conflict","agent_invalid_env","agent_too_large","agent_limit_reached","skill_not_found","skill_name_not_found","skill_ref_invalid","skill_unresolvable","skill_invalid","skill_in_use","skill_too_large","skill_limit_reached","too_many_concurrent_skill_uploads","secret_not_found","secret_ambiguous","secret_brokered_unsupported","secret_exists","secret_not_attached","agent_version_not_found","agent_version_unresolvable","agent_kwarg_unsupported","agent_config_unsupported","agent_config_key_refused","agent_preset_unsupported","provider_unsupported","job_not_found","job_not_terminal","no_failed_trials","trial_not_found","trial_not_settled","concurrent_update","regrade_source_ineligible","no_regradable_trials","invalid_rubric","analysis_already_running","analysis_not_found","analysis_not_terminal","check_not_found","check_not_terminal","no_checkable_tasks","too_many_concurrent_check_uploads","no_analyzable_trials","not_a_job_dir","invalid_trial","trial_too_large","upload_too_large","job_uploaded","job_already_uploaded","too_many_concurrent_job_uploads","job_import_not_found","import_not_found","import_too_large","too_many_concurrent_imports","invalid_archive","unpinned_git_ref","hub_package_not_found","hub_unreachable","package_not_retained","package_corrupt","package_missing","too_many_concurrent_package_downloads","org_not_found","org_slug_taken","org_forbidden","org_personal_immutable","org_last_owner","org_in_use","org_member_not_found","invite_not_found","invite_invalid","not_found","not_captured","filesystem_state","feature_unsupported","provider_unreachable","task_package_not_retained","internal_error"];function Tn(t){return typeof t=="string"&&ys.includes(t)}var Ea=["level","binary","none"];var Hu=6e5,zu=5e3;function Ta(t,e,n){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} must be a positive number`);return r}function qu(t){let e=t?.apiKey||process.env[O];if(!e)throw new Error(`sessions() requires an API key. Set ${O} or pass { apiKey } in config.`);let n=t?.dashboardUrl||T;async function r(i,a){let c=await fetch(`${n}${i}`,{...a,headers:{Authorization:`Bearer ${e}`,...a?.headers}});if(!c.ok){let p=await c.text().catch(()=>"");throw new Error(`Dashboard API error (${c.status}): ${p||c.statusText}`)}return c}function s(i){return {id:i.id,tag:i.tag,agent:i.agent,model:i.model||null,reasoningEffort:typeof i.reasoningEffort=="string"?i.reasoningEffort:null,provider:i.provider,sandboxId:i.sandboxId||null,state:i.isEnded?"ended":"live",runtimeStatus:i.runtimeStatus||"unknown",cost:typeof i.cost=="number"?i.cost:null,usage:Je(i.usage),createdAt:i.createdAt,endedAt:i.endedAt||null,stepCount:i.stepCount||0,toolStats:i.toolStats||null}}function o(i,a){if(i.status!=="ready")throw new Error(`Browser replay is not ready (status: ${String(i.status||"unknown")})`);if(typeof i.replayUrl!="string"||typeof i.downloadUrl!="string")throw new Error("Browser replay response missing replayUrl or downloadUrl");return {sessionId:i.sessionId||a,status:"ready",replayUrl:i.replayUrl,downloadUrl:i.downloadUrl,suggestedStartSeconds:typeof i.suggestedStartSeconds=="number"?i.suggestedStartSeconds:void 0,sizeBytes:typeof i.sizeBytes=="number"?i.sizeBytes:void 0,readyAt:typeof i.readyAt=="string"?i.readyAt:void 0}}let d=i=>new Promise(a=>setTimeout(a,i));function u(i){if(i==null)return [];if(!Array.isArray(i))throw new Error("Session transcript response gatewayCalls is not a list");return i.map((a,c)=>{let p=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!p||En({data:p})===null)throw new Error(`Session transcript response gatewayCalls[${c}] is not a gateway usage event`);return p})}async function l(i,a){let c=new URLSearchParams;a?.since!=null&&c.set("since",String(a.since));let p=c.toString(),m=await(await r(`/api/sessions/${encodeURIComponent(i)}/events${p?`?${p}`:""}`)).json(),f=m.session;if(!f||typeof f!="object"||Array.isArray(f))throw new Error("Session transcript response missing session");let h=m.events||[];return {session:s(f),events:h,total:typeof m.total=="number"?m.total:(a?.since??0)+h.length,gatewayCalls:u(m.gatewayCalls),storedAt:wt(m.storedAt,h.length,"Session transcript response")}}return {async list(i){let a=new URLSearchParams({paginationMode:"cursor",pageSize:String(Math.min(i?.limit??20,200)),paginated:"true"});if(i?.cursor&&a.set("cursor",i.cursor),i?.state&&i.state!=="all"&&a.set("state",i.state),i?.agent&&a.set("agent",i.agent),i?.tagPrefix&&a.set("tagPrefix",i.tagPrefix),i?.sort){let g={newest:"desc",oldest:"asc",cost:"desc"};a.set("sortDirection",g[i.sort]),i.sort==="cost"?a.set("sortField","cost"):a.set("sortField","timestamp");}let p=await(await r(`/api/sessions?${a}`)).json();return {items:(p.items||[]).map(s),nextCursor:p.nextCursor||null,hasMore:!!p.hasMore}},async get(i){let c=await(await r(`/api/sessions/${encodeURIComponent(i)}`)).json();return s(c)},async events(i,a){return (await l(i,a)).events},transcript:l,async download(i,a){let g=(await(await r(`/api/sessions/${encodeURIComponent(i)}`)).json()).tag||i,m=await fetch(`${n}/api/sessions/${encodeURIComponent(i)}/download`,{headers:{Authorization:`Bearer ${e}`},redirect:"follow"});if(!m.ok){let b=await m.text().catch(()=>"");throw new Error(`Download failed (${m.status}): ${b||m.statusText}`)}let f=a?.to||process.cwd();await promises.mkdir(f,{recursive:true});let h=X.join(f,`${g}.jsonl`);if(!m.body)throw new Error("Download response has no body");let y=stream.Readable.fromWeb(m.body);return await promises$1.pipeline(y,Q.createWriteStream(h)),h},async browserReplay(i,a){let c=Ta("timeoutMs",a?.timeoutMs,Hu),p=Ta("intervalMs",a?.intervalMs,zu),g=Date.now()+c,m=`/api/sessions/${encodeURIComponent(i)}/browser-replay`;for(;;){let f=g-Date.now();if(f<=0)throw new Error(`Browser replay timed out after ${c}ms`);let h;try{h=await fetch(`${n}${m}`,{headers:{Authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(Math.max(1,f))});}catch(b){let _=b.name;throw _==="AbortError"||_==="TimeoutError"?new Error(`Browser replay timed out after ${c}ms`):b}let y={};if(h.ok)y=await h.json();else {let b=await h.text().catch(()=>"");throw new Error(`Dashboard API error (${h.status}): ${b||h.statusText}`)}if(y.status==="ready")return o(y,i);if(y.status==="failed"){let b=typeof y.error=="string"?y.error:"unknown error";throw new Error(`Browser replay failed: ${b}`)}if(Date.now()>=g)throw new Error(`Browser replay timed out after ${c}ms`);await d(Math.min(p,Math.max(0,g-Date.now())));}}}}vs();bs();function sp(t,e,n){return t==="measured"&&e===0&&n.every(r=>(r??null)===null)}function ip(t,e,n){return typeof t!="number"||!Number.isFinite(t)?{lane:"unmeasured"}:e==="measured"?sp(e,t,n)?{lane:"unmeasured"}:{lane:"measured",usd:t}:e==="measured_provisional"?{lane:"floor",usd:t}:{lane:"unmeasured"}}function Ss(t){let e=t.agent_result;return ip(e?.cost_usd,t.spend_source,[e?.n_input_tokens,e?.n_cache_tokens,e?.n_output_tokens])}var xs={stdoutFile:"stdout.log",harborCopies:[]},In={claude:{stdoutFile:"claude-code.txt",harborCopies:[{sandboxRoot:"/root/.claude",agentDir:"sessions"}]},codex:{stdoutFile:"codex.txt",harborCopies:[{sandboxRoot:"/root/.codex/sessions",agentDir:"sessions"}]},gemini:{stdoutFile:"gemini-cli.txt",harborCopies:[]},qwen:{stdoutFile:"qwen-code.txt",harborCopies:[{sandboxRoot:"/root/.qwen/projects",agentDir:"qwen-sessions"}]},kimi:{stdoutFile:"kimi-code.txt",harborCopies:[]},opencode:{stdoutFile:"opencode.txt",harborCopies:[{sandboxRoot:"/root/.local/share/opencode",agentDir:"opencode/xdg-data/opencode"}]},droid:{stdoutFile:"droid.txt",harborCopies:[]}},op={"claude-code":"claude",codex:"codex","gemini-cli":"gemini","qwen-coder":"qwen","kimi-code":"kimi",opencode:"opencode"};function Cs(t){let e=t in In?t:op[t];return e===void 0?xs:In[e]}var ap="/logs/agent",lp="agent-home.json";function Rs(t){let e=La(ap,t);if(e!==null)return e;let n=t.replace(/^\/+/,"");if(n===lp)return n;let r=/^(?:root|home\/[^/]+)\/(.+)$/.exec(n);return r!==null?r[1]:`sessions/${n}`}function La(t,e){return e.startsWith(`${t}/`)?e.slice(t.length+1):null}function Es(t,e){let n=Rs(e),r=e.replace(/^\/+/,"");t.has(n)&&(n=r);for(let s=2;t.has(n);s++)n=`${r}.${s}`;return t.add(n),n}function Ts(t,e){for(let n of t.harborCopies){let r=La(n.sandboxRoot,e);if(r!==null)return `${n.agentDir}/${r}`}return null}function cp(t,e){let n=new Set,r={};for(let s of Object.keys(e).sort()){r[`agent/${Es(n,s)}`]=e[s];let o=Ts(t,s);o!==null&&!n.has(o)&&(n.add(o),r[`agent/${o}`]=e[s]);}return Object.fromEntries(Object.keys(r).sort().map(s=>[s,r[s]]))}function An(t){return JSON.stringify(t,null,2)+`
|
|
660
|
+
`}function Ps(t,e,n){return {trial_id:t.id,job_id:t.job_id,user_id:n,provider:t.sandbox_provider,gateway:{cost_usd:t.agent_result?.cost_usd??null,n_input_tokens:t.agent_result?.n_input_tokens??null,n_cache_tokens:t.agent_result?.n_cache_tokens??null,n_output_tokens:t.agent_result?.n_output_tokens??null,spend_source:t.spend_source,max_trial_spend_usd:t.max_trial_spend_usd,judge:t.judge_result?{cost_usd:t.judge_result.cost_usd,n_input_tokens:t.judge_result.n_input_tokens,n_cache_tokens:t.judge_result.n_cache_tokens,n_output_tokens:t.judge_result.n_output_tokens,spend_source:t.judge_spend_source??null}:null},regrade_lineage:{is_regrade:e?.is_regrade??false,source_jobs:e?.source_jobs??[],n_retries:t.n_retries,retries:t.retries}}}function $a(t,e){return {job_id:t.id,user_id:e,provider:t.sandbox_provider,gateway:{cost_usd:t.stats.cost_usd??null,judge_cost_usd:t.stats.judge_cost_usd??null,n_unmeasured_trials:t.stats.n_unmeasured_trials??null,n_unmeasured_judge_trials:t.stats.n_unmeasured_judge_trials??null,n_input_tokens:t.stats.n_input_tokens??null,n_cache_tokens:t.stats.n_cache_tokens??null,n_output_tokens:t.stats.n_output_tokens??null,max_trial_spend_usd:t.max_trial_spend_usd,worst_case_spend_usd:t.worst_case_spend_usd},regrade_lineage:{is_regrade:t.is_regrade,source_jobs:t.source_jobs}}}function dp(t){let e=t.agent_result;return e==null?e??null:Ss(t).lane==="measured"?e:{...e,cost_usd:null}}function Fa(t){let{trial:e}=t,n={};n["config.json"]=An({trial_name:e.id,task:{name:e.task_name,source:e.source},agent:{name:e.agent_info.name,version:e.agent_info.version,model_name:e.agent_info.model_info.name,reasoning_effort:e.agent_info.reasoning_effort}}),n["result.json"]=An({trial_name:e.id,task_name:e.task_name,status:e.status,reward:e.reward,verifier_result:e.verifier_result,exception_info:e.exception_info,agent_result:dp(e),started_at:e.started_at,finished_at:e.finished_at,environment_setup:e.environment_setup,agent_setup:e.agent_setup,agent_execution:e.agent_execution,verifier:e.verifier});let r=Cs(e.agent_info.name);return t.atif!==null&&(n["agent/trajectory.json"]=t.atif),t.stdout!==null&&(n[`agent/${r.stdoutFile}`]=t.stdout),t.stderr!==null&&(n["agent/stderr.log"]=t.stderr),t.events.length>0&&(n["agent/trace-parsed.jsonl"]=t.events.map(s=>JSON.stringify(s)).join(`
|
|
661
661
|
`)+`
|
|
662
|
-
`),t.home!==null&&Object.assign(n,
|
|
663
|
-
`),n["evolve.json"]=En(vs(e,t.job,t.userId)),n}function Ia(t,e){return {analysis_id:t.id,analyzed_trial_id:t.trial_id,job_id:t.job_id,task_name:t.task_name,user_id:e,status:t.status,model_name:t.model_name,gateway:{cost_usd:t.estimated_cost_usd,n_input_tokens:t.usage?.input_tokens??null,n_cache_tokens:t.usage?.cached_input_tokens??null,n_output_tokens:t.usage?.output_tokens??null}}}function Oa(t,e,n){return {task_check_id:t.id,check_id:e.id,dataset:e.source.dataset,task_name:t.task_name,user_id:n,provider:e.sandbox_provider,status:t.status,model_name:e.model_name,gateway:{cost_usd:t.cost_usd}}}function Ma(t,e){return {check_id:t.id,user_id:e,source:t.source,provider:t.sandbox_provider,status:t.status,model_name:t.model_name,gateway:{cost_usd:t.cost_usd}}}xs();var B=class extends Error{status;code;param;details;retryAfterSec;requestId;constructor(e,n,r,s){super(r),this.name="EvolveApiError",this.status=e,this.code=n,s?.param!==void 0&&(this.param=s.param),s?.details!==void 0&&(this.details=s.details),s?.retryAfterSec!==void 0&&(this.retryAfterSec=s.retryAfterSec),s?.requestId!==void 0&&(this.requestId=s.requestId);}isKnownCode(){return Rn(this.code)}};async function Pt(t){let e=await t.text().catch(()=>""),n=t.headers?.get?.("x-request-id")??void 0,r=wt(e,t);try{let s=JSON.parse(e);if(s?.error&&typeof s.error=="object"){let o=typeof s.error.code=="string"?s.error.code:"unknown_error",d=typeof s.error.message=="string"?s.error.message:t.statusText;throw new B(t.status,o,d,{param:typeof s.error.param=="string"?s.error.param:void 0,details:s.error.details&&typeof s.error.details=="object"?s.error.details:void 0,retryAfterSec:r,requestId:typeof s.error.requestId=="string"?s.error.requestId:n})}if(typeof s?.error=="string")throw new B(t.status,"unknown_error",s.error,{retryAfterSec:r,requestId:n})}catch(s){if(s instanceof B)throw s}throw new B(t.status,"unknown_error",e||t.statusText,{retryAfterSec:r,requestId:n})}var Mn=class extends Error{dataset;constructor(e){super(`Dataset "${e}" has no active version`),this.name="NoActiveVersionError",this.dataset=e;}},Ct=class extends Error{name="ImportSettleError";code;importId;dataset;version;state;constructor(e,n,r){super(n),this.code=e,this.importId=r.importId,this.dataset=r.dataset,this.version=r.version,this.state=r.state;}},cp=1e3,xt=3e4,dp=new Set(["COMPLETED","CANCELLED","FAILED"]),up=new Set(["job.completed","job.cancelled","job.failed"]),Rt=2e3,pp=30*6e4;function de(t,e){let n=e?.apiKey||process.env[O];if(!n)throw new Error(`${t}() requires an API key. Set ${O} or pass { apiKey } in config.`);let r=(e?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"");return {apiKey:n,baseUrl:r}}async function v(t,e,n){let r=await fetch(`${t.baseUrl}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,...n?.headers}});return r.ok||await Pt(r),r}function Cs(t){let e=t.indexOf("@");if(e===-1)return {name:t.trim()};let n=t.slice(0,e).trim(),r=t.slice(e+1).trim();if(!n||!r)throw new Error(`Invalid dataset ref "${t}": expected "name" or "name@version"`);return {name:n,version:r}}function As(t){return {name:t.name,version:t.version}}function Ba(t){let e=t.kwargs,n=Array.isArray(t.skills)?t.skills.filter(o=>typeof o=="string"):[],r=Array.isArray(t.skill_locks)?t.skill_locks:null,s=r?r.flatMap(o=>{if(!o||typeof o!="object")return [];let d=o;return typeof d.name!="string"||typeof d.digest!="string"?[]:[{name:d.name,source:typeof d.source=="string"?d.source:"",digest:d.digest,git_url:typeof d.git_url=="string"?d.git_url:null,git_commit_id:typeof d.git_commit_id=="string"?d.git_commit_id:null}]}):null;return {name:t.name,model_name:t.model_name,version:t.version??null,reasoning_effort:t.reasoning_effort??null,kwargs:e&&typeof e=="object"&&!Array.isArray(e)?e:null,preset:typeof t.preset=="string"?t.preset:null,skills:n,skill_locks:s}}function gp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.name!="string")return null;let n=Array.isArray(e.authors)?e.authors.flatMap(r=>{if(!r||typeof r!="object"||Array.isArray(r))return [];let s=r;return typeof s.name!="string"?[]:[{name:s.name,email:typeof s.email=="string"?s.email:null}]}):[];return {name:e.name,version:typeof e.version=="string"?e.version:null,description:typeof e.description=="string"?e.description:"",authors:n,keywords:Array.isArray(e.keywords)?e.keywords.filter(r=>typeof r=="string"):[],task_count:typeof e.task_count=="number"?e.task_count:null}}function fp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,n=s=>typeof e[s]=="string"?e[s]:null;switch(n("kind")??(n("commit")!==null?"git":null)){case "git":{let s=n("ref"),o=n("commit");return s===null||o===null?null:{kind:"git",git_url:n("git_url"),ref:s,commit:o,path:n("path")}}case "archive":{let s=n("digest");return s===null?null:{kind:"archive",digest:s}}case "archive_url":{let s=n("archive_url"),o=n("digest");return s===null||o===null?null:{kind:"archive_url",archive_url:s,digest:o}}case "hub_package":{let s=n("hub_package"),o=n("digest");return s===null||o===null?null:{kind:"hub_package",hub_package:s,digest:o}}default:return null}}function Ke(t){return {version:t.version,state:t.state,created_at:t.created_at,task_count:t.task_count??0,n_failed_tasks:typeof t.n_failed_tasks=="number"?t.n_failed_tasks:0,manifest:gp(t.manifest),source:fp(t.source)}}function Na(t){return {code:t.code??"",step:t.step??"",message:t.message??"",excerpt:t.excerpt??null}}function mp(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object").map(e=>({task_name:e.task_name??"",failure:Na(e.failure??{})})):[]}function hp(t){return {task_name:t.task_name,agent_timeout_sec:t.agent_timeout_sec,verifier_timeout_sec:t.verifier_timeout_sec,gpus:typeof t.gpus=="number"&&t.gpus>0?t.gpus:0,gpu_types:Array.isArray(t.gpu_types)&&t.gpu_types.length>0?t.gpu_types.map(String):null,providers:t.providers,notes:Array.isArray(t.notes)?t.notes:[]}}function yp(t){return {action:t.action,type:t.type,job_id:t.job_id}}function bp(t){let e=t&&typeof t=="object"?t:{};return {max_retries:typeof e.max_retries=="number"?e.max_retries:0,include_exceptions:Array.isArray(e.include_exceptions)?e.include_exceptions:null,exclude_exceptions:Array.isArray(e.exclude_exceptions)?e.exclude_exceptions:[],wait_multiplier:typeof e.wait_multiplier=="number"?e.wait_multiplier:1,min_wait_sec:typeof e.min_wait_sec=="number"?e.min_wait_sec:1,max_wait_sec:typeof e.max_wait_sec=="number"?e.max_wait_sec:60}}function _p(t){return {attempt_number:t.attempt_number,exception_info:t.exception_info??{exception_type:"InfrastructureError",exception_message:""},cost_usd:t.cost_usd??null,started_at:t.started_at??null,settled_at:t.settled_at??null}}function An(t){return typeof t=="number"?t:null}function wp(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object").map(e=>{let n=typeof e.n_tasks_ran=="number"?e.n_tasks_ran:0;return {dataset:As(e.dataset??{}),n_tasks_ran:n,n_tasks_selected:typeof e.n_tasks_selected=="number"?e.n_tasks_selected:n,n_tasks_failed_to_build:typeof e.n_tasks_failed_to_build=="number"?e.n_tasks_failed_to_build:0,failed_task_names:Array.isArray(e.failed_task_names)?e.failed_task_names.map(String):[],note:e.note??""}}):[]}function kp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.uploaded_at!="string")return null;let n=e.reported_totals,r=o=>typeof o=="number"&&Number.isFinite(o)?o:null,s=n&&typeof n=="object"&&!Array.isArray(n)&&Number.isInteger(n.n_trials_reporting)?{cost_usd:r(n.cost_usd),n_input_tokens:r(n.n_input_tokens),n_cache_tokens:r(n.n_cache_tokens),n_output_tokens:r(n.n_output_tokens),n_trials_reporting:n.n_trials_reporting}:null;return {original_job_id:typeof e.original_job_id=="string"?e.original_job_id:null,original_job_name:typeof e.original_job_name=="string"?e.original_job_name:null,uploaded_at:e.uploaded_at,reported_totals:s,task_links:Fa(e.task_links)}}var ja=t=>typeof t=="string"&&vn.includes(t),Ts=t=>typeof t=="string"&&Sn.includes(t),Es=t=>Array.isArray(t)&&t.every(e=>typeof e=="string")?[...t]:null;function Fa(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(typeof r.task_name!="string"||!ja(r.linked_by)||![r.n_trials,r.n_linked,r.n_unlinked].every(l=>Number.isInteger(l)&&l>=0))return null;let o=Es(r.datasets),d=Es(r.candidates);if(o===null||d===null||!r.link_reasons||typeof r.link_reasons!="object"||Array.isArray(r.link_reasons))return null;let u={};for(let[l,i]of Object.entries(r.link_reasons)){if(!Ts(l)||!Number.isInteger(i))return null;u[l]=i;}e.push({task_name:r.task_name,n_trials:r.n_trials,n_linked:r.n_linked,n_unlinked:r.n_unlinked,linked_by:r.linked_by,datasets:o,link_reasons:u,candidates:d});}return e}function vp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(!ja(e.linked_by)||e.link_reason!==null&&e.link_reason!==void 0&&!Ts(e.link_reason))return null;let n=e.candidates===void 0?[]:Es(e.candidates);return n===null?null:{linked_by:e.linked_by,link_reason:Ts(e.link_reason)?e.link_reason:null,dataset:typeof e.dataset=="string"?e.dataset:null,version:typeof e.version=="string"?e.version:null,task_digest:typeof e.task_digest=="string"?e.task_digest:null,candidates:n}}function Z(t){let e=t.trials??{};return {id:t.id,job_name:t.job_name,status:t.status,datasets:(t.datasets??[]).map(As),agents:(t.agents??[]).map(Ba),n_attempts:t.n_attempts,n_concurrent_trials:t.n_concurrent_trials,max_trial_spend_usd:t.max_trial_spend_usd,worst_case_spend_usd:t.worst_case_spend_usd,retry:bp(t.retry),analyze:t.analyze&&typeof t.analyze=="object"&&!Array.isArray(t.analyze)?t.analyze:null,timeout_multiplier:typeof t.timeout_multiplier=="number"?t.timeout_multiplier:1,agent_timeout_multiplier:An(t.agent_timeout_multiplier),verifier_timeout_multiplier:An(t.verifier_timeout_multiplier),agent_setup_timeout_multiplier:An(t.agent_setup_timeout_multiplier),environment_build_timeout_multiplier:An(t.environment_build_timeout_multiplier),sandbox_provider:t.sandbox_provider??null,counts:t.counts,build_exclusions:wp(t.build_exclusions),n_total_trials:t.n_total_trials??0,trials:{total:e.total??0,byStatus:e.byStatus??{}},stats:t.stats??{},failure:t.failure??null,source_jobs:(t.source_jobs??[]).map(yp),is_regrade:t.is_regrade===true,upload:kp(t.upload),idempotent_replay:t.idempotent_replay===true,started_at:t.started_at,updated_at:t.updated_at,finished_at:t.finished_at??null}}function L(t,e){let n=t??{};return {items:Array.isArray(n.items)?n.items.map(e):[],nextCursor:n.nextCursor??null,hasMore:n.hasMore===true}}function G(t,e){let n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);for(let[s,o]of Object.entries(e??{}))o!==void 0&&n.set(s,o);let r=n.toString();return r?`?${r}`:""}function pe(t){if(!t||typeof t!="object")return null;let e=t;return {started_at:e.started_at??null,finished_at:e.finished_at??null}}function Sp(t){let e=t.model_info??{};return {name:t.name,version:t.version??null,model_info:{name:e.name,provider:e.provider??null},reasoning_effort:t.reasoning_effort??null}}function Dn(t){return !t||typeof t!="object"||Array.isArray(t)?null:{...t,usage:Fe(t.usage)}}function xp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let{from:e,to:n,reason:r}=t;return typeof e!="string"||typeof n!="string"||typeof r!="string"?null:{from:e,to:n,reason:r}}function Ps(t){return {id:t.id,job_id:t.job_id,task_name:t.task_name,source:t.source,agent_info:Sp(t.agent_info||{}),attempt:t.attempt,status:t.status,reward:t.reward??null,verifier_result:t.verifier_result??null,exception_info:t.exception_info??null,agent_result:t.agent_result??null,judge_result:t.judge_result??null,analysis:Dn(t.analysis),environment_setup:pe(t.environment_setup),agent_setup:pe(t.agent_setup),agent_execution:pe(t.agent_execution),verifier:pe(t.verifier),queue_wait:pe(t.queue_wait),harness_bundle:pe(t.harness_bundle),image_prepare:pe(t.image_prepare),shared_verify_setup:pe(t.shared_verify_setup),harness_bundle_cache_hit:typeof t.harness_bundle_cache_hit=="boolean"?t.harness_bundle_cache_hit:null,step_results:t.step_results??null,spend_source:t.spend_source??null,judge_spend_source:t.judge_spend_source??null,live_spent_usd:t.live_spent_usd??null,live_spend_at:t.live_spend_at??null,usage:Fe(t.usage),max_trial_spend_usd:t.max_trial_spend_usd??null,sandbox_provider:t.sandbox_provider??null,sandbox_provider_degrade:xp(t.sandbox_provider_degrade),gpu_cost:t.gpu_cost&&typeof t.gpu_cost=="object"&&!Array.isArray(t.gpu_cost)?t.gpu_cost:null,sandbox_id:t.sandbox_id??null,verifier_sandbox_id:t.verifier_sandbox_id??null,verifier_environment_mode:t.verifier_environment_mode??null,attempt_phase:t.attempt_phase??null,n_retries:t.n_retries??0,retries:Array.isArray(t.retries)?t.retries.map(_p):[],session_ref:t.session_ref??null,upload:Cp(t.upload),started_at:t.started_at??null,finished_at:t.finished_at??null}}function Cp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.original_trial_name!="string"||typeof e.original_task_name!="string")return null;let n=e.reported_agent_result,r=s=>typeof s=="number"&&Number.isFinite(s)?s:null;return {original_trial_id:typeof e.original_trial_id=="string"?e.original_trial_id:null,original_trial_name:e.original_trial_name,original_task_name:e.original_task_name,reported_agent_result:n&&typeof n=="object"&&!Array.isArray(n)?{n_input_tokens:r(n.n_input_tokens),n_cache_tokens:r(n.n_cache_tokens),n_output_tokens:r(n.n_output_tokens),cost_usd:r(n.cost_usd)}:null,link:vp(e.link)}}function In(t){return {name:t.name,source:t.source,run_command:t.run_command,env:t.env??{},created_at:t.created_at,updated_at:t.updated_at}}function Ve(t){let e={id:t.id,status:t.status,name:t.name,version:t.version,failure:t.failure??null,warnings:t.warnings??[],progress:t.progress??null};return typeof t.receiving=="boolean"&&(e.receiving=t.receiving),typeof t.task_count=="number"&&(e.task_count=t.task_count),typeof t.created_at=="string"&&(e.created_at=t.created_at),typeof t.updated_at=="string"&&(e.updated_at=t.updated_at),e}function St(t){let e={id:t.id,status:t.status,receiving:t.receiving===true,source:t.source??null,dataset:t.dataset??null,job_id:t.job_id??null,n_trials_uploaded:t.n_trials_uploaded??null,n_trials_skipped:t.n_trials_skipped??null,skipped_trials:Array.isArray(t.skipped_trials)?t.skipped_trials:null,task_links:Fa(t.task_links),failure:t.failure??null,progress:t.progress??null};return typeof t.created_at=="string"&&(e.created_at=t.created_at),typeof t.updated_at=="string"&&(e.updated_at=t.updated_at),e}function Ja(t){let e=t??{};return {scored:e.scored??0,total:e.total??0}}function Rp(t){return {id:t.id,datasets:(t.datasets??[]).map(As),status:t.status,mean_reward:t.mean_reward??null,coverage:Ja(t.coverage),cost_usd:t.cost_usd??0,agents:(t.agents||[]).map(Ba),started_at:t.started_at}}function Tp(t){return {job_id:t.job_id,status:t.status,mean_reward:t.mean_reward??null,coverage:Ja(t.coverage)}}function Ep(t){return {task_name:t.task_name,disagreement:t.disagreement===true,cells:(t.cells||[]).map(Tp)}}function Ka(t){return {seq:t.seq,type:t.type,data:t.data??{}}}function Va(t){return (Array.isArray(t)?t:[]).map((n,r)=>({seq:xn+r,type:"usage",data:n&&typeof n=="object"&&!Array.isArray(n)?n:{}}))}function Pp(t){return {trial_id:t.trial_id,task_name:t.task_name??null,match_count:t.match_count,events:(t.events||[]).map(Ka)}}function Ap(t){return t?t.suffix!==void 0?`bytes=-${t.suffix}`:t.start===void 0?null:`bytes=${t.start}-${t.end??""}`:null}function ge(t){if(t?.aborted)throw t.reason instanceof Error?t.reason:new Error("Watch aborted")}function $a(t,e){return e?.aborted?true:t?.name==="AbortError"}function F(t,e){return new Promise((n,r)=>{let s=setTimeout(()=>{e?.removeEventListener("abort",o),n();},t),o=()=>{clearTimeout(s),r(e?.reason instanceof Error?e.reason:new Error("Watch aborted"));};e?.addEventListener("abort",o,{once:true});})}function Ip(t){let e="",n=false;return {push(r){n&&(r="\r"+r,n=false),r.endsWith("\r")&&(r=r.slice(0,-1),n=true),e+=r.replace(/\r\n|\r/g,`
|
|
662
|
+
`),t.home!==null&&Object.assign(n,cp(r,t.home)),t.verifierLog!==null&&(n["verifier/test-stdout.txt"]=t.verifierLog),e.verifier_result?.rewards&&(n["verifier/reward.json"]=An(e.verifier_result.rewards)),e.exception_info&&(n["exception.txt"]=`${e.exception_info.exception_type}: ${e.exception_info.exception_message}
|
|
663
|
+
`),n["evolve.json"]=An(Ps(e,t.job,t.userId)),n}function Ba(t,e){return {analysis_id:t.id,analyzed_trial_id:t.trial_id,job_id:t.job_id,task_name:t.task_name,user_id:e,status:t.status,model_name:t.model_name,gateway:{cost_usd:t.estimated_cost_usd,n_input_tokens:t.usage?.input_tokens??null,n_cache_tokens:t.usage?.cached_input_tokens??null,n_output_tokens:t.usage?.output_tokens??null}}}function Na(t,e,n){return {task_check_id:t.id,check_id:e.id,dataset:e.source.dataset,task_name:t.task_name,user_id:n,provider:e.sandbox_provider,status:t.status,model_name:e.model_name,gateway:{cost_usd:t.cost_usd}}}function ja(t,e){return {check_id:t.id,user_id:e,source:t.source,provider:t.sandbox_provider,status:t.status,model_name:t.model_name,gateway:{cost_usd:t.cost_usd}}}Is();var F=class extends Error{status;code;param;details;retryAfterSec;requestId;constructor(e,n,r,s){super(r),this.name="EvolveApiError",this.status=e,this.code=n,s?.param!==void 0&&(this.param=s.param),s?.details!==void 0&&(this.details=s.details),s?.retryAfterSec!==void 0&&(this.retryAfterSec=s.retryAfterSec),s?.requestId!==void 0&&(this.requestId=s.requestId);}isKnownCode(){return Tn(this.code)}};async function At(t){let e=await t.text().catch(()=>""),n=t.headers?.get?.("x-request-id")??void 0,r=kt(e,t);try{let s=JSON.parse(e);if(s?.error&&typeof s.error=="object"){let o=typeof s.error.code=="string"?s.error.code:"unknown_error",d=typeof s.error.message=="string"?s.error.message:t.statusText;throw new F(t.status,o,d,{param:typeof s.error.param=="string"?s.error.param:void 0,details:s.error.details&&typeof s.error.details=="object"?s.error.details:void 0,retryAfterSec:r,requestId:typeof s.error.requestId=="string"?s.error.requestId:n})}if(typeof s?.error=="string")throw new F(t.status,"unknown_error",s.error,{retryAfterSec:r,requestId:n})}catch(s){if(s instanceof F)throw s}throw new F(t.status,"unknown_error",e||t.statusText,{retryAfterSec:r,requestId:n})}var Ln=class extends Error{dataset;constructor(e){super(`Dataset "${e}" has no active version`),this.name="NoActiveVersionError",this.dataset=e;}},Rt=class extends Error{name="ImportSettleError";code;importId;dataset;version;state;constructor(e,n,r){super(n),this.code=e,this.importId=r.importId,this.dataset=r.dataset,this.version=r.version,this.state=r.state;}},Cp=1e3,Ct=3e4,Rp=new Set(["COMPLETED","CANCELLED","FAILED"]),Ep=new Set(["job.completed","job.cancelled","job.failed"]),Et=2e3,Tp=30*6e4;function de(t,e){let n=e?.apiKey||process.env[O];if(!n)throw new Error(`${t}() requires an API key. Set ${O} or pass { apiKey } in config.`);let r=(e?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,"");return {apiKey:n,baseUrl:r}}async function k(t,e,n){let r=await fetch(`${t.baseUrl}${e}`,{...n,headers:{Authorization:`Bearer ${t.apiKey}`,...n?.headers}});return r.ok||await At(r),r}function On(t){let e=t.indexOf("@");if(e===-1)return {name:t.trim()};let n=t.slice(0,e).trim(),r=t.slice(e+1).trim();if(!n||!r)throw new Error(`Invalid dataset ref "${t}": expected "name" or "name@version"`);return {name:n,version:r}}function Ls(t){return {name:t.name,version:t.version}}function za(t){let e=t.kwargs,n=Array.isArray(t.skills)?t.skills.filter(o=>typeof o=="string"):[],r=Array.isArray(t.skill_locks)?t.skill_locks:null,s=r?r.flatMap(o=>{if(!o||typeof o!="object")return [];let d=o;return typeof d.name!="string"||typeof d.digest!="string"?[]:[{name:d.name,source:typeof d.source=="string"?d.source:"",digest:d.digest,git_url:typeof d.git_url=="string"?d.git_url:null,git_commit_id:typeof d.git_commit_id=="string"?d.git_commit_id:null}]}):null;return {name:t.name,model_name:t.model_name,version:t.version??null,reasoning_effort:t.reasoning_effort??null,kwargs:e&&typeof e=="object"&&!Array.isArray(e)?e:null,preset:typeof t.preset=="string"?t.preset:null,skills:n,skill_locks:s}}function Pp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.name!="string")return null;let n=Array.isArray(e.authors)?e.authors.flatMap(r=>{if(!r||typeof r!="object"||Array.isArray(r))return [];let s=r;return typeof s.name!="string"?[]:[{name:s.name,email:typeof s.email=="string"?s.email:null}]}):[];return {name:e.name,version:typeof e.version=="string"?e.version:null,description:typeof e.description=="string"?e.description:"",authors:n,keywords:Array.isArray(e.keywords)?e.keywords.filter(r=>typeof r=="string"):[],task_count:typeof e.task_count=="number"?e.task_count:null}}function Ap(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,n=s=>typeof e[s]=="string"?e[s]:null;switch(n("kind")??(n("commit")!==null?"git":null)){case "git":{let s=n("ref"),o=n("commit");return s===null||o===null?null:{kind:"git",git_url:n("git_url"),ref:s,commit:o,path:n("path")}}case "archive":{let s=n("digest");return s===null?null:{kind:"archive",digest:s}}case "archive_url":{let s=n("archive_url"),o=n("digest");return s===null||o===null?null:{kind:"archive_url",archive_url:s,digest:o}}case "hub_package":{let s=n("hub_package"),o=n("digest");return s===null||o===null?null:{kind:"hub_package",hub_package:s,digest:o}}default:return null}}function Ge(t){return {version:t.version,state:t.state,created_at:t.created_at,task_count:t.task_count??0,n_failed_tasks:typeof t.n_failed_tasks=="number"?t.n_failed_tasks:0,manifest:Pp(t.manifest),source:Ap(t.source)}}function qa(t){return {code:t.code??"",step:t.step??"",message:t.message??"",excerpt:t.excerpt??null}}function Ip(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object").map(e=>({task_name:e.task_name??"",failure:qa(e.failure??{})})):[]}function Op(t){return {task_name:t.task_name,agent_timeout_sec:t.agent_timeout_sec,verifier_timeout_sec:t.verifier_timeout_sec,gpus:typeof t.gpus=="number"&&t.gpus>0?t.gpus:0,gpu_types:Array.isArray(t.gpu_types)&&t.gpu_types.length>0?t.gpu_types.map(String):null,providers:t.providers,notes:Array.isArray(t.notes)?t.notes:[]}}function Mp(t){return {action:t.action,type:t.type,job_id:t.job_id}}function Dp(t){let e=t&&typeof t=="object"?t:{};return {max_retries:typeof e.max_retries=="number"?e.max_retries:0,include_exceptions:Array.isArray(e.include_exceptions)?e.include_exceptions:null,exclude_exceptions:Array.isArray(e.exclude_exceptions)?e.exclude_exceptions:[],wait_multiplier:typeof e.wait_multiplier=="number"?e.wait_multiplier:1,min_wait_sec:typeof e.min_wait_sec=="number"?e.min_wait_sec:1,max_wait_sec:typeof e.max_wait_sec=="number"?e.max_wait_sec:60}}function Up(t){return {attempt_number:t.attempt_number,exception_info:t.exception_info??{exception_type:"InfrastructureError",exception_message:""},cost_usd:t.cost_usd??null,started_at:t.started_at??null,settled_at:t.settled_at??null}}function Mn(t){return typeof t=="number"?t:null}function Lp(t){return Array.isArray(t)?t.filter(e=>e&&typeof e=="object").map(e=>{let n=typeof e.n_tasks_ran=="number"?e.n_tasks_ran:0;return {dataset:Ls(e.dataset??{}),n_tasks_ran:n,n_tasks_selected:typeof e.n_tasks_selected=="number"?e.n_tasks_selected:n,n_tasks_failed_to_build:typeof e.n_tasks_failed_to_build=="number"?e.n_tasks_failed_to_build:0,failed_task_names:Array.isArray(e.failed_task_names)?e.failed_task_names.map(String):[],note:e.note??""}}):[]}function $p(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.uploaded_at!="string")return null;let n=e.reported_totals,r=o=>typeof o=="number"&&Number.isFinite(o)?o:null,s=n&&typeof n=="object"&&!Array.isArray(n)&&Number.isInteger(n.n_trials_reporting)?{cost_usd:r(n.cost_usd),n_input_tokens:r(n.n_input_tokens),n_cache_tokens:r(n.n_cache_tokens),n_output_tokens:r(n.n_output_tokens),n_trials_reporting:n.n_trials_reporting}:null;return {original_job_id:typeof e.original_job_id=="string"?e.original_job_id:null,original_job_name:typeof e.original_job_name=="string"?e.original_job_name:null,uploaded_at:e.uploaded_at,reported_totals:s,task_links:Ya(e.task_links)}}var Wa=t=>typeof t=="string"&&xn.includes(t),Ms=t=>typeof t=="string"&&Cn.includes(t),Ds=t=>Array.isArray(t)&&t.every(e=>typeof e=="string")?[...t]:null;function Ya(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(typeof r.task_name!="string"||!Wa(r.linked_by)||![r.n_trials,r.n_linked,r.n_unlinked].every(l=>Number.isInteger(l)&&l>=0))return null;let o=Ds(r.datasets),d=Ds(r.candidates);if(o===null||d===null||!r.link_reasons||typeof r.link_reasons!="object"||Array.isArray(r.link_reasons))return null;let u={};for(let[l,i]of Object.entries(r.link_reasons)){if(!Ms(l)||!Number.isInteger(i))return null;u[l]=i;}e.push({task_name:r.task_name,n_trials:r.n_trials,n_linked:r.n_linked,n_unlinked:r.n_unlinked,linked_by:r.linked_by,datasets:o,link_reasons:u,candidates:d});}return e}function Fp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(!Wa(e.linked_by)||e.link_reason!==null&&e.link_reason!==void 0&&!Ms(e.link_reason))return null;let n=e.candidates===void 0?[]:Ds(e.candidates);return n===null?null:{linked_by:e.linked_by,link_reason:Ms(e.link_reason)?e.link_reason:null,dataset:typeof e.dataset=="string"?e.dataset:null,version:typeof e.version=="string"?e.version:null,task_digest:typeof e.task_digest=="string"?e.task_digest:null,candidates:n}}function Z(t){let e=t.trials??{};return {id:t.id,job_name:t.job_name,status:t.status,datasets:(t.datasets??[]).map(Ls),agents:(t.agents??[]).map(za),n_attempts:t.n_attempts,n_concurrent_trials:t.n_concurrent_trials,max_trial_spend_usd:t.max_trial_spend_usd,worst_case_spend_usd:t.worst_case_spend_usd,retry:Dp(t.retry),analyze:t.analyze&&typeof t.analyze=="object"&&!Array.isArray(t.analyze)?t.analyze:null,timeout_multiplier:typeof t.timeout_multiplier=="number"?t.timeout_multiplier:1,agent_timeout_multiplier:Mn(t.agent_timeout_multiplier),verifier_timeout_multiplier:Mn(t.verifier_timeout_multiplier),agent_setup_timeout_multiplier:Mn(t.agent_setup_timeout_multiplier),environment_build_timeout_multiplier:Mn(t.environment_build_timeout_multiplier),sandbox_provider:t.sandbox_provider??null,system_log:t.system_log===true,counts:t.counts,build_exclusions:Lp(t.build_exclusions),n_total_trials:t.n_total_trials??0,trials:{total:e.total??0,byStatus:e.byStatus??{}},stats:t.stats??{},failure:t.failure??null,source_jobs:(t.source_jobs??[]).map(Mp),is_regrade:t.is_regrade===true,upload:$p(t.upload),idempotent_replay:t.idempotent_replay===true,started_at:t.started_at,updated_at:t.updated_at,finished_at:t.finished_at??null}}function $(t,e){let n=t??{};return {items:Array.isArray(n.items)?n.items.map(e):[],nextCursor:n.nextCursor??null,hasMore:n.hasMore===true}}function V(t,e){let n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);for(let[s,o]of Object.entries(e??{}))o!==void 0&&n.set(s,o);let r=n.toString();return r?`?${r}`:""}function pe(t){if(!t||typeof t!="object")return null;let e=t;return {started_at:e.started_at??null,finished_at:e.finished_at??null}}function Bp(t){let e=t.model_info??{};return {name:t.name,version:t.version??null,model_info:{name:e.name,provider:e.provider??null},reasoning_effort:t.reasoning_effort??null}}function $n(t){return !t||typeof t!="object"||Array.isArray(t)?null:{...t,usage:Je(t.usage)}}function Np(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let{from:e,to:n,reason:r}=t;return typeof e!="string"||typeof n!="string"||typeof r!="string"?null:{from:e,to:n,reason:r}}function Us(t){return {id:t.id,job_id:t.job_id,task_name:t.task_name,source:t.source,agent_info:Bp(t.agent_info||{}),attempt:t.attempt,status:t.status,reward:t.reward??null,verifier_result:t.verifier_result??null,exception_info:t.exception_info??null,agent_result:t.agent_result??null,judge_result:t.judge_result??null,analysis:$n(t.analysis),environment_setup:pe(t.environment_setup),agent_setup:pe(t.agent_setup),agent_execution:pe(t.agent_execution),verifier:pe(t.verifier),queue_wait:pe(t.queue_wait),harness_bundle:pe(t.harness_bundle),image_prepare:pe(t.image_prepare),shared_verify_setup:pe(t.shared_verify_setup),harness_bundle_cache_hit:typeof t.harness_bundle_cache_hit=="boolean"?t.harness_bundle_cache_hit:null,step_results:t.step_results??null,spend_source:t.spend_source??null,judge_spend_source:t.judge_spend_source??null,live_spent_usd:t.live_spent_usd??null,live_spend_at:t.live_spend_at??null,usage:Je(t.usage),max_trial_spend_usd:t.max_trial_spend_usd??null,sandbox_provider:t.sandbox_provider??null,sandbox_provider_degrade:Np(t.sandbox_provider_degrade),gpu_cost:t.gpu_cost&&typeof t.gpu_cost=="object"&&!Array.isArray(t.gpu_cost)?t.gpu_cost:null,sandbox_id:t.sandbox_id??null,verifier_sandbox_id:t.verifier_sandbox_id??null,verifier_environment_mode:t.verifier_environment_mode??null,attempt_phase:t.attempt_phase??null,n_retries:t.n_retries??0,retries:Array.isArray(t.retries)?t.retries.map(Up):[],session_ref:t.session_ref??null,upload:jp(t.upload),started_at:t.started_at??null,finished_at:t.finished_at??null}}function jp(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(typeof e.original_trial_name!="string"||typeof e.original_task_name!="string")return null;let n=e.reported_agent_result,r=s=>typeof s=="number"&&Number.isFinite(s)?s:null;return {original_trial_id:typeof e.original_trial_id=="string"?e.original_trial_id:null,original_trial_name:e.original_trial_name,original_task_name:e.original_task_name,reported_agent_result:n&&typeof n=="object"&&!Array.isArray(n)?{n_input_tokens:r(n.n_input_tokens),n_cache_tokens:r(n.n_cache_tokens),n_output_tokens:r(n.n_output_tokens),cost_usd:r(n.cost_usd)}:null,link:Fp(e.link)}}function Dn(t){return {name:t.name,source:t.source,run_command:t.run_command,env:t.env??{},created_at:t.created_at,updated_at:t.updated_at}}function Ve(t){let e={id:t.id,status:t.status,name:t.name,version:t.version,failure:t.failure??null,warnings:t.warnings??[],progress:t.progress??null};return typeof t.receiving=="boolean"&&(e.receiving=t.receiving),typeof t.task_count=="number"&&(e.task_count=t.task_count),typeof t.created_at=="string"&&(e.created_at=t.created_at),typeof t.updated_at=="string"&&(e.updated_at=t.updated_at),e}function xt(t){let e={id:t.id,status:t.status,receiving:t.receiving===true,source:t.source??null,dataset:t.dataset??null,job_id:t.job_id??null,n_trials_uploaded:t.n_trials_uploaded??null,n_trials_skipped:t.n_trials_skipped??null,skipped_trials:Array.isArray(t.skipped_trials)?t.skipped_trials:null,task_links:Ya(t.task_links),failure:t.failure??null,progress:t.progress??null};return typeof t.created_at=="string"&&(e.created_at=t.created_at),typeof t.updated_at=="string"&&(e.updated_at=t.updated_at),e}function Xa(t){let e=t??{};return {scored:e.scored??0,total:e.total??0}}function Jp(t){return {id:t.id,datasets:(t.datasets??[]).map(Ls),status:t.status,mean_reward:t.mean_reward??null,coverage:Xa(t.coverage),cost_usd:t.cost_usd??0,agents:(t.agents||[]).map(za),started_at:t.started_at}}function Kp(t){return {job_id:t.job_id,status:t.status,mean_reward:t.mean_reward??null,coverage:Xa(t.coverage)}}function Gp(t){return {task_name:t.task_name,disagreement:t.disagreement===true,cells:(t.cells||[]).map(Kp)}}function Qa(t){return {seq:t.seq,type:t.type,data:t.data??{}}}function Za(t){return (Array.isArray(t)?t:[]).map((n,r)=>({seq:Rn+r,type:"usage",data:n&&typeof n=="object"&&!Array.isArray(n)?n:{}}))}function Vp(t){return {trial_id:t.trial_id,task_name:t.task_name??null,match_count:t.match_count,events:(t.events||[]).map(Qa)}}function $s(t){return t?t.suffix!==void 0?`bytes=-${t.suffix}`:t.start===void 0?null:`bytes=${t.start}-${t.end??""}`:null}function ge(t){if(t?.aborted)throw t.reason instanceof Error?t.reason:new Error("Watch aborted")}function Ga(t,e){return e?.aborted?true:t?.name==="AbortError"}function j(t,e){return new Promise((n,r)=>{let s=setTimeout(()=>{e?.removeEventListener("abort",o),n();},t),o=()=>{clearTimeout(s),r(e?.reason instanceof Error?e.reason:new Error("Watch aborted"));};e?.addEventListener("abort",o,{once:true});})}function el(t){let e="",n=false;return {push(r){n&&(r="\r"+r,n=false),r.endsWith("\r")&&(r=r.slice(0,-1),n=true),e+=r.replace(/\r\n|\r/g,`
|
|
664
664
|
`);let s;for(;(s=e.indexOf(`
|
|
665
665
|
|
|
666
666
|
`))!==-1;){let o=e.slice(0,s);e=e.slice(s+2);let d,u,l=[];for(let i of o.split(`
|
|
667
667
|
`)){if(!i||i.startsWith(":"))continue;let a=i.indexOf(":"),c=a===-1?i:i.slice(0,a),p=a===-1?"":i.slice(a+1);p.startsWith(" ")&&(p=p.slice(1)),c==="id"?d=p:c==="event"?u=p:c==="data"&&l.push(p);}(d!==void 0||u!==void 0||l.length>0)&&t({id:d,event:u,data:l.join(`
|
|
668
|
-
`)});}}}}function ee(t,e){let n,r=()=>n??=t({limit:e?.limit,cursor:e?.cursor});return {then(s,o){return r().then(s,o)},catch(s){return r().catch(s)},finally(s){return r().finally(s)},async*[Symbol.asyncIterator](){let s=e?.cursor;for(;;){let o=await t({limit:e?.limit,cursor:s});for(let d of o.items)yield d;if(!o.nextCursor)return;s=o.nextCursor;}}}}function _e(t){let e=new FormData;for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,r);return e}async function Op(t){let{readFileSync:e,readdirSync:n,statSync:r}=await import('fs'),{basename:s,join:o,resolve:d}=await import('path'),u=d(t),l=g=>r(g,{throwIfNoEntry:false})?.isFile()===true,i=g=>r(g,{throwIfNoEntry:false})?.isDirectory()===true;if(!i(u))throw new Error(`datasets().preflight(): not a directory: ${u}`);let a=[],c=u;if(l(o(u,"task.toml"))){let g=n(u,{withFileTypes:true}).filter(f=>f.isDirectory()&&!f.name.startsWith(".")).filter(f=>l(o(u,f.name,"task.toml"))).map(f=>f.name);if(i(o(u,"tasks"))||g.length>0)throw new Error(`${u} is ambiguous: it carries task.toml at its root (a single-task shape) AND corpus-shaped content \u2014 the import refuses this too; point at the one task directory or at a corpus of task directories, not a mix`);a.push({name:s(u),dir:u});}else {c=i(o(u,"tasks"))?o(u,"tasks"):u;for(let g of n(c,{withFileTypes:true})){if(!g.isDirectory()||g.name.startsWith("."))continue;let f=o(c,g.name);if(!l(o(f,"task.toml")))throw new Error(`${f} has no task.toml \u2014 every directory of a corpus must be a task directory (the import fails on it rather than skipping it)`);a.push({name:g.name,dir:f});}if(a.length===0)throw new Error(`${c} holds no task directories \u2014 nothing to check`);a.sort((g,f)=>g.name<f.name?-1:g.name>f.name?1:0);}let p=(c===u?[u]:[c,u]).map(g=>o(g,"dataset.toml")).find(l);return {tasks:a.map(({name:g,dir:f})=>({name:g,task_toml:e(o(f,"task.toml"),"utf8")})),...p!==void 0?{dataset_toml:e(p,"utf8")}:{}}}async function Mp(t,e,n){let{postMultipartFile:r}=await Promise.resolve().then(()=>(xs(),Ua)),s=await r({url:`${t.baseUrl}${e}`,method:n.method??"POST",headers:{Authorization:`Bearer ${t.apiKey}`},fields:n.fields,file:n.file,...n.onBytes!==void 0?{onBytes:n.onBytes}:{}});return s.ok||await Pt(s),s}async function Ga(t,e,n,r){if(r.resumableThreshold!==void 0){let{stat:s}=await import('fs/promises'),{size:o}=await s(n);if(o>r.resumableThreshold){let{uploadArchiveResumable:d}=await Promise.resolve().then(()=>(ms(),Ta)),u=await d({baseUrl:t.baseUrl,headers:{Authorization:`Bearer ${t.apiKey}`},file:{path:n},fields:r.fields,...r.resumablePath!==void 0?{sessionsPath:r.resumablePath}:{},...r.onBytes!==void 0?{onBytes:r.onBytes}:{},...r.onRegistered!==void 0?{onRegistered:r.onRegistered}:{}});return u.ok||await Pt(u),u}}return await Mp(t,e,{method:r.method,fields:r.fields,file:{path:n,filename:r.filename},...r.onBytes!==void 0?{onBytes:r.onBytes}:{}})}async function Ge(t,e,n){let{tarGzipDirectoryToFile:r}=await Promise.resolve().then(()=>(gr(),pr)),{mkdtemp:s,rm:o}=await import('fs/promises'),{tmpdir:d}=await import('os'),{join:u}=await import('path'),l=await s(u(d(),"evolve-upload-"));try{let i=u(l,n.filename);return await r(n.directory,i),await Ga(t,e,i,n)}finally{await o(l,{recursive:true,force:true});}}function Dp(t){let e,n=()=>(e||(e=(async()=>{let r=await t.next();for(;!r.done;)r=await t.next();return r.value})()),e);return {then(r,s){return n().then(r,s)},catch(r){return n().catch(r)},finally(r){return n().finally(r)},[Symbol.asyncIterator](){return t}}}var za="x-package-sha256",Tt=class extends Error{constructor(n,r){super(`downloaded bytes do not match the digest the server stated (expected ${n}, got ${r})`);this.expected=n;this.actual=r;}name="EvolveDigestMismatchError"},Et=class extends Error{constructor(n,r){super(`download ended early: the server declared ${n} bytes and ${r} arrived`);this.expectedBytes=n;this.receivedBytes=r;}name="EvolveIncompleteDownloadError"};function Ha(t,e){let n=t.headers.get("Content-Length");if(n===null)return;let r=Number(n);if(Number.isFinite(r)&&e!==r)throw new Et(r,e)}async function qa(t,e){let n=t.headers.get(za);if(!n)return;let{createHash:r}=await import('crypto'),s=r("sha256").update(e).digest("hex");if(s!==n)throw new Tt(n,s)}function Up(t,e){let r=(t.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/);if(!r)return e;let s=X.basename(r[1]);return s===""||s==="."||s===".."||/[/\\]/.test(s)||/[\u0000-\u001f]/.test(s)?e:s}async function Wa(t,e,n){if(!t.body)throw new Error("Download response has no body");await promises.mkdir(e,{recursive:true});let r=X.join(e,Up(t,n)),{createHash:s,randomBytes:o}=await import('crypto'),d=`${r}.${o(8).toString("hex")}.part`,u=s("sha256"),l=0,i=stream.Readable.fromWeb(t.body);i.on("data",a=>{u.update(a),l+=a.length;});try{await promises$1.pipeline(i,Q.createWriteStream(d));let a=t.headers.get("Content-Length");if(a!==null&&l!==Number(a))throw new Et(Number(a),l);let c=t.headers.get(za),p=u.digest("hex");if(c&&p!==c)throw new Tt(c,p);await promises.rename(d,r);}catch(a){throw await promises.rm(d,{force:true}).catch(()=>{}),a}return r}async function Is(t,e,n,r){let s=await v(t,e);if(n?.stream){if(!s.body)throw new Error("Download response has no body");return s.body}if(n?.to)return Wa(s,n.to,r);let o=Buffer.from(await s.arrayBuffer());return Ha(s,o.length),await qa(s,o),o}function Ya(t){let e=de("datasets",t);async function n(i){let a=await v(e,`/api/datasets/imports/${encodeURIComponent(i)}`);return Ve(await a.json())}function r(i){if(!i||typeof i!="object")return null;let a=i;return {git_url:a.git_url??null,ref:a.ref,current_commit:a.current_commit,path:a.path??null,latest_commit:a.latest_commit??null,acked_commit:a.acked_commit??null,moved:a.moved===true,behind_by:typeof a.behind_by=="number"?a.behind_by:null,checked_at:a.checked_at??null,error:a.error??null,auto_import:a.auto_import===true}}function s(i){return {name:i.name,title:i.title??null,description:i.description??null,active_version:i.active_version?Ke(i.active_version):null,latest_version:i.latest_version?Ke(i.latest_version):null,versions:(i.versions||[]).map(Ke),selected_version:i.selected_version?Ke(i.selected_version):null,tasks:L(i.tasks,hp),failed_tasks:mp(i.failed_tasks),upstream:r(i.upstream),created_at:i.created_at,updated_at:i.updated_at}}async function o(i,a){let c=Cs(i),p=G(a,{version:c.version}),g=await v(e,`/api/datasets/${encodeURIComponent(c.name)}${p}`);return s(await g.json())}async function d(i,a){let c=a?.pollIntervalMs??Rt,p=a?.settleTimeoutMs??pp,g=Date.now()+p,f=`${i.name}@${i.version}`,m=null,h=null,y=()=>h?.state==="FAILED"?new Ct("settle_timeout",`Import ${i.id}'s dataset "${i.name}" version "${i.version}" settled FAILED, but the final import read kept answering rate-limited/unavailable past the ${p}ms settle budget. Read the failure with datasets().getImport("${i.id}").`,{importId:i.id,dataset:i.name,version:i.version,state:h.state}):new Ct("settle_timeout",`Import ${i.id} completed, but dataset "${i.name}" version "${i.version}" did not settle within ${p}ms: last observed state ${h?.state??"never observed"}. Keep following with datasets().get("${f}").`,{importId:i.id,dataset:i.name,version:i.version,state:h?.state??null}),b=async _=>{for(;;){ge(a?.signal);try{return await _()}catch(w){if(!(w instanceof B)||w.status!==429&&w.status!==503)throw w;let S=g-Date.now();if(S<=0)throw y();await F(Math.min(Math.max((w.retryAfterSec??0)*1e3,c),S),a?.signal);}}};for(;;){ge(a?.signal);let _=await b(()=>o(f,{limit:1})),w=_.selected_version;if(w){if(h=w,w.state!==m&&(m=w.state,a?.onVersion?.(w,_)),w.state==="FAILED")return b(()=>n(i.id));if(w.state==="READY"||w.state==="ARCHIVED")return i}if(Date.now()>=g)throw y();await F(c,a?.signal);}}function u(i){return {name:i.name,title:i.title??null,description:i.description??null,active_version:i.active_version?Ke(i.active_version):null,latest_version:i.latest_version?Ke(i.latest_version):null,upstream:r(i.upstream)}}async function l(i){let a=await v(e,`/api/datasets${G(i,{search:i?.search})}`);return L(await a.json(),u)}return {list(i){return ee(a=>l({...a,search:i?.search}),i)},get:o,async getActive(i,a){let c=await o(i,a);if(c.active_version===null)throw new Mn(i);return {name:c.name,title:c.title,description:c.description,active_version:c.active_version,version:c.active_version.version,tasks:c.tasks??{items:[],nextCursor:null,hasMore:false},versions:c.versions??[],created_at:c.created_at,updated_at:c.updated_at}},async getTaskBuild(i,a){let c=Cs(i);if(c.version===void 0)throw new Error(`datasets().getTaskBuild() needs "name@version" \u2014 a task's build outcome belongs to one immutable version (got "${i}")`);let g=await(await v(e,`/api/datasets/${encodeURIComponent(c.name)}/versions/${encodeURIComponent(c.version)}/tasks/${encodeURIComponent(a)}/build`)).json();return {task_name:g.task_name??a,state:g.state,failure:g.failure&&typeof g.failure=="object"?Na(g.failure):null,build_log_ref:g.build_log_ref??null}},async preflight(i){let a=i?.source?.directory;if(typeof a!="string"||a==="")throw new Error("datasets().preflight() requires { source: { directory } } \u2014 a local corpus directory whose task.toml files are checked server-side before any upload");let c=await Op(a);return await(await v(e,"/api/datasets/preflight",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()},async publish(i,a){let c=i.source;if(c?.directory){if(i.name===void 0||i.version===void 0){let{existsSync:g}=await import('fs'),{join:f}=await import('path');if(!(g(f(c.directory,"dataset.toml"))||g(f(c.directory,"tasks","dataset.toml"))))throw new Error(`datasets().publish() needs ${i.name===void 0?"a name":"a version"} \u2014 pass it explicitly, or add a dataset.toml manifest to the corpus directory (the server then derives name and version from it)`)}let p=await Ge(e,"/api/datasets/publish",{fields:{name:i.name,version:i.version},directory:c.directory,filename:"corpus.tar.gz",...a?.onUploadProgress!==void 0?{onBytes:a.onUploadProgress}:{},...a?.onRegistered!==void 0?{onRegistered:a.onRegistered}:{},resumableThreshold:vt});return Ve(await p.json())}if(c&&"archive_url"in c&&c.archive_url){if(i.name===void 0||i.version===void 0)throw new Error("datasets().publish() requires name and version for an archive_url source \u2014 the server fetches the tarball only after the publish is accepted, so a manifest cannot supply them");let p=await v(e,"/api/datasets/publish",{method:"POST",body:_e({name:i.name,version:i.version,archive_url:c.archive_url})});return Ve(await p.json())}if(c&&"hub_package"in c&&c.hub_package){let p=await v(e,"/api/datasets/publish",{method:"POST",body:_e({...i.name!==void 0?{name:i.name}:{},...i.version!==void 0?{version:i.version}:{},hub_package:c.hub_package})});return Ve(await p.json())}if(c&&"git_url"in c&&c.git_url){if(i.name===void 0||i.version===void 0)throw new Error("datasets().publish() requires name and version for a git source \u2014 a dataset.toml manifest can only supply them for a directory source, because a git repository is cloned server-side after the publish is accepted");let p=await v(e,"/api/datasets/publish",{method:"POST",body:_e({name:i.name,version:i.version,git_url:c.git_url,git_ref:c.git_ref,...c.git_path!==void 0?{git_path:c.git_path}:{}})});return Ve(await p.json())}throw new Error("datasets().publish() requires a source: a git source ({ source: { git_url, git_ref } }), a local corpus directory ({ source: { directory } }), a public tarball url ({ source: { archive_url } }), or a Harbor hub package ({ source: { hub_package } }); plus name and version (optional for a directory whose corpus carries a dataset.toml manifest, and for a hub package, which supplies its own defaults)")},getImport:n,async watchImport(i,a){let c=a?.pollIntervalMs??Rt,p=null,g=null;for(;;){ge(a?.signal);let f;try{f=await n(i);}catch(h){if(h instanceof B&&(h.status===429||h.status===503)){await F(Math.max((h.retryAfterSec??0)*1e3,c),a?.signal);continue}throw h}let m=`${f.status}${f.receiving===true?":receiving":""}`;if(m!==p&&(p=m,a?.onStatus?.(f)),f.progress!==null){let h=JSON.stringify(f.progress);h!==g&&(g=h,a?.onProgress?.(f.progress,f));}if(f.status==="FAILED")return f;if(f.status==="COMPLETED")return d(f,a);await F(c,a?.signal);}},download:(async(i,a)=>{let c=Cs(i),p=c.version?`?version=${encodeURIComponent(c.version)}`:"",g=await v(e,`/api/datasets/${encodeURIComponent(c.name)}/download${p}`);if(a?.stream){if(!g.body)throw new Error("Package response has no body");return g.body}if(a?.to)return Wa(g,a.to,`${c.name}-corpus.tar.gz`);let f=Buffer.from(await g.arrayBuffer());return Ha(g,f.length),await qa(g,f),f}),listImports(i){return ee(async a=>{let c=new URLSearchParams;a.limit!==void 0&&c.set("limit",String(a.limit)),a.cursor!==void 0&&c.set("cursor",a.cursor),i?.status!==void 0&&c.set("status",i.status),i?.dataset!==void 0&&c.set("dataset",i.dataset);let p=c.toString()?`?${c}`:"",g=await v(e,`/api/datasets/imports${p}`);return L(await g.json(),Ve)},i)},async activate(i,a){let c=await v(e,`/api/datasets/${encodeURIComponent(i)}/versions/${encodeURIComponent(a)}/activate`,{method:"POST"});return s(await c.json())},async update(i,a){let c=await v(e,`/api/datasets/${encodeURIComponent(i)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});return u(await c.json())},async delete(i){await v(e,`/api/datasets/${encodeURIComponent(i)}`,{method:"DELETE"});}}}function Xa(t){let e=de("agents",t);return {async create(n){let r=La("agents().create()",n),s=r.directory?await Ge(e,"/api/agents",{fields:r.fields,directory:r.directory,filename:"source.tar.gz"}):await v(e,"/api/agents",{method:"POST",body:_e(r.fields)});return In(await s.json())},list(n){return ee(async r=>{let s=await v(e,`/api/agents${G(r)}`);return L(await s.json(),In)},n)},async get(n){let r=await v(e,`/api/agents/${encodeURIComponent(n)}`);return In(await r.json())},async delete(n){await v(e,`/api/agents/${encodeURIComponent(n)}`,{method:"DELETE"});},async upsert(n,r){let s=La("agents().upsert()",{...r,name:n}),o=s.directory?await Ge(e,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",fields:s.fields,directory:s.directory,filename:"source.tar.gz"}):await v(e,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",body:_e(s.fields)});return In(await o.json())}}}function La(t,e){let n=typeof e.install_script=="string",r=typeof e.directory=="string";if(n&&r)throw new Error(`${t} takes EITHER an install script ({ install_script }) or a local directory ({ directory }), not both`);if(!n&&!r)throw new Error(`${t} requires either an install script ({ install_script }) or a local directory ({ directory }), plus run_command`);let s={name:e.name,run_command:e.run_command,...e.env!==void 0?{env:JSON.stringify(e.env)}:{},...n?{install_script:e.install_script}:{}};return r?{fields:s,directory:e.directory}:{fields:s}}function Rs(t){return {id:t.id,name:t.name,digest:t.digest,size_bytes:t.size_bytes??0,description:t.description??null,ref:t.ref??`upload:${t.id}`,created_at:t.created_at}}function Qa(t){let e=de("skills",t);return {async upload(n){if(typeof n!="string"||!n.trim())throw new Error("skills().upload() requires a local skill directory path");let{basename:r,resolve:s}=await import('path'),o=r(s(n)),u=await(await Ge(e,"/api/skills",{fields:{name:o||void 0},directory:n,filename:"skill.tar.gz"})).json();return (Array.isArray(u.skills)?u.skills:[u]).map(Rs)},list(n){return ee(async r=>{let s=await v(e,`/api/skills${G(r)}`);return L(await s.json(),Rs)},n)},async get(n){let s=await(await v(e,`/api/skills/${encodeURIComponent(n)}`)).json();return {...Rs(s),skill_md:s.skill_md??null}},async delete(n){await v(e,`/api/skills/${encodeURIComponent(n)}`,{method:"DELETE"});}}}function Za(t){let e=de("jobs",t);async function n(l){let i=await v(e,`/api/jobs/${encodeURIComponent(l)}`);return Z(await i.json())}async function r(l){let i=await v(e,`/api/jobs/imports/${encodeURIComponent(l)}`);return St(await i.json())}async function s(l){let i=await v(e,`/api/jobs${G(l,{search:l?.search,scope:l?.scope})}`);return L(await i.json(),Z)}function o(l){let i=l.trials??{};return {task_name:l.task_name,source:l.source,trials:{total:i.total??0,byStatus:i.byStatus??{}},mean_reward:l.mean_reward??null,cost_usd:l.cost_usd??null,check:l.check&&typeof l.check=="object"&&!Array.isArray(l.check)?l.check:null}}async function d(l,i){let a=G(i,{status:i?.status?.length?i.status.join(","):void 0,dataset:i?.dataset}),c=await v(e,`/api/jobs/${encodeURIComponent(l)}/trials${a}`);return L(await c.json(),Ps)}async function*u(l,i){let{onEvent:a,signal:c}=i??{},p=i?.reconnectDelayMs??cp,g=i?.maxReconnectDelayMs??xt,f=null,m=false,h=false,y=p;for(;!m;){ge(c);let b;try{b=await fetch(`${e.baseUrl}/api/jobs/${encodeURIComponent(l)}/events`,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"text/event-stream",...f!==null?{"Last-Event-ID":String(f)}:{}},signal:c});}catch(T){if($a(T,c))throw T;await F(y,c),y=Math.min(y*2,g);continue}if(!b.ok){if(b.status===429||b.status>=500){let T=await b.text().catch(()=>""),P=wt(T,b)??0,I=P>0?Math.max(P*1e3,y):y;await F(I,c),y=Math.min(y*2,g);continue}await Pt(b);}if(!b.body)throw new Error("Event stream response has no body");let _=false,w=[],S=Ip(T=>{let P=Number(T.id),I={seq:Number.isInteger(P)?P:-1,type:T.event||"message",data:T.data?Bp(T.data):{}};Number.isInteger(P)&&(f=P),_=true,up.has(I.type)&&(m=true),w.push(I);}),k=b.body.getReader(),x=new TextDecoder;try{for(;!m;){let{done:T,value:P}=await k.read();if(T)break;S.push(x.decode(P,{stream:!0}));for(let I of w)a?.(I),yield I;w.length=0;}}catch(T){if($a(T,c))throw T}finally{await k.cancel().catch(()=>{});}if(m)break;ge(c);let R=await n(l);if(dp.has(R.status)){if(h)return R;h=true;continue}_&&(y=p),await F(y,c),y=Math.min(y*2,g);}return n(l)}return {async start(l,i){let a=await v(e,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...i?.idempotencyKey?{"Idempotency-Key":i.idempotencyKey}:{}},body:JSON.stringify(l)});return Z(await a.json())},get:n,list(l){return ee(i=>s({...i,search:l?.search,scope:l?.scope}),l)},trials(l,i){return ee(a=>d(l,{...a,status:i?.status,dataset:i?.dataset}),i)},tasks(l,i){return ee(async a=>{let c=await v(e,`/api/jobs/${encodeURIComponent(l)}/tasks${G(a)}`);return L(await c.json(),o)},i)},watch(l,i){return Dp(u(l,i))},async cancel(l){let i=await v(e,`/api/jobs/${encodeURIComponent(l)}/cancel`,{method:"POST"});return Z(await i.json())},async compare(l){let i=l.map(encodeURIComponent).join(","),c=await(await v(e,`/api/jobs/compare?ids=${i}`)).json();return {jobs:(c.jobs||[]).map(Rp),taskMatrix:(c.taskMatrix||[]).map(Ep)}},async resume(l,i,a){let c=await v(e,`/api/jobs/${encodeURIComponent(l)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...a?.idempotencyKey?{"Idempotency-Key":a.idempotencyKey}:{}},body:JSON.stringify(i??{})});return Z(await c.json())},async retry(l,i,a){let c=await v(e,`/api/jobs/${encodeURIComponent(l)}/retry`,{method:"POST",headers:{"Content-Type":"application/json",...a?.idempotencyKey?{"Idempotency-Key":a.idempotencyKey}:{}},body:JSON.stringify(i??{})});return Z(await c.json())},async regrade(l,i){let a={};i?.statuses?.length&&(a.statuses=i.statuses),i?.task_name!==void 0&&(a.task_name=i.task_name);let c=await v(e,`/api/jobs/${encodeURIComponent(l)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});return Z(await c.json())},async analyze(l,i){let a=await v(e,`/api/jobs/${encodeURIComponent(l)}/analyze`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i??{})});return Z(await a.json())},async watchAnalysis(l,i){let a=i?.pollIntervalMs??Rt,c=a,p=null;for(;;){ge(i?.signal);let g;try{g=await n(l);}catch(y){if(y instanceof B&&(y.status===429||y.status===503)){await F(Math.max((y.retryAfterSec??0)*1e3,c),i?.signal),c=Math.min(c*2,xt);continue}throw y}let f=g.stats.analysis??null,m=f?JSON.stringify([f.n_completed,f.n_failed,f.n_pending]):null,h=m!==null&&m!==p;if(h&&(p=m,i?.onStats?.(g)),f?.n_pending===0)return g;c=h?a:Math.min(c*2,xt),await F(c,i?.signal);}},download:(async(l,i)=>Is(e,`/api/jobs/${encodeURIComponent(l)}/download`,i,`job-${l}-results.tar.gz`)),async upload(l,i){let a={dataset:i?.dataset};if(typeof l=="object"&&l!==null){if(typeof l.archive_url!="string"||!l.archive_url.trim())throw new Error("jobs().upload() with a URL source requires { archive_url: 'https://\u2026' }");let _=await v(e,"/api/jobs/upload",{method:"POST",body:_e({...a,archive_url:l.archive_url})});return St(await _.json())}if(typeof l!="string"||!l.trim())throw new Error("jobs().upload() requires a job directory (or .tar.gz archive) path, or { archive_url }");let c={fields:a,filename:"job.tar.gz",resumableThreshold:vt,resumablePath:"/api/jobs/upload/uploads",...i?.onUploadProgress!==void 0?{onBytes:i.onUploadProgress}:{},...i?.onRegistered!==void 0?{onRegistered:i.onRegistered}:{}},{stat:p}=await import('fs/promises');if((await p(l).catch(()=>null))?.isFile()){let _=await Ga(e,"/api/jobs/upload",l,c);return St(await _.json())}let{existsSync:f}=await import('fs'),{join:m,resolve:h}=await import('path'),y=h(l);for(let _ of ["result.json","config.json"])if(!f(m(y,_)))throw new Error(`${y} does not contain ${_}`);let b=await Ge(e,"/api/jobs/upload",{...c,directory:y});return St(await b.json())},getImport:r,async watchImport(l,i){let a=i?.pollIntervalMs??Rt,c=null,p=null;for(;;){ge(i?.signal);let g;try{g=await r(l);}catch(m){if(m instanceof B&&(m.status===429||m.status===503)){await F(Math.max((m.retryAfterSec??0)*1e3,a),i?.signal);continue}throw m}let f=`${g.status}${g.receiving?":receiving":""}`;if(f!==c&&(c=f,i?.onStatus?.(g)),g.progress!==null){let m=JSON.stringify(g.progress);m!==p&&(p=m,i?.onProgress?.(g.progress,g));}if(g.status==="COMPLETED"||g.status==="FAILED")return g;await F(a,i?.signal);}},listImports(l){return ee(async i=>{let a=new URLSearchParams;i.limit!==void 0&&a.set("limit",String(i.limit)),i.cursor!==void 0&&a.set("cursor",i.cursor),l?.status!==void 0&&a.set("status",l.status);let c=a.toString()?`?${a}`:"",p=await v(e,`/api/jobs/imports${c}`);return L(await p.json(),St)},l)},async delete(l){let a=await(await v(e,`/api/jobs/${encodeURIComponent(l)}`,{method:"DELETE"})).json();return {job_id:a.job_id??l,trials_deleted:a.trials_deleted??0,analyses_deleted:a.analyses_deleted??0}},async grep(l,i,a){let c=await v(e,`/api/jobs/${encodeURIComponent(l)}/grep${G(a,{q:i,type:a?.type})}`);return L(await c.json(),Pp)}}}function el(t){let e=de("trials",t);async function n(s,o){let d=await v(e,`/api/trials/${encodeURIComponent(s)}/trace${G(o,{type:o?.type,grep:o?.grep,tail:o?.tail!==void 0?String(o.tail):void 0})}`);return L(await d.json(),Ka)}async function r(s,o){let u=await(await v(e,`/api/trials/${encodeURIComponent(s)}/trace?stream=${o}`)).json();return o==="agent-home"?u.files??null:u.log??null}return {async get(s){let o=await v(e,`/api/trials/${encodeURIComponent(s)}`);return Ps(await o.json())},trace:n,artifact:r,async*traceEvents(s,o){let d=o?.cursor;for(;;){let u=await n(s,{...o,cursor:d});for(let l of u.items)yield l;if(!u.nextCursor)return;d=u.nextCursor;}},async regrade(s){let o=await v(e,`/api/trials/${encodeURIComponent(s)}/regrade`,{method:"POST"});return Z(await o.json())},async retry(s,o){let d=await v(e,`/api/trials/${encodeURIComponent(s)}/retry`,{method:"POST",...o?.idempotencyKey?{headers:{"Idempotency-Key":o.idempotencyKey}}:{}});return Z(await d.json())},async stop(s){let d=await(await v(e,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:s})})).json();return {stopped:(d.stopped??[]).map(Ps),stopped_analyses:(d.stopped_analyses??[]).map(Dn).filter(u=>u!==null),already_terminal:d.already_terminal??[],not_found:d.not_found??[]}},async files(s,o){let d=await v(e,`/api/trials/${encodeURIComponent(s)}/files${G(o)}`);return L(await d.json(),u=>({path:u.path,size_bytes:u.size_bytes}))},async file(s,o,d){let u=o.split("/").filter(Boolean).map(encodeURIComponent).join("/"),l=Ap(d),i=await v(e,`/api/trials/${encodeURIComponent(s)}/files/${u}`,l?{headers:{Range:l}}:void 0);return Buffer.from(await i.arrayBuffer())}}}function tl(t){let e=t?.update;return typeof e?.sessionUpdate=="string"?e.sessionUpdate:"unknown"}function nl(t){let e=de("analyses",t),n=new Set;async function r(d){if(n.has(d))return;let u;try{u=await v(e,`/api/traces/trials/${encodeURIComponent(d)}/artifacts?what=analysis`);}catch(l){throw l instanceof B&&l.status===400?new Error(`"${d}" is not an analysis run (the artifacts door refuses it typed) \u2014 for a trial's artifacts use trials()`):l}await u.text().catch(()=>{}),n.add(d);}async function s(d,u){await r(d);let i=await(await v(e,`/api/traces/trials/${encodeURIComponent(d)}/artifacts?what=${u}`)).json();return u==="agent-home"?i.files??null:i.log??null}async function o(d){let u=await v(e,`/api/analyses${G(d,{scope:d?.scope,job:d?.job,status:d?.status&&d.status.length>0?d.status.join(","):void 0})}`);return L(await u.json(),l=>{let i=Dn(l);if(i===null)throw new Error("The analyses list served an unreadable analysis object");return i})}return {list(d){return ee(u=>o({...u,scope:d?.scope,job:d?.job,status:d?.status}),d)},async get(d){let l=await(await v(e,`/api/traces/trials/${encodeURIComponent(d)}/artifacts?what=analysis`)).json(),i=Dn(l.analysis);if(i===null)throw new Error(`The analysis feed served no readable verdict object for "${d}"`);return n.add(d),i},async transcript(d,u){let l=u?.since;if(l!==void 0&&(!Number.isInteger(l)||l<0))throw new Error(`transcript() since must be a non-negative integer, got ${l}`);let a=await(await v(e,`/api/traces/trials/${encodeURIComponent(d)}/events`+(l!==void 0?`?since=${l}`:""))).json(),c=a.session??{};if(c.kind!=="analysis"){let f=typeof c.kind=="string"?c.kind:"trial";throw new Error(`"${d}" is not an analysis run (the feed resolves it as a ${f}) \u2014 for a trial's trace use trials()`)}let p=l??0,g=Array.isArray(a.events)?a.events:[];return {id:typeof c.id=="string"?c.id:d,analyzed_trial_id:typeof c.analyzedTrialId=="string"?c.analyzedTrialId:null,job_id:typeof c.jobId=="string"?c.jobId:null,task_name:typeof c.tag=="string"?c.tag:null,model_name:typeof c.model=="string"?c.model:null,sandbox_provider:typeof c.provider=="string"?c.provider:null,sandbox_id:typeof c.sandboxId=="string"?c.sandboxId:null,is_ended:c.isEnded===true,total:typeof a.total=="number"?a.total:p+g.length,events:g.map((f,m)=>({seq:p+m,type:tl(f),data:f&&typeof f=="object"&&!Array.isArray(f)?f:{}})),gateway_calls:Va(a.gatewayCalls),stored_at:_t(a.storedAt,g.length,"Analysis transcript response")}},artifact:s,download:(async(d,u)=>Is(e,`/api/analyses/${encodeURIComponent(d)}/download`,u,`analysis-${d}.tar.gz`))}}function On(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("The checks surface served an unreadable check object");let e=t,n=Array.isArray(e.results)?e.results.filter(r=>!!r&&typeof r=="object"&&!Array.isArray(r)):[];return {...e,results:n}}function rl(t){let e=de("checks",t);async function n(u){let l=await v(e,`/api/checks/${encodeURIComponent(u)}`);return On(await l.json())}async function r(u){let l=await v(e,`/api/checks${G(u,{scope:u?.scope,status:u?.status&&u.status.length>0?u.status.join(","):void 0})}`);return L(await l.json(),On)}let s=new Set;async function o(u){let l;try{l=await v(e,`/api/traces/trials/${encodeURIComponent(u)}/artifacts?what=task-check`);}catch(c){throw c instanceof B&&c.status===400?new Error(`"${u}" is not a task check (the artifacts door refuses it typed) \u2014 for a trial's artifacts use trials(), for an analysis's use analyses()`):c}let a=(await l.json()).task_check;if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`The traces feed served no readable task check for "${u}"`);return s.add(u),a}async function d(u,l){s.has(u)||await o(u);let a=await(await v(e,`/api/traces/trials/${encodeURIComponent(u)}/artifacts?what=${l}`)).json();return l==="agent-home"?a.files??null:a.log??null}return {async create(u){let{source:l,onUploadProgress:i,...a}=u,c={config:JSON.stringify(a)};if("dataset"in l){if(typeof l.dataset!="string"||l.dataset.trim()==="")throw new Error('checks().create(): source.dataset must be "name" or "name@version"');let b=await v(e,"/api/checks",{method:"POST",body:_e({...c,dataset:l.dataset.trim()})});return On(await b.json())}let{existsSync:p,statSync:g}=await import('fs'),{basename:f,resolve:m}=await import('path'),h=m(l.directory);if(!p(h)||!g(h).isDirectory())throw new Error(`checks().create(): Path '${l.directory}' does not exist or is not a directory`);let y=await Ge(e,"/api/checks",{directory:h,fields:c,filename:`${f(h)||"task"}.tar.gz`,...i!==void 0?{onBytes:i}:{}});return On(await y.json())},get:n,list(u){return ee(l=>r({...l,scope:u?.scope,status:u?.status}),u)},task:o,async transcript(u,l){let i=l?.since;if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new Error(`transcript() since must be a non-negative integer, got ${i}`);let c=await(await v(e,`/api/traces/trials/${encodeURIComponent(u)}/events`+(i!==void 0?`?since=${i}`:""))).json(),p=c.session??{};if(p.kind!=="check"){let m=typeof p.kind=="string"?p.kind:"trial";throw new Error(`"${u}" is not a task check (the feed resolves it as a ${m}) \u2014 for a trial's trace use trials(), for an analysis's use analyses()`)}let g=i??0,f=Array.isArray(c.events)?c.events:[];return {id:typeof p.id=="string"?p.id:u,check_id:typeof p.checkId=="string"?p.checkId:null,dataset:typeof p.datasetRef=="string"?p.datasetRef:null,task_name:typeof p.tag=="string"?p.tag:null,model_name:typeof p.model=="string"?p.model:null,sandbox_provider:typeof p.provider=="string"?p.provider:null,sandbox_id:typeof p.sandboxId=="string"?p.sandboxId:null,is_ended:p.isEnded===true,total:typeof c.total=="number"?c.total:g+f.length,events:f.map((m,h)=>({seq:g+h,type:tl(m),data:m&&typeof m=="object"&&!Array.isArray(m)?m:{}})),gateway_calls:Va(c.gatewayCalls),stored_at:_t(c.storedAt,f.length,"Task check transcript response")}},artifact:d,download:(async(u,l)=>Is(e,`/api/checks/${encodeURIComponent(u)}/download`,l,`check-${u}.tar.gz`)),async watch(u,l){let i=l?.pollIntervalMs??Rt,a=i,c=null;for(;;){ge(l?.signal);let p;try{p=await n(u);}catch(m){if(m instanceof B&&(m.status===429||m.status===503)){await F(Math.max((m.retryAfterSec??0)*1e3,a),l?.signal),a=Math.min(a*2,xt);continue}throw m}let g=JSON.stringify(p.results.map(m=>[m.task_name,m.status])),f=g!==c;if(f&&(c=g,l?.onProgress?.(p)),p.status==="completed")return p;a=f?i:Math.min(a*2,xt),await F(a,l?.signal);}}}}function $p(t){let e=de("auth",t);return {async status(){let r=await(await v(e,"/api/auth/status")).json(),s=r.key??{};return {user_id:r.user_id,email:r.email??null,key:{id:s.id,label:s.label??null,created_at:s.created_at,last_used_at:s.last_used_at??null}}}}}function sl(t){return {org_id:t.org_id,slug:t.slug,display_name:t.display_name,personal:t.personal===true,...t.role==="owner"||t.role==="member"?{role:t.role}:{},created_at:t.created_at}}function Lp(t){let e=t.quota??{},n=t.usage??{},r=s=>typeof s=="number"?s:0;return {...sl(t),member_count:r(t.member_count),quota:{max_concurrent_trials:r(e.max_concurrent_trials),max_queued_trials:r(e.max_queued_trials),max_concurrent_imports:r(e.max_concurrent_imports),max_concurrent_analyses:r(e.max_concurrent_analyses),max_concurrent_sessions:r(e.max_concurrent_sessions),monthly_budget_usd:typeof e.monthly_budget_usd=="number"?e.monthly_budget_usd:null,max_concurrent_sandboxes_e2b:r(e.max_concurrent_sandboxes_e2b),max_concurrent_sandboxes_daytona:r(e.max_concurrent_sandboxes_daytona),max_concurrent_sandboxes_modal:r(e.max_concurrent_sandboxes_modal)},usage:{in_flight_trials:r(n.in_flight_trials),queued_trials:r(n.queued_trials),in_flight_imports:r(n.in_flight_imports),in_flight_analyses:r(n.in_flight_analyses),active_sessions:r(n.active_sessions),month_spend_usd:typeof n.month_spend_usd=="number"?n.month_spend_usd:null,month_spend_as_of:typeof n.month_spend_as_of=="string"?n.month_spend_as_of:null}}}function il(t){let e=de("orgs",t);return {async list(){let r=await(await v(e,"/api/orgs")).json();return (Array.isArray(r.items)?r.items:[]).map(s=>sl(s))},async get(n){let r=await v(e,`/api/orgs/${encodeURIComponent(n)}`);return Lp(await r.json())}}}function Bp(t){try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{value:e}}catch{return {raw:t}}}function Np(t){let e,n,r,s,o,d,u,l;return {get datasets(){return e??=Ya(t)},get agents(){return n??=Xa(t)},get jobs(){return r??=Za(t)},get trials(){return s??=el(t)},get analyses(){return o??=nl(t)},get checks(){return d??=rl(t)},get skills(){return u??=Qa(t)},get orgs(){return l??=il(t)},meta(){return ol(t)}}}async function ol(t){let e=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,""),n=await fetch(`${e}/api/meta`);return n.ok||await Pt(n),await n.json()}
|
|
669
|
-
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_EFFORT_SUPPORT_VALUES=
|
|
668
|
+
`)});}}}}async function*Va(t,e,n){let r=await k(t,e,{headers:{Accept:"text/event-stream",...n?.lastEventId!==void 0?{"Last-Event-ID":n.lastEventId}:{}},signal:n?.signal});if(!r.body)throw new Error("Event stream response has no body");let s=[],o=el(l=>{s.push({event:l.event||"message",...l.id!==void 0?{id:l.id}:{},data:l.data?yl(l.data):{}});}),d=r.body.getReader(),u=new TextDecoder;try{for(;;){let{done:l,value:i}=await d.read();if(l)break;for(o.push(u.decode(i,{stream:!0}));s.length>0;)yield s.shift();}}finally{d.cancel().catch(()=>{});}}function _e(t){let e=new URLSearchParams;for(let[r,s]of Object.entries(t))s!==void 0&&e.set(r,String(s));let n=e.toString();return n?`?${n}`:""}function tl(t){return t.split("/").filter(Boolean).map(encodeURIComponent).join("/")}function Fs(t,e){return {async status(){return await(await k(t,`${e}/filesystem`)).json()},async list(n){return await(await k(t,`${e}/filesystem/files${_e({path:n?.path,source:n?.source,cursor:n?.cursor,limit:n?.limit})}`)).json()},async read(n,r){let s=$s(r?.range),o=await k(t,`${e}/filesystem/files/${tl(n)}${_e({source:r?.source})}`,s?{headers:{Range:s}}:void 0);return Buffer.from(await o.arrayBuffer())},async search(n){return await(await k(t,`${e}/filesystem/search${_e({q:n.q,path:n.path,regex:n.regex,limit:n.limit,source:n.source})}`)).json()},async changes(n){return await(await k(t,`${e}/filesystem/changes${_e({source:n?.source,phase:n?.phase,cursor:n?.cursor,limit:n?.limit})}`)).json()},archive:(async n=>Fn(t,`${e}/filesystem/archive${_e({path:n?.path,source:n?.source})}`,n,"filesystem.tar.gz")),async watch(n){return await(await k(t,`${e}/filesystem/watch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:n})})).json()},events(n){return Va(t,`${e}/filesystem/events`,n)},async logs(n){return await(await k(t,`${e}/logs${_e({stream:n.stream,cursor:n.cursor,limit:n.limit})}`)).json()},logEvents(n){return Va(t,`${e}/logs/events`,n)},async procs(){return await(await k(t,`${e}/procs`)).json()}}}function Hp(t,e){return {async status(){return await(await k(t,`${e}/filesystem`)).json()},async list(n){return await(await k(t,`${e}/filesystem/files${_e({path:n?.path,cursor:n?.cursor,limit:n?.limit})}`)).json()},async read(n,r){let s=$s(r?.range),o=await k(t,`${e}/filesystem/files/${tl(n)}`,s?{headers:{Range:s}}:void 0);return Buffer.from(await o.arrayBuffer())}}}function ee(t,e){let n,r=()=>n??=t({limit:e?.limit,cursor:e?.cursor});return {then(s,o){return r().then(s,o)},catch(s){return r().catch(s)},finally(s){return r().finally(s)},async*[Symbol.asyncIterator](){let s=e?.cursor;for(;;){let o=await t({limit:e?.limit,cursor:s});for(let d of o.items)yield d;if(!o.nextCursor)return;s=o.nextCursor;}}}}function we(t){let e=new FormData;for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,r);return e}async function zp(t){let{readFileSync:e,readdirSync:n,statSync:r}=await import('fs'),{basename:s,join:o,resolve:d}=await import('path'),u=d(t),l=g=>r(g,{throwIfNoEntry:false})?.isFile()===true,i=g=>r(g,{throwIfNoEntry:false})?.isDirectory()===true;if(!i(u))throw new Error(`datasets().preflight(): not a directory: ${u}`);let a=[],c=u;if(l(o(u,"task.toml"))){let g=n(u,{withFileTypes:true}).filter(m=>m.isDirectory()&&!m.name.startsWith(".")).filter(m=>l(o(u,m.name,"task.toml"))).map(m=>m.name);if(i(o(u,"tasks"))||g.length>0)throw new Error(`${u} is ambiguous: it carries task.toml at its root (a single-task shape) AND corpus-shaped content \u2014 the import refuses this too; point at the one task directory or at a corpus of task directories, not a mix`);a.push({name:s(u),dir:u});}else {c=i(o(u,"tasks"))?o(u,"tasks"):u;for(let g of n(c,{withFileTypes:true})){if(!g.isDirectory()||g.name.startsWith("."))continue;let m=o(c,g.name);if(!l(o(m,"task.toml")))throw new Error(`${m} has no task.toml \u2014 every directory of a corpus must be a task directory (the import fails on it rather than skipping it)`);a.push({name:g.name,dir:m});}if(a.length===0)throw new Error(`${c} holds no task directories \u2014 nothing to check`);a.sort((g,m)=>g.name<m.name?-1:g.name>m.name?1:0);}let p=(c===u?[u]:[c,u]).map(g=>o(g,"dataset.toml")).find(l);return {tasks:a.map(({name:g,dir:m})=>({name:g,task_toml:e(o(m,"task.toml"),"utf8")})),...p!==void 0?{dataset_toml:e(p,"utf8")}:{}}}async function qp(t,e,n){let{postMultipartFile:r}=await Promise.resolve().then(()=>(Is(),Ka)),s=await r({url:`${t.baseUrl}${e}`,method:n.method??"POST",headers:{Authorization:`Bearer ${t.apiKey}`},fields:n.fields,file:n.file,...n.onBytes!==void 0?{onBytes:n.onBytes}:{}});return s.ok||await At(s),s}async function nl(t,e,n,r){if(r.resumableThreshold!==void 0){let{stat:s}=await import('fs/promises'),{size:o}=await s(n);if(o>r.resumableThreshold){let{uploadArchiveResumable:d}=await Promise.resolve().then(()=>(vs(),Ua)),u=await d({baseUrl:t.baseUrl,headers:{Authorization:`Bearer ${t.apiKey}`},file:{path:n},fields:r.fields,...r.resumablePath!==void 0?{sessionsPath:r.resumablePath}:{},...r.onBytes!==void 0?{onBytes:r.onBytes}:{},...r.onRegistered!==void 0?{onRegistered:r.onRegistered}:{}});return u.ok||await At(u),u}}return await qp(t,e,{method:r.method,fields:r.fields,file:{path:n,filename:r.filename},...r.onBytes!==void 0?{onBytes:r.onBytes}:{}})}async function He(t,e,n){let{tarGzipDirectoryToFile:r}=await Promise.resolve().then(()=>(yr(),hr)),{mkdtemp:s,rm:o}=await import('fs/promises'),{tmpdir:d}=await import('os'),{join:u}=await import('path'),l=await s(u(d(),"evolve-upload-"));try{let i=u(l,n.filename);return await r(n.directory,i),await nl(t,e,i,n)}finally{await o(l,{recursive:true,force:true});}}function Wp(t){let e,n=()=>(e||(e=(async()=>{let r=await t.next();for(;!r.done;)r=await t.next();return r.value})()),e);return {then(r,s){return n().then(r,s)},catch(r){return n().catch(r)},finally(r){return n().finally(r)},[Symbol.asyncIterator](){return t}}}var rl="x-package-sha256",Tt=class extends Error{constructor(n,r){super(`downloaded bytes do not match the digest the server stated (expected ${n}, got ${r})`);this.expected=n;this.actual=r;}name="EvolveDigestMismatchError"},Pt=class extends Error{constructor(n,r){super(`download ended early: the server declared ${n} bytes and ${r} arrived`);this.expectedBytes=n;this.receivedBytes=r;}name="EvolveIncompleteDownloadError"};function sl(t,e){let n=t.headers.get("Content-Length");if(n===null)return;let r=Number(n);if(Number.isFinite(r)&&e!==r)throw new Pt(r,e)}async function il(t,e){let n=t.headers.get(rl);if(!n)return;let{createHash:r}=await import('crypto'),s=r("sha256").update(e).digest("hex");if(s!==n)throw new Tt(n,s)}function Yp(t,e){let r=(t.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/);if(!r)return e;let s=X.basename(r[1]);return s===""||s==="."||s===".."||/[/\\]/.test(s)||/[\u0000-\u001f]/.test(s)?e:s}async function ol(t,e,n){if(!t.body)throw new Error("Download response has no body");await promises.mkdir(e,{recursive:true});let r=X.join(e,Yp(t,n)),{createHash:s,randomBytes:o}=await import('crypto'),d=`${r}.${o(8).toString("hex")}.part`,u=s("sha256"),l=0,i=stream.Readable.fromWeb(t.body);i.on("data",a=>{u.update(a),l+=a.length;});try{await promises$1.pipeline(i,Q.createWriteStream(d));let a=t.headers.get("Content-Length");if(a!==null&&l!==Number(a))throw new Pt(Number(a),l);let c=t.headers.get(rl),p=u.digest("hex");if(c&&p!==c)throw new Tt(c,p);await promises.rename(d,r);}catch(a){throw await promises.rm(d,{force:true}).catch(()=>{}),a}return r}async function Fn(t,e,n,r){let s=await k(t,e);if(n?.stream){if(!s.body)throw new Error("Download response has no body");return s.body}if(n?.to)return ol(s,n.to,r);let o=Buffer.from(await s.arrayBuffer());return sl(s,o.length),await il(s,o),o}function al(t){let e=de("datasets",t);async function n(i){let a=await k(e,`/api/datasets/imports/${encodeURIComponent(i)}`);return Ve(await a.json())}function r(i){if(!i||typeof i!="object")return null;let a=i;return {git_url:a.git_url??null,ref:a.ref,current_commit:a.current_commit,path:a.path??null,latest_commit:a.latest_commit??null,acked_commit:a.acked_commit??null,moved:a.moved===true,behind_by:typeof a.behind_by=="number"?a.behind_by:null,checked_at:a.checked_at??null,error:a.error??null,auto_import:a.auto_import===true}}function s(i){return {name:i.name,title:i.title??null,description:i.description??null,active_version:i.active_version?Ge(i.active_version):null,latest_version:i.latest_version?Ge(i.latest_version):null,versions:(i.versions||[]).map(Ge),selected_version:i.selected_version?Ge(i.selected_version):null,tasks:$(i.tasks,Op),failed_tasks:Ip(i.failed_tasks),upstream:r(i.upstream),created_at:i.created_at,updated_at:i.updated_at}}async function o(i,a){let c=On(i),p=V(a,{version:c.version}),g=await k(e,`/api/datasets/${encodeURIComponent(c.name)}${p}`);return s(await g.json())}async function d(i,a){let c=a?.pollIntervalMs??Et,p=a?.settleTimeoutMs??Tp,g=Date.now()+p,m=`${i.name}@${i.version}`,f=null,h=null,y=()=>h?.state==="FAILED"?new Rt("settle_timeout",`Import ${i.id}'s dataset "${i.name}" version "${i.version}" settled FAILED, but the final import read kept answering rate-limited/unavailable past the ${p}ms settle budget. Read the failure with datasets().getImport("${i.id}").`,{importId:i.id,dataset:i.name,version:i.version,state:h.state}):new Rt("settle_timeout",`Import ${i.id} completed, but dataset "${i.name}" version "${i.version}" did not settle within ${p}ms: last observed state ${h?.state??"never observed"}. Keep following with datasets().get("${m}").`,{importId:i.id,dataset:i.name,version:i.version,state:h?.state??null}),b=async _=>{for(;;){ge(a?.signal);try{return await _()}catch(w){if(!(w instanceof F)||w.status!==429&&w.status!==503)throw w;let S=g-Date.now();if(S<=0)throw y();await j(Math.min(Math.max((w.retryAfterSec??0)*1e3,c),S),a?.signal);}}};for(;;){ge(a?.signal);let _=await b(()=>o(m,{limit:1})),w=_.selected_version;if(w){if(h=w,w.state!==f&&(f=w.state,a?.onVersion?.(w,_)),w.state==="FAILED")return b(()=>n(i.id));if(w.state==="READY"||w.state==="ARCHIVED")return i}if(Date.now()>=g)throw y();await j(c,a?.signal);}}function u(i){return {name:i.name,title:i.title??null,description:i.description??null,active_version:i.active_version?Ge(i.active_version):null,latest_version:i.latest_version?Ge(i.latest_version):null,upstream:r(i.upstream)}}async function l(i){let a=await k(e,`/api/datasets${V(i,{search:i?.search})}`);return $(await a.json(),u)}return {list(i){return ee(a=>l({...a,search:i?.search}),i)},get:o,async getActive(i,a){let c=await o(i,a);if(c.active_version===null)throw new Ln(i);return {name:c.name,title:c.title,description:c.description,active_version:c.active_version,version:c.active_version.version,tasks:c.tasks??{items:[],nextCursor:null,hasMore:false},versions:c.versions??[],created_at:c.created_at,updated_at:c.updated_at}},async getTaskBuild(i,a){let c=On(i);if(c.version===void 0)throw new Error(`datasets().getTaskBuild() needs "name@version" \u2014 a task's build outcome belongs to one immutable version (got "${i}")`);let g=await(await k(e,`/api/datasets/${encodeURIComponent(c.name)}/versions/${encodeURIComponent(c.version)}/tasks/${encodeURIComponent(a)}/build`)).json();return {task_name:g.task_name??a,state:g.state,failure:g.failure&&typeof g.failure=="object"?qa(g.failure):null,build_log_ref:g.build_log_ref??null}},async preflight(i){let a=i?.source?.directory;if(typeof a!="string"||a==="")throw new Error("datasets().preflight() requires { source: { directory } } \u2014 a local corpus directory whose task.toml files are checked server-side before any upload");let c=await zp(a);return await(await k(e,"/api/datasets/preflight",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json()},async publish(i,a){let c=i.source;if(c?.directory){if(i.name===void 0||i.version===void 0){let{existsSync:g}=await import('fs'),{join:m}=await import('path');if(!(g(m(c.directory,"dataset.toml"))||g(m(c.directory,"tasks","dataset.toml"))))throw new Error(`datasets().publish() needs ${i.name===void 0?"a name":"a version"} \u2014 pass it explicitly, or add a dataset.toml manifest to the corpus directory (the server then derives name and version from it)`)}let p=await He(e,"/api/datasets/publish",{fields:{name:i.name,version:i.version},directory:c.directory,filename:"corpus.tar.gz",...a?.onUploadProgress!==void 0?{onBytes:a.onUploadProgress}:{},...a?.onRegistered!==void 0?{onRegistered:a.onRegistered}:{},resumableThreshold:St});return Ve(await p.json())}if(c&&"archive_url"in c&&c.archive_url){if(i.name===void 0||i.version===void 0)throw new Error("datasets().publish() requires name and version for an archive_url source \u2014 the server fetches the tarball only after the publish is accepted, so a manifest cannot supply them");let p=await k(e,"/api/datasets/publish",{method:"POST",body:we({name:i.name,version:i.version,archive_url:c.archive_url})});return Ve(await p.json())}if(c&&"hub_package"in c&&c.hub_package){let p=await k(e,"/api/datasets/publish",{method:"POST",body:we({...i.name!==void 0?{name:i.name}:{},...i.version!==void 0?{version:i.version}:{},hub_package:c.hub_package})});return Ve(await p.json())}if(c&&"git_url"in c&&c.git_url){if(i.name===void 0||i.version===void 0)throw new Error("datasets().publish() requires name and version for a git source \u2014 a dataset.toml manifest can only supply them for a directory source, because a git repository is cloned server-side after the publish is accepted");let p=await k(e,"/api/datasets/publish",{method:"POST",body:we({name:i.name,version:i.version,git_url:c.git_url,git_ref:c.git_ref,...c.git_path!==void 0?{git_path:c.git_path}:{}})});return Ve(await p.json())}throw new Error("datasets().publish() requires a source: a git source ({ source: { git_url, git_ref } }), a local corpus directory ({ source: { directory } }), a public tarball url ({ source: { archive_url } }), or a Harbor hub package ({ source: { hub_package } }); plus name and version (optional for a directory whose corpus carries a dataset.toml manifest, and for a hub package, which supplies its own defaults)")},getImport:n,async watchImport(i,a){let c=a?.pollIntervalMs??Et,p=null,g=null;for(;;){ge(a?.signal);let m;try{m=await n(i);}catch(h){if(h instanceof F&&(h.status===429||h.status===503)){await j(Math.max((h.retryAfterSec??0)*1e3,c),a?.signal);continue}throw h}let f=`${m.status}${m.receiving===true?":receiving":""}`;if(f!==p&&(p=f,a?.onStatus?.(m)),m.progress!==null){let h=JSON.stringify(m.progress);h!==g&&(g=h,a?.onProgress?.(m.progress,m));}if(m.status==="FAILED")return m;if(m.status==="COMPLETED")return d(m,a);await j(c,a?.signal);}},download:(async(i,a)=>{let c=On(i),p=c.version?`?version=${encodeURIComponent(c.version)}`:"",g=await k(e,`/api/datasets/${encodeURIComponent(c.name)}/download${p}`);if(a?.stream){if(!g.body)throw new Error("Package response has no body");return g.body}if(a?.to)return ol(g,a.to,`${c.name}-corpus.tar.gz`);let m=Buffer.from(await g.arrayBuffer());return sl(g,m.length),await il(g,m),m}),listImports(i){return ee(async a=>{let c=new URLSearchParams;a.limit!==void 0&&c.set("limit",String(a.limit)),a.cursor!==void 0&&c.set("cursor",a.cursor),i?.status!==void 0&&c.set("status",i.status),i?.dataset!==void 0&&c.set("dataset",i.dataset);let p=c.toString()?`?${c}`:"",g=await k(e,`/api/datasets/imports${p}`);return $(await g.json(),Ve)},i)},async activate(i,a){let c=await k(e,`/api/datasets/${encodeURIComponent(i)}/versions/${encodeURIComponent(a)}/activate`,{method:"POST"});return s(await c.json())},async update(i,a){let c=await k(e,`/api/datasets/${encodeURIComponent(i)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});return u(await c.json())},async delete(i){await k(e,`/api/datasets/${encodeURIComponent(i)}`,{method:"DELETE"});},taskFiles(i,a){let c=On(i);if(c.version===void 0)throw new Error(`datasets().taskFiles() needs "name@version" \u2014 a task's files belong to one immutable version (got "${i}")`);return Hp(e,`/api/datasets/${encodeURIComponent(c.name)}/versions/${encodeURIComponent(c.version)}/tasks/${encodeURIComponent(a)}`)}}}function ll(t){let e=de("agents",t);return {async create(n){let r=Ha("agents().create()",n),s=r.directory?await He(e,"/api/agents",{fields:r.fields,directory:r.directory,filename:"source.tar.gz"}):await k(e,"/api/agents",{method:"POST",body:we(r.fields)});return Dn(await s.json())},list(n){return ee(async r=>{let s=await k(e,`/api/agents${V(r)}`);return $(await s.json(),Dn)},n)},async get(n){let r=await k(e,`/api/agents/${encodeURIComponent(n)}`);return Dn(await r.json())},async delete(n){await k(e,`/api/agents/${encodeURIComponent(n)}`,{method:"DELETE"});},async upsert(n,r){let s=Ha("agents().upsert()",{...r,name:n}),o=s.directory?await He(e,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",fields:s.fields,directory:s.directory,filename:"source.tar.gz"}):await k(e,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",body:we(s.fields)});return Dn(await o.json())}}}function Ha(t,e){let n=typeof e.install_script=="string",r=typeof e.directory=="string";if(n&&r)throw new Error(`${t} takes EITHER an install script ({ install_script }) or a local directory ({ directory }), not both`);if(!n&&!r)throw new Error(`${t} requires either an install script ({ install_script }) or a local directory ({ directory }), plus run_command`);let s={name:e.name,run_command:e.run_command,...e.env!==void 0?{env:JSON.stringify(e.env)}:{},...n?{install_script:e.install_script}:{}};return r?{fields:s,directory:e.directory}:{fields:s}}function Os(t){return {id:t.id,name:t.name,digest:t.digest,size_bytes:t.size_bytes??0,description:t.description??null,ref:t.ref??`upload:${t.id}`,created_at:t.created_at}}function cl(t){let e=de("skills",t);return {async upload(n){if(typeof n!="string"||!n.trim())throw new Error("skills().upload() requires a local skill directory path");let{basename:r,resolve:s}=await import('path'),o=r(s(n)),u=await(await He(e,"/api/skills",{fields:{name:o||void 0},directory:n,filename:"skill.tar.gz"})).json();return (Array.isArray(u.skills)?u.skills:[u]).map(Os)},list(n){return ee(async r=>{let s=await k(e,`/api/skills${V(r)}`);return $(await s.json(),Os)},n)},async get(n){let s=await(await k(e,`/api/skills/${encodeURIComponent(n)}`)).json();return {...Os(s),skill_md:s.skill_md??null}},async delete(n){await k(e,`/api/skills/${encodeURIComponent(n)}`,{method:"DELETE"});}}}function dl(t){let e=de("jobs",t);async function n(l){let i=await k(e,`/api/jobs/${encodeURIComponent(l)}`);return Z(await i.json())}async function r(l){let i=await k(e,`/api/jobs/imports/${encodeURIComponent(l)}`);return xt(await i.json())}async function s(l){let i=await k(e,`/api/jobs${V(l,{search:l?.search,scope:l?.scope})}`);return $(await i.json(),Z)}function o(l){let i=l.trials??{};return {task_name:l.task_name,source:l.source,trials:{total:i.total??0,byStatus:i.byStatus??{}},mean_reward:l.mean_reward??null,cost_usd:l.cost_usd??null,check:l.check&&typeof l.check=="object"&&!Array.isArray(l.check)?l.check:null}}async function d(l,i){let a=V(i,{status:i?.status?.length?i.status.join(","):void 0,dataset:i?.dataset}),c=await k(e,`/api/jobs/${encodeURIComponent(l)}/trials${a}`);return $(await c.json(),Us)}async function*u(l,i){let{onEvent:a,signal:c}=i??{},p=i?.reconnectDelayMs??Cp,g=i?.maxReconnectDelayMs??Ct,m=null,f=false,h=false,y=p;for(;!f;){ge(c);let b;try{b=await fetch(`${e.baseUrl}/api/jobs/${encodeURIComponent(l)}/events`,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:"text/event-stream",...m!==null?{"Last-Event-ID":String(m)}:{}},signal:c});}catch(E){if(Ga(E,c))throw E;await j(y,c),y=Math.min(y*2,g);continue}if(!b.ok){if(b.status===429||b.status>=500){let E=await b.text().catch(()=>""),P=kt(E,b)??0,I=P>0?Math.max(P*1e3,y):y;await j(I,c),y=Math.min(y*2,g);continue}await At(b);}if(!b.body)throw new Error("Event stream response has no body");let _=false,w=[],S=el(E=>{let P=Number(E.id),I={seq:Number.isInteger(P)?P:-1,type:E.event||"message",data:E.data?yl(E.data):{}};Number.isInteger(P)&&(m=P),_=true,Ep.has(I.type)&&(f=true),w.push(I);}),v=b.body.getReader(),x=new TextDecoder;try{for(;!f;){let{done:E,value:P}=await v.read();if(E)break;S.push(x.decode(P,{stream:!0}));for(let I of w)a?.(I),yield I;w.length=0;}}catch(E){if(Ga(E,c))throw E}finally{await v.cancel().catch(()=>{});}if(f)break;ge(c);let R=await n(l);if(Rp.has(R.status)){if(h)return R;h=true;continue}_&&(y=p),await j(y,c),y=Math.min(y*2,g);}return n(l)}return {async start(l,i){let a=await k(e,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...i?.idempotencyKey?{"Idempotency-Key":i.idempotencyKey}:{}},body:JSON.stringify(l)});return Z(await a.json())},get:n,list(l){return ee(i=>s({...i,search:l?.search,scope:l?.scope}),l)},trials(l,i){return ee(a=>d(l,{...a,status:i?.status,dataset:i?.dataset}),i)},tasks(l,i){return ee(async a=>{let c=await k(e,`/api/jobs/${encodeURIComponent(l)}/tasks${V(a)}`);return $(await c.json(),o)},i)},watch(l,i){return Wp(u(l,i))},async cancel(l){let i=await k(e,`/api/jobs/${encodeURIComponent(l)}/cancel`,{method:"POST"});return Z(await i.json())},async compare(l){let i=l.map(encodeURIComponent).join(","),c=await(await k(e,`/api/jobs/compare?ids=${i}`)).json();return {jobs:(c.jobs||[]).map(Jp),taskMatrix:(c.taskMatrix||[]).map(Gp)}},async resume(l,i,a){let c=await k(e,`/api/jobs/${encodeURIComponent(l)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...a?.idempotencyKey?{"Idempotency-Key":a.idempotencyKey}:{}},body:JSON.stringify(i??{})});return Z(await c.json())},async retry(l,i,a){let c=await k(e,`/api/jobs/${encodeURIComponent(l)}/retry`,{method:"POST",headers:{"Content-Type":"application/json",...a?.idempotencyKey?{"Idempotency-Key":a.idempotencyKey}:{}},body:JSON.stringify(i??{})});return Z(await c.json())},async regrade(l,i){let a={};i?.statuses?.length&&(a.statuses=i.statuses),i?.task_name!==void 0&&(a.task_name=i.task_name);let c=await k(e,`/api/jobs/${encodeURIComponent(l)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});return Z(await c.json())},async analyze(l,i){let a=await k(e,`/api/jobs/${encodeURIComponent(l)}/analyze`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i??{})});return Z(await a.json())},async watchAnalysis(l,i){let a=i?.pollIntervalMs??Et,c=a,p=null;for(;;){ge(i?.signal);let g;try{g=await n(l);}catch(y){if(y instanceof F&&(y.status===429||y.status===503)){await j(Math.max((y.retryAfterSec??0)*1e3,c),i?.signal),c=Math.min(c*2,Ct);continue}throw y}let m=g.stats.analysis??null,f=m?JSON.stringify([m.n_completed,m.n_failed,m.n_pending]):null,h=f!==null&&f!==p;if(h&&(p=f,i?.onStats?.(g)),m?.n_pending===0)return g;c=h?a:Math.min(c*2,Ct),await j(c,i?.signal);}},download:(async(l,i)=>Fn(e,`/api/jobs/${encodeURIComponent(l)}/download`,i,`job-${l}-results.tar.gz`)),async upload(l,i){let a={dataset:i?.dataset};if(typeof l=="object"&&l!==null){if(typeof l.archive_url!="string"||!l.archive_url.trim())throw new Error("jobs().upload() with a URL source requires { archive_url: 'https://\u2026' }");let _=await k(e,"/api/jobs/upload",{method:"POST",body:we({...a,archive_url:l.archive_url})});return xt(await _.json())}if(typeof l!="string"||!l.trim())throw new Error("jobs().upload() requires a job directory (or .tar.gz archive) path, or { archive_url }");let c={fields:a,filename:"job.tar.gz",resumableThreshold:St,resumablePath:"/api/jobs/upload/uploads",...i?.onUploadProgress!==void 0?{onBytes:i.onUploadProgress}:{},...i?.onRegistered!==void 0?{onRegistered:i.onRegistered}:{}},{stat:p}=await import('fs/promises');if((await p(l).catch(()=>null))?.isFile()){let _=await nl(e,"/api/jobs/upload",l,c);return xt(await _.json())}let{existsSync:m}=await import('fs'),{join:f,resolve:h}=await import('path'),y=h(l);for(let _ of ["result.json","config.json"])if(!m(f(y,_)))throw new Error(`${y} does not contain ${_}`);let b=await He(e,"/api/jobs/upload",{...c,directory:y});return xt(await b.json())},getImport:r,async watchImport(l,i){let a=i?.pollIntervalMs??Et,c=null,p=null;for(;;){ge(i?.signal);let g;try{g=await r(l);}catch(f){if(f instanceof F&&(f.status===429||f.status===503)){await j(Math.max((f.retryAfterSec??0)*1e3,a),i?.signal);continue}throw f}let m=`${g.status}${g.receiving?":receiving":""}`;if(m!==c&&(c=m,i?.onStatus?.(g)),g.progress!==null){let f=JSON.stringify(g.progress);f!==p&&(p=f,i?.onProgress?.(g.progress,g));}if(g.status==="COMPLETED"||g.status==="FAILED")return g;await j(a,i?.signal);}},listImports(l){return ee(async i=>{let a=new URLSearchParams;i.limit!==void 0&&a.set("limit",String(i.limit)),i.cursor!==void 0&&a.set("cursor",i.cursor),l?.status!==void 0&&a.set("status",l.status);let c=a.toString()?`?${a}`:"",p=await k(e,`/api/jobs/imports${c}`);return $(await p.json(),xt)},l)},async delete(l){let a=await(await k(e,`/api/jobs/${encodeURIComponent(l)}`,{method:"DELETE"})).json();return {job_id:a.job_id??l,trials_deleted:a.trials_deleted??0,analyses_deleted:a.analyses_deleted??0}},async grep(l,i,a){let c=await k(e,`/api/jobs/${encodeURIComponent(l)}/grep${V(a,{q:i,type:a?.type})}`);return $(await c.json(),Vp)}}}function ul(t){let e=de("trials",t);async function n(s,o){let d=await k(e,`/api/trials/${encodeURIComponent(s)}/trace${V(o,{type:o?.type,grep:o?.grep,tail:o?.tail!==void 0?String(o.tail):void 0})}`);return $(await d.json(),Qa)}async function r(s,o){let u=await(await k(e,`/api/trials/${encodeURIComponent(s)}/trace?stream=${o}`)).json();return o==="agent-home"?u.files??null:u.log??null}return {async get(s){let o=await k(e,`/api/trials/${encodeURIComponent(s)}`);return Us(await o.json())},trace:n,artifact:r,async*traceEvents(s,o){let d=o?.cursor;for(;;){let u=await n(s,{...o,cursor:d});for(let l of u.items)yield l;if(!u.nextCursor)return;d=u.nextCursor;}},async regrade(s){let o=await k(e,`/api/trials/${encodeURIComponent(s)}/regrade`,{method:"POST"});return Z(await o.json())},async retry(s,o){let d=await k(e,`/api/trials/${encodeURIComponent(s)}/retry`,{method:"POST",...o?.idempotencyKey?{headers:{"Idempotency-Key":o.idempotencyKey}}:{}});return Z(await d.json())},async stop(s){let d=await(await k(e,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:s})})).json();return {stopped:(d.stopped??[]).map(Us),stopped_analyses:(d.stopped_analyses??[]).map($n).filter(u=>u!==null),already_terminal:d.already_terminal??[],not_found:d.not_found??[]}},async files(s,o){let d=await k(e,`/api/trials/${encodeURIComponent(s)}/files${V(o)}`);return $(await d.json(),u=>({path:u.path,size_bytes:u.size_bytes}))},async file(s,o,d){let u=o.split("/").filter(Boolean).map(encodeURIComponent).join("/"),l=$s(d),i=await k(e,`/api/trials/${encodeURIComponent(s)}/files/${u}`,l?{headers:{Range:l}}:void 0);return Buffer.from(await i.arrayBuffer())},filesystem:s=>Fs(e,`/api/trials/${encodeURIComponent(s)}`)}}function pl(t){let e=t?.update;return typeof e?.sessionUpdate=="string"?e.sessionUpdate:"unknown"}function gl(t){let e=de("analyses",t),n=new Set;async function r(d){if(n.has(d))return;let u;try{u=await k(e,`/api/traces/trials/${encodeURIComponent(d)}/artifacts?what=analysis`);}catch(l){throw l instanceof F&&l.status===400?new Error(`"${d}" is not an analysis run (the artifacts door refuses it typed) \u2014 for a trial's artifacts use trials()`):l}await u.text().catch(()=>{}),n.add(d);}async function s(d,u){await r(d);let i=await(await k(e,`/api/traces/trials/${encodeURIComponent(d)}/artifacts?what=${u}`)).json();return u==="agent-home"?i.files??null:i.log??null}async function o(d){let u=await k(e,`/api/analyses${V(d,{scope:d?.scope,job:d?.job,status:d?.status&&d.status.length>0?d.status.join(","):void 0})}`);return $(await u.json(),l=>{let i=$n(l);if(i===null)throw new Error("The analyses list served an unreadable analysis object");return i})}return {list(d){return ee(u=>o({...u,scope:d?.scope,job:d?.job,status:d?.status}),d)},async get(d){let l=await(await k(e,`/api/traces/trials/${encodeURIComponent(d)}/artifacts?what=analysis`)).json(),i=$n(l.analysis);if(i===null)throw new Error(`The analysis feed served no readable verdict object for "${d}"`);return n.add(d),i},async transcript(d,u){let l=u?.since;if(l!==void 0&&(!Number.isInteger(l)||l<0))throw new Error(`transcript() since must be a non-negative integer, got ${l}`);let a=await(await k(e,`/api/traces/trials/${encodeURIComponent(d)}/events`+(l!==void 0?`?since=${l}`:""))).json(),c=a.session??{};if(c.kind!=="analysis"){let m=typeof c.kind=="string"?c.kind:"trial";throw new Error(`"${d}" is not an analysis run (the feed resolves it as a ${m}) \u2014 for a trial's trace use trials()`)}let p=l??0,g=Array.isArray(a.events)?a.events:[];return {id:typeof c.id=="string"?c.id:d,analyzed_trial_id:typeof c.analyzedTrialId=="string"?c.analyzedTrialId:null,job_id:typeof c.jobId=="string"?c.jobId:null,task_name:typeof c.tag=="string"?c.tag:null,model_name:typeof c.model=="string"?c.model:null,sandbox_provider:typeof c.provider=="string"?c.provider:null,sandbox_id:typeof c.sandboxId=="string"?c.sandboxId:null,is_ended:c.isEnded===true,total:typeof a.total=="number"?a.total:p+g.length,events:g.map((m,f)=>({seq:p+f,type:pl(m),data:m&&typeof m=="object"&&!Array.isArray(m)?m:{}})),gateway_calls:Za(a.gatewayCalls),stored_at:wt(a.storedAt,g.length,"Analysis transcript response")}},artifact:s,download:(async(d,u)=>Fn(e,`/api/analyses/${encodeURIComponent(d)}/download`,u,`analysis-${d}.tar.gz`)),filesystem:d=>Fs(e,`/api/analyses/${encodeURIComponent(d)}`)}}function Un(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("The checks surface served an unreadable check object");let e=t,n=Array.isArray(e.results)?e.results.filter(r=>!!r&&typeof r=="object"&&!Array.isArray(r)):[];return {...e,results:n}}function ml(t){let e=de("checks",t);async function n(u){let l=await k(e,`/api/checks/${encodeURIComponent(u)}`);return Un(await l.json())}async function r(u){let l=await k(e,`/api/checks${V(u,{scope:u?.scope,status:u?.status&&u.status.length>0?u.status.join(","):void 0,dataset:u?.dataset})}`);return $(await l.json(),Un)}let s=new Set;async function o(u){let l;try{l=await k(e,`/api/traces/trials/${encodeURIComponent(u)}/artifacts?what=task-check`);}catch(c){throw c instanceof F&&c.status===400?new Error(`"${u}" is not a task check (the artifacts door refuses it typed) \u2014 for a trial's artifacts use trials(), for an analysis's use analyses()`):c}let a=(await l.json()).task_check;if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`The traces feed served no readable task check for "${u}"`);return s.add(u),a}async function d(u,l){s.has(u)||await o(u);let a=await(await k(e,`/api/traces/trials/${encodeURIComponent(u)}/artifacts?what=${l}`)).json();return l==="agent-home"?a.files??null:a.log??null}return {async create(u){let{source:l,onUploadProgress:i,...a}=u,c={config:JSON.stringify(a)};if("dataset"in l){if(typeof l.dataset!="string"||l.dataset.trim()==="")throw new Error('checks().create(): source.dataset must be "name" or "name@version"');let b=await k(e,"/api/checks",{method:"POST",body:we({...c,dataset:l.dataset.trim()})});return Un(await b.json())}let{existsSync:p,statSync:g}=await import('fs'),{basename:m,resolve:f}=await import('path'),h=f(l.directory);if(!p(h)||!g(h).isDirectory())throw new Error(`checks().create(): Path '${l.directory}' does not exist or is not a directory`);let y=await He(e,"/api/checks",{directory:h,fields:c,filename:`${m(h)||"task"}.tar.gz`,...i!==void 0?{onBytes:i}:{}});return Un(await y.json())},get:n,async defaults(){return await(await k(e,"/api/checks/defaults")).json()},list(u){return ee(l=>r({...l,scope:u?.scope,status:u?.status,dataset:u?.dataset}),u)},task:o,async transcript(u,l){let i=l?.since;if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new Error(`transcript() since must be a non-negative integer, got ${i}`);let c=await(await k(e,`/api/traces/trials/${encodeURIComponent(u)}/events`+(i!==void 0?`?since=${i}`:""))).json(),p=c.session??{};if(p.kind!=="check"){let f=typeof p.kind=="string"?p.kind:"trial";throw new Error(`"${u}" is not a task check (the feed resolves it as a ${f}) \u2014 for a trial's trace use trials(), for an analysis's use analyses()`)}let g=i??0,m=Array.isArray(c.events)?c.events:[];return {id:typeof p.id=="string"?p.id:u,check_id:typeof p.checkId=="string"?p.checkId:null,dataset:typeof p.datasetRef=="string"?p.datasetRef:null,task_name:typeof p.tag=="string"?p.tag:null,model_name:typeof p.model=="string"?p.model:null,sandbox_provider:typeof p.provider=="string"?p.provider:null,sandbox_id:typeof p.sandboxId=="string"?p.sandboxId:null,is_ended:p.isEnded===true,total:typeof c.total=="number"?c.total:g+m.length,events:m.map((f,h)=>({seq:g+h,type:pl(f),data:f&&typeof f=="object"&&!Array.isArray(f)?f:{}})),gateway_calls:Za(c.gatewayCalls),stored_at:wt(c.storedAt,m.length,"Task check transcript response")}},artifact:d,download:(async(u,l)=>Fn(e,`/api/checks/${encodeURIComponent(u)}/download`,l,`check-${u}.tar.gz`)),async watch(u,l){let i=l?.pollIntervalMs??Et,a=i,c=null;for(;;){ge(l?.signal);let p;try{p=await n(u);}catch(f){if(f instanceof F&&(f.status===429||f.status===503)){await j(Math.max((f.retryAfterSec??0)*1e3,a),l?.signal),a=Math.min(a*2,Ct);continue}throw f}let g=JSON.stringify(p.results.map(f=>[f.task_name,f.status])),m=g!==c;if(m&&(c=g,l?.onProgress?.(p)),p.status==="completed")return p;a=m?i:Math.min(a*2,Ct),await j(a,l?.signal);}},taskFilesystem:(u,l)=>Fs(e,`/api/checks/${encodeURIComponent(u)}/tasks/${encodeURIComponent(l)}`)}}function Xp(t){let e=de("auth",t);return {async status(){let r=await(await k(e,"/api/auth/status")).json(),s=r.key??{};return {user_id:r.user_id,email:r.email??null,key:{id:s.id,label:s.label??null,created_at:s.created_at,last_used_at:s.last_used_at??null}}}}}function fl(t){return {org_id:t.org_id,slug:t.slug,display_name:t.display_name,personal:t.personal===true,...t.role==="owner"||t.role==="member"?{role:t.role}:{},created_at:t.created_at}}function Qp(t){let e=t.quota??{},n=t.usage??{},r=s=>typeof s=="number"?s:0;return {...fl(t),member_count:r(t.member_count),quota:{max_concurrent_trials:r(e.max_concurrent_trials),max_queued_trials:r(e.max_queued_trials),max_concurrent_imports:r(e.max_concurrent_imports),max_concurrent_analyses:r(e.max_concurrent_analyses),max_concurrent_sessions:r(e.max_concurrent_sessions),monthly_budget_usd:typeof e.monthly_budget_usd=="number"?e.monthly_budget_usd:null,max_concurrent_sandboxes_e2b:r(e.max_concurrent_sandboxes_e2b),max_concurrent_sandboxes_daytona:r(e.max_concurrent_sandboxes_daytona),max_concurrent_sandboxes_modal:r(e.max_concurrent_sandboxes_modal)},usage:{in_flight_trials:r(n.in_flight_trials),queued_trials:r(n.queued_trials),in_flight_imports:r(n.in_flight_imports),in_flight_analyses:r(n.in_flight_analyses),active_sessions:r(n.active_sessions),month_spend_usd:typeof n.month_spend_usd=="number"?n.month_spend_usd:null,month_spend_as_of:typeof n.month_spend_as_of=="string"?n.month_spend_as_of:null}}}function hl(t){let e=de("orgs",t);return {async list(){let r=await(await k(e,"/api/orgs")).json();return (Array.isArray(r.items)?r.items:[]).map(s=>fl(s))},async get(n){let r=await k(e,`/api/orgs/${encodeURIComponent(n)}`);return Qp(await r.json())}}}function yl(t){try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{value:e}}catch{return {raw:t}}}function Zp(t){let e,n,r,s,o,d,u,l;return {get datasets(){return e??=al(t)},get agents(){return n??=ll(t)},get jobs(){return r??=dl(t)},get trials(){return s??=ul(t)},get analyses(){return o??=gl(t)},get checks(){return d??=ml(t)},get skills(){return u??=cl(t)},get orgs(){return l??=hl(t)},meta(){return bl(t)}}}async function bl(t){let e=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||T).replace(/\/$/,""),n=await fetch(`${e}/api/meta`);return n.ok||await At(n),await n.json()}
|
|
669
|
+
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_EFFORT_SUPPORT_VALUES=Ea;exports.AGENT_REGISTRY=J;exports.AGENT_TYPES=kl;exports.ANALYSIS_ARTIFACT_STREAMS=Ra;exports.ANALYSIS_STATUSES=ka;exports.Agent=bt;exports.BINARY_EFFORT_VALUES=Ws;exports.BROWSER_ACTIONBOOK_PROMPT=Br;exports.BROWSER_LOGIN_MCP_SERVER_NAME=ns;exports.BrowserCredentialsClient=hn;exports.BrowserProfilesClient=kn;exports.CHECK_STATUSES=va;exports.DEFAULT_HARNESS_TRIAL_LAYOUT=xs;exports.DEFAULT_REASONING_EFFORT=Ys;exports.EVAL_SANDBOX_PROVIDERS=_a;exports.Evolve=_t;exports.EvolveApiError=F;exports.EvolveConfigError=A;exports.EvolveDigestMismatchError=Tt;exports.EvolveIncompleteDownloadError=Pt;exports.GATEWAY_TRACE_SEQ_BASE=Rn;exports.HARNESS_TRIAL_LAYOUTS=In;exports.HOSTED_ERROR_CODES=ys;exports.ImportSettleError=Rt;exports.JOB_LIST_SCOPES=wa;exports.JUDGE_PROMPT=Nr;exports.MANAGED_SANDBOX_PROVIDERS=ve;exports.MAX_SKILL_BYTES=wr;exports.MAX_SKILL_FILES=_r;exports.NoActiveVersionError=Ln;exports.Pipeline=vn;exports.REASONING_EFFORTS=qs;exports.RETRY_FEEDBACK_PROMPT=Jr;exports.SANDBOX_LOG_STREAMS=Ca;exports.SCHEMA_PROMPT=no;exports.SKILL_FILE_NAME=ae;exports.SUPPORTED_RUN_OPTIONS=vl;exports.SWARM_RESULT_BRAND=ye;exports.SYSTEM_PROMPT=to;exports.SandboxFeatureUnsupportedError=gs;exports.SandboxNotRunningError=fs;exports.SandboxPathNotFoundError=ms;exports.Semaphore=Ne;exports.SkillRefError=z;exports.SkillResolveError=N;exports.Swarm=ps;exports.SwarmResultList=je;exports.TASK_LINKED_BY=xn;exports.TASK_LINK_REASONS=Cn;exports.TRIAL_ARTIFACT_STREAMS=xa;exports.TRIAL_STATUSES=ba;exports.TerminalPipeline=Sn;exports.VALIDATION_PRESETS=Nn;exports.VERIFY_PROMPT=jr;exports.WORKSPACE_PROMPT=Zi;exports.WORKSPACE_SWE_PROMPT=eo;exports.agents=ll;exports.analyses=gl;exports.analysisEvolveRecord=Ba;exports.applyTemplate=le;exports.assembleTrialTree=Fa;exports.auth=Xp;exports.browserCredentials=rs;exports.browserProfiles=us;exports.buildWorkerSystemPrompt=Kr;exports.checkEvolveRecord=ja;exports.checks=ml;exports.computeSkillDigest=kr;exports.createAgentParser=fe;exports.createClaudeParser=zt;exports.createCodexParser=qt;exports.createDroidParser=Wt;exports.createGeminiParser=Yt;exports.datasets=al;exports.executeWithRetry=G;exports.expandPath=B;exports.gatewayUsageOf=En;exports.getAgentConfig=K;exports.getMcpSettingsDir=re;exports.getMcpSettingsPath=ne;exports.harborCopyPath=Ts;exports.harnessEffortVocabulary=Sl;exports.harnessTrialLayout=Cs;exports.homeRelativePath=Rs;exports.hosted=Zp;exports.isAgentWorkUpdate=ti;exports.isHostedErrorCode=Tn;exports.isSandboxFeatureUnsupportedError=Fu;exports.isSandboxNotRunningError=Nu;exports.isSandboxPathNotFoundError=Bu;exports.isValidAgentType=zn;exports.isZodSchema=Y;exports.jobEvolveRecord=$a;exports.jobs=dl;exports.jsonSchemaToString=Te;exports.managedSandbox=nd;exports.managedSecrets=as;exports.meta=bl;exports.mountSkills=Pr;exports.orgs=hl;exports.parseNdjsonLine=ic;exports.parseNdjsonOutput=oc;exports.parseQwenOutput=ui;exports.parseSkillRef=xr;exports.passAtK=Sa;exports.pinSkillRef=Vc;exports.placeHomeObject=Es;exports.readLocalDir=Ei;exports.resolveDefaultSandbox=un;exports.resolveSkillSha=Rr;exports.resolveSkills=Tr;exports.resolveStorageConfig=mn;exports.saveLocalDir=Ti;exports.sessions=qu;exports.skillCloneUrl=Cr;exports.skillDisplayUrl=Re;exports.skills=cl;exports.storage=Xd;exports.taskCheckEvolveRecord=Na;exports.trialEvolveRecord=Ps;exports.trials=ul;exports.writeClaudeMcpConfig=Ft;exports.writeCodexMcpConfig=Gt;exports.writeDroidGatewaySettings=Kt;exports.writeDroidMcpConfig=Jt;exports.writeGeminiMcpConfig=Bt;exports.writeMcpConfig=rr;exports.writeQwenMcpConfig=Nt;exports.zodSchemaToJson=Ee;
|