@evolvingmachines/evolve 0.0.55-project-sable.20260916.db0bc0bb
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/LICENSE +201 -0
- package/README.md +25 -0
- package/dist/chunk-5GVMBEYI.js +11 -0
- package/dist/chunk-HQJI3HHU.js +1 -0
- package/dist/chunk-JS2UTK2I.js +427 -0
- package/dist/cli/index.cjs +73 -0
- package/dist/cli/index.d.cts +270 -0
- package/dist/cli/index.d.ts +270 -0
- package/dist/cli/index.js +54 -0
- package/dist/index.cjs +669 -0
- package/dist/index.d.cts +5023 -0
- package/dist/index.d.ts +5023 -0
- package/dist/index.js +230 -0
- package/dist/managed-modal-IJW62SSK.js +4 -0
- package/dist/resumable-HFSICSH3.js +1 -0
- package/dist/tar-GVC4KE52.js +1 -0
- package/dist/types-DlpTxdR_.d.cts +4777 -0
- package/dist/types-DlpTxdR_.d.ts +4777 -0
- package/dist/upload-KPYDMWFJ.js +1 -0
- package/docs-agents/SKILL.md +138 -0
- package/docs-agents/index.md +81 -0
- package/docs-agents/python/01-getting-started.md +511 -0
- package/docs-agents/python/02-configuration.md +855 -0
- package/docs-agents/python/03-runtime.md +899 -0
- package/docs-agents/python/04-streaming.md +451 -0
- package/docs-agents/python/05-swarm-pipeline.md +953 -0
- package/docs-agents/python/index.md +122 -0
- package/docs-agents/typescript/01-getting-started.md +494 -0
- package/docs-agents/typescript/02-configuration.md +841 -0
- package/docs-agents/typescript/03-runtime.md +864 -0
- package/docs-agents/typescript/04-streaming.md +478 -0
- package/docs-agents/typescript/05-swarm-pipeline.md +957 -0
- package/docs-agents/typescript/index.md +121 -0
- package/docs-evals/SKILL.md +112 -0
- package/docs-evals/cli-reference/agent.mdx +67 -0
- package/docs-evals/cli-reference/analysis.mdx +91 -0
- package/docs-evals/cli-reference/analyze.mdx +74 -0
- package/docs-evals/cli-reference/auth.mdx +60 -0
- package/docs-evals/cli-reference/check.mdx +146 -0
- package/docs-evals/cli-reference/dataset.mdx +133 -0
- package/docs-evals/cli-reference/index.mdx +108 -0
- package/docs-evals/cli-reference/job.mdx +239 -0
- package/docs-evals/cli-reference/run.mdx +196 -0
- package/docs-evals/cli-reference/secrets.mdx +95 -0
- package/docs-evals/cli-reference/skill.mdx +51 -0
- package/docs-evals/cli-reference/skills.mdx +81 -0
- package/docs-evals/cli-reference/trial.mdx +112 -0
- package/docs-evals/cli-reference/upload.mdx +36 -0
- package/docs-evals/core-concepts/agents.mdx +106 -0
- package/docs-evals/core-concepts/analyze.mdx +86 -0
- package/docs-evals/core-concepts/check.mdx +51 -0
- package/docs-evals/core-concepts/datasets.mdx +138 -0
- package/docs-evals/core-concepts/index.mdx +42 -0
- package/docs-evals/core-concepts/jobs.mdx +136 -0
- package/docs-evals/core-concepts/models.mdx +68 -0
- package/docs-evals/core-concepts/sandboxes.mdx +52 -0
- package/docs-evals/core-concepts/secrets.mdx +41 -0
- package/docs-evals/core-concepts/skills.mdx +42 -0
- package/docs-evals/core-concepts/tasks.mdx +216 -0
- package/docs-evals/core-concepts/trial-outputs.mdx +103 -0
- package/docs-evals/core-concepts/trials.mdx +103 -0
- package/docs-evals/core-concepts/upload.mdx +45 -0
- package/docs-evals/dashboard/checks.mdx +15 -0
- package/docs-evals/dashboard/datasets.mdx +24 -0
- package/docs-evals/dashboard/jobs.mdx +65 -0
- package/docs-evals/dashboard/traces.mdx +15 -0
- package/docs-evals/dashboard/trial-viewer.mdx +30 -0
- package/docs-evals/docs.json +180 -0
- package/docs-evals/getting-started/installation.mdx +56 -0
- package/docs-evals/getting-started/quick-start.mdx +85 -0
- package/docs-evals/index.mdx +36 -0
- package/docs-evals/sdk/python.mdx +139 -0
- package/docs-evals/sdk/typescript.mdx +141 -0
- package/docs-evals/sdk-reference/agents.mdx +105 -0
- package/docs-evals/sdk-reference/analyses.mdx +125 -0
- package/docs-evals/sdk-reference/auth.mdx +76 -0
- package/docs-evals/sdk-reference/checks.mdx +166 -0
- package/docs-evals/sdk-reference/datasets.mdx +305 -0
- package/docs-evals/sdk-reference/errors.mdx +199 -0
- package/docs-evals/sdk-reference/index.mdx +58 -0
- package/docs-evals/sdk-reference/jobs.mdx +731 -0
- package/docs-evals/sdk-reference/meta.mdx +52 -0
- package/docs-evals/sdk-reference/skills.mdx +68 -0
- package/docs-evals/sdk-reference/trials.mdx +232 -0
- package/docs-evals/sdk-reference/types.mdx +272 -0
- package/docs-evals/snippets/global-options.mdx +13 -0
- package/docs-evals/snippets/list-flags.mdx +23 -0
- package/harness-capabilities.json +430 -0
- package/hosted-error-codes.json +120 -0
- package/package.json +163 -0
- package/skills/create-adapter/SKILL.md +287 -0
- package/skills/create-task/SKILL.md +491 -0
- package/skills/evolve/SKILL.md +39 -0
- package/skills/publish/SKILL.md +142 -0
- package/skills/rewardkit/SKILL.md +330 -0
- package/spec/atif/README.md +45 -0
- package/spec/atif/trajectory.schema.json +865 -0
- package/spec/openapi.yaml +13447 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
'use strict';var Wl=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'),uu=require('ajv'),smolToml=require('smol-toml'),child_process=require('child_process'),util=require('util'),Lc=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 Wl__default=/*#__PURE__*/_interopDefault(Wl);var Q__namespace=/*#__PURE__*/_interopNamespace(Q);var X__namespace=/*#__PURE__*/_interopNamespace(X);var uu__default=/*#__PURE__*/_interopDefault(uu);var Lc__default=/*#__PURE__*/_interopDefault(Lc);var ll=Object.defineProperty;var ze=(t,e)=>()=>(t&&(e=t(t=0)),e);var It=(t,e)=>{for(var n in e)ll(t,n,{get:e[n],enumerable:true});};var pr={};It(pr,{MAX_INLINE_ARCHIVE_BYTES:()=>mi,crc32Fallback:()=>gi,extractTarGz:()=>yc,shouldStore:()=>pi,tarGzTopLevelName:()=>bc,tarGzipDirectory:()=>hc,tarGzipDirectoryToFile:()=>fi});async function cc(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(lc.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 pi(t,e){if(e<dc)return false;let n=await promises.open(t,"r"),r;try{let o=Buffer.allocUnsafe(oi),{bytesRead:d}=await n.read(o,0,oi,0);r=o.subarray(0,d);}finally{await n.close();}return r.length===0?false:Wl.deflateRawSync(r,{level:1}).length*20>=r.length*19}function gi(t,e=0){let n=~e;for(let r=0;r<t.length;r++)n=gc[(n^t[r])&255]^n>>>8;return ~n>>>0}async function mc(t){let e=Symbol("pending"),n=await Promise.race([t,Promise.resolve(e)]);return n===e?null:n}async function fi(t,e){let n=await cc(t),r=tarStream.pack(),s=Q.createWriteStream(e);s.on("error",()=>{}),r.on("error",()=>{});let o=new dr(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 pi(a,p));let g=r.entry({name:i,size:p,mode:c,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"}),f=promises$1.pipeline(Q.createReadStream(a),g),m=!1,h=null;for(f.then(()=>{},()=>{}).then(()=>{m=!0,h?.(ai);});;){if(!m){let b=await new Promise((_,w)=>{h=_,l().then(_,w);});if(h=null,b===ai)continue;if(u=null,b.done)break;await o.write(b.value);continue}await new Promise(b=>setImmediate(b));let y=await mc(l());if(y===null||(u=null,y.done))break;await o.write(y.value);}await f;}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 hc(t,e=mi){let n=await promises.mkdtemp(X.join(os$1.tmpdir(),"evolve-tar-"));try{let r=X.join(n,"archive.tar.gz");await fi(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 yc(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),Wl.createGunzip(),r),o]);}catch(d){throw r.destroy(),d}return s}async function bc(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),Wl.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 lc,dc,oi,uc,pc,cr,gc,fc,dr,ai,mi,gr=ze(()=>{lc=new Set([".git",".DS_Store",".venv"]);dc=64*1024,oi=128*1024,uc=65535,pc=1024*1024,cr=32*1024;gc=(()=>{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})(),fc=Wl__default.default.crc32??gi,dr=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?uc:pc;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=fc(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(Wl.deflateRawSync(e,{level:9,finishFlush:Wl.constants.Z_SYNC_FLUSH,...this.window?{dictionary:this.window}:{}}));this.window=e.length>=cr?Buffer.from(e.subarray(e.length-cr)):this.window?Buffer.concat([this.window,e]).subarray(-cr):Buffer.from(e);}out(e){return new Promise((n,r)=>{this.sink.write(e,s=>s==null?n():r(s));})}},ai=Symbol("feed settled");mi=256*1024*1024;});var Pi={};It(Pi,{ManagedModalProvider:()=>Or,ManagedModalWriteLimitError:()=>ln,_testManagedModalSandbox:()=>Jc});function Fc(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 Ei(t){return {sandboxId:t.sandboxId,image:t.image??"",metadata:t.metadata??{},startedAt:t.startedAt??""}}var ln,cn,Ar,Ir,rt,Or,Jc,Ai=ze(()=>{ln=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;}};cn=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)}}},Ar=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
|
+
`))!==-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
|
+
`))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}},Ir=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(Fc(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 ln(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}));}};rt=class{constructor(e,n){this.door=e;this.sandboxId=n;this.commands=new Ar(e,n),this.files=new Ir(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 Ei(await e.json())}},Or=class{providerType="modal";name="Managed Modal";door;constructor(e){this.door=new cn(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 rt(this.door,r.sandboxId)}async connect(e,n){let r=new rt(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(Ei);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`}:{}}}},Jc=(t,e)=>new rt(new cn(t),e);});function wt(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 us=ze(()=>{});var Ta={};It(Ta,{RESUMABLE_UPLOAD_CHUNK_BYTES:()=>Sa,RESUMABLE_UPLOAD_MAX_ATTEMPTS:()=>kt,RESUMABLE_UPLOAD_MAX_RATE_LIMIT_WAITS:()=>xa,RESUMABLE_UPLOAD_MAX_RETRY_AFTER_SEC:()=>Ca,RESUMABLE_UPLOAD_THRESHOLD_BYTES:()=>vt,retryAfterWaitMs:()=>Ra,setResumableUploadThresholdBytes:()=>$u,uploadArchiveResumable:()=>Fu});function $u(t){vt=t;}async function Bu(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 gs(t){return Math.min(500*2**(t-1),4e3)}function Ra(t,e){let n=t===void 0?0:t*1e3;return Math.min(Math.max(n,gs(e)),Ca*1e3)}async function ps(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 Tn(t){for(let e=0;;e+=1){let n=await t();if(!Nu(n)||e>=xa)return n;let r=await n.text().catch(()=>"");await fs(Ra(wt(r,n),e+1));}}function ju(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[f,m]of Object.entries(i.headers))if(typeof m=="string")c.set(f,m);else if(Array.isArray(m))for(let h of m)c.append(f,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 Fu(t){let e=t.timeoutMs??Lu,n=t.chunkBytes??Sa,{size:r}=await promises.stat(t.file.path),s=await Bu(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,f]of Object.entries(t.fields))f!==void 0&&(u[g]=f);let l=await Tn(()=>ps(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 Tn(()=>ps(a,{method:"HEAD",headers:t.headers},e));if(!g.ok)throw new Error(`upload session probe failed: HTTP ${g.status}`);let f=Number(g.headers.get("upload-offset"));if(!Number.isInteger(f))throw new Error("upload session probe did not return Upload-Offset");return f},p=await promises.open(t.file.path,"r");try{let g=0,f=0,m=Buffer.alloc(n);for(;g<r;){let y=Math.min(n,r-g),{bytesRead:b}=await p.read(m,0,y,g);if(b!==y)throw new Error(`archive shrank mid-upload: read ${b} of ${y} bytes at offset ${g}`);let _=m.subarray(0,y),w=crypto.createHash("sha256").update(_).digest(),S;try{S=await Tn(()=>ps(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(f+=1,f>=kt)throw x;await fs(gs(f));try{g=await c();}catch{}continue}if(S.status===409){if(f+=1,f>=kt)return S;g=await c();continue}if(!S.ok)return S;let k=Number(S.headers.get("upload-offset"));if(!Number.isInteger(k)||k<=g)throw new Error("resumable upload did not advance Upload-Offset");g=k,f=0,t.onBytes?.(g,r);}let h;for(let y=1;y<=kt;y++)try{return await Tn(()=>ju(`${a}/complete`,t.headers,e))}catch(b){h=b,y<kt&&await fs(gs(y));}throw h}finally{await p.close();}}var vt,Sa,kt,xa,Ca,Lu,fs,Nu,ms=ze(()=>{us();vt=256*1024*1024;Sa=6*1024*1024,kt=4,xa=3,Ca=60,Lu=6e5;fs=t=>new Promise(e=>setTimeout(e,t));Nu=t=>t.status===429||t.status===503;});var Ua={};It(Ua,{EvolveUploadTimeoutError:()=>exports.EvolveUploadTimeoutError,UPLOAD_TIMEOUT_MS:()=>Ss,postMultipartFile:()=>ep});function Da(t,e){return new Promise((n,r)=>{t.write(e,s=>s?r(s):n());})}async function ep(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
|
+
Content-Disposition: form-data; name="${_}"\r
|
|
6
|
+
\r
|
|
7
|
+
${w}\r
|
|
8
|
+
`);n.push(`--${e}\r
|
|
9
|
+
Content-Disposition: form-data; name="archive"; filename="${t.file.filename}"\r
|
|
10
|
+
Content-Type: application/gzip\r
|
|
11
|
+
\r
|
|
12
|
+
`);let r=Buffer.from(n.join(""),"utf8"),s=Buffer.from(`\r
|
|
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 vl(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 Kt(t,e,n){for(let[u,l]of Object.entries(e))Vn(u,l);let r=re("codex",n),s=ne("codex",n);await t.files.makeDir(r);let o=await Hs(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]=vl(u,l));await Xn(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 Hs(t,d),l={...n?{[z]: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"&&Yn(a["evolve-gateway"],i)||(u.model_provider="evolve-gateway",a["evolve-gateway"]=i,u.model_providers=a,await Xn(t,d,u));}async function Qn(t,e,n,r,s){let o=N(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 Xn(t,o,u);}async function Zn(t,e,n,r,s){if(!(!r||Object.keys(r).length===0))switch(t){case "claude":await Lt(e,n,r,s);break;case "codex":await Kt(e,r,s);break;case "gemini":await Bt(e,r,s);break;case "qwen":await Nt(e,r,s);break;case "kimi":await Hn(e,r,s);break;case "opencode":await qn(e,n,r);break;case "droid":await Ft(e,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${t}`)}}function qs(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 Gt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function et(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,n=Gt(e.input_tokens),r=Gt(e.output_tokens),s=Gt(e.cache_read_input_tokens),o=Gt(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=et(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,f=et(a.usage)??(g!==void 0?{}:null);if(f&&(g!==void 0&&(f.costUsd=g),p.push({sessionUpdate:"usage",scope:"run",usage:f})),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,f=typeof c?.id=="string"&&c.id?c.id:void 0,m=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}:{},...f!==void 0?{messageId:f}:{},...m!==void 0?{parentToolCallId:m}:{},...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 f=r(p);g={sessionUpdate:"tool_call",toolCallId:p.id,status:"pending",...f,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 f=t[p.tool_use_id];if(!f||(delete t[p.tool_use_id],f.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,f),...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 Ht(){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 f=r(g);f&&p.push({update:f});break}case "item.updated":{let g=c.item;if(!g)return null;let f=s(g);f&&p.push({update:f});break}case "item.completed":{let g=c.item;if(!g)return null;let f=o(g);f&&p.push({update:f});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),f=c(a.output_tokens),m=c(a.cached_input_tokens);g!==void 0&&(p.promptTokens=g),f!==void 0&&(p.completionTokens=f),m!==void 0&&(p.cachedTokens=m);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
|
+
`)??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:{},f=p.status,m=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:m,toolName:a,kind:y,status:"pending",rawInput:g,content:b,locations:_}),c==="todowrite"){let R=ri(g.todos);if(R.length===0&&typeof p.output=="string")try{R=ri(JSON.parse(p.output));}catch{}R.length>0&&w.push({sessionUpdate:"plan",entries:R});}let S=Gl(f,h);if(S==="pending")return w;let k=Vl(f,p),x=[];if(typeof k=="string"&&k.length>0&&x.push({type:"content",content:{type:"text",text:k}}),Array.isArray(p.attachments))for(let R of p.attachments){let T=Kl(R);T&&x.push(T);}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=Nl[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 zl={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 Yt(){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 f=g.session_id||void 0,m=[];switch(g.type){case "assistant":{let k=g;m.push(...r(k));let x=n(k.message?.usage);x&&m.push({sessionUpdate:"usage",scope:"call",usage:x});break}case "stream_event":{m.push(...s(g));break}case "user":{m.push(...o(g));break}case "system":return null;case "result":{let k=n(g.usage);if(k&&m.push({sessionUpdate:"usage",scope:"run",usage:k}),g.is_error!==true)break;let x=g.error;m.push({sessionUpdate:"error",message:D([x?.message,g.subtype],g.error??g),fatal:true});break}default:return null}if(m.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 m.map(k=>({sessionId:f,update:k,...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={},f=p(c.input_tokens),m=p(c.output_tokens),h=p(c.cache_read_input_tokens);f!==void 0&&(g.promptTokens=f),m!==void 0&&(g.completionTokens=m),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 f=d(g);c.push(...f);}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,f=p.content_block;f&&(t.set(g,f),f.type==="tool_use"&&e.set(g,""));break}case "content_block_delta":{let g=p.index??0,f=p.delta,m=t.get(g);if(f?.type==="text_delta"&&f.text)c.push({sessionUpdate:"agent_message_chunk",content:{type:"text",text:f.text}});else if(f?.type==="thinking_delta"&&f.thinking)c.push({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:f.thinking}});else if(f?.type==="input_json_delta"&&f.partial_json&&m?.type==="tool_use"){let h=e.get(g)||"";e.set(g,h+f.partial_json);}break}case "content_block_stop":{let g=p.index??0,f=t.get(g);if(f&&!(f.type==="text"&&f.text)){if(!(f.type==="thinking"&&f.thinking)){if(f.type==="tool_use"){let m=f,h=e.get(g)||"";e.delete(g);let y=m.input;if(h)try{y=JSON.parse(h);}catch{}let b={...m,input:y},_=u(b);_&&c.push(_);}else if(f.type==="tool_result"){let m=l(f);m&&c.push(m);}}}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 f=l(g);f&&p.push(f);}}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:f,kind:m,content:h,locations:y}=i(p,g||{});return {sessionUpdate:"tool_call",toolCallId:c,title:f,toolName:p,kind:m,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,f=[];if(typeof g=="string"&&g.length>0)f.push({type:"content",content:{type:"text",text:g}});else if(Array.isArray(g))for(let m of g)m.type==="text"&&f.push({type:"content",content:{type:"text",text:m.text}});return {sessionUpdate:"tool_call_update",toolCallId:c,status:p?"failed":"completed",content:f}}function i(a,c){let p=zl[a]||"other",g=[],f=[],m=a;switch(a){case "Read":case "read_file":m=`Read ${c.file_path||c.absolute_path||"file"}`,(c.file_path||c.absolute_path)&&f.push({path:c.file_path||c.absolute_path});break;case "Write":case "write_file":m=`Write ${c.file_path||"file"}`,c.file_path&&(f.push({path:c.file_path}),g.push({type:"diff",path:c.file_path,oldText:null,newText:c.content||""}));break;case "Edit":case "edit_file":m=`Edit ${c.file_path||"file"}`,c.file_path&&f.push({path:c.file_path});break;case "Bash":case "shell":case "run_shell_command":m=c.command?`\`${c.command}\``:"Run command",c.description&&g.push({type:"content",content:{type:"text",text:c.description}});break;case "WebFetch":m=c.url?`Fetch ${c.url}`:"Web fetch";break;case "WebSearch":case "brave_web_search":m=c.query?`"${c.query}"`:"Web search";break;case "Glob":m=`Find ${c.pattern||"files"}`,c.path&&f.push({path:c.path});break;case "Grep":m=`grep "${c.pattern||""}"`;break;case "LS":case "list_directory":m=`List ${c.path||"directory"}`,c.path&&f.push({path:c.path});break;case "Task":m=c.description||"Subagent task";break;case "TodoWrite":m="Update todos";break;case "ExitPlanMode":m="Exit plan mode";break;default:m=a;}return {title:m,kind:p,content:g,locations:f}}}function si(t){return Yt()(t)}function me(t){switch(t){case "claude":return zt();case "codex":return Ht();case "gemini":return Wt();case "qwen":return Yt();case "kimi":return ar();case "opencode":return lr();case "droid":return qt();default:return ()=>null}}function Hl(t,e){let n=e.trim();return n?me(t)(n):null}function ql(t,e){let n=[],r=e.split(`
|
|
20
|
+
`),s=me(t);for(let o of r){let d=o.trim();if(!d)continue;let u=s(d);u&&n.push(...u);}return n}var Rc=util.promisify(child_process.execFile),ae="SKILL.md",Tc=X.join(os$1.homedir(),".cache","evolve","skills"),_r=["skills","skills/.curated","skills/.experimental","skills/.system",".claude/skills"],Ec=/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)(?:@(.+))?$/,Pc=/^[0-9a-f]{40}$/,mr=2e3,hr=64*1024*1024,H=class extends Error{constructor(e){super(e),this.name="SkillRefError";}},j=class extends Error{constructor(e){super(e),this.name="SkillResolveError";}};function Ac(t){return t==="~"?os$1.homedir():t.startsWith("~/")?X.join(os$1.homedir(),t.slice(2)):t}function Ic(t){let e=t.indexOf("@");if(e===-1)return {base:t};let n=t.slice(e+1);if(!n)throw new H(`Empty @ref in skill reference segment: ${JSON.stringify(t)}`);return {base:t.slice(0,e),gitRef:n}}var Oc=/^[A-Za-z0-9._-]+$/;function Zt(t,e,n){if(!Oc.test(t))throw new H(`Cannot parse skill reference ${JSON.stringify(n)}: ${e} ${JSON.stringify(t)} may only contain letters, digits, ".", "_" and "-".`);return t}function wr(t){let e=String(t??"").trim();if(!e)throw new H("Skill reference cannot be empty.");if(e.startsWith("upload:")){let o=e.slice(7);if(!o)throw new H(`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 H(`Skill name reference ${JSON.stringify(e)} names no skill.`);return Zt(o,"skill name",e),{kind:"name",name:o,raw:e}}if(e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.startsWith("~"))return {kind:"local",path:Ac(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 H(`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}=Ic(d[d.length-1]);d[d.length-1]=u;let[i,a,c]=d;return Zt(i,"owner",e),Zt(a,"repo",e),c!==void 0&&Zt(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 H(`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(Ec);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 H(`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 kr(t){return `https://${t.host}/${t.org}/${t.repo}.git`}function Ce(t){return `https://${t.host}/${t.org}/${t.repo}`}async function oe(t,e){try{let{stdout:n}=await Rc("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 j(`git ${t[0]} failed${r.killed?" (timed out)":""}: ${s}`)}}async function vr(t,e={}){if(t.gitRef&&Pc.test(t.gitRef))return t.gitRef;let n=t.gitRef??"HEAD",s=(await oe(["ls-remote",kr(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 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 Oi(t){return t.message?.includes("Cannot find module")||t.message?.includes("MODULE_NOT_FOUND")}function Dr(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 st(t,e="e2b",n){let r=t||process.env[O];if(!r)throw new Error(`${O} is required for Evolve-managed sandbox features`);if(!ke.includes(e))throw new Error(`Unknown managed sandbox provider "${e}". Supported: ${ke.join(", ")}`);if(e==="daytona")try{let{createDaytonaProvider:s}=await import('@evolvingmachines/daytona');return Dr(Mr(s({apiKey:r,apiUrl:He("daytona"),managedToolboxUrl:Ms()})),n)}catch(s){let o=s;throw Oi(o)?Ii("@evolvingmachines/daytona","npm install @evolvingmachines/daytona"):o}if(e==="modal"){let{ManagedModalProvider:s}=await Promise.resolve().then(()=>(Ai(),Pi));return Dr(Mr(new s({apiKey:r,baseUrl:He("modal")})),n)}try{let{createE2BProvider:s}=await import('@evolvingmachines/e2b');return Dr(Mr(s({apiKey:Kc(r),apiUrl:Ln()})),n)}catch(s){let o=s;throw Oi(o)?Ii("@evolvingmachines/e2b","npm install @evolvingmachines/evolve"):o}}function Vc(t="e2b",e){let n=typeof e=="string"?{apiKey:e}:e??{},{apiKey:r,...s}=n;return st(r,t,s)}async function Ur(){let t=process.env[Mt];if(t)try{let{createE2BProvider:o}=await import('@evolvingmachines/e2b');return process.env.E2B_API_URL===Ln()&&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(`${Mt} is set but @evolvingmachines/e2b failed to load.
|
|
23
|
+
Try reinstalling: npm install @evolvingmachines/evolve`):d}let e=process.env[Dt];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(`${Dt} is set but @evolvingmachines/daytona failed to load.
|
|
24
|
+
Try installing: npm install @evolvingmachines/daytona`):d}let n=process.env[Ut],r=process.env[Bn];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(`${Ut} is set but @evolvingmachines/modal failed to load.
|
|
25
|
+
Try installing: npm install @evolvingmachines/modal`):d}let s=process.env[O];if(s)return st(s);throw new Error(`No sandbox provider configured. Either:
|
|
26
|
+
1. Set ${O} environment variable (recommended, get key at https://dashboard.evolvingmachines.ai)
|
|
27
|
+
2. Set ${Mt} environment variable (direct E2B access, get key at https://e2b.dev)
|
|
28
|
+
3. Set ${Dt} environment variable (direct Daytona access, get key at https://app.daytona.io)
|
|
29
|
+
4. Set ${Ut} and ${Bn} environment variables (direct Modal access, get tokens at https://modal.com/settings/tokens)
|
|
30
|
+
5. Pass sandbox explicitly: .withSandbox(provider)`)}function Gc(t){return new Promise(e=>setTimeout(e,t))}async function V(t,e,n=0){let r=zc(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 Gc(u),u*=r.backoffMultiplier;}return o}function zc(t){return {maxAttempts:t?.maxAttempts??3,backoffMs:t?.backoffMs??1e3,backoffMultiplier:t?.backoffMultiplier??2,retryOn:t?.retryOn??(e=>e.status==="error")}}var Di=`## FILESYSTEM INSTRUCTIONS:
|
|
31
|
+
|
|
32
|
+
You are running in a sandbox environment.
|
|
33
|
+
|
|
34
|
+
The file system is mounted at \`{{workingDir}}/\`
|
|
35
|
+
|
|
36
|
+
Your present working directory: \`{{workingDir}}/\`
|
|
37
|
+
|
|
38
|
+
IMPORTANT - Directory structure:
|
|
39
|
+
\`\`\`
|
|
40
|
+
{{workingDir}}/
|
|
41
|
+
\u251C\u2500\u2500 context/ # Input files (read-only) provided by the user
|
|
42
|
+
\u251C\u2500\u2500 scripts/ # Your code goes here
|
|
43
|
+
\u251C\u2500\u2500 temp/ # Scratch space
|
|
44
|
+
\u2514\u2500\u2500 output/ # Where you can save final deliverables
|
|
45
|
+
\`\`\`
|
|
46
|
+
|
|
47
|
+
### OUTPUT RULES:
|
|
48
|
+
|
|
49
|
+
The \`output/\` folder is how you deliver files to the user\u2014the SDK retrieves everything from there.
|
|
50
|
+
|
|
51
|
+
Use your best judgment:
|
|
52
|
+
- **Questions, explanations, conversation** \u2192 respond in chat
|
|
53
|
+
- **Artifacts** (files, documents, code, charts, data) \u2192 save to \`output/\`
|
|
54
|
+
|
|
55
|
+
Examples:
|
|
56
|
+
- "What is a binary search?" \u2192 chat
|
|
57
|
+
- "Summarize this document" \u2192 chat
|
|
58
|
+
- "Create an Excel report" \u2192 \`output/sales_report.xlsx\`
|
|
59
|
+
- "Build an HTML dashboard" \u2192 \`output/dashboard.html\`
|
|
60
|
+
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
61
|
+
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
62
|
+
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
63
|
+
`;var Ui=`## FILESYSTEM INSTRUCTIONS:
|
|
64
|
+
|
|
65
|
+
You are running in a sandbox environment.
|
|
66
|
+
|
|
67
|
+
The file system is mounted at \`{{workingDir}}/\`
|
|
68
|
+
|
|
69
|
+
Your present working directory: \`{{workingDir}}/\`
|
|
70
|
+
|
|
71
|
+
IMPORTANT - Directory structure:
|
|
72
|
+
\`\`\`
|
|
73
|
+
{{workingDir}}/
|
|
74
|
+
\u251C\u2500\u2500 repo/ # Code repository
|
|
75
|
+
\u251C\u2500\u2500 context/ # Input files (read-only) provided by the user
|
|
76
|
+
\u251C\u2500\u2500 scripts/ # Your code goes here
|
|
77
|
+
\u251C\u2500\u2500 temp/ # Scratch space
|
|
78
|
+
\u2514\u2500\u2500 output/ # Final deliverables
|
|
79
|
+
\`\`\`
|
|
80
|
+
|
|
81
|
+
### OUTPUT RULES:
|
|
82
|
+
|
|
83
|
+
The \`output/\` folder is how you deliver files to the user\u2014the SDK retrieves everything from there.
|
|
84
|
+
|
|
85
|
+
Use your best judgment:
|
|
86
|
+
- **Questions, explanations, conversation** \u2192 respond in chat
|
|
87
|
+
- **Artifacts** (files, documents, code, charts, data) \u2192 save to \`output/\`
|
|
88
|
+
|
|
89
|
+
Examples:
|
|
90
|
+
- "What is a binary search?" \u2192 chat
|
|
91
|
+
- "Summarize this document" \u2192 chat
|
|
92
|
+
- "Create an Excel report" \u2192 \`output/sales_report.xlsx\`
|
|
93
|
+
- "Build an HTML dashboard" \u2192 \`output/dashboard.html\`
|
|
94
|
+
- "Generate a bar chart" \u2192 \`output/revenue_chart.png\`
|
|
95
|
+
- "Write a Python script" \u2192 \`output/parser.py\`
|
|
96
|
+
- "Convert this to JSON" \u2192 \`output/data.json\`
|
|
97
|
+
`;var $i=`## SYSTEM PROMPT
|
|
98
|
+
|
|
99
|
+
{{systemPrompt}}`;var Li=`## STRUCTURED OUTPUT
|
|
100
|
+
|
|
101
|
+
Your final result MUST be saved to \`output/result.json\` following this schema:
|
|
102
|
+
|
|
103
|
+
\`\`\`json
|
|
104
|
+
{{schema}}
|
|
105
|
+
\`\`\`
|
|
106
|
+
|
|
107
|
+
You are free to:
|
|
108
|
+
- Reason through the problem step by step
|
|
109
|
+
- Read and analyze context files
|
|
110
|
+
- Use any available tools
|
|
111
|
+
- Process incrementally
|
|
112
|
+
- Create intermediate files in \`temp/\` or \`scripts/\`
|
|
113
|
+
|
|
114
|
+
But your final \`output/result.json\` MUST conform to the schema above.
|
|
115
|
+
|
|
116
|
+
### OUTPUT RESULTS (DELIVERABLES) MUST BE WRITTEN to \`output/result.json\` as files.
|
|
117
|
+
### Never just state results as text.`;var Bi=`## BROWSER AUTOMATION
|
|
118
|
+
|
|
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 Ni=`## Browser Automation
|
|
121
|
+
|
|
122
|
+
The agent-browser CDP connection is already configured. Use normal \`agent-browser\` commands when browser automation is needed.
|
|
123
|
+
`;var ji=`### 1. YOUR ROLE: BEST OF N JUDGE
|
|
124
|
+
|
|
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
|
+
|
|
127
|
+
### 2. CONTEXT STRUCTURE
|
|
128
|
+
|
|
129
|
+
\`\`\`
|
|
130
|
+
{{fileTree}}
|
|
131
|
+
\`\`\`
|
|
132
|
+
|
|
133
|
+
### 3. YOUR EVALUATION CRITERIA
|
|
134
|
+
|
|
135
|
+
You must judge their work based on:
|
|
136
|
+
|
|
137
|
+
\`\`\`
|
|
138
|
+
{{criteria}}
|
|
139
|
+
\`\`\`
|
|
140
|
+
|
|
141
|
+
### 4. YOUR PROCESS
|
|
142
|
+
|
|
143
|
+
1. Read \`worker_task/\` to understand the task:
|
|
144
|
+
- Review the worker system prompt and task prompt
|
|
145
|
+
- Check the expected output schema (if present)
|
|
146
|
+
- Examine the worker input files in \`input/\`
|
|
147
|
+
2. Carefully review EACH solution attempt in \`candidate_i/\`
|
|
148
|
+
3. Compare outputs against the evaluation criteria
|
|
149
|
+
4. Reason through your findings \u2014 perform all necessary evidence-based analyses and verifications before deciding
|
|
150
|
+
5. Pick the best candidate (0-indexed)
|
|
151
|
+
|
|
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 Fi=`### 1. YOUR ROLE: OUTPUT VERIFIER
|
|
154
|
+
|
|
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
|
+
|
|
157
|
+
### 2. CONTEXT STRUCTURE
|
|
158
|
+
|
|
159
|
+
\`\`\`
|
|
160
|
+
{{fileTree}}
|
|
161
|
+
\`\`\`
|
|
162
|
+
|
|
163
|
+
### 3. VERIFICATION CRITERIA
|
|
164
|
+
|
|
165
|
+
The output must satisfy:
|
|
166
|
+
|
|
167
|
+
\`\`\`
|
|
168
|
+
{{criteria}}
|
|
169
|
+
\`\`\`
|
|
170
|
+
|
|
171
|
+
### 4. YOUR PROCESS
|
|
172
|
+
|
|
173
|
+
1. Read \`worker_task/\` to understand what was asked:
|
|
174
|
+
- Review the worker system prompt (if present)
|
|
175
|
+
- Review the task prompt
|
|
176
|
+
- Check the expected output schema (if present)
|
|
177
|
+
- Examine any input files in \`input/\`
|
|
178
|
+
2. Carefully review the worker's output in \`worker_output/\`
|
|
179
|
+
3. Evaluate against the verification criteria
|
|
180
|
+
4. Reason through your findings
|
|
181
|
+
5. Make your decision
|
|
182
|
+
|
|
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
|
+
|
|
185
|
+
If failing, provide specific, actionable feedback explaining what needs to be fixed.
|
|
186
|
+
`;var Ji=`### CONTEXT STRUCTURE
|
|
187
|
+
|
|
188
|
+
\`\`\`
|
|
189
|
+
{{fileTree}}
|
|
190
|
+
\`\`\`
|
|
191
|
+
|
|
192
|
+
Examine all files within each item folder before producing your output.
|
|
193
|
+
`;var Ki="Evaluate the candidates and select the best one. You MUST save your decision to the file `output/result.json`.\n";var Vi="Verify the worker output against the criteria. You MUST save your decision to the file `output/result.json`.\n";var Gi=`{{originalPrompt}}
|
|
194
|
+
|
|
195
|
+
## IMPORTANT: Previous Attempt Failed Verification
|
|
196
|
+
|
|
197
|
+
Your previous attempt did not pass quality verification. Please address this feedback:
|
|
198
|
+
|
|
199
|
+
{{feedback}}
|
|
200
|
+
|
|
201
|
+
Make sure your output addresses all the feedback points above.
|
|
202
|
+
`;var zi=Di,Hi=Ui,qi=$i,Wi=Li,$r=Bi,Yi=Ni,Lr=ji,Xi=Ki,Br=Fi,Qi=Vi,Zi=Ji,Nr=Gi;function le(t,e){return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>Object.prototype.hasOwnProperty.call(e,r)?e[r]:n)}function jr(t){let e=t.mode==="swe"?Hi:zi,n=le(e,{workingDir:t.workingDir}).trim();if(t.browserPrompt&&(n+=`
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
${t.browserPrompt.trim()}`),t.systemPrompt&&(n+=`
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
${le(qi,{systemPrompt:t.systemPrompt}).trim()}`),t.schema){let r=Y(t.schema)?Re(t.schema):Te(t.schema);n+=`
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
${le(Wi,{schema:r}).trim()}`;}return n}function dn(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((f,m)=>{let y=m===g.length-1?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ";o.push({line:`${p}${y}${f.name}`,comment:f.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 eo=X.join(os$1.homedir(),Ls),it=class{tag;timestamp;provider;agent;model;sandboxId;apiKey;dashboardUrl;localFilePath;observability;parser;isClosed=false;metaWritten=false;warnedKeys=new Set;localQueue=Promise.resolve();dirReady=promises.mkdir(eo,{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.sandboxId=e.sandboxId,this.apiKey=e.apiKey,this.dashboardUrl=Ot(),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(eo,r),this.parser=me(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
|
+
`)?e:e+`
|
|
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
|
+
`;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=_o(e,l);if(!await lo(e,g)){let h=await yo(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 lo(e,g))throw new Error("Checkpoint upload verification failed (HeadObject)")}p=Ad();let m={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 Pd(e,wo(e,p),m);}else {let g=await ko(e,s.tag,l,"put");if(!g.alreadyExists){let m=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(m.exitCode!==0)throw new Error(`Checkpoint upload failed: ${m.stderr}`)}p=(await Id(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 vo(t,e,n){let r=await Yr(e,n),s=r.hash,o={agentType:r.agentType,workspaceMode:r.workspaceMode},d=await Ro(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 So(t,e){let n=e?.gatewayApiKey||process.env.EVOLVE_API_KEY,r=e?.gatewayUrl||E,s=!t.url&&!t.bucket&&!!n;return pn(t,s,r,n)}async function xo(t,e){let{s3:n}=await Me(),r=await ut(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 f of g.Contents)f.Key?.endsWith(".json")&&f.LastModified&&d.push({key:f.Key,lastModified:f.LastModified});u=g.IsTruncated?g.NextContinuationToken:void 0;}while(u);if(d.length===0)return [];d.sort((p,g)=>{let f=g.lastModified.getTime()-p.lastModified.getTime();return f!==0?f: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 bo(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 Co(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 Md(t){return t&&t>0?Math.min(t,500):100}async function Wr(t,e){return t.mode==="byok"?(await xo(t,{limit:1,tag:e?.tag}))[0]??null:(await Co(t,{limit:1,tag:e?.tag}))[0]??null}async function Yr(t,e){if(t.mode==="byok"){let n=wo(t,e);try{return await bo(t,n)}catch(r){throw Dd(r)?new Error(`Checkpoint ${e} not found`):r}}else return await Od(t,e)}async function co(t,e,n){if(e==="latest"){let r=await Wr(t,{tag:n});if(!r)throw new Error("No checkpoints found");return r.id}return e}async function Ro(t,e){if(t.mode==="byok")return yo(t,_o(t,e.hash),"get");{let n=await ko(t,e.tag,e.hash,"get");if(!n.url)throw new Error("Gateway presign returned no download URL");return n.url}}function To(t){return !(!t||X.isAbsolute(t)||t.startsWith("-")||X.normalize(t).startsWith("..")||t.includes("\0"))}function uo(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 Dd(t){let e=t.name,n=t.message;return t?.$metadata?.httpStatusCode===404||e==="NoSuchKey"||e==="NotFound"||n==="NoSuchKey"}function Kr(t){let e=t.filter(n=>!To(n));if(e.length>0)throw new Error(`Archive contains unsafe path(s): ${e.slice(0,3).join(", ")}`);return t}var Eo=10*1024*1024,po=false;async function Po(){if(!po)try{await Hr("tar",["--version"]),po=!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 go(t,e){let n=await Yr(t,e),r=await Ro(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:f,value:m}=await a.read();if(f){l.end();break}u.update(m),l.write(m)||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 zr=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";}},Ud={LC_ALL:"C",LANG:"C"};function $d(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 zr(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 fo(t){await Po();let{stdout:e}=await Hr("tar",["-tvzf",t],{maxBuffer:Eo,env:{...process.env,...Ud}}),{filePaths:n,dirPaths:r,symlinkPaths:s}=$d(e);return Kr(r),Kr(s),Kr(n)}async function Vr(t,e,n){await Po(),await promises.mkdir(e,{recursive:true});let r=["-xzf",t,"--no-same-owner","--no-same-permissions","-C",e];n?.length&&r.push("--",...n),await Hr("tar",r,{maxBuffer:Eo});}function Ld(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 Xr(t,e){let n=So(t,e);return Ao(n)}function Bd(t){let e=So(t||{});return Ao(e)}function Ao(t){return {async listCheckpoints(e){let n=Md(e?.limit);return t.mode==="byok"?xo(t,{limit:n,tag:e?.tag}):Co(t,{limit:n,tag:e?.tag})},async getCheckpoint(e){return Yr(t,e)},async downloadCheckpoint(e,n){let r=n?.extract!==false,s=n?.to||process.cwd(),o=await co(t,e),{tmpPath:d,metadata:u}=await go(t,o);try{if(r)return await promises.mkdir(s,{recursive:!0}),await fo(d),await Vr(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 co(t,e),{tmpPath:s}=await go(t,r),o;try{let d=await fo(s),u;if(n?.files){let i=n.files.filter(c=>!To(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(Ld);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 Vr(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 Vr(s,o);}let l={};return await Promise.all(u.map(async i=>{uo(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])=>{uo(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 gn(t){return typeof t=="string"&&t.length>0}function De(t,e,n){let r=t[e];if(!gn(r))throw new Error(`withPlugins() for ${n} requires ${e}`);return r}function Nd(t,e){let n=e.stderr||e.stdout||`exit code ${e.exitCode}`;return new Error(`Plugin setup failed while running: ${t}
|
|
221
|
+
${n}`)}function jd(t,e){switch(t){case "droid":{let n=De(e,"marketplace",t),r=De(e,"plugin",t);return [`droid plugin marketplace add ${ce(n)}`,`droid plugin install ${ce(r)} --scope user`]}case "claude":{let n=De(e,"marketplace",t),r=De(e,"plugin",t);return [`claude plugin marketplace add ${ce(n)} --scope user`,`claude plugin install ${ce(r)} --scope user`]}case "gemini":{let n=De(e,"source",t),r=e,s=[`gemini extensions install ${ce(n)}`];return gn(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=De(e,"marketplace",t),r=e,s=[`codex plugin marketplace add ${ce(n)}`];if(gn(r.ref)&&s.push(`--ref ${ce(r.ref)}`),Array.isArray(r.sparse))for(let o of r.sparse){if(!gn(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 Io(t,e,n){if(n?.length)for(let r of n){let s=jd(t,r);for(let o of s){let d=await e.commands.run(o,{timeoutMs:12e4});if(d.exitCode!==0)throw Nd(o,d)}}}var Uo="/home/user/.agent-browser",Oo=`${Uo}/config.json`,$o="/home/user/.actionbook",Jd=`${$o}/config.toml`;function Mo(t){return t==="actionbook"||t==="agent-browser"}function Kd(t){return t.remote===true}function Do(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 Lo(t){if(typeof t=="string"){if(t==="browser-use")return {provider:"browser-use",managed:false};if(Mo(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:Do(t.profile)};if(Mo(t.provider))return {provider:t.provider,managed:Kd(t),profile:Do(t.profile)};throw new Error("Unsupported browser configuration")}function Qr(t,e){return t==="actionbook"?{envs:{},files:[{path:Jd,data:smolToml.stringify({version:1,browser:{mode:"cloud",cdp_endpoint:e.cdpUrl}}).trimEnd()+`
|
|
222
|
+
`}],directories:[$o]}:{envs:{AGENT_BROWSER_CONFIG:Oo},files:[{path:Oo,data:`${JSON.stringify({cdp:e.cdpUrl},null,2)}
|
|
223
|
+
`}],directories:[Uo]}}function Bo(t){return (t?.dashboardUrl||E).replace(/\/$/,"")}async function No(t){return await t.text().catch(()=>"")}async function jo(t,e,n={}){let r=await fetch(`${Bo(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 No(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 Fo(t,e){let n=await fetch(`${Bo(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 No(n)}`)}var zd="RSA-OAEP-256",Zr="browser-login";function Hd(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function qd(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 Wd(t){return await t.text().catch(()=>"")}async function pt(t,e,n={}){let r=await fetch(`${Hd(t?.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${qd(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 Wd(r)}`);return await r.json()}async function Yd(t,e){let n=await pt(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:zd,keyId:n.id,ciphertext:r.toString("base64url")}}var fn=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 pt(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 Yd(this.config,e.password),r=await pt(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 pt(this.config,"/api/browser-credentials",{method:"DELETE",body:JSON.stringify(n)})}};function es(t={}){return new fn(t)}async function Jo(t){return (await pt({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:Xd(t.config)})})).server}function Xd(t){return t?.allow?.map(e=>({website:e.website,...e.accountLabel||e.account_label?{account_label:e.accountLabel||e.account_label}:{}}))}var ts="x-evolve-provider-runtime-binding";function Qd(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}async function Zd(t){return await t.text().catch(()=>"")}var gt=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ProviderRuntimeTokenRequestError";}};function Ko(t){return t instanceof gt&&t.status===404}async function ns(t,e,n={}){let r=await fetch(`${Qd(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 gt(r.status,`Provider runtime token request failed (${r.status}): ${await Zd(r)}`);return await r.json()}function eu(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 Vo(t,e){let n=await ns(t,"/api/provider-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!eu(n))throw new gt(502,"Provider runtime token response was invalid");return n}async function Go(t,e){return (await ns(t,"/api/provider-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function zo(t,e){return (await ns(t,"/api/provider-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}function rs(t){return t.delivery==="direct"}var hn=18181,$="/tmp/evolve-managed-secrets",ft=`${$}/proxy.py`,Le=`${$}/config.json`,he=`${$}/ca.crt`,mn=`${$}/ca.key`,Ue=`${$}/ca-bundle.crt`,Wo=["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 Yo(){return [...Wo]}var Xo=String.raw`#!/usr/bin/env python3
|
|
224
|
+
import base64
|
|
225
|
+
import json
|
|
226
|
+
import os
|
|
227
|
+
import select
|
|
228
|
+
import secrets
|
|
229
|
+
import socket
|
|
230
|
+
import ssl
|
|
231
|
+
import subprocess
|
|
232
|
+
import sys
|
|
233
|
+
import tempfile
|
|
234
|
+
import threading
|
|
235
|
+
import time
|
|
236
|
+
import urllib.error
|
|
237
|
+
import urllib.request
|
|
238
|
+
|
|
239
|
+
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]:
|
|
240
|
+
os.environ.pop(key, None)
|
|
241
|
+
|
|
242
|
+
CONFIG_PATH = sys.argv[1]
|
|
243
|
+
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
244
|
+
CONFIG = json.load(f)
|
|
245
|
+
try:
|
|
246
|
+
os.unlink(CONFIG_PATH)
|
|
247
|
+
except FileNotFoundError:
|
|
248
|
+
pass
|
|
249
|
+
|
|
250
|
+
MAX_BODY_BYTES = int(CONFIG.get("max_body_bytes", 10 * 1024 * 1024))
|
|
251
|
+
CONNECT_TIMEOUT_SECONDS = 15
|
|
252
|
+
SOCKET_TIMEOUT_SECONDS = 130
|
|
253
|
+
MAX_WORKERS = 100
|
|
254
|
+
WORKERS = threading.BoundedSemaphore(MAX_WORKERS)
|
|
255
|
+
HOST_PATTERNS = [h.lower() for h in CONFIG["hosts"]]
|
|
256
|
+
PLACEHOLDERS = set(CONFIG["placeholders"])
|
|
257
|
+
PLACEHOLDER_BYTES = [p.encode("utf-8") for p in CONFIG["placeholders"]]
|
|
258
|
+
BASE_DIR = CONFIG["base_dir"]
|
|
259
|
+
CERT_DIR = os.path.join(BASE_DIR, "certs")
|
|
260
|
+
os.makedirs(CERT_DIR, exist_ok=True)
|
|
261
|
+
CHANNEL_SECRET = secrets.token_urlsafe(32)
|
|
262
|
+
|
|
263
|
+
def register_channel():
|
|
264
|
+
payload = json.dumps({}).encode("utf-8")
|
|
265
|
+
req = urllib.request.Request(
|
|
266
|
+
CONFIG["channel_url"],
|
|
267
|
+
data=payload,
|
|
268
|
+
method="POST",
|
|
269
|
+
headers={
|
|
270
|
+
"content-type": "application/json",
|
|
271
|
+
"accept": "application/json",
|
|
272
|
+
"x-evolve-managed-secret-token": CONFIG["token"],
|
|
273
|
+
"x-evolve-managed-secret-binding": CONFIG["binding"],
|
|
274
|
+
"x-evolve-managed-secret-channel": CHANNEL_SECRET,
|
|
275
|
+
},
|
|
276
|
+
)
|
|
277
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
278
|
+
if resp.status < 200 or resp.status >= 300:
|
|
279
|
+
raise RuntimeError("managed secret channel registration failed")
|
|
280
|
+
|
|
281
|
+
def host_matches(pattern, host):
|
|
282
|
+
host = host.lower()
|
|
283
|
+
if pattern.startswith("*."):
|
|
284
|
+
base = pattern[2:]
|
|
285
|
+
return host != base and host.endswith("." + base)
|
|
286
|
+
return host == pattern
|
|
287
|
+
|
|
288
|
+
def is_managed_host(host):
|
|
289
|
+
clean = host.split(":", 1)[0].strip("[]").lower()
|
|
290
|
+
return any(host_matches(pattern, clean) for pattern in HOST_PATTERNS)
|
|
291
|
+
|
|
292
|
+
def safe_name(host):
|
|
293
|
+
return "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in host)[:180]
|
|
294
|
+
|
|
295
|
+
def ensure_cert(host):
|
|
296
|
+
name = safe_name(host)
|
|
297
|
+
cert = os.path.join(CERT_DIR, name + ".crt")
|
|
298
|
+
key = os.path.join(CERT_DIR, name + ".key")
|
|
299
|
+
if os.path.exists(cert) and os.path.exists(key):
|
|
300
|
+
return cert, key
|
|
301
|
+
csr = os.path.join(CERT_DIR, name + ".csr")
|
|
302
|
+
ext = os.path.join(CERT_DIR, name + ".ext")
|
|
303
|
+
san = "IP:" + host if host.replace(".", "").isdigit() else "DNS:" + host
|
|
304
|
+
with open(ext, "w", encoding="utf-8") as f:
|
|
305
|
+
f.write("basicConstraints=critical,CA:FALSE\n")
|
|
306
|
+
f.write("keyUsage=critical,digitalSignature,keyEncipherment\n")
|
|
307
|
+
f.write("subjectAltName=" + san + "\n")
|
|
308
|
+
f.write("extendedKeyUsage=serverAuth\n")
|
|
309
|
+
subprocess.run(
|
|
310
|
+
["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-subj", "/CN=" + host, "-out", csr],
|
|
311
|
+
check=True,
|
|
312
|
+
stdout=subprocess.DEVNULL,
|
|
313
|
+
stderr=subprocess.DEVNULL,
|
|
314
|
+
)
|
|
315
|
+
subprocess.run(
|
|
316
|
+
[
|
|
317
|
+
"openssl", "x509", "-req", "-in", csr,
|
|
318
|
+
"-CA", CONFIG["ca_cert"], "-CAkey", CONFIG["ca_key"], "-CAcreateserial",
|
|
319
|
+
"-out", cert, "-days", "30", "-sha256", "-extfile", ext,
|
|
320
|
+
],
|
|
321
|
+
check=True,
|
|
322
|
+
stdout=subprocess.DEVNULL,
|
|
323
|
+
stderr=subprocess.DEVNULL,
|
|
324
|
+
)
|
|
325
|
+
return cert, key
|
|
326
|
+
|
|
327
|
+
def pipe_raw(client, host, port):
|
|
328
|
+
upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS)
|
|
329
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
330
|
+
upstream.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
331
|
+
try:
|
|
332
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
333
|
+
sockets = [client, upstream]
|
|
334
|
+
while True:
|
|
335
|
+
readable, _, _ = select.select(sockets, [], [], 120)
|
|
336
|
+
if not readable:
|
|
337
|
+
break
|
|
338
|
+
for sock in readable:
|
|
339
|
+
data = sock.recv(65536)
|
|
340
|
+
if not data:
|
|
341
|
+
return
|
|
342
|
+
(upstream if sock is client else client).sendall(data)
|
|
343
|
+
finally:
|
|
344
|
+
upstream.close()
|
|
345
|
+
|
|
346
|
+
def recv_until(sock, marker, limit=65536):
|
|
347
|
+
data = b""
|
|
348
|
+
while marker not in data:
|
|
349
|
+
chunk = sock.recv(4096)
|
|
350
|
+
if not chunk:
|
|
351
|
+
break
|
|
352
|
+
data += chunk
|
|
353
|
+
if len(data) > limit:
|
|
354
|
+
raise RuntimeError("request headers too large")
|
|
355
|
+
return data
|
|
356
|
+
|
|
357
|
+
def parse_headers(blob):
|
|
358
|
+
head, rest = blob.split(b"\r\n\r\n", 1)
|
|
359
|
+
lines = head.decode("iso-8859-1").split("\r\n")
|
|
360
|
+
request_line = lines[0]
|
|
361
|
+
headers = {}
|
|
362
|
+
for line in lines[1:]:
|
|
363
|
+
if not line or ":" not in line:
|
|
364
|
+
continue
|
|
365
|
+
name, value = line.split(":", 1)
|
|
366
|
+
headers[name.strip()] = value.strip()
|
|
367
|
+
return request_line, headers, rest
|
|
368
|
+
|
|
369
|
+
def header_value(headers, name):
|
|
370
|
+
wanted = name.lower()
|
|
371
|
+
for key, value in headers.items():
|
|
372
|
+
if key.lower() == wanted:
|
|
373
|
+
return value
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
def read_chunked_body(sock, initial):
|
|
377
|
+
data = initial
|
|
378
|
+
body = b""
|
|
379
|
+
while True:
|
|
380
|
+
while b"\r\n" not in data:
|
|
381
|
+
chunk = sock.recv(4096)
|
|
382
|
+
if not chunk:
|
|
383
|
+
raise RuntimeError("incomplete chunked request")
|
|
384
|
+
data += chunk
|
|
385
|
+
line, data = data.split(b"\r\n", 1)
|
|
386
|
+
size = int((line.split(b";", 1)[0].strip() or b"0"), 16)
|
|
387
|
+
if size == 0:
|
|
388
|
+
return body
|
|
389
|
+
if len(body) + size > MAX_BODY_BYTES:
|
|
390
|
+
raise RuntimeError("request body too large")
|
|
391
|
+
while len(data) < size + 2:
|
|
392
|
+
chunk = sock.recv(65536)
|
|
393
|
+
if not chunk:
|
|
394
|
+
raise RuntimeError("incomplete chunked request")
|
|
395
|
+
data += chunk
|
|
396
|
+
body += data[:size]
|
|
397
|
+
data = data[size + 2:]
|
|
398
|
+
|
|
399
|
+
def read_request(tls_sock):
|
|
400
|
+
blob = recv_until(tls_sock, b"\r\n\r\n")
|
|
401
|
+
if not blob:
|
|
402
|
+
return None
|
|
403
|
+
request_line, headers, rest = parse_headers(blob)
|
|
404
|
+
transfer_encoding = (header_value(headers, "Transfer-Encoding") or "").lower()
|
|
405
|
+
if "chunked" in transfer_encoding:
|
|
406
|
+
return request_line, headers, read_chunked_body(tls_sock, rest)
|
|
407
|
+
length = int(header_value(headers, "Content-Length") or "0")
|
|
408
|
+
if length > MAX_BODY_BYTES:
|
|
409
|
+
raise RuntimeError("request body too large")
|
|
410
|
+
body = rest
|
|
411
|
+
while len(body) < length:
|
|
412
|
+
chunk = tls_sock.recv(min(65536, length - len(body)))
|
|
413
|
+
if not chunk:
|
|
414
|
+
break
|
|
415
|
+
body += chunk
|
|
416
|
+
return request_line, headers, body[:length]
|
|
417
|
+
|
|
418
|
+
def uses_placeholder(path, headers, body):
|
|
419
|
+
if any(ph in path for ph in PLACEHOLDERS):
|
|
420
|
+
return True
|
|
421
|
+
if any(ph in value for ph in PLACEHOLDERS for value in headers.values()):
|
|
422
|
+
return True
|
|
423
|
+
return any(ph_b in body for ph_b in PLACEHOLDER_BYTES)
|
|
424
|
+
|
|
425
|
+
def brokered_status(transport_status, transport_reason, payload):
|
|
426
|
+
# A brokered reply carries the TRUE upstream status inside the payload;
|
|
427
|
+
# the dashboard's own status reports only the health of the hop to it.
|
|
428
|
+
# Servers older than the status lane omit it: those fall back.
|
|
429
|
+
status = payload.get("status")
|
|
430
|
+
if isinstance(status, bool) or not isinstance(status, int) or not 100 <= status <= 599:
|
|
431
|
+
return transport_status, transport_reason
|
|
432
|
+
reason = payload.get("statusText")
|
|
433
|
+
return status, reason if isinstance(reason, str) else ""
|
|
434
|
+
|
|
435
|
+
def egress_failure(exc):
|
|
436
|
+
body = json.dumps({
|
|
437
|
+
"error": "managed secret egress request failed",
|
|
438
|
+
"detail": str(exc),
|
|
439
|
+
}).encode("utf-8")
|
|
440
|
+
return 502, "Managed Secret Egress Unavailable", {
|
|
441
|
+
"headers": {"content-type": "application/json"},
|
|
442
|
+
"bodyBase64": base64.b64encode(body).decode("ascii"),
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
def call_dashboard(method, url, headers, body):
|
|
446
|
+
payload = json.dumps({
|
|
447
|
+
"method": method,
|
|
448
|
+
"url": url,
|
|
449
|
+
"headers": headers,
|
|
450
|
+
"bodyBase64": base64.b64encode(body).decode("ascii") if body else "",
|
|
451
|
+
}).encode("utf-8")
|
|
452
|
+
req = urllib.request.Request(
|
|
453
|
+
CONFIG["egress_url"],
|
|
454
|
+
data=payload,
|
|
455
|
+
method="POST",
|
|
456
|
+
headers={
|
|
457
|
+
"content-type": "application/json",
|
|
458
|
+
"accept": "application/json",
|
|
459
|
+
"x-evolve-managed-secret-token": CONFIG["token"],
|
|
460
|
+
"x-evolve-managed-secret-binding": CONFIG["binding"],
|
|
461
|
+
"x-evolve-managed-secret-channel": CHANNEL_SECRET,
|
|
462
|
+
},
|
|
463
|
+
)
|
|
464
|
+
try:
|
|
465
|
+
with urllib.request.urlopen(req, timeout=130) as resp:
|
|
466
|
+
result = json.loads(resp.read().decode("utf-8"))
|
|
467
|
+
if not isinstance(result, dict):
|
|
468
|
+
raise ValueError("managed secret egress returned a non-object response")
|
|
469
|
+
status, reason = brokered_status(resp.status, resp.reason, result)
|
|
470
|
+
return status, reason, result
|
|
471
|
+
except urllib.error.HTTPError as err:
|
|
472
|
+
text = err.read().decode("utf-8", "replace")
|
|
473
|
+
return err.code, "Managed Secret Egress Error", {"headers": {"content-type": "application/json"}, "bodyBase64": base64.b64encode(text.encode()).decode("ascii")}
|
|
474
|
+
except (urllib.error.URLError, OSError, ValueError) as err:
|
|
475
|
+
# Connection reset, SSL EOF, timeout, or an unreadable body: the agent
|
|
476
|
+
# gets a typed 502 and the proxy keeps serving.
|
|
477
|
+
return egress_failure(err)
|
|
478
|
+
|
|
479
|
+
def read_limited_response(stream):
|
|
480
|
+
chunks = []
|
|
481
|
+
total = 0
|
|
482
|
+
while True:
|
|
483
|
+
chunk = stream.read(65536)
|
|
484
|
+
if not chunk:
|
|
485
|
+
break
|
|
486
|
+
total += len(chunk)
|
|
487
|
+
if total > MAX_BODY_BYTES:
|
|
488
|
+
raise RuntimeError("response body too large")
|
|
489
|
+
chunks.append(chunk)
|
|
490
|
+
return b"".join(chunks)
|
|
491
|
+
|
|
492
|
+
def call_direct(method, url, headers, body):
|
|
493
|
+
hop_by_hop = {"connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "host", "content-length"}
|
|
494
|
+
request_headers = {k: v for k, v in headers.items() if k.lower() not in hop_by_hop}
|
|
495
|
+
req = urllib.request.Request(
|
|
496
|
+
url,
|
|
497
|
+
data=body if body else None,
|
|
498
|
+
method=method,
|
|
499
|
+
headers=request_headers,
|
|
500
|
+
)
|
|
501
|
+
try:
|
|
502
|
+
with urllib.request.urlopen(req, timeout=130) as resp:
|
|
503
|
+
return resp.status, resp.reason, {
|
|
504
|
+
"headers": dict(resp.headers.items()),
|
|
505
|
+
"bodyBase64": base64.b64encode(read_limited_response(resp)).decode("ascii"),
|
|
506
|
+
}
|
|
507
|
+
except urllib.error.HTTPError as err:
|
|
508
|
+
return err.code, err.reason, {
|
|
509
|
+
"headers": dict(err.headers.items()),
|
|
510
|
+
"bodyBase64": base64.b64encode(read_limited_response(err)).decode("ascii"),
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
def send_response(tls_sock, status, reason, result):
|
|
514
|
+
body = base64.b64decode(result.get("bodyBase64") or "")
|
|
515
|
+
headers = {str(k): str(v) for k, v in (result.get("headers") or {}).items()}
|
|
516
|
+
headers["content-length"] = str(len(body))
|
|
517
|
+
headers["connection"] = "close"
|
|
518
|
+
status_line = ("HTTP/1.1 %d %s\r\n" % (status, reason or "")).encode("ascii", "replace")
|
|
519
|
+
header_blob = b"".join((name + ": " + value + "\r\n").encode("iso-8859-1", "replace") for name, value in headers.items())
|
|
520
|
+
tls_sock.sendall(status_line + header_blob + b"\r\n" + body)
|
|
521
|
+
|
|
522
|
+
def dispatch_managed_request(method, url, headers, body):
|
|
523
|
+
if uses_placeholder(url, headers, body):
|
|
524
|
+
return call_dashboard(method, url, headers, body)
|
|
525
|
+
return call_direct(method, url, headers, body)
|
|
526
|
+
|
|
527
|
+
def handle_managed_connect(client, host, port):
|
|
528
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
529
|
+
cert, key = ensure_cert(host)
|
|
530
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
531
|
+
ctx.load_cert_chain(cert, key)
|
|
532
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
533
|
+
tls_sock = ctx.wrap_socket(client, server_side=True)
|
|
534
|
+
tls_sock.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
535
|
+
try:
|
|
536
|
+
request = read_request(tls_sock)
|
|
537
|
+
if not request:
|
|
538
|
+
return
|
|
539
|
+
request_line, headers, body = request
|
|
540
|
+
parts = request_line.split()
|
|
541
|
+
if len(parts) < 2:
|
|
542
|
+
raise RuntimeError("bad request line")
|
|
543
|
+
method, path = parts[0].upper(), parts[1]
|
|
544
|
+
if path.startswith("http://") or path.startswith("https://"):
|
|
545
|
+
url = path
|
|
546
|
+
else:
|
|
547
|
+
url = "https://%s%s" % (host if port == 443 else host + ":" + str(port), path)
|
|
548
|
+
status, reason, result = dispatch_managed_request(method, url, headers, body)
|
|
549
|
+
send_response(tls_sock, status, reason, result)
|
|
550
|
+
finally:
|
|
551
|
+
try:
|
|
552
|
+
tls_sock.close()
|
|
553
|
+
except Exception:
|
|
554
|
+
pass
|
|
555
|
+
|
|
556
|
+
def handle_client(client):
|
|
557
|
+
try:
|
|
558
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
559
|
+
blob = recv_until(client, b"\r\n\r\n")
|
|
560
|
+
if not blob:
|
|
561
|
+
return
|
|
562
|
+
request_line, headers, rest = parse_headers(blob)
|
|
563
|
+
parts = request_line.split()
|
|
564
|
+
if len(parts) < 3:
|
|
565
|
+
return
|
|
566
|
+
if parts[0].upper() == "CONNECT":
|
|
567
|
+
target = parts[1]
|
|
568
|
+
if ":" in target:
|
|
569
|
+
host, port_s = target.rsplit(":", 1)
|
|
570
|
+
port = int(port_s)
|
|
571
|
+
else:
|
|
572
|
+
host, port = target, 443
|
|
573
|
+
host = host.strip("[]")
|
|
574
|
+
if is_managed_host(host):
|
|
575
|
+
handle_managed_connect(client, host, port)
|
|
576
|
+
else:
|
|
577
|
+
pipe_raw(client, host, port)
|
|
578
|
+
return
|
|
579
|
+
client.sendall(b"HTTP/1.1 501 Not Implemented\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
|
|
580
|
+
except Exception as exc:
|
|
581
|
+
try:
|
|
582
|
+
body = json.dumps({"error": str(exc)}).encode("utf-8")
|
|
583
|
+
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\ncontent-type: application/json\r\ncontent-length: " + str(len(body)).encode() + b"\r\nconnection: close\r\n\r\n" + body)
|
|
584
|
+
except Exception:
|
|
585
|
+
pass
|
|
586
|
+
finally:
|
|
587
|
+
try:
|
|
588
|
+
client.close()
|
|
589
|
+
except Exception:
|
|
590
|
+
pass
|
|
591
|
+
|
|
592
|
+
def close_quietly(sock):
|
|
593
|
+
try:
|
|
594
|
+
sock.close()
|
|
595
|
+
except Exception:
|
|
596
|
+
pass
|
|
597
|
+
|
|
598
|
+
def reject_client(client):
|
|
599
|
+
try:
|
|
600
|
+
client.sendall(b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
|
|
601
|
+
except Exception:
|
|
602
|
+
pass
|
|
603
|
+
close_quietly(client)
|
|
604
|
+
|
|
605
|
+
def serve():
|
|
606
|
+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
607
|
+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
608
|
+
server.bind(("127.0.0.1", int(CONFIG["port"])))
|
|
609
|
+
server.listen(100)
|
|
610
|
+
while True:
|
|
611
|
+
# The listener outlives every connection: nothing a single accept or
|
|
612
|
+
# handoff raises may end the loop, or the sandbox loses egress for the
|
|
613
|
+
# rest of the session.
|
|
614
|
+
try:
|
|
615
|
+
client, _ = server.accept()
|
|
616
|
+
except Exception:
|
|
617
|
+
time.sleep(0.05)
|
|
618
|
+
continue
|
|
619
|
+
if not WORKERS.acquire(blocking=False):
|
|
620
|
+
reject_client(client)
|
|
621
|
+
continue
|
|
622
|
+
# Bound per thread: the loop rebinds the client on the next accept.
|
|
623
|
+
def run_client(sock=client):
|
|
624
|
+
try:
|
|
625
|
+
handle_client(sock)
|
|
626
|
+
except Exception:
|
|
627
|
+
pass
|
|
628
|
+
finally:
|
|
629
|
+
WORKERS.release()
|
|
630
|
+
try:
|
|
631
|
+
threading.Thread(target=run_client, daemon=True).start()
|
|
632
|
+
except Exception:
|
|
633
|
+
WORKERS.release()
|
|
634
|
+
close_quietly(client)
|
|
635
|
+
|
|
636
|
+
if __name__ == "__main__":
|
|
637
|
+
register_channel()
|
|
638
|
+
serve()
|
|
639
|
+
`;function tu(t){return (t||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"")}function nu(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 ru(t){return await t.text().catch(()=>"")}async function $e(t,e,n={}){let r=await fetch(`${tu(t.dashboardUrl)}${e}`,{...n,headers:{Authorization:`Bearer ${nu(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 ru(r)}`);return await r.json()}function su(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 ss(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:su(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 iu(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function Ho(t){try{return new URL(t).protocol==="https:"}catch{return false}}function ou(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"&&Ho(e.egressUrl)&&typeof e.channelUrl=="string"&&Ho(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"||!iu(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 Qo(t,e){let n=await $e(t,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(e)});if(!ou(n))throw new Error("Invalid managed secret runtime token response");return n}async function Zo(t,e){return (await $e(t,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(e)})).ok}async function ea(t,e){return (await $e(t,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(e)})).ok}var au=/^[A-Za-z0-9._-]{1,80}$/;function lu(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=qo(e.name,`managedSecrets[${n}].name`),s;if(e.label!==void 0){if(typeof e.label!="string"||!au.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:qo(e.as,`managedSecrets[${n}].as`);return {name:r,...s!==void 0?{label:s}:{},...o!==void 0?{as:o}:{}}})}function qo(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 cu(t){let e=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...Wo]),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 ta(t,e){if(!t)return;let n=lu(t),r=cu(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 is(t){return t.env.some(e=>!rs(e))}function na(t){let e={};for(let s of t.env)rs(s)?e[s.envName]=s.value:e[s.envName]=s.placeholder;if(!is(t))return e;let n=`http://127.0.0.1:${hn}`;e.HTTPS_PROXY=n,e.https_proxy=n,e.NODE_EXTRA_CA_CERTS=he,e.SSL_CERT_FILE=Ue,e.REQUESTS_CA_BUNDLE=Ue,e.CURL_CA_BUNDLE=Ue,e.GIT_SSL_CAINFO=Ue;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 ra(t){let e=t.env.filter(r=>!rs(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:$,ca_cert:he,ca_key:mn,port:hn,max_body_bytes:10*1024*1024},null,2)}function sa(){return ["umask 077",`mkdir -p ${$}/certs`,`chmod 700 ${$} ${$}/certs`,`chmod 700 ${ft} 2>/dev/null || true`,`chmod 600 ${Le} 2>/dev/null || true`,`if [ ! -f ${mn} ]; then openssl genrsa -out ${mn} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${he} ]; then openssl req -x509 -new -nodes -key ${mn} -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} > ${Ue}; else cp ${he} ${Ue}; 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 ia(){return `umask 077 && exec python3 ${ft} ${Le}`}function oa(){return `rm -f ${Le}`}function mt(t){return `'${t.replaceAll("'",`'"'"'`)}'`}function du(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 aa(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 ${mt(a)} ]; then echo MISSING ${mt(a)}; elif [ ! -r ${mt(a)} ]; then echo UNREADABLE ${mt(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(mt).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=du(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(f=>a===f||a.startsWith(`${f.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 yn="EVOLVE_PROVIDER_RUNTIME_BINDING",os="gemini-api-key";function ht(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 mu(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`")}function la(t){return `${t}-${crypto.randomBytes(8).toString("hex")}`}function as(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 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'
|
|
642
|
+
import socket, sys, time
|
|
643
|
+
for _ in range(50):
|
|
644
|
+
try:
|
|
645
|
+
s = socket.create_connection(("127.0.0.1", ${hn}), timeout=0.2)
|
|
646
|
+
s.close()
|
|
647
|
+
sys.exit(0)
|
|
648
|
+
except OSError:
|
|
649
|
+
time.sleep(0.1)
|
|
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 T=f(R);if(this.captureDroidSession(R,T),this.sessionLogger?.writeEventParsed(R,T),n?.onStdout?.(R+`
|
|
653
|
+
`),T&&n?.onContent)for(let P of T)n.onContent(P);}},h=k=>{n?.onStderr?.(k);},y=await i.commands.spawn(a,{cwd:this.workingDir,timeoutMs:s,envs:p,onStdout:m,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(k){throw this.interruptedOperations.delete(b),this.finalizeOperation(b,n,"run_failed","error"),k}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 k=f(g);if(this.captureDroidSession(g,k),this.sessionLogger?.writeEventParsed(g,k),n?.onStdout?.(g+`
|
|
654
|
+
`),k&&n?.onContent)for(let x of k)n.onContent(x);}await this.writeDroidSessionState(i),this.sessionLogger&&!o&&await this.flushSessionLoggerWithTimeout();let S;if(this.storage&&!o&&_.exitCode===0)try{S=await qr(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(k){console.warn(`[Evolve] Auto-checkpoint failed: ${k.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=qe,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 f;try{f=await p.wait();}catch(h){throw this.interruptedOperations.delete(g),this.finalizeOperation(g,r,"command_failed","error"),h}return this.interruptedOperations.delete(g)||f.exitCode===130?this.finalizeOperation(g,r,"command_interrupted","interrupted"):f.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:f.exitCode,stdout:u||f.stdout||"",stderr:l||f.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 aa(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 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}
|
|
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
|
|
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 vs(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 Pa(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 qu(t){let e=t.agent_result;return e==null?e??null:hs(t).lane==="measured"?e:{...e,cost_usd:null}}function Aa(t){let{trial:e}=t,n={};n["config.json"]=En({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"]=En({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:qu(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=bs(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
|
+
`)+`
|
|
662
|
+
`),t.home!==null&&Object.assign(n,Hu(r,t.home)),t.verifierLog!==null&&(n["verifier/test-stdout.txt"]=t.verifierLog),e.verifier_result?.rewards&&(n["verifier/reward.json"]=En(e.verifier_result.rewards)),e.exception_info&&(n["exception.txt"]=`${e.exception_info.exception_type}: ${e.exception_info.exception_message}
|
|
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,`
|
|
664
|
+
`);let s;for(;(s=e.indexOf(`
|
|
665
|
+
|
|
666
|
+
`))!==-1;){let o=e.slice(0,s);e=e.slice(s+2);let d,u,l=[];for(let i of o.split(`
|
|
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=_a;exports.AGENT_REGISTRY=J;exports.AGENT_TYPES=cl;exports.ANALYSIS_ARTIFACT_STREAMS=ba;exports.ANALYSIS_STATUSES=fa;exports.Agent=yt;exports.BINARY_EFFORT_VALUES=Js;exports.BROWSER_ACTIONBOOK_PROMPT=$r;exports.BROWSER_LOGIN_MCP_SERVER_NAME=Zr;exports.BrowserCredentialsClient=fn;exports.BrowserProfilesClient=_n;exports.CHECK_STATUSES=ma;exports.DEFAULT_HARNESS_TRIAL_LAYOUT=ys;exports.DEFAULT_REASONING_EFFORT=Ks;exports.EVAL_SANDBOX_PROVIDERS=pa;exports.Evolve=bt;exports.EvolveApiError=B;exports.EvolveConfigError=A;exports.EvolveDigestMismatchError=Tt;exports.EvolveIncompleteDownloadError=Et;exports.GATEWAY_TRACE_SEQ_BASE=xn;exports.HARNESS_TRIAL_LAYOUTS=Pn;exports.HOSTED_ERROR_CODES=ds;exports.ImportSettleError=Ct;exports.JOB_LIST_SCOPES=ga;exports.JUDGE_PROMPT=Lr;exports.MANAGED_SANDBOX_PROVIDERS=ke;exports.MAX_SKILL_BYTES=hr;exports.MAX_SKILL_FILES=mr;exports.NoActiveVersionError=Mn;exports.Pipeline=wn;exports.REASONING_EFFORTS=Fs;exports.RETRY_FEEDBACK_PROMPT=Nr;exports.SCHEMA_PROMPT=Wi;exports.SKILL_FILE_NAME=ae;exports.SUPPORTED_RUN_OPTIONS=dl;exports.SWARM_RESULT_BRAND=ye;exports.SYSTEM_PROMPT=qi;exports.Semaphore=Ne;exports.SkillRefError=H;exports.SkillResolveError=j;exports.Swarm=cs;exports.SwarmResultList=je;exports.TASK_LINKED_BY=vn;exports.TASK_LINK_REASONS=Sn;exports.TRIAL_ARTIFACT_STREAMS=ya;exports.TRIAL_STATUSES=ua;exports.TerminalPipeline=kn;exports.VALIDATION_PRESETS=$n;exports.VERIFY_PROMPT=Br;exports.WORKSPACE_PROMPT=zi;exports.WORKSPACE_SWE_PROMPT=Hi;exports.agents=Xa;exports.analyses=nl;exports.analysisEvolveRecord=Ia;exports.applyTemplate=le;exports.assembleTrialTree=Aa;exports.auth=$p;exports.browserCredentials=es;exports.browserProfiles=ls;exports.buildWorkerSystemPrompt=jr;exports.checkEvolveRecord=Ma;exports.checks=rl;exports.computeSkillDigest=yr;exports.createAgentParser=me;exports.createClaudeParser=zt;exports.createCodexParser=Ht;exports.createDroidParser=qt;exports.createGeminiParser=Wt;exports.datasets=Ya;exports.executeWithRetry=V;exports.expandPath=N;exports.gatewayUsageOf=Cn;exports.getAgentConfig=K;exports.getMcpSettingsDir=re;exports.getMcpSettingsPath=ne;exports.harborCopyPath=ks;exports.harnessEffortVocabulary=ul;exports.harnessTrialLayout=bs;exports.homeRelativePath=_s;exports.hosted=Np;exports.isAgentWorkUpdate=qs;exports.isHostedErrorCode=Rn;exports.isValidAgentType=Kn;exports.isZodSchema=Y;exports.jobEvolveRecord=Pa;exports.jobs=Za;exports.jsonSchemaToString=Te;exports.managedSandbox=Vc;exports.managedSecrets=ss;exports.meta=ol;exports.mountSkills=Cr;exports.orgs=il;exports.parseNdjsonLine=Hl;exports.parseNdjsonOutput=ql;exports.parseQwenOutput=si;exports.parseSkillRef=wr;exports.passAtK=ha;exports.pinSkillRef=Mc;exports.placeHomeObject=ws;exports.readLocalDir=wi;exports.resolveSkillSha=vr;exports.resolveSkills=xr;exports.resolveStorageConfig=pn;exports.saveLocalDir=ki;exports.sessions=Ou;exports.skillCloneUrl=kr;exports.skillDisplayUrl=Ce;exports.skills=Qa;exports.storage=Bd;exports.taskCheckEvolveRecord=Oa;exports.trialEvolveRecord=vs;exports.trials=el;exports.writeClaudeMcpConfig=Lt;exports.writeCodexMcpConfig=Kt;exports.writeDroidGatewaySettings=Jt;exports.writeDroidMcpConfig=Ft;exports.writeGeminiMcpConfig=Bt;exports.writeMcpConfig=Zn;exports.writeQwenMcpConfig=Nt;exports.zodSchemaToJson=Re;
|