@evolvingmachines/sail 0.0.0-stage → 0.0.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import {randomUUID,randomBytes,createHash}from'crypto';import {existsSync,readdirSync,readFileSync}from'fs';import {mkdir,writeFile,rename,rm}from'fs/promises';import {createRequire}from'module';import {homedir}from'os';import {join,posix,dirname}from'path';import {rootCertificates}from'tls';import {gunzipSync}from'zlib';var w=class extends Error{feature;provider;reason;code="feature_unsupported";unsupported=true;alternatives;constructor(e,t,n,i){super(`${t} does not support ${e}${n?`: ${n}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=e,this.provider=t,this.reason=n,i?.alternatives?.length&&(this.alternatives=[...i.alternatives]);}};var x=class extends Error{path;provider;constructor(e,t){super(`${t}: no such file or directory: ${e}`),this.name="SandboxPathNotFoundError",this.path=e,this.provider=t;}},R=class extends Error{sandboxId;provider;state;constructor(e,t,n){super(`${t} sandbox ${e} is not running (${n}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=e,this.provider=t,this.state=n;}};function ee(r,e){return !!r&&typeof r=="object"&&r.name===e}function ht(r){if(ee(r,"SandboxFeatureUnsupportedError"))return true;if(!r||typeof r!="object")return false;let e=r;return e.unsupported===true&&typeof e.feature=="string"}function St(r){return ee(r,"SandboxPathNotFoundError")}function bt(r){return ee(r,"SandboxNotRunningError")}var O=2,te=20;function b(r){return `'${r.replace(/'/g,"'\\''")}'`}function re(r){if(!Number.isInteger(r.offset)||r.offset<0)throw new RangeError(`offset must be a non-negative integer, got ${r.offset}`);if(!Number.isInteger(r.length)||r.length<0)throw new RangeError(`length must be a non-negative integer, got ${r.length}`)}function Ee(r){if(typeof r=="number")return Ie((r&4095).toString(8));if(/^[0-7]{1,4}$/.test(r))return Ie(r);throw new RangeError(`not an octal mode: ${r}`)}function Ie(r){return r.padStart(4,"0")}function F(r){let e=r instanceof Date?r:typeof r=="number"?new Date(r*1e3):new Date(r);if(Number.isNaN(e.getTime()))throw new RangeError(`not a timestamp: ${String(r)}`);return e.toISOString()}async function Re(r,e,t){if(re(e),e.length===0)return new Uint8Array(0);let n=e.offset+e.length-1,i=await fetch(r,{headers:{Range:`bytes=${e.offset}-${n}`},signal:AbortSignal.timeout(t.timeoutMs)});if(i.status===206){let s=new Uint8Array(await i.arrayBuffer());return s.length>e.length?s.subarray(0,e.length):s}if(i.status===200)return yt(i,e);if(i.status===416)return await i.body?.cancel().catch(()=>{}),new Uint8Array(0);throw await i.body?.cancel().catch(()=>{}),i.status===404?new x(t.path,t.provider):new Error(`${t.provider}: range read of ${t.path} failed (HTTP ${i.status})`)}async function yt(r,e){if(!r.body)return new Uint8Array(0);let t=r.body.getReader(),n=[],i=0,s=0,o=e.offset+e.length;try{for(;;){let{done:l,value:u}=await t.read();if(l)break;let m=i;if(i+=u.length,i>e.offset){let g=Math.max(0,e.offset-m),c=Math.min(u.length,o-m);c>g&&(n.push(u.subarray(g,c)),s+=c-g);}if(i>=o)break}}finally{await t.cancel().catch(()=>{});}let a=new Uint8Array(s),d=0;for(let l of n)a.set(l,d),d+=l.length;return a}function ne(r,e,t,n){return wt(r,e,xt(t,n))}function wt(r,e,t){return `if find / -maxdepth 0 -printf '' >/dev/null 2>&1; then find ${r} -printf '${e}'; else find ${r} -exec sh -c ${b(t)} sh {} +; fi`}function xt(r,e){return `stat -c "%f|%s|%Y|%y|%u|%U|%g|%G" -- "$@" | { for f; do IFS="|" read -r m s y t u un g gn || exit 70; case $(( 0x$m & 61440 )) in 32768) k=f;; 16384) k=d;; 40960) k=l;; 24576) k=b;; 8192) k=c;; 4096) k=p;; 49152) k=s;; *) k=U;; esac; case $t in *.*) t=\${t#*.}; t=\${t%% *}0;; *) t=0000000000;; esac; [ "$un" = UNKNOWN ] && un=$u; [ "$gn" = UNKNOWN ] && gn=$g; l=; [ $k = l ] && { l=$(readlink -- "$f"; printf x); l=\${l%x}; l=\${l%"
2
+ "}; }; e=\${f##*[!/]}; n=\${f%"$e"}; n=\${n##*/}$e; printf "${["%s","%s","%s.%s","%o","%s","%s","%s","%s"].join(r)+e}" "$k" "$s" "$y" "$t" $(( 0x$m & 4095 )) "$un" "$gn" "$l" "$n"; done; }`}function ie(r){return r.split(`
3
+ `).some(e=>e.includes("-printf")&&/unrecognized|unknown (?:primary|predicate|option)|invalid (?:predicate|option|argument)|not supported/i.test(e)||/(?:^|\W)stat: (?:command )?not found/.test(e))}var B="c-09256e558937";var D=class{length=0;half;head="";before="";last="";constructor(e=268369920){this.half=Math.max(1,Math.floor(e/2));}add(e){this.length+=e.length;let t=this.half-this.head.length;t>0&&(this.head+=e.length>t?e.slice(0,t):e),!(e.length<=t)&&(this.last+=t>0?e.slice(t):e,!(this.last.length<this.half)&&(this.before=this.last.slice(-this.half),this.last=""));}get cut(){return this.length>2*this.half}starts(e){return this.cut?e.length>=this.length&&e.startsWith(this.head)&&e.slice(this.length-this.half,this.length)===(this.before+this.last).slice(-this.half):e.startsWith(this.toString())}toString(){let e=this.before+this.last;if(!this.cut)return this.head+e;let t=`${this.head}
4
+ [... ${this.length-2*this.half} characters left out ...]
5
+ ${e.slice(-this.half)}`;return Buffer.from(t,"utf8").toString("utf8")}};var L=class extends Error{constructor(e){super(e),this.name="ImageBuildError";}},kt=r=>r.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`),_t=new Set(["buildArgs","env"]);function se(r){return Array.isArray(r)?r.map(se):r===null||typeof r!="object"?r:Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0).map(([e,t])=>[kt(e),_t.has(e)?t:e==="architecture"?`IMAGE_ARCHITECTURE_${String(t).toUpperCase()}`:se(t)]))}function It(r){let e=se(r);if(typeof e.dockerfile!="object"||e.dockerfile===null)throw new Error("Sail's build returned no Dockerfile spec");return e}async function ve(r,e,t){t.log?.(`Sail image of ${t.dockerfile.path}: ${t.forceBuild?"building again (force_build)":"built once, then reused while unchanged"}`);let n=await r.Image.fromDockerfile(t.dockerfile.path,{contextDir:t.contextDir}).build({client:r.Client.fromConfig({apiKey:e}),forceBuild:t.forceBuild??false,timeoutSeconds:Math.max(1,Math.ceil(t.timeoutMs/1e3))});return It(n)}var Tt="0.21.0",Ot={version:Tt,sdk:"sha512-FBYH3IsyUyjZWvMPejUGK6rA174tT3gxJiBA2jbTt7rWjm7/mFRFLzRBMImY3OAv35qKuLM0mrB3pTnkQQTxgw==",bindings:{"darwin-x64":"sha512-HOgMK+PEXfysWC3NgQ9jzUojlRgUYT+5OxBcEF1Dj2wKz3APViI6Vuq2Y9HLSJT0tGLo83ClCLj4R/eFvUop/g==","darwin-arm64":"sha512-1yQCeHq/7tunSHPgf2ZZRl9jYKReQJIgtQEY7LlurT21JuyKMurJrQe9FzObyrUYeXhiYkUuLtzuX6EpaQRTJA==","linux-x64-gnu":"sha512-pYuw2GmmipEQCCESrmDp5cO3duQGq8UMeYSIm6pO8gKSoxxrA1qeUkuGfL7k1cVyrJ3fmZnq+nr1QknS4PqV6Q==","linux-x64-musl":"sha512-i/2Sbk2mXbZYJFAzAWOT69RdsW/M7akUnbPznrQZToqTXSsLAd8YXxR+uAAVxJXy4Iw43UyFmZrJwdIWhfgoGw==","linux-arm64-gnu":"sha512-4Ek45KGiz+BVMCfqsH3qz3BSoUuGrlJOM7Es2uS+KXFo9IpZvVxaa8oadbyBoBo3QUJo1+M9QTn+j6CSBMVZhw==","linux-arm64-musl":"sha512-Twjv/yfoBJXNTzNMOMyJMhU619KQw9oSPsESCPdM7r1F7WAbG6HuOzdwvNDfgOeAxtTj3vUUyaj9h11a/3yMXA==","win32-x64-msvc":"sha512-ewSPLJ/lQZDemTelHxfC5Cs1dPPPm8lbAOzLEDoXgOKTUeQ1t3cAFai9g9mOSdjwISGRBGTaBf1XnMJFdORWDg=="}},k="@sailresearch/sdk",Dt=k,Lt="https://registry.npmjs.org",Mt=3e5,K=class extends Error{constructor(e){super(e),this.name="SailSdkIntegrityError";}};function Nt(){let r=Symbol;for(let e of ["dispose","asyncDispose"])typeof r[e]!="symbol"&&Object.defineProperty(Symbol,e,{value:Symbol.for(`Symbol.${e}`),writable:true,configurable:true});}function Ct(r){let{os:e,arch:t}=r;if(e==="darwin"&&(t==="x64"||t==="arm64"))return `darwin-${t}`;if(e==="win32"&&t==="x64")return "win32-x64-msvc";if(e==="linux"&&(t==="x64"||t==="arm64"))return `linux-${t}-${r.libc??"gnu"}`}function Ut(){try{return readFileSync("/usr/bin/ldd","utf-8").includes("musl")?"musl":"gnu"}catch{}try{let r=process.report?.getReport()??{};if(r.header?.glibcVersionRuntime)return "gnu";if(r.sharedObjects?.some(e=>e.includes("libc.musl-")||e.includes("ld-musl-")))return "musl"}catch{}try{if(readdirSync("/lib").some(r=>r.startsWith("ld-musl-")))return "musl"}catch{}return "gnu"}function Ft(){return {os:process.platform,arch:process.arch,libc:process.platform==="linux"?Ut():void 0}}var Bt=["/etc/ssl/certs/ca-certificates.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem","/etc/pki/tls/certs/ca-bundle.crt","/etc/ssl/ca-bundle.pem","/etc/pki/tls/cacert.pem","/etc/ssl/cert.pem","/opt/etc/ssl/certs/ca-certificates.crt","/etc/ssl/certs/cacert.pem"];async function jt(r,e,t,n=Bt){if(t!=="linux"||r.SSL_CERT_FILE||r.SSL_CERT_DIR||n.some(s=>existsSync(s)))return;let i=join(e,"node-root-certs.pem");if(!existsSync(i))try{await mkdir(e,{recursive:!0});let s=`${i}.${process.pid}-${randomBytes(4).toString("hex")}`;await writeFile(s,`${rootCertificates.join(`
6
+ `)}
7
+ `,{mode:420}),await rename(s,i);}catch{return}return r.SSL_CERT_FILE=i,i}function Pe(r=process.env){return r.EVOLVE_SAIL_SDK_DIR?r.EVOLVE_SAIL_SDK_DIR:join(r.XDG_CACHE_HOME||join(homedir(),".cache"),"evolve","sail-sdk")}function j(r,e){return join(r,"node_modules",...e.split("/"))}function Gt(r){return `sha512-${createHash("sha512").update(r).digest("base64")}`}function M(r){return r instanceof Error?r.message:String(r)}async function Kt(r,e){let t=gunzipSync(r),n=(o,a,d)=>{let l=o.subarray(a,a+d),u=l.indexOf(0);return l.subarray(0,u===-1?l.length:u).toString("utf-8")},i=0,s;for(;i+512<=t.length;){let o=t.subarray(i,i+512);if(o.every(p=>p===0))break;let a=parseInt(n(o,124,12).trim()||"0",8);if(!Number.isFinite(a)||a<0)throw new Error("corrupt tarball: bad entry size");let d=o[156]?String.fromCharCode(o[156]):"0",l=t.subarray(i+512,i+512+a);if(l.length!==a)throw new Error("corrupt tarball: truncated entry");if(i+=512+Math.ceil(a/512)*512,d==="x"){let p=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(l.toString("utf-8"));p&&(s=p[1]);continue}if(d==="L"){s=n(l,0,l.length);continue}if(d==="g")continue;let u=n(o,257,5)==="ustar"?n(o,345,155):"",m=s??(u?`${u}/${n(o,0,100)}`:n(o,0,100));if(s=void 0,d!=="0"&&d!=="7"&&d!=="5")continue;let g=m.replace(/\\/g,"/").split("/").slice(1),c=posix.normalize(g.join("/"));if(!g.length||c==="."||c==="")continue;if(posix.isAbsolute(c)||c===".."||c.startsWith("../"))throw new Error(`refusing tarball entry outside the package: ${m}`);let f=join(e,...c.split("/"));if(d==="5"){await mkdir(f,{recursive:true});continue}await mkdir(dirname(f),{recursive:true}),await writeFile(f,l,{mode:420});}}async function Wt(r,e,t){let n=await r(e,{signal:AbortSignal.timeout(Mt)});if(!n.ok)throw new Error(`GET ${e} answered ${n.status}`);let i=new Uint8Array(await n.arrayBuffer()),s=Gt(i);if(s!==t)throw new K(`Sail's SDK download ${e} does not match its pinned checksum (expected ${t}, got ${s}), so it was not loaded`);return i}async function Vt(r,e){await mkdir(dirname(e),{recursive:true});try{await rename(r,e);}catch(t){if(!existsSync(join(e,"package.json")))throw t}}function zt(r,e,t){return `${r.replace(/\/+$/,"")}/${e}/-/${e.split("/").pop()}-${t}.tgz`}async function Ht(r,e,t,n,i){if(!i)throw new Error("this Node.js has no fetch(); Sail image builds need Node.js 18 or later");let s=n.npm_config_registry||n.NPM_CONFIG_REGISTRY||Lt,o=join(r,`.staging-${process.pid}-${randomBytes(4).toString("hex")}`);try{for(let{name:a,integrity:d}of e){let l=zt(s,a,t.version),u;try{u=await Wt(i,l,d);}catch(g){throw g instanceof K?g:new Error(`could not download Sail's SDK ${t.version} (${M(g)}). This download does not use HTTPS_PROXY; set npm_config_registry to a registry you can reach, or copy the folder ${r} from a machine where a Sail image build ran and set EVOLVE_SAIL_SDK_DIR to the folder that holds the copy`)}let m=join(o,a.replace("/","__"));try{if(await Kt(u,m),!existsSync(join(m,"package.json")))throw new Error(`${l} holds no package.json`);await Vt(m,j(r,a));}catch(g){throw new Error(`could not write Sail's SDK cache at ${r} (${M(g)}); set EVOLVE_SAIL_SDK_DIR to a writable folder that only you can write to`)}}}finally{await rm(o,{recursive:true,force:true}).catch(()=>{});}}async function Ne(r={}){Nt();let e=r.env??process.env,t=r.platform??Ft();await jt(e,Pe(e),t.os,r.caBundlePaths);let n=r.importInstalled??(async()=>{let m=await import(Dt);if(!m.Client)throw new Error(`${k} is not whole`);return m}),i;try{return await n()}catch(m){i=m;}let s=r.pins??Ot,o=Ct(t);if(!o||!s.bindings[o])throw new Error(`Sail's SDK has no native build for ${[t.os,t.arch,t.libc].filter(Boolean).join("-")}; Sail image builds run on Linux (x64, arm64), macOS (x64, arm64) and Windows (x64) (the installed ${k} did not load either: ${M(i)})`);let a=join(Pe(e),s.version),l=[{name:`${k}-${o}`,integrity:s.bindings[o]},{name:k,integrity:s.sdk}].filter(({name:m})=>!existsSync(join(j(a,m),"package.json")));l.length&&await Ht(a,l,s,e,r.fetch??globalThis.fetch);let u=j(a,k);try{let m=j(a,`${k}-${o}`),g=readdirSync(m).find(p=>p.endsWith(".node"));g&&process.versions.bun&&(process.env.NAPI_RS_NATIVE_LIBRARY_PATH??=join(m,g));let c=join(u,"package.json"),{main:f="index.js"}=JSON.parse(readFileSync(c,"utf-8"));return createRequire(c)(join(u,f))}catch(m){throw new Error(`Sail's SDK ${s.version} in ${a} failed to load (${M(m)}; the installed ${k} did not load either: ${M(i)}). Delete that folder to download it again`)}}var Yt="https://sailbox-api.sailresearch.com/v1",qt="https://api.sailresearch.com/v1",h="sail",ue="user",Xt="evolve-sandbox",Xe="EVOLVE_SANDBOX_METADATA",Ce=4096,Je="evolve.image",Qe="evolve.user",Ze=100,oe=100,Ue=64,Jt=8,Fe=256,Qt=8,Be=1024,ae=3e5,V=6e4,Zt=8,er=1024*1024,me=new Set(["terminating","terminated","failed","create_failed","interrupted_unsafe_to_retry"]),tr=["terminating","terminated","failed"],et=new Set(["paused","interrupted_restorable"]),tt=new Set(["running","sleeping","creating"]),rr={[`evolve-all-${B}`]:`docker.io/evolvingmachines/evolve-all:${B}`,"evolve-all":"docker.io/evolvingmachines/evolve-all:latest"},nr={"sail:debian":"BASE_IMAGE_DEBIAN","sail:devbox":"BASE_IMAGE_DEVBOX"},rt=["docker.io","ghcr.io","quay.io","registry.gitlab.com","public.ecr.aws"],nt=[{label:"<account>.dkr.ecr.<region>.amazonaws.com",re:/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/},{label:"<region>-docker.pkg.dev",re:/^[a-z0-9-]+-docker\.pkg\.dev$/},{label:"<name>.azurecr.io",re:/^[a-z0-9]+\.azurecr\.io$/}];function ir(r){return rt.includes(r)||nt.some(e=>e.re.test(r))}var v=class extends Error{constructor(e){super(e),this.name="SailImageError";}};function W(r){let e=r.trim();if(!e)throw new v("image name is empty");let t=nr[e];if(t)return {base:t};let n=rr[e]??e,i=n.split("/")[0],s=n.includes("/")&&(i.includes(".")||i.includes(":")||i==="localhost"),o;if(!s)o=n.includes("/")?`docker.io/${n}`:`docker.io/library/${n}`;else {if(!ir(i)){let a=[...rt,...nt.map(d=>d.label)];throw new v(`Sail pulls images only from ${a.join(", ")}; "${r}" names ${i}. Push the image to one of those registries first (a private one needs registryLogins).`)}o=n;}return {oci:{ref:o}}}var je=20,y=class extends Error{constructor(e){super(e),this.name="SailRegistryLoginError";}},it={basic:"REGISTRY_LOGIN_KIND_BASIC",aws_access_key:"REGISTRY_LOGIN_KIND_AWS_ACCESS_KEY",gcp_service_account:"REGISTRY_LOGIN_KIND_GCP_SERVICE_ACCOUNT"};function sr(r,e){let t=`registryLogins[${e}]`;if(!r||typeof r!="object")throw new y(`${t} must be an object`);let n=r.kind??"basic";if(!(n in it))throw new y(`${t}.kind must be basic, aws_access_key or gcp_service_account, got ${String(n)}`);let i=(r.prefix??"").trim();if(i&&!/^[a-z0-9.\-]+(:\d+)?(\/[a-zA-Z0-9._\-]+)*$/.test(i))throw new y(`${t}.prefix must be a registry host, optionally with a repository path (e.g. ghcr.io/acme); got "${i}"`);let s=typeof r.password=="string"&&r.password.length>0,o=typeof r.secretName=="string"&&r.secretName.length>0;if(s===o)throw new y(`${t} needs exactly one of password and secretName`);if(n==="gcp_service_account"){if(r.username)throw new y(`${t}: a gcp_service_account login takes no username`)}else if(!r.username)throw new y(`${t}.username is required for a ${n} login`);return {...r,prefix:i,kind:n}}function st(r,e){return r?e.startsWith(r)?e.length===r.length||"/:@".includes(e[r.length]):false:true}function ot(r,e){if(!e||e.length===0)return [];if(!Array.isArray(e))throw new y("registryLogins must be an array");let t=e.map(sr).filter(n=>st(n.prefix,r));if(t.length>je)throw new y(`Sail takes at most ${je} registry logins per image; ${t.length} match ${r}`);return t.map(n=>({...n.prefix?{prefix:n.prefix}:{},kind:it[n.kind],...n.username?{username:n.username}:{},...n.password?{secret_value:n.password}:{secret_name:n.secretName}}))}function at(r,e){let t;for(let n of e)st(n.prefix??"",r)&&(!t||(n.prefix??"").length>(t.prefix??"").length)&&(t=n);return t}function or(r){return "base"in r?r.base:r.oci.ref}var E=class extends Error{constructor(e){super(e),this.name="SailResourcesError";}},ge=class extends Error{constructor(){super("Sail has no idle timeout that ends a Sailbox: an idle Sailbox SLEEPS (memory and disk kept, woken by the next command) and only max_lifetime_seconds ends it. Use timeoutMs for the lifetime."),this.name="SailIdleTimeoutError";}},pe=class extends Error{constructor(){super("Sail takes no create-time boot command: a Sailbox never runs the image's ENTRYPOINT or CMD, so the boot is already inert. Start the process by exec after create (commands.spawn)."),this.name="SailBootCommandError";}},_=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="SailNetworkPolicyError",this.reason=e,this.destination=n;}},fe=class extends Error{constructor(e){super(e),this.name="SailMetadataError";}},z=class extends Error{sailboxId;status;constructor(e,t,n){super(t),this.name="SailCreateFailedError",this.status=e,this.sailboxId=n;}},H=class extends Error{constructor(e,t){super(`Sail command timed out${t?` after ${t} ms`:""}: ${e.slice(0,200)}`),this.name="TimeoutError";}},I=class extends Error{status;type;code;retryAfterSec;constructor(e,t,n){super(t),this.name="SailApiError",this.status=e,this.type=n?.type,this.code=n?.code,this.retryAfterSec=n?.retryAfterSec;}};function ar(r){return r<=1?2:r<=4?8:16}function ct(r){if(!r)return {};if((r.gpu??0)>0||(r.gpuTypes?.length??0)>0)throw new E("Sail offers no GPUs: a Sailbox has vCPUs, memory and disk only");let e=(i,s)=>{if(!Number.isFinite(s)||s<=0)throw new E(`resources.${i} must be a positive number, got ${s}`)},t={},n;if(r.cpu!==void 0){if(e("cpu",r.cpu),n=Math.ceil(r.cpu),n>Ue)throw new E(`Sail allows at most ${Ue} vCPUs per Sailbox; asked for ${r.cpu}`);t.vcpu_count=n;}if(r.memory!==void 0){e("memory",r.memory);let i=Math.ceil(r.memory);if(i>Fe)throw new E(`Sail allows at most ${Fe} GiB of memory per Sailbox; asked for ${r.memory}`);t.memory_limit_gib=Math.max(i,ar(n??Jt));}if(r.disk!==void 0){e("disk",r.disk);let i=Math.ceil(r.disk);if(i>Be)throw new E(`Sail allows at most ${Be} GiB of disk per Sailbox; asked for ${r.disk}`);t.state_disk_limit_gib=Math.max(i,Qt);}return t}var Y="(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)",cr=new RegExp(`^${Y}(\\.${Y}){3}$`),dr=new RegExp(`^${Y}(\\.${Y}){3}/(3[0-2]|[12]?\\d)$`),Ge="[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?",lr=new RegExp(`^${Ge}(\\.${Ge})*\\.?$`);function ur(r){let e=r.trim();if(e.includes(":")&&!e.startsWith("["))throw /^[0-9a-fA-F:]+(\/\d+)?$/.test(e)&&e.split(":").length>2?new _("ipv6-unsupported",`Sail egress allowlists take IPv4 only; ${r} is IPv6`,r):new _("port-unsupported",`Sail egress allowlists name hosts, not ports (a hostname entry allows every port); remove the port from ${r}`,r);if(e.startsWith("["))throw new _("ipv6-unsupported",`Sail egress allowlists take IPv4 only; ${r} is IPv6`,r);if(cr.test(e)||dr.test(e))return e;let t=e.startsWith("*.")?e.slice(2):e;if(!/^\d+(\.\d+)*(\/\d+)?$/.test(t)&&lr.test(t))return e;throw new _("invalid-entry",`${r} is not a hostname, a *.domain wildcard, an IPv4 address or an IPv4 CIDR range`,r)}function C(r){if(r?.noNetwork)return mr(r);if(!r||r.outbound==="open"){if(r?.allowedDestinations?.length)throw new _("open-with-allowlist","network.allowedDestinations is only valid when outbound is blocked");return {}}return {allowlist:[...new Set((r.allowedDestinations??[]).map(ur))]}}function mr(r){if(r.outbound!=="blocked"||r.allowedDestinations?.length)throw new _("no-network-conflict","network.noNetwork is only valid when outbound is blocked with no allowedDestinations");return {no_network:true}}function dt(r){let e=JSON.stringify(r);if(e.length>Ce)throw new fe(`sandbox metadata is ${e.length} characters as JSON; Sail stores it in one environment value, which holds at most ${Ce}`);return e}function Q(r){let e=r?.[Xe];if(!e)return {};try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return {};let n={};for(let[i,s]of Object.entries(t))typeof s=="string"&&(n[i]=s);return n}catch{return {}}}function Ke(r,e){if(me.has(r))return false;if(!e||e.length===0)return true;let t=et.has(r);return e.includes("paused")&&t||e.includes("running")&&!t}var gr=10080*60*1e3,pr=3600,q=4;function X(r){return new Promise(e=>setTimeout(e,r))}function lt(r){let e=r.headers.get("retry-after");if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,(n-Date.now())/1e3)}var he=class{constructor(e,t,n,i){this.sailboxApiUrl=t;this.apiUrl=n;this.fetchImpl=i;this.#e=e;}#e;url(e){let t=(e.host==="api"?this.apiUrl:this.sailboxApiUrl).replace(/\/$/,""),n=new URL(`${t}${e.path}`);for(let[i,s]of Object.entries(e.query??{}))s!==void 0&&n.searchParams.set(i,String(s));return n.toString()}async request(e){let t={Authorization:`Bearer ${this.#e}`,...e.headers},n=e.body;e.json!==void 0&&(t["Content-Type"]="application/json",n=JSON.stringify(e.json));for(let i=1;;i++){let s;try{s=await this.fetchImpl(this.url(e),{method:e.method,headers:t,body:n,...n instanceof ReadableStream?{duplex:"half"}:{},...e.timeoutMs?{signal:AbortSignal.timeout(e.timeoutMs)}:{}});}catch(d){if(e.retry&&i<q){await X(1e3*2**(i-1));continue}throw d}if(s.ok||e.allow?.includes(s.status))return s;let o=lt(s),a=s.status===429&&o!==void 0||[500,502,503,504].includes(s.status);if(e.retry&&a&&i<q){await s.body?.cancel().catch(()=>{}),await X(o!==void 0?Math.min(o,60)*1e3:1e3*2**(i-1));continue}throw await fr(s,`${e.method} ${e.path}`)}}async json(e){return await(await this.request(e)).json()}};async function fr(r,e){let t="",n,i;try{let s=await r.text();try{let o=JSON.parse(s);t=o.error?.message??s,n=o.error?.type,i=o.error?.code;}catch{t=s;}}catch{}return new I(r.status,`Sail ${e} failed (HTTP ${r.status})${t?`: ${t.slice(0,500)}`:""}`,{type:n,code:i,retryAfterSec:lt(r)})}async function U(r,e,t,n={}){let i=await r.request({method:"POST",path:`/sailboxes/${encodeURIComponent(e)}/exec`,json:t}),s={stdout:new TextDecoder,stderr:new TextDecoder},o=new D(n.maxOutput),a=new D(n.maxOutput),d,l,u,m=c=>{if(c.type==="started"&&c.exec_request_id)d=c.exec_request_id,n.onStarted?.(d);else if((c.type==="stdout"||c.type==="stderr")&&c.data){let f=Buffer.from(c.data,"base64");if(c.type==="stdout"){if(n.onStdoutBytes){n.onStdoutBytes(new Uint8Array(f));return}let p=s.stdout.decode(f,{stream:true});o.add(p),p&&n.onStdout?.(p);}else {let p=s.stderr.decode(f,{stream:true});a.add(p),p&&n.onStderr?.(p);}}else c.type==="exit"?l=c:c.type==="error"&&(u=c);};try{if(i.body){let c=i.body.getReader(),f=new TextDecoder,p="";for(;;){let{done:A,value:T}=await c.read();if(A)break;p+=f.decode(T,{stream:!0});let Z;for(;(Z=p.indexOf(`
8
+ `))>=0;){let _e=p.slice(0,Z).trim();p=p.slice(Z+1),_e&&m(JSON.parse(_e));}}let P=(p+f.decode()).trim();P&&m(JSON.parse(P));}}catch(c){if(!d)throw c}let g=()=>{let c=s.stdout.decode(),f=s.stderr.decode();c&&(o.add(c),n.onStdout?.(c)),f&&(a.add(f),n.onStderr?.(f));};if(l)return g(),{exitCode:l.return_code??(l.status==="succeeded"?0:1),stdout:o.toString(),stderr:a.toString(),timedOut:l.status==="timed_out"||l.timed_out===true};if(!d){let c=u;throw new Error(`Sail exec on ${e} ended before it started`+(c?`: ${c.error_code??"error"} ${c.message??c.error?.message??""}`:""))}for(g();;){let c=await r.json({method:"POST",path:`/sailboxes/${encodeURIComponent(e)}/exec/${encodeURIComponent(d)}/wait`,json:{},retry:true});if(!(c.status==="running"||c.status==="unspecified")){if(c.status==="worker_lost")throw new Error(`Sail lost the worker running exec ${d} on ${e}; the command's result is unknown`);return {exitCode:c.return_code,stdout:o.length>=c.stdout.length?o.toString():c.stdout,stderr:a.length>=c.stderr.length?a.toString():c.stderr,timedOut:c.timed_out||c.status==="timed_out"}}}}function $(r){return Math.max(1,Math.ceil(r/1e3))}function We(r,e,t,n){return e&&(r.timedOut||r.exitCode>=128&&n-t>=$(e)*1e3)?124:r.exitCode}function J(r){if(!r)return;let e=Object.fromEntries(Object.entries(r).filter(([,t])=>t!=null));return Object.keys(e).length>0?e:void 0}function Ve(r){if(typeof r=="string")return new Uint8Array(Buffer.from(r,"utf-8"));if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);throw new Error(`Unsupported data type for file upload: ${typeof r}`)}function hr(r){if(!r.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(r)}catch{}return r}function Sr(r){let e=r.lastIndexOf("/");return e>0?r.slice(0,e):""}var Se=class{constructor(e){this.box=e;}stdinOffsets=new Map;body(e,t){return {command:e,...t?.timeoutMs?{timeout:$(t.timeoutMs)}:{},...t?.cwd??this.box.workingDirectory?{cwd:t?.cwd??this.box.workingDirectory}:{},...J({...this.box.envs,...t?.envs})?{env:J({...this.box.envs,...t?.envs})}:{},user:this.box.user,...t?.stdin?{open_stdin:true}:{}}}async run(e,t){let n=Date.now(),i=await U(this.box.http,this.box.sailboxId,this.body(e,t),{onStdout:t?.onStdout,onStderr:t?.onStderr,maxOutput:t?.maxOutput});if(i.timedOut&&!t?.timeoutMs)throw new H(e,0);return {exitCode:We(i,t?.timeoutMs,n,Date.now()),stdout:i.stdout,stderr:i.stderr}}async spawn(e,t){let n,i,s=new Promise((u,m)=>{n=u,i=m;}),o=Date.now(),a=0,d=U(this.box.http,this.box.sailboxId,this.body(e,t),{onStarted:n,onStdout:t?.onStdout,onStderr:t?.onStderr,maxOutput:t?.maxOutput}).finally(()=>{a=Date.now();});d.catch(i);let l=await s;return t?.stdin&&this.stdinOffsets.set(l,0),d.catch(()=>{}),{processId:l,wait:async()=>{let u=await d;if(this.stdinOffsets.delete(l),u.timedOut&&!t?.timeoutMs)throw new H(e,0);return {exitCode:We(u,t?.timeoutMs,o,a),stdout:u.stdout,stderr:u.stderr}},kill:()=>this.kill(l)}}async list(){return (await this.run("ps -eo pid,comm,args",{timeoutMs:V})).stdout.trim().split(`
9
+ `).slice(1).filter(t=>t.trim()).map(t=>{let n=t.trim().split(/\s+/);return {processId:n[0],cmd:n[1]??"",args:n.slice(2),envs:{}}})}async kill(e){if(/^\d+$/.test(e))return (await U(this.box.http,this.box.sailboxId,{command:["kill","-9",e],user:"root",timeout:$(V)})).exitCode===0;try{return await this.box.http.request({method:"POST",path:`/sailboxes/${encodeURIComponent(this.box.sailboxId)}/exec/${encodeURIComponent(e)}/cancel`,json:{force:!0},retry:!0}),this.stdinOffsets.delete(e),!0}catch(t){if(t instanceof I&&(t.status===404||t.status===409))return false;throw t}}async sendStdin(e,t){await this.writeStdin(e,typeof t=="string"?new Uint8Array(Buffer.from(t,"utf-8")):t,false);}async closeStdin(e){await this.writeStdin(e,new Uint8Array(0),true);}async writeStdin(e,t,n){let i=this.stdinOffsets.get(e);if(i===void 0)throw new w("commands.sendStdin",h,`process ${e} was not spawned with stdin: true by this client`);let s=0;do{let o=t.subarray(s,s+er),a=s+o.length>=t.length;await this.box.http.request({method:"PUT",path:`/sailboxes/${encodeURIComponent(this.box.sailboxId)}/exec/${encodeURIComponent(e)}/stdin`,query:{offset:i+s,...n&&a?{eof:true}:{}},body:o,headers:{"Content-Type":"application/octet-stream"},retry:true}),s+=o.length;}while(s<t.length);this.stdinOffsets.set(e,i+t.length);}},ze="%y\\t%s\\t%T@\\t%m\\t%u\\t%g\\t%l\\t%f\\0";function br(r){return r==="d"?"dir":r==="l"?"symlink":r==="f"?"file":"other"}function be(r,e){let t=[];for(let n of r.split("\0")){if(!n)continue;let i=n.split(" ");if(i.length<8)continue;let[s,o,a,d,l,u,m]=i,g=i.slice(7).join(" "),c=br(s),f=e===null?g:e.endsWith("/")?`${e}${g}`:`${e}/${g}`,p={name:g.includes("/")&&g.slice(g.lastIndexOf("/")+1)||g,path:f,type:c,size:Number(o),mtime:F(Number(a)),mode:Ee(d),owner:l,group:u};c==="symlink"&&(p.target=m),t.push(p);}return t}function He(r,e){if(ie(e))return new w(r,h,`this image has neither GNU find's -printf nor stat(1), so its entries cannot be listed as themselves: ${e.trim()}`)}var ye=class{constructor(e){this.box=e;}get base(){return `/sailboxes/${encodeURIComponent(this.box.sailboxId)}`}rootExec(e,t=V,n="bash"){return U(this.box.http,this.box.sailboxId,{command:[n,"-c",e],user:"root",timeout:$(t)})}async mustRootExec(e,t,n){let i=await this.rootExec(e,n);if(i.exitCode!==0)throw new Error(`sail: ${t} failed (exit ${i.exitCode}): ${i.stderr.trim().slice(0,500)}`)}async chownToUser(e,t=false){if(this.box.user==="root"||e.length===0)return;let n=b(`${this.box.user}:${this.box.user}`);await this.mustRootExec(`chown ${t?"-R ":""}${n} -- ${e.map(b).join(" ")}`,`chown of ${e.length} path(s)`,t?12e4:V);}async read(e){let t=await this.box.http.request({method:"GET",path:`${this.base}/files`,query:{path:e},timeoutMs:ae,retry:true,allow:[404]});if(t.status===404)throw await t.body?.cancel().catch(()=>{}),new x(e,h);return hr(new Uint8Array(await t.arrayBuffer()))}async put(e,t,n){await this.box.http.request({method:"PUT",path:`${this.base}/files`,query:{path:e,create_parents:true,user:"root"},body:t,headers:{"Content-Type":"application/octet-stream"},timeoutMs:ae,retry:n});}async write(e,t){await this.put(e,Ve(t),true),await this.chownToUser([e]);}async writeBatch(e){let t=0,n=async()=>{for(;t<e.length;){let s=e[t++];await this.put(s.path,Ve(s.data),true);}};await Promise.all(Array.from({length:Math.min(Zt,e.length)},n));let i=new Set;for(let s of e){let o=Sr(s.path);o&&i.add(o.split("/").slice(0,4).join("/"));}await this.chownToUser([...i],true);}async makeDir(e){await this.mustRootExec(`mkdir -p -- ${b(e)}`,`mkdir ${e}`),await this.chownToUser([e],true);}async writeFromPath(e,t){let{createReadStream:n}=await import('fs'),{Readable:i}=await import('stream'),s=i.toWeb(n(t,{highWaterMark:4*1024*1024}));await this.put(e,s,false),await this.chownToUser([e]);}async exists(e){return (await this.rootExec(`test -e ${b(e)} || test -L ${b(e)}`)).exitCode===0}async list(e){let t=b(e),n=await this.rootExec(`[ -e ${t} ] || exit ${O}; [ -d ${t} ] || exit ${te}; `+ne(`${t} -mindepth 1 -maxdepth 1`,ze,"\\t","\\0"),void 0,"sh");if(n.exitCode===O)throw new x(e,h);if(n.exitCode===te)throw new Error(`sail: ${e} is not a directory`);if(n.exitCode!==0)throw He("files.list",n.stderr)??new Error(`sail: listing ${e} failed (exit ${n.exitCode}): ${n.stderr.trim()}`);return be(n.stdout,e).sort((i,s)=>i.name<s.name?-1:i.name>s.name?1:0)}async stat(e){let t=b(e),n=await this.rootExec(`[ -e ${t} ] || [ -L ${t} ] || exit ${O}; ${ne(`${t} -maxdepth 0`,ze,"\\t","\\0")}`,void 0,"sh");if(n.exitCode===O)throw new x(e,h);if(n.exitCode!==0)throw He("files.stat",n.stderr)??new Error(`sail: stat of ${e} failed (exit ${n.exitCode}): ${n.stderr.trim()}`);let[i]=be(n.stdout,null);if(!i)throw new x(e,h);return {...i,path:e,name:e==="/"?"/":e.replace(/\/+$/,"").split("/").pop()??e}}async readRange(e,t){if(re(t),t.length===0)return new Uint8Array(0);let n=await this.box.http.request({method:"POST",path:`${this.base}/files/download-url`,json:{path:e,expires_in_seconds:300},retry:true,allow:[404]});if(n.status===404)throw await n.body?.cancel().catch(()=>{}),new x(e,h);let{url:i}=await n.json();return Re(i,t,{provider:h,path:e,timeoutMs:ae})}async remove(e){await this.mustRootExec(`rm -rf -- ${b(e)}`,`remove ${e}`,12e4);}async rename(e,t){await this.mustRootExec(`mv -- ${b(e)} ${b(t)}`,`rename ${e}`,12e4);}async watchDir(e,t,n){throw new w("files.watchDir",h,"Sail has no filesystem watch API; poll files.list()")}async downloadUrl(e,t=3600){let{url:n}=await this.box.http.json({method:"POST",path:`${this.base}/files/download-url`,json:{path:e,expires_in_seconds:t},retry:true});return n}};function ce(r){return Q(r.env)[Qe]||ue}function ut(r){let e=Q(r.env);return {sandboxId:r.sailbox_id,image:e[Je]??r.image_id??"",...r.name?{name:r.name}:{},metadata:e,startedAt:r.started_at?F(r.started_at):new Date(0).toISOString()}}var we=class{constructor(e,t,n,i,s,o){this.http=e;this.sandboxId=t;this.user=n;this.workingDirectory=i;this.envs=s;this.startFromCheckpoint=o;let a={http:e,sailboxId:t,user:n,workingDirectory:i,envs:s};this.commands=new Se(a),this.files=new ye(a);}commands;files;get base(){return `/sailboxes/${encodeURIComponent(this.sandboxId)}`}retrieve(){return this.http.json({method:"GET",path:this.base,retry:true})}async getHost(e){let t=await this.http.json({method:"POST",path:`${this.base}/listeners`,json:{guest_port:e,protocol:"http"},retry:true});if(t.public_url)return new URL(t.public_url).host;if(t.public_host)return t.public_host;throw new Error(`sail: publishing port ${e} on ${this.sandboxId} returned no address`)}async kill(){await this.http.request({method:"POST",path:`${this.base}/terminate`,json:{},retry:true,allow:[404]});}async pause(){await this.http.request({method:"POST",path:`${this.base}/pause`,json:{},retry:true});}async isRunning(){try{return tt.has((await this.retrieve()).status)}catch(e){if(e instanceof I&&e.status===404)return false;throw e}}async getInfo(){return ut(await this.retrieve())}async metrics(){let e=await this.retrieve(),t=e.cpu_used_vcpu??0,n=e.memory_used_bytes??0;if(t===0&&n===0)return null;let i=e.vcpu_count&&e.vcpu_count>0?e.vcpu_count:1;return {cpuPct:t/i*100,memUsedMb:n/(1024*1024),memTotalMb:e.memory_mib??0,...e.disk_used_bytes!==void 0?{diskUsedMb:e.disk_used_bytes/(1024*1024)}:{},sampledAt:new Date().toISOString(),source:"sail.sailboxes.retrieve"}}async updateNetwork(e){await this.http.request({method:"PUT",path:`${this.base}/egress-policy`,json:{document:C(e)},retry:true});}async checkpoint(e,t){let n=await this.http.json({method:"POST",path:`${this.base}/checkpoint`,json:{include_memory:e,ttl_seconds:t},headers:{"Idempotency-Key":`evolve-checkpoint-${randomUUID()}`},retry:true});if(!n.checkpoint_id)throw new Error(`sail: checkpoint of ${this.sandboxId} returned no checkpoint id`);return n}async snapshot(e={}){let t=e.kind??"filesystem";if(t!=="filesystem"&&t!=="memory")throw new Error(`Unknown snapshot kind "${String(t)}": use "filesystem" or "memory"`);let n=e.ttlMs??gr;if(!Number.isFinite(n)||n<1e3)throw new Error(`Snapshot ttlMs must be at least 1000 (Sail keeps checkpoints in whole seconds), got ${String(e.ttlMs)}`);let i=Math.floor(n/1e3),s=new Date().toISOString(),o=await this.checkpoint(t==="memory",i);return {snapshotId:o.checkpoint_id,provider:h,kind:o.include_memory===false?"filesystem":o.include_memory===true?"memory":t,sourceSandboxId:this.sandboxId,createdAt:s,expiresAt:o.expires_at?F(o.expires_at):new Date(Date.parse(s)+i*1e3).toISOString()}}async fork(e={}){if(!this.startFromCheckpoint)throw new Error("sail: this sandbox handle cannot fork (no provider attached)");let t=await this.checkpoint(true,pr);try{return await this.startFromCheckpoint(t.checkpoint_id,e.timeoutMs,{user:this.user,workingDirectory:this.workingDirectory,envs:this.envs})}finally{await mt(this.http,t.checkpoint_id).catch(()=>{});}}};async function mt(r,e){let t=await r.request({method:"DELETE",path:`/sailbox-checkpoints/${encodeURIComponent(e)}`,retry:true,allow:[404]});return t.status===404?(await t.body?.cancel().catch(()=>{}),false):(await t.json().catch(()=>({}))).deleted!==false}var de;async function ke(r){let e=de??=Ne();try{return await e}catch(t){de===e&&(de=void 0);let n=t instanceof Error?t.message:String(t);throw new v(`Sail must build ${r} once for your organization, and building needs Sail's SDK, which failed to load: ${n}`+(/failed to map segment/.test(n)?". The temporary folder allows no programs: set TMPDIR to a folder that does":""))}}async function Wr(){return ke("the tasks' images").then(()=>null,r=>r.message)}var yr=async(r,e,t)=>{let n=await ke(`image ${r}`),i=n.Client.fromConfig({apiKey:e});await gt(n,r,at(r,t.registryLogins??[])).build({client:i,forceBuild:t.force,timeoutSeconds:3600});};function gt(r,e,t){if(!t)return r.Image.fromRegistry(e);let n=r.Secret;if(!n||!r.Image.fromAwsEcr||!r.Image.fromGcpArtifactRegistry)throw new v(`Sail must build the private image ${e} with a registry login, and the installed @sailresearch/sdk is too old to send one. Upgrade it with: npm install @sailresearch/sdk@^0.21.0, or remove it so the pinned one is fetched`);let i=t.secret_value!==void 0?n.ephemeral(t.secret_value):n.named(t.secret_name);switch(t.kind){case "REGISTRY_LOGIN_KIND_AWS_ACCESS_KEY":return r.Image.fromAwsEcr(e,{accessKeyId:t.username,secretAccessKey:i});case "REGISTRY_LOGIN_KIND_GCP_SERVICE_ACCOUNT":return r.Image.fromGcpArtifactRegistry(e,{keyJson:i});default:return r.Image.fromRegistry(e,{username:t.username,password:i})}}function pt(r){let e=r instanceof Error?r.message:typeof r=="string"?r:"",t=/unsupported base distro:?\s*"?([A-Za-z0-9._-]+)/i.exec(e);if(!t)return;let n=new w("image.baseDistro",h,`Sail builds only Debian- or Ubuntu-based images (got ${t[1]})`);return Object.defineProperty(n,"cause",{value:r,writable:true,configurable:true,enumerable:false}),n}async function Ye(r){await r.kill().catch(e=>console.warn(`[sail] Sailbox ${r.sandboxId} may still be running: its create failed and so did its terminate (${e instanceof Error?e.message:String(e)})`));}var xe=class{providerType="sail";name="Sail";supportsBootCommand=false;supportsRegistryLogins=true;http;#e;appName;imageName;defaultTimeoutMs;autoSleep;buildImage;buildDockerfileImage;#t;appId;builds=new Map;taskImages=new Map;boxes=new Map;constructor(e={}){let t=e.apiKey??process.env.SAIL_API_KEY;if(!t)throw new Error("Sail API key is required: pass apiKey or set SAIL_API_KEY (create one at https://app.sailresearch.com)");if(this.#e=t,this.http=new he(t,e.sailboxApiUrl??Yt,e.apiUrl??qt,e.fetch??((n,i)=>fetch(n,i))),this.appName=e.appName??Xt,this.imageName=e.imageName??`evolve-all-${B}`,this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,typeof e.autoSleep=="number"&&(!Number.isInteger(e.autoSleep)||e.autoSleep<0||e.autoSleep>3600))throw new Error(`autoSleep must be a whole number of seconds from 0 to 3600, got ${e.autoSleep}`);if(this.autoSleep=e.autoSleep,this.buildImage=e.buildImage??yr,this.buildDockerfileImage=e.buildDockerfileImage??(async(n,i)=>ve(await ke(`the image of ${n.dockerfile.path}`),i,n)),e.registryLogins!==void 0&&!Array.isArray(e.registryLogins)&&typeof e.registryLogins!="function")throw new y("registryLogins must be an array of logins or a function returning one");this.#t=e.registryLogins;}async loginsFor(e){let t=this.#t;if(!("oci"in e)||t===void 0)return [];let n=typeof t=="function"?await t(e.oci.ref):t;return ot(e.oci.ref,n)}getAppId(){return this.appId||(this.appId=this.http.json({method:"POST",path:"/apps/find",host:"api",json:{name:this.appName,mint_if_missing:true},retry:true}).then(e=>e.id),this.appId.catch(()=>{this.appId=void 0;})),this.appId}autoSleepParam(){return this.autoSleep===void 0?{}:this.autoSleep===false?{auto_sleep:{automatic:false}}:this.autoSleep===true?{auto_sleep:{automatic:true}}:{auto_sleep:{automatic:true,min_seconds_before_sleep:this.autoSleep}}}ensureBuilt(e,t,n=false){if("base"in e)return Promise.resolve();let i=`${e.oci.ref}${n?"#force":""}`,s=this.builds.get(i);return s||(s=this.buildImage(e.oci.ref,this.#e,{force:n,...t.length?{registryLogins:t}:{}}).catch(o=>{throw pt(o)??o}),this.builds.set(i,s),s.catch(()=>this.builds.delete(i))),s}async buildTaskImage(e){let t=s=>{let o=s;throw o.name!=="ImageBuildError"&&!(o instanceof w)?s:Object.assign(new L(`Sail could not build ${e.dockerfile?.path??e.dockerImage}: ${o.message}`),{cause:s})};if(!e.dockerfile){let s=W(e.dockerImage);return await this.ensureBuilt(s,await this.loginsFor(s),e.forceBuild).catch(t),{image:e.dockerImage,workdir:null}}let n=()=>this.buildDockerfileImage(e,this.#e).catch(t),i=`evolve-local-${e.key}`;return this.taskImages.set(i,{spec:await n(),build:n}),{image:i,workdir:null}}async prepareImage(e){let t=W(e||this.imageName);await this.ensureBuilt(t,await this.loginsFor(t));}async create(e){if(e.idleTimeoutMs!==void 0)throw new ge;if(e.bootCommand!==void 0)throw new pe;let t=e.timeoutMs??this.defaultTimeoutMs;if(!Number.isFinite(t)||t<=0)throw new Error(`timeoutMs must be a positive number of milliseconds, got ${t}`);for(let T of e.phaseNetworkPolicies??[])C(T);let n=C(e.network);if(e.fromSnapshot!==void 0)return this.createFromCheckpoint(e.fromSnapshot,e,t);let i=ct(e.resources),o=this.taskImages.get(e.image??"")?.spec??W(e.image||this.imageName),a=e.user??ue,d=dt({...e.metadata,[Je]:"dockerfile"in o?e.image:or(o),[Qe]:a}),l=J(e.envs),u={[Xe]:d},m=await this.loginsFor(o),g=await this.getAppId(),c=`evolve-${randomUUID()}`,f={app_id:g,name:c,image:o,...m.length?{registry_logins:m}:{},max_lifetime_seconds:$(t),...i,env:u,...Object.keys(n).length>0?{egress_policy:n}:{},...this.autoSleepParam()},P=(await this.createWithBuild(f,o,m,c,g)).sailbox_id;this.boxes.set(P,{user:a,workingDirectory:e.workingDirectory,envs:l});let A=this.boxFor(P,a,e.workingDirectory,l);if(e.workingDirectory)try{await A.files.makeDir(e.workingDirectory);}catch(T){throw await Ye(A),T}return A}async createDockerHost(e){return this.create({...e,image:e.image??"sail:devbox",user:"root"})}async createFromCheckpoint(e,t,n){if(t.image!==void 0)throw new Error("Pass either `image` or `fromSnapshot`, not both: a restored sandbox boots from its snapshot");if(t.resources!==void 0&&Object.values(t.resources).some(i=>i!==void 0))throw new w("sandbox.restore.resources",h,"a Sailbox started from a checkpoint keeps the size of the Sailbox the checkpoint was taken from");if(t.metadata!==void 0&&Object.keys(t.metadata).length>0)throw new w("sandbox.restore.metadata",h,"a Sailbox started from a checkpoint keeps the metadata of the Sailbox the checkpoint was taken from");return t.network!==void 0&&C(t.network),this.startFromCheckpoint(e,n,{user:t.user??ue,workingDirectory:t.workingDirectory,envs:J(t.envs)},t.network,t.user===void 0)}async startFromCheckpoint(e,t,n,i,s=false){let o=t??this.defaultTimeoutMs;if(!Number.isFinite(o)||o<=0)throw new Error(`timeoutMs must be a positive number of milliseconds, got ${o}`);let a=`evolve-${randomUUID()}`,d=await this.http.json({method:"POST",path:"/sailboxes/from_checkpoint",json:{checkpoint_id:e,name:a,max_lifetime_seconds:$(o)},headers:{"Idempotency-Key":a},retry:true}),l=d.state??d.status;if(l==="failed"||l==="create_failed")throw new z(l,`Sail could not start a Sailbox from checkpoint ${e}: ${d.error_message??l}`,d.sailbox_id);let u=d.sailbox_id,m=n.user;s&&(m=await this.retrieve(u).then(ce).catch(()=>n.user)),this.boxes.set(u,{...n,user:m});let g=this.boxFor(u,m,n.workingDirectory,n.envs);try{let c=this.autoSleepParam().auto_sleep;c!==void 0&&await this.http.request({method:"POST",path:`/sailboxes/${encodeURIComponent(u)}/auto_sleep`,json:c,retry:!0}),i&&await g.updateNetwork(i),n.workingDirectory&&await g.files.makeDir(n.workingDirectory);}catch(c){throw await Ye(g),c}return g}boxFor(e,t,n,i){return new we(this.http,e,t,n,i,(s,o,a)=>this.startFromCheckpoint(s,o,a))}async deleteSnapshot(e){return mt(this.http,e)}async createWithBuild(e,t,n,i,s){try{return await this.createOnce(e,i,s,i)}catch(o){if(!(o instanceof I)||o.status!==409||"base"in t)throw o;if("dockerfile"in t){let a=[...this.taskImages.values()].find(d=>d.spec===t);return this.createOnce({...e,image:a.spec=await a.build()},i,s,`${i}-after-build`)}return await this.ensureBuilt(t,n),this.createOnce(e,i,s,`${i}-after-build`)}}async createOnce(e,t,n,i){for(let s=1;;s++){let o;try{o=await this.http.json({method:"POST",path:"/sailboxes",json:e,headers:{"Idempotency-Key":i}});}catch(a){let d=!(a instanceof I)||[500,502,503,504].includes(a.status);if(a instanceof I&&a.status===429&&a.retryAfterSec!==void 0&&s<q){await X(Math.min(a.retryAfterSec,60)*1e3);continue}if(!d)throw a;let u=await this.findByName(t,n).catch(()=>{});if(u)o=u;else if(s<q){await X(1e3*2**(s-1));continue}else throw a}if(o.status==="failed"||o.status==="create_failed")throw new z(o.status,`Sail accepted the create and could not bring the Sailbox up: ${o.error_message??o.status}`,o.sailbox_id);return o}}async findByName(e,t){return (await this.http.json({method:"GET",path:"/sailboxes",query:{app:t,name:e,limit:10},retry:true})).data.find(i=>!me.has(i.status))}async retrieve(e){return this.http.json({method:"GET",path:`/sailboxes/${encodeURIComponent(e)}`,retry:true})}async connect(e,t){let n=await this.retrieve(e);if(me.has(n.status))throw new R(e,h,n.status);if(et.has(n.status)){let s=await this.http.json({method:"POST",path:`/sailboxes/${encodeURIComponent(e)}/resume`,json:{},retry:true});if(s.resume_state==="terminal_unavailable")throw new R(e,h,s.error_message??"terminal_unavailable")}let i=this.boxes.get(e);return this.boxFor(e,i?.user??ce(n),i?.workingDirectory,i?.envs)}async inspect(e,t){let n=await this.retrieve(e);if(!tt.has(n.status))throw new R(e,h,n.status);let i=this.boxes.get(e);return this.boxFor(e,t?.user??i?.user??ce(n),i?.workingDirectory,i?.envs)}async list(e){let t=await this.listAll(e);if(!t.complete&&t.error)throw new Error(`sail: listing Sailboxes failed: ${t.error}`);return t.sandboxes}async listAll(e){let t;try{t=await this.getAppId();}catch(n){return {sandboxes:[],complete:false,pagesFetched:0,error:n instanceof Error?n.message:String(n)}}return ft(n=>this.http.json({method:"GET",path:"/sailboxes",query:{app:t,limit:Ze,offset:n,exclude_status:tr.join(",")},retry:!0}),e)}};async function ft(r,e){let t=e?.limit,n=[];if(t!==void 0&&t<=0)try{let o=await r(0),a=o.data.some(d=>Ke(d.status,e?.state)&&qe(Q(d.env),e?.metadata));return {sandboxes:n,complete:!a&&!o.has_more,pagesFetched:1}}catch(o){return {sandboxes:n,complete:false,pagesFetched:1,error:o instanceof Error?o.message:String(o)}}let i=0,s=0;for(;;){if(s>=oe)return {sandboxes:n,complete:false,pagesFetched:s,error:`stopped at ${oe} pages (${oe*Ze} Sailboxes)`};let o;try{o=await r(i);}catch(a){return {sandboxes:n,complete:false,pagesFetched:s+1,error:a instanceof Error?a.message:String(a)}}s++;for(let a=0;a<o.data.length;a++){let d=o.data[a];if(!Ke(d.status,e?.state))continue;let l=ut(d);if(qe(l.metadata,e?.metadata)){if(t!==void 0&&n.length>=t)return {sandboxes:n,complete:false,pagesFetched:s};n.push(l);}}if(!o.has_more||o.data.length===0)return {sandboxes:n,complete:true,pagesFetched:s};i+=o.data.length;}}function qe(r,e){return e?Object.entries(e).every(([t,n])=>r[t]===n):true}function Vr(r={}){return new xe(r)}var zr=W,Hr=ot,Yr=at,qr=gt,Xr=pt,Jr=ie,Qr=ct,Zr=C,en=dt,tn=Q,rn=ft,nn=be,sn=U;
10
+ export{B as EVOLVE_IMAGE_VERSION,L as ImageBuildError,qt as SAIL_API_URL,Jt as SAIL_DEFAULT_VCPUS,Be as SAIL_MAX_DISK_GIB,Ce as SAIL_MAX_ENV_VALUE_CHARS,oe as SAIL_MAX_LIST_PAGES,Fe as SAIL_MAX_MEMORY_GIB,Ze as SAIL_MAX_PAGE_SIZE,je as SAIL_MAX_REGISTRY_LOGINS,Ue as SAIL_MAX_VCPUS,Xe as SAIL_METADATA_ENV,Qt as SAIL_MIN_DISK_GIB,Yt as SAIL_SAILBOX_API_URL,gr as SAIL_SNAPSHOT_DEFAULT_TTL_MS,I as SailApiError,pe as SailBootCommandError,H as SailCommandTimeoutError,Se as SailCommands,z as SailCreateFailedError,ye as SailFiles,he as SailHttp,ge as SailIdleTimeoutError,v as SailImageError,fe as SailMetadataError,_ as SailNetworkPolicyError,xe as SailProvider,y as SailRegistryLoginError,E as SailResourcesError,w as SandboxFeatureUnsupportedError,R as SandboxNotRunningError,x as SandboxPathNotFoundError,Xr as _testBaseDistroRefusal,rn as _testCollectSailboxes,tn as _testDecodeMetadata,en as _testEncodeMetadata,Jr as _testFindRefusesPrintf,Zr as _testMapNetworkPolicy,Qr as _testMapResources,nn as _testParseFindRecords,Yr as _testPickLogin,Hr as _testRegistryLoginsFor,zr as _testResolveImageRef,sn as _testRunExec,qr as _testSdkImageFor,Vr as createSailProvider,ht as isSandboxFeatureUnsupportedError,bt as isSandboxNotRunningError,St as isSandboxPathNotFoundError,Wr as sailBuilderMissing,ar as sailMemoryFloorGib};
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@evolvingmachines/sail",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.72",
4
+ "keywords": [
5
+ "ai",
6
+ "agents",
7
+ "sandbox",
8
+ "sail",
9
+ "sailbox",
10
+ "evolve",
11
+ "orchestration"
12
+ ],
13
+ "homepage": "https://github.com/evolving-machines-lab/evolve",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/evolving-machines-lab/evolve.git"
17
+ },
18
+ "type": "module",
19
+ "main": "dist/index.cjs",
20
+ "types": "dist/index.d.ts",
21
+ "license": "Apache-2.0",
22
+ "files": [
23
+ "dist",
24
+ "LICENSE"
25
+ ],
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "require": {
33
+ "types": "./dist/index.d.cts",
34
+ "default": "./dist/index.cjs"
35
+ }
36
+ }
37
+ },
38
+ "scripts": {
39
+ "build": "tsup --minify",
40
+ "dev": "tsup --watch",
41
+ "type-check": "tsc --noEmit",
42
+ "test:unit": "tsx tests/unit/sail-provider.test.ts && tsx tests/unit/sail-list-pagination.test.ts && tsx tests/unit/sail-exec.test.ts && tsx tests/unit/sail-snapshots.test.ts && tsx tests/unit/sail-docker-host.test.ts && tsx tests/unit/sail-task-image.test.ts && tsx tests/unit/sail-sdk-loader.test.ts"
43
+ },
44
+ "dependencies": {},
45
+ "devDependencies": {
46
+ "@types/node": "^22.15.18",
47
+ "tsup": "^8.4.0",
48
+ "typescript": "^5.8.3"
49
+ },
50
+ "optionalDependencies": {
51
+ "@sailresearch/sdk": "^0.21.0"
52
+ }
53
+ }