@evolvingmachines/daytona 0.0.55 → 0.0.57
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/README.md +2 -2
- package/dist/index.cjs +8 -2
- package/dist/index.d.cts +1207 -8
- package/dist/index.d.ts +1207 -8
- package/dist/index.js +8 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
# Evolving Machines — Evolve Daytona Provider
|
|
10
10
|
|
|
11
|
-
Daytona sandbox provider for [Evolve SDK](https://www.npmjs.com/package/@evolvingmachines/
|
|
11
|
+
Daytona sandbox provider for [Evolve SDK](https://www.npmjs.com/package/@evolvingmachines/evolve).
|
|
12
12
|
|
|
13
|
-
**Note:** This package is automatically installed as a dependency of `@evolvingmachines/
|
|
13
|
+
**Note:** This package is automatically installed as a dependency of `@evolvingmachines/evolve`. You don't need to install it separately.
|
|
14
14
|
|
|
15
15
|
Check out the [official documentation](https://github.com/evolving-machines-lab/evolve/tree/main/docs) and [cookbooks](https://github.com/evolving-machines-lab/evolve/tree/main/cookbooks).
|
|
16
16
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,8 @@
|
|
|
1
|
-
'use strict';var sdk=require('@daytonaio/sdk');var
|
|
2
|
-
|
|
1
|
+
'use strict';var sdk=require('@daytonaio/sdk'),crypto=require('crypto');var I="c-880c264ce574";var z={[`evolve-all-${I}`]:`evolvingmachines/evolve-all:${I}`,"evolve-all":"evolvingmachines/evolve-all"},Lt=10,tt=10,et=20,Nt=18e4,Bt=2e3,ut=6e5,ft=5e3,Rt={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},S=s=>new Promise(t=>setTimeout(t,Math.max(0,s))),Ut=100,C=1e4;function Ft(s){let t=s.lastIndexOf("/");return t>0?s.substring(0,t):"/"}function Yt(s){let t=s.lastIndexOf("/");return t>=0?s.substring(t+1):s}var b=class extends Error{reason;destination;constructor(t,e,n){super(e),this.name="DaytonaNetworkPolicyError",this.reason=t,this.destination=n;}},M=class extends Error{image;constructor(t,e){let n=e instanceof Error?e.message:String(e??"unknown error");super(`Failed to pull image "${t}" on Daytona: ${n}. Private registry images require the registry pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret; AWS ECR registrations name an IAM role Daytona assumes (no password). Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=t;}},nt=class extends Error{snapshot;constructor(t){super(`Daytona cannot constrain the GPU type for "${t}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=t;}},T=class extends Error{snapshot;constructor(t){super(`Daytona snapshot "${t}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=t;}},O=class extends Error{constructor(){super("Daytona takes no create-time boot command: it never runs an image entrypoint or any argv at boot (harbor daytona/environment.py:706-708 works around exactly that, starting dockerd by hand). The boot is already inert \u2014 run the process by exec after create."),this.name="DaytonaBootCommandError";}},E=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError";}},Gt=new Set(["pending_build","building_snapshot","pulling_snapshot"]);function st(s){return s!=null&&Gt.has(s)?"image_pull":"boot"}var L=class extends Error{phase;state;sandboxId;constructor(t,e,n){super(`Daytona sandbox boot abandoned during ${t} (provider state ${e??"not yet reported"}, sandbox ${n??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=t,this.state=e,this.sandboxId=n;}},ot="evolve_boot",Wt=5e3,rt=30;async function oe(s,t,e={}){let n=crypto.randomUUID(),r=e.pollMs??Wt,o=null,a=null,i=false,d=(l,u)=>{let h=l==="build_log"?"image_pull":st(a);e.onProgress?.({signal:l,phase:h,state:a,sandboxId:o?.id??null,...u===void 0?{}:{line:u}});},f=s.create({...t,labels:{...t.labels??{},[ot]:n}},{timeout:0,onSnapshotCreateLogs:l=>{for(let u of l.split(`
|
|
2
|
+
`)){let h=u.trimEnd();h.length>0&&d("build_log",h);}}});(async()=>{for(;!i;){try{if(o===null)for await(let u of s.list({labels:{[ot]:n}})){o=u;break}else await o.refreshData();let l=o?.state??null;l!==a&&(a=l,d("state"));}catch{}i||await S(r);}})();let c=()=>{let l=new L(st(a),a,o?.id??null);return f.then(u=>u.delete(rt).catch(()=>{}),()=>{}),o!==null&&o.delete(rt).catch(()=>{}),l},g=new Promise((l,u)=>{let h=e.signal;if(h){if(h.aborted){u(c());return}h.addEventListener("abort",()=>{i||u(c());},{once:true});}});try{return await Promise.race([f,g])}finally{i=true;}}var A=class extends Error{snapshot;constructor(t,e){super(`Daytona snapshot "${t}" exists but could not be activated: ${e}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=t;}};async function N(s,t,e,n){let r=n?.timeoutMs??Nt,o=n?.pollMs??Bt;console.log(`[daytona] Snapshot "${t}" is inactive (unused for 2+ weeks) \u2014 reactivating...`);let a;try{a=await s.snapshot.activate(e);}catch(d){throw new A(t,`the activate call failed (${d instanceof Error?d.message:String(d)})`)}let i=Date.now()+r;for(;a?.state!=="active";){if(a?.state==="error"||a?.state==="build_failed")throw new A(t,`it entered state "${a.state}"`);if(Date.now()>=i)throw new A(t,`still "${a?.state??"unknown"}" after ${r}ms`);await S(o);try{a=await s.snapshot.get(t);}catch(d){throw new A(t,`the activation poll failed (${d instanceof Error?d.message:String(d)})`)}}return console.log(`[daytona] Snapshot "${t}" reactivated.`),a}var D=class extends Error{snapshot;constructor(t,e){super(`Daytona snapshot "${t}" is being created by another process and this run could not wait it out: ${e}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=t;}},gt=Symbol("daytona-snapshot-gone"),mt=new Set(["pending","pulling","building","snapshotting"]),jt=3;function V(s){let t=s;return t?.status??t?.statusCode??t?.response?.status}var at=new Set(["error","build_failed"]),Ht=new Set(["latest","lts","stable"]);function B(s){let t=z[s]??s;if(t.includes("@"))return /@[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[0-9a-f]{32,}$/i.test(t);let e=t.substring(t.lastIndexOf("/")+1),n=e.lastIndexOf(":");if(n<0)return false;let r=e.substring(n+1);return r===""?false:!Ht.has(r.toLowerCase())}function R(s){let t=s.toLowerCase();return t.includes("not found")||t.includes("404")||t.includes("does not exist")}var pt=6e4,ht=2e3;async function it(s,t,e,n){let r=e.errorReason?`: ${e.errorReason}`:"";console.warn(`[daytona] Deleting dead snapshot "${t}" (state "${e.state??"unknown"}"${r}) before rebuilding it.`);try{await s.snapshot.delete(e);}catch(d){let f=d instanceof Error?d.message:String(d);if(!R(f))return console.warn(`[daytona] Could not delete dead snapshot "${t}" (${f}) \u2014 delete it in the Daytona dashboard (Snapshots page) to restore the fast path; falling back to a direct image pull for now.`),false}let o=n?.timeoutMs??pt,a=n?.pollMs??ht,i=Date.now()+o;for(;;){try{await s.snapshot.get(t);}catch(d){if(R(d instanceof Error?d.message:String(d)))return true}if(Date.now()>=i)return console.warn(`[daytona] Dead snapshot "${t}" still resolves ${o}ms after it was deleted \u2014 leaving the rebuild to the next run rather than racing the removal.`),false;await S(a);}}function wt(s){if(V(s)===409)return true;let t=(s instanceof Error?s.message:String(s)).toLowerCase();return t.includes("already exists")||t.includes("conflict")}function Kt(s){let t=V(s);if(t===401||t===403)return true;let e=(s instanceof Error?s.message:String(s)).toLowerCase();return e.includes("unauthorized")||e.includes("forbidden")||e.includes("status code 401")||e.includes("status code 403")}async function bt(s,t,e){let n=e?.timeoutMs??ut,r=e?.pollMs??ft;console.log(`[daytona] Snapshot "${t}" is already being created by another process \u2014 waiting for it (up to ${Math.round(n/1e3)}s) instead of pulling the image directly...`);let o=Date.now()+n,a,i="",d=0;for(;;){try{a=await s.snapshot.get(t),i="",d=0;}catch(f){a=void 0;let m=f instanceof Error?f.message:String(f);if(R(m))return console.log(`[daytona] Snapshot "${t}" no longer exists \u2014 the name is clear, building it.`),gt;if(Kt(f))throw new D(t,`the poll was refused (${m}) \u2014 these credentials cannot read the snapshot, so waiting longer cannot help`);if(d=m===i?d+1:1,i=m,d>=jt)throw new D(t,`${d} consecutive polls failed the same way (${m}) \u2014 the control plane is not answering, so waiting longer cannot help`);console.warn(`[daytona] Poll of contended snapshot "${t}" failed, retrying: ${m}`);}if(a!==void 0&&!mt.has(a.state??""))return a;if(Date.now()>=o)throw new D(t,`it was still "${a?.state??"unknown"}" after ${n}ms \u2014 retry once that build finishes, or check the snapshot in the Daytona dashboard (Snapshots page)`);await S(r);}}function U(s,t){if(!t||t<=0)return s;let e=Buffer.from(s).toString("base64"),n=`/tmp/.evolve-cmd-${Date.now()}-${Math.random().toString(36).slice(2,8)}.sh`;return `sh -c '${`echo ${e} | base64 -d > ${n} && [ -s ${n} ] || { rm -f ${n}; exit 126; }; if command -v timeout >/dev/null 2>&1; then timeout -k 10 ${t} bash ${n}; else bash ${n}; fi; rc=$?; rm -f ${n}; exit $rc`}'`}function dt(){return `EVOLVE-EOS-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function F(s,t){return s.trim()?`exec 9>&1 && { :
|
|
3
|
+
${s}
|
|
4
|
+
|
|
5
|
+
}; __evolve_eos=$?; printf '%s' '${t}' 2>/dev/null >&9; exec 9>&-; (exit $__evolve_eos)`:s}function yt(s,t){return s.endsWith(`${t}
|
|
6
|
+
`)?s.slice(0,-(t.length+1)):s.endsWith(t)?s.slice(0,-t.length):s}function v(s,t){let e=_t(s);return {stdout:yt(e.stdout,t),stderr:e.stderr}}function Y(s,t){let e=`${s}
|
|
7
|
+
`,n="",r=o=>{for(let a=Math.min(o.length,e.length);a>0;a--)if(e.startsWith(o.slice(o.length-a)))return a;return 0};return {push(o){n+=o;let a=r(n);a!==n.length&&(t(n.slice(0,n.length-a)),n=n.slice(n.length-a));},flush(){let o=n===e||n===s?"":n;n="",o&&t(o);}}}function G(s,t,e,n){let r=s;return t&&(r=`cd '${t.replace(/'/g,"'\\''")}' && ${r}`),e&&Object.keys(e).length>0&&(r=`${Object.entries(e).filter(([,a])=>a!=null).map(([a,i])=>`export ${a}='${String(i).replace(/'/g,"'\\''")}'`).join("; ")}; ${r}`),n==="root"&&(r=`echo ${Buffer.from(r).toString("base64")} | base64 -d | sudo -n bash`),r}function xt(s){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(s);return !(!t||[t[1],t[2],t[3],t[4]].some(e=>Number(e)>255)||t[5]!==void 0&&Number(t[5])>32)}function zt(s){return /^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(s)&&!xt(s)}function Vt(s){return s.startsWith("[")?true:(s.match(/:/g)?.length??0)>=2}function qt(s){return /^[^:]+:\d+$/.test(s)}function Xt(s){return s.startsWith("*.")&&s.length>2&&!s.slice(2).includes("*")}function $(s){if(!s||s.outbound==="open"){if(s?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return s?{networkBlockAll:false}:{}}let t=s.allowedDestinations??[];if(t.length===0)return {networkBlockAll:true};for(let o of t){if(o.trim()==="")throw new b("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(o)}). Every entry must be a hostname, *.wildcard domain, IPv4 address, or IPv4 CIDR \u2014 remove the blank entry (an empty allowlist would open the sandbox, not seal it).`,o);if(o.includes(","))throw new b("invalid-destination",`network.allowedDestinations entry "${o}" contains a comma. Daytona's allowlists are sent as one comma-joined string, so a comma inside an entry would smuggle extra destinations past the list caps \u2014 pass one destination per array entry.`,o)}let e=[],n=[];for(let o of t)if(xt(o))e.push(o.includes("/")?o:`${o}/32`);else {if(zt(o))throw new b("invalid-ipv4",`"${o}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,o);if(Vt(o))throw new b("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${o}".`,o);if(qt(o))throw new b("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${o}" and list just the host or IP.`,o);if(o.includes("*")&&!Xt(o))throw new b("wildcard-hostname",`Daytona's domain allowlist supports exactly one wildcard form \u2014 a "*." prefix ("*.example.com" allows example.com and its subdomains) \u2014 and cannot express "${o}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,o);n.push(o);}if(e.length>0&&n.length>0)throw new b("mixed-allowlist",`Daytona's networkAllowList (IPv4 CIDRs) and domainAllowList (DNS names) are mutually exclusive \u2014 at most one may be non-empty per sandbox, and this policy names both kinds (CIDRs: ${e.join(", ")}; domains: ${n.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(n.length>0){let o=[...new Set(n)];if(o.length>et)throw new b("allowlist-too-large",`Daytona allows at most ${et} entries in its domain allowlist; this policy names ${o.length} domains (${o.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return {networkBlockAll:false,domainAllowList:o.join(",")}}let r=[...new Set(e)];if(r.length>tt)throw new b("allowlist-too-large",`Daytona allows at most ${tt} entries in its network allowlist; this policy resolved to ${r.length} CIDRs (${r.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return {networkBlockAll:false,networkAllowList:r.join(",")}}function St(s){let t=$(s);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:false,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===true,networkAllowList:"",domainAllowList:""}}function At(s){let t=V(s),e=(s instanceof Error?s.message:String(s)).toLowerCase(),n=e.includes("network policy")||e.includes("network settings")||e.includes("network configuration"),r=e.includes("tier")||e.includes("plan")||e.includes("upgrade")||e.includes("not allowed")||e.includes("not permitted")||e.includes("cannot override");return (t===402||t===403)&&(r||n)?true:n&&r}function vt(s){let t=s.indexOf("/");if(t<0)return;let e=s.substring(0,t);return e.includes(".")||e.includes(":")||e==="localhost"?e:void 0}function q(s){return {sandboxId:s.id,image:s.snapshot??"",name:s.name,metadata:s.labels??{},startedAt:s.createdAt??""}}function Dt(s){if(s==="started")return "running";if(s==="stopped"||s==="archived"||s==="paused")return "paused"}function Pt(s,t){if(!s||typeof s!="object")return;let e=s;if(typeof e.toolboxProxyUrl=="string"&&(e.toolboxProxyUrl=t),Array.isArray(e.items))for(let n of e.items)Pt(n,t);}function Qt(s,t){return new Proxy(s,{get(e,n,r){if(n==="getToolboxProxyUrl")return async()=>({data:{url:t}});let o=Reflect.get(e,n,r);return typeof o!="function"?o:function(...a){let i=o.apply(e,a);return i instanceof Promise?i.then(d=>(Pt(d?.data,t),d)):i}}})}var W=class extends sdk.Daytona{constructor(t,e){super(t);let n=this;n.sandboxApi=Qt(n.sandboxApi,e);}};function Jt(s,t){let e=new Uint8Array(new ArrayBuffer(s.length+t.length));return e.set(s,0),e.set(t,s.length),e}function lt(s,t,e){t:for(let n=e;n+t.length<=s.length;n++){for(let r=0;r<t.length;r++)if(s[n+r]!==t[r])continue t;return n}return -1}function kt(s,t){let e=new TextDecoder("utf-8"),n=new TextDecoder("utf-8"),r=new Uint8Array(0),o="stdout",a=i=>{i.length!==0&&(o==="stdout"?s(e.decode(i,{stream:true})):t(n.decode(i,{stream:true})));};return {push(i){for(r=Jt(r,i);;){let d=lt(r,sdk.STDOUT_PREFIX_BYTES,0),f=lt(r,sdk.STDERR_PREFIX_BYTES,0),m=-1,c="stdout",g=0;if(d!==-1&&(f===-1||d<f)?(m=d,c="stdout",g=sdk.STDOUT_PREFIX_BYTES.length):f!==-1&&(m=f,c="stderr",g=sdk.STDERR_PREFIX_BYTES.length),m===-1){let l=Math.max(0,r.length-(sdk.MAX_PREFIX_LEN-1));a(r.subarray(0,l)),r=r.slice(l);return}a(r.subarray(0,m)),o=c,r=r.slice(m+g);}},flush(){a(r),r=new Uint8Array(0);let i=e.decode();i&&s(i);let d=n.decode();d&&t(d);}}}async function Tt(s,t,e,n,r,o,a){let i=`${s.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(e)}/command/${encodeURIComponent(n)}/logs?follow=true`,d=await fetch(i,{headers:{Authorization:`Bearer ${s.apiKey}`,accept:"application/octet-stream"},...a?{signal:a}:{}});if(!d.ok)throw new Error(`Daytona managed log follow failed: ${d.status} ${await d.text()}`);if(!d.body)return;let f=kt(r,o),m=d.body.getReader();try{for(;;){let{done:c,value:g}=await m.read();if(c)break;g&&f.push(g);}}finally{f.flush(),await m.cancel().catch(()=>{});}}function _t(s){let t=s.stdout||"",e=s.stderr||"",n=s.output||"";return !t&&!e&&n?{stdout:n,stderr:""}:{stdout:t,stderr:e}}var j=class{constructor(t,e,n){this.sandbox=t;this.user=e;this.managedStream=n;}streamTimings=Rt;followLogs(t,e,n,r,o){return this.managedStream?Tt(this.managedStream,this.sandbox.id,t,e,n,r,o):this.sandbox.process.getSessionCommandLogs(t,e,n,r)}async run(t,e){let n=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let o=!!(e?.onStdout||e?.onStderr),a=dt(),i=await this.sandbox.process.executeSessionCommand(r,{command:U(G(F(t,a),e?.cwd,e?.envs,this.user),n),runAsync:o},n),d=i.cmdId;if(o&&!d)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(o&&d){let c="",g="",l=!0,u=Date.now(),h=Y(a,p=>{c+=p,e?.onStdout?.(p);}),w=new AbortController,y=this.followLogs(r,d,p=>{l&&(u=Date.now(),h.push(p));},p=>{l&&(u=Date.now(),g+=p,e?.onStderr?.(p));},w.signal),x=!1,P,$t=y.then(()=>{},p=>{x||(P=p);}),X;try{X=await this.awaitStreamedExit(r,d,y,()=>u,e?.timeoutMs);}finally{x=!0,w.abort(),await Promise.race([$t,S(this.streamTimings.drainMs)]),l=!1,P===void 0&&h.flush();}if(P!==void 0){let p;try{let Ct=await this.sandbox.process.getSessionCommandLogs(r,d);p=v(Ct,a);}catch{throw P}if(!p.stdout.startsWith(c)||!p.stderr.startsWith(g))throw P;let k=p.stdout.slice(c.length),Q=p.stderr.slice(g.length);c=p.stdout,g=p.stderr,k&&e?.onStdout?.(k),Q&&e?.onStderr?.(Q);}else if(!c&&!g)try{let p=await this.sandbox.process.getSessionCommandLogs(r,d),k=v(p,a);c=k.stdout,g=k.stderr,c&&e?.onStdout?.(c),g&&e?.onStderr?.(g);}catch{}return {exitCode:X,stdout:c,stderr:g}}let{stdout:f,stderr:m}=v(i,a);if(!f&&!m&&d)try{let c=await this.sandbox.process.getSessionCommandLogs(r,d),g=v(c,a);f=g.stdout,m=g.stderr||m;}catch{}return {exitCode:i.exitCode??0,stdout:f,stderr:m}}finally{try{await this.sandbox.process.deleteSession(r);}catch{}}}async awaitStreamedExit(t,e,n,r,o){let a=this.streamTimings,i,d,f=n.then(()=>{i=Date.now();},g=>{i=Date.now(),d=g;}),m=o!==void 0&&o>0?Date.now()+o+a.killGraceMs:void 0,c=a.pollMinMs;for(;;){let g=await this.sandbox.process.getSessionCommand(t,e);if(g.exitCode!==void 0&&g.exitCode!==null){for(;i===void 0;){let h=Date.now()-r();if(h>=a.drainMs)break;await Promise.race([f,S(a.drainMs-h)]);}return g.exitCode}let l=i!==void 0?i+a.settleMs:void 0,u=m!==void 0&&l!==void 0?Math.min(m,l):m??l;if(u!==void 0&&Date.now()>=u)throw d!==void 0?d:new Error(`Daytona reported no exit code for command ${e} after `+(i!==void 0?"its log stream closed":`${o}ms`));await S(c),c=Math.min(c*2,a.pollMaxMs);}}async spawn(t,e){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,o=Date.now(),a=e?.timeoutMs,i=dt(),f=(await this.sandbox.process.executeSessionCommand(n,{command:U(G(F(t,i),e?.cwd,e?.envs,this.user),r),runAsync:true},r)).cmdId;if(f&&(e?.onStdout||e?.onStderr)){let c=Y(i,e.onStdout||(()=>{}));this.followLogs(n,f,g=>c.push(g),e.onStderr||(()=>{})).catch(()=>{}).finally(()=>c.flush());}let m=this.sandbox;return {processId:n,wait:async()=>{if(!f)return {exitCode:0,stdout:"",stderr:""};for(;;){if(a&&Date.now()-o>=a){try{await m.process.deleteSession(n);}catch{}return {exitCode:124,stdout:"",stderr:"operation timed out"}}try{let c=await m.process.getSessionCommand(n,f);if(c.exitCode!==void 0)try{let g=await m.process.getSessionCommandLogs(n,f);return {exitCode:c.exitCode,...v(g,i)}}catch{return {exitCode:c.exitCode,stdout:"",stderr:""}}}catch(c){let g=c instanceof Error?c.message.toLowerCase():String(c).toLowerCase();if(g.includes("not found")){let l=g.includes("sandbox");try{await m.refreshData(),l=!1;}catch(u){(u instanceof Error?u.message.toLowerCase():String(u).toLowerCase()).includes("not found")&&(l=true);}return {exitCode:-1,stdout:"",stderr:l?"sandbox deleted during run":"session terminated"}}throw c}await S(500);}},kill:async()=>{try{return await m.process.deleteSession(n),!0}catch{return false}}}}async list(){try{return (await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return []}}async kill(t){try{return await this.sandbox.process.deleteSession(t),!0}catch{return false}}},H=class{constructor(t){this.sandbox=t;}async read(t){let e=new Uint8Array(await this.sandbox.fs.downloadFile(t));if(!e.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{}return e}async write(t,e){let n;if(typeof e=="string")n=Buffer.from(e,"utf-8");else if(Buffer.isBuffer(e))n=e;else if(e instanceof ArrayBuffer)n=Buffer.from(e);else if(e instanceof Uint8Array)n=Buffer.from(e);else throw new Error(`Unsupported content type: ${typeof e}`);await this.sandbox.fs.uploadFile(n,t);}async writeBatch(t){let e=t.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return {source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(e);}async writeFromPath(t,e){await this.sandbox.fs.uploadFile(e,t);}async makeDir(t){await this.sandbox.fs.createFolder(t,"755");}async exists(t){try{let e=Ft(t),n=Yt(t);return (await this.sandbox.fs.listFiles(e)).some(o=>o.name===n)}catch{return false}}async list(t){return (await this.sandbox.fs.listFiles(t)).map(n=>({name:n.name,path:t.endsWith("/")?`${t}${n.name}`:`${t}/${n.name}`,type:n.isDir?"dir":"file"}))}async remove(t){await this.sandbox.fs.deleteFile(t,true);}async rename(t,e){await this.sandbox.fs.moveFiles(t,e);}},_=class{constructor(t,e,n){this.sandbox=t;this.commands=new j(t,e,n),this.files=new H(t);}commands;files;get sandboxId(){return this.sandbox.id}async getHost(t){return (await this.sandbox.getPreviewLink(t)).url}async isRunning(){try{await this.sandbox.refreshData();}catch{return false}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),q(this.sandbox)}async updateNetwork(t){let e=St(t);try{await this.sandbox.updateNetworkSettings(e);}catch(n){throw At(n)?new b("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete();}async pause(){await this.sandbox.stop();}},K=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:ut,pollMs:ft};snapshotDeleteTiming={timeoutMs:pt,pollMs:ht};constructor(t){let e={apiKey:t.apiKey,apiUrl:t.apiUrl,target:t.target,useDeprecatedPolling:true};this.client=t.managedToolboxUrl?new W(e,t.managedToolboxUrl):new sdk.Daytona(e),t.managedToolboxUrl&&(this.managedStream={toolboxUrl:t.managedToolboxUrl,apiKey:t.apiKey}),this.defaultTimeoutMs=t.defaultTimeoutMs??36e5,this.snapshotName=t.snapshotName??(t.managedToolboxUrl?"evolve-all":`evolve-all-${I}`);}async create(t){if(t.idleTimeoutMs!==void 0)throw new E;if(t.bootCommand!==void 0)throw new O;for(let l of t.phaseNetworkPolicies??[])$(l);let e=$(t.network),n=t.user,r=n&&n!=="root"?n:void 0,o=t.timeoutMs??this.defaultTimeoutMs,a=Math.max(1,Math.ceil(o/6e4)),i=t.image||this.snapshotName,d={envVars:t.envs,labels:t.metadata,autoStopInterval:a,autoDeleteInterval:Lt,...r?{user:r}:{},...e},f,m=t.resources!==void 0&&(t.resources.cpu!==void 0||t.resources.memory!==void 0||t.resources.disk!==void 0||t.resources.gpu!==void 0||t.resources.gpuTypes!==void 0);if(this.managedStream){if(m)throw new T(i);let l=await this.client.create({snapshot:i,...d},{timeout:600});return t.workingDirectory&&await l.fs.createFolder(t.workingDirectory,"755"),n&&this.sandboxUsers.set(l.id,n),new _(l,n,this.managedStream)}let c,g;try{let l=await this.client.snapshot.get(i),u=l?.state;if(l&&mt.has(u??"")&&(c=u),l&&(u==="active"||u==="inactive")&&m)throw new T(i);if(l&&u==="inactive"&&(u=(await N(this.client,i,l)).state),l&&at.has(u??"")&&(B(i)?g=await it(this.client,i,l,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${i}" is dead (state "${u}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),l&&u==="active")console.log(`[daytona] Using cached snapshot: ${i}`),f=await this.client.create({snapshot:i,...d},{timeout:600});else throw new Error("Snapshot not active")}catch(l){if(l instanceof T||l instanceof A)throw l;let u=z[i]??i,h=c!==void 0&&!m;h?console.log(`[daytona] Snapshot "${i}" is mid-build (state "${c}") \u2014 joining that build rather than starting a second one.`):c!==void 0?console.log(`[daytona] Snapshot "${i}" is mid-build (state "${c}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${u}`):(console.log(`[daytona] Snapshot "${i}" not found, building from image: ${u}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(g===!1)throw new Error(`dead snapshot "${i}" was not confirmed removed \u2014 not racing its removal`);let w=()=>this.client.snapshot.create({name:i,image:sdk.Image.base(u),resources:{cpu:t.resources?.cpu??4,memory:t.resources?.memory??4,disk:t.resources?.disk??10,...(t.resources?.gpu??0)>0?{gpu:t.resources.gpu}:{},...t.resources?.gpuTypes?.length?{gpuType:t.resources.gpuTypes}:{}}},{onLogs:x=>console.log(`[daytona] ${x}`)}),y=async()=>{await w(),console.log(`[daytona] Snapshot "${i}" ready (rebuilt here after a dead build).`);};if(c!==void 0){if(!h)throw new Error(`snapshot "${i}" is mid-build (state "${c}") and cannot be resized`);await this.joinInFlightSnapshotBuild(i)&&await y();}else try{await w(),console.log(`[daytona] Snapshot "${i}" ready (built here).`);}catch(x){if(!wt(x)||m)throw x;await this.joinInFlightSnapshotBuild(i)&&await y();}f=await this.client.create({snapshot:i,...d},{timeout:600});}catch(w){if(w instanceof D||w instanceof A)throw w;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${w instanceof Error?w.message:w}`);try{f=await this.client.create({image:u,...d,resources:{cpu:t.resources?.cpu??4,memory:t.resources?.memory??4,disk:t.resources?.disk??10,...(t.resources?.gpu??0)>0?{gpu:t.resources.gpu}:{},...t.resources?.gpuTypes?.length?{gpuType:t.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:y=>console.log(`[daytona] ${y}`)});}catch(y){throw vt(u)?new M(u,y):y}}}return t.workingDirectory&&await f.fs.createFolder(t.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new _(f,n,this.managedStream)}async joinInFlightSnapshotBuild(t){let e=await bt(this.client,t,this.snapshotConflictTiming);if(e===gt)return true;if(e.state==="active")return console.log(`[daytona] Snapshot "${t}" ready (built by another process) \u2014 reusing it.`),false;if(e.state==="inactive")return await N(this.client,t,e),console.log(`[daytona] Snapshot "${t}" ready (built by another process) \u2014 reusing it.`),false;if(at.has(e.state??"")&&B(t)&&await it(this.client,t,e,this.snapshotDeleteTiming))return true;throw new Error(`the in-flight build of snapshot "${t}" ended in state "${e.state??"unknown"}"`)}async connect(t,e){let n=await this.client.get(t);return n.state!=="started"&&await n.start(),new _(n,this.sandboxUsers.get(t),this.managedStream)}async list(t){let e=await this.paginate(t);if(e.error&&!e.stoppedAtLimit)throw new Error(e.error);return e.sandboxes}async listAll(t){let{stoppedAtLimit:e,...n}=await this.paginate(t);return n}async paginate(t){return It(this.listStream(t),t)}listStream(t){let e=t?.state?Zt(t.state):void 0,n={limit:Ut,...t?.metadata?{labels:t.metadata}:{},...e&&e.length>0?{states:e}:{}};return this.client.list(n)}};function Zt(s){let t=[];for(let e of s)e==="running"&&t.push("started"),e==="paused"&&t.push("stopped","archived","paused");return t}async function It(s,t){let e=t?.limit,n=[],r=0,o=new Set;try{for await(let a of s){if(e!==void 0&&n.length>=e)return {sandboxes:n,complete:!1,pagesFetched:r,stoppedAtLimit:!0,error:`stopped at the requested limit of ${e} with more sandboxes available`};if(r+=1,r>C)return {sandboxes:n,complete:!1,pagesFetched:C,stoppedAtLimit:!1,error:`sandbox list exceeded ${C} sandboxes scanned`};if(t?.state){let i=Dt(a.state);if(i===void 0||!t.state.includes(i))continue}o.has(a.id)||(o.add(a.id),n.push(q(a)));}}catch(a){return {sandboxes:n,complete:false,pagesFetched:r,stoppedAtLimit:false,error:`sandbox list failed: ${a instanceof Error?a.message:String(a)}`}}return {sandboxes:n,complete:true,pagesFetched:r,stoppedAtLimit:false}}var re=It;function ae(s={}){let t=s.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new K({...s,apiKey:t})}var ie=G,de=U,le=$,ce=St,ue=At,fe=vt,ge=q,me=Dt,pe=N,he=bt,we=wt,be=B,ye=z,xe=F,Se=yt,Ae=v,ve=Y,De=kt,Pe=Tt,ke=_t;
|
|
8
|
+
exports.DAYTONA_AUTO_DELETE_GRACE_MINUTES=Lt;exports.DAYTONA_BOOT_LABEL=ot;exports.DAYTONA_BOOT_POLL_MS=Wt;exports.DAYTONA_LIST_PAGE_SIZE=Ut;exports.DAYTONA_MAX_DOMAIN_ALLOWLIST=et;exports.DAYTONA_MAX_LIST_SCAN=C;exports.DAYTONA_MAX_NETWORK_ALLOWLIST=tt;exports.DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS=Nt;exports.DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS=ut;exports.DAYTONA_SNAPSHOT_GONE=gt;exports.DAYTONA_STREAM_TIMINGS=Rt;exports.DaytonaBootAbortedError=L;exports.DaytonaBootCommandError=O;exports.DaytonaCommands=j;exports.DaytonaFiles=H;exports.DaytonaGpuTypeError=nt;exports.DaytonaIdleTimeoutError=E;exports.DaytonaImagePullError=M;exports.DaytonaNetworkPolicyError=b;exports.DaytonaProvider=K;exports.DaytonaResourcesError=T;exports.DaytonaSnapshotActivationError=A;exports.DaytonaSnapshotConflictError=D;exports.EVOLVE_IMAGE_VERSION=I;exports._testActivateSnapshot=pe;exports._testCollectSandboxStream=re;exports._testCreateLogDemuxer=De;exports._testCreateSentinelFilter=ve;exports._testDaytonaStateToEvolveState=me;exports._testFollowManagedSessionLogs=Pe;exports._testImageMap=ye;exports._testImageRegistryHost=fe;exports._testIsNetworkPolicyTierRefusal=ue;exports._testIsSnapshotNameConflict=we;exports._testMapNetworkPolicy=le;exports._testMapNetworkPolicyForUpdate=ce;exports._testProviderCanRebuildSnapshot=be;exports._testReadCommandStreams=ke;exports._testSettledStreams=Ae;exports._testStripEndOfOutputSentinel=Se;exports._testToSandboxInfo=ge;exports._testWaitForSnapshotConflictWinner=he;exports._testWithEndOfOutputSentinel=xe;exports._testWithInBoxTimeout=de;exports._testWrapCommand=ie;exports.createDaytonaProvider=ae;exports.createSandboxObserved=oe;exports.daytonaBootPhaseOf=st;exports.mapNetworkPolicy=$;
|