@evolvingmachines/daytona 0.0.60 → 0.0.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- 'use strict';var sdk=require('@daytonaio/sdk'),crypto=require('crypto');var I="c-4bfce70a407f";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}
1
+ 'use strict';var sdk=require('@daytonaio/sdk'),crypto=require('crypto');require('fs');var E=class extends Error{feature;provider;reason;constructor(t,e,s){super(`${e} does not support ${t}${s?`: ${s}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=t,this.provider=e,this.reason=s;}},A=class extends Error{path;provider;constructor(t,e){super(`${e}: no such file or directory: ${t}`),this.name="SandboxPathNotFoundError",this.path=t,this.provider=e;}},_=class extends Error{sandboxId;provider;state;constructor(t,e,s){super(`${e} sandbox ${t} is not running (${s}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=t,this.provider=e,this.state=s;}};function L(n,t){return !!n&&typeof n=="object"&&n.name===t}function Xt(n){return L(n,"SandboxFeatureUnsupportedError")}function Vt(n){return L(n,"SandboxPathNotFoundError")}function qt(n){return L(n,"SandboxNotRunningError")}var M=2,N=20;function R(n){return `'${n.replace(/'/g,"'\\''")}'`}function U(n){if(!Number.isInteger(n.offset)||n.offset<0)throw new RangeError(`offset must be a non-negative integer, got ${n.offset}`);if(!Number.isInteger(n.length)||n.length<0)throw new RangeError(`length must be a non-negative integer, got ${n.length}`)}function ct(n){if(typeof n=="number")return lt((n&4095).toString(8));if(/^[0-7]{1,4}$/.test(n))return lt(n);throw new RangeError(`not an octal mode: ${n}`)}function lt(n){return n.padStart(4,"0")}function F(n){let t=n instanceof Date?n:typeof n=="number"?new Date(n*1e3):new Date(n);if(Number.isNaN(t.getTime()))throw new RangeError(`not a timestamp: ${String(n)}`);return t.toISOString()}function ut(n,t){return n.endsWith("/")?`${n}${t}`:`${n}/${t}`}async function ft(n,t,e){if(U(t),t.length===0)return new Uint8Array(0);let s=t.offset+t.length-1,o=await fetch(n,{headers:{Range:`bytes=${t.offset}-${s}`},signal:AbortSignal.timeout(e.timeoutMs)});if(o.status===206){let r=new Uint8Array(await o.arrayBuffer());return r.length>t.length?r.subarray(0,t.length):r}if(o.status===200)return Qt(o,t);if(o.status===416)return await o.body?.cancel().catch(()=>{}),new Uint8Array(0);throw await o.body?.cancel().catch(()=>{}),o.status===404?new A(e.path,e.provider):new Error(`${e.provider}: range read of ${e.path} failed (HTTP ${o.status})`)}async function Qt(n,t){if(!n.body)return new Uint8Array(0);let e=n.body.getReader(),s=[],o=0,r=0,a=t.offset+t.length;try{for(;;){let{done:u,value:m}=await e.read();if(u)break;let c=o;if(o+=m.length,o>t.offset){let f=Math.max(0,t.offset-c),l=Math.min(m.length,a-c);l>f&&(s.push(m.subarray(f,l)),r+=l-f);}if(o>=a)break}}finally{await e.cancel().catch(()=>{});}let i=new Uint8Array(r),d=0;for(let u of s)i.set(u,d),d+=u.length;return i}var O="c-4bfce70a407f";var ot={[`evolve-all-${O}`]:`evolvingmachines/evolve-all:${O}`,"evolve-all":"evolvingmachines/evolve-all"},ee=10,pt=10,ht=20,ne=18e4,se=2e3,$t=6e5,It=5e3,oe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},S=n=>new Promise(t=>setTimeout(t,Math.max(0,n))),re=100,B=1e4;function ae(n){let t=n.lastIndexOf("/");return t>0?n.substring(0,t):"/"}function ie(n){let t=n.lastIndexOf("/");return t>=0?n.substring(t+1):n}var b=class extends Error{reason;destination;constructor(t,e,s){super(e),this.name="DaytonaNetworkPolicyError",this.reason=t,this.destination=s;}},W=class extends Error{image;constructor(t,e){let s=e instanceof Error?e.message:String(e??"unknown error");super(`Failed to pull image "${t}" on Daytona: ${s}. 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;}},wt=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;}},k=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;}},H=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";}},j=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";}},de=new Set(["pending_build","building_snapshot","pulling_snapshot"]);function yt(n){return n!=null&&de.has(n)?"image_pull":"boot"}var z=class extends Error{phase;state;sandboxId;constructor(t,e,s){super(`Daytona sandbox boot abandoned during ${t} (provider state ${e??"not yet reported"}, sandbox ${s??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=t,this.state=e,this.sandboxId=s;}},bt="evolve_boot",le=5e3,xt=30;async function Ce(n,t,e={}){let s=crypto.randomUUID(),o=e.pollMs??le,r=null,a=null,i=false,d=(l,g)=>{let p=l==="build_log"?"image_pull":yt(a);e.onProgress?.({signal:l,phase:p,state:a,sandboxId:r?.id??null,...g===void 0?{}:{line:g}});},u=n.create({...t,labels:{...t.labels??{},[bt]:s}},{timeout:0,onSnapshotCreateLogs:l=>{for(let g of l.split(`
2
+ `)){let p=g.trimEnd();p.length>0&&d("build_log",p);}}});(async()=>{for(;!i;){try{if(r===null)for await(let g of n.list({labels:{[bt]:s}})){r=g;break}else await r.refreshData();let l=r?.state??null;l!==a&&(a=l,d("state"));}catch{}i||await S(o);}})();let c=()=>{let l=new z(yt(a),a,r?.id??null);return u.then(g=>g.delete(xt).catch(()=>{}),()=>{}),r!==null&&r.delete(xt).catch(()=>{}),l},f=new Promise((l,g)=>{let p=e.signal;if(p){if(p.aborted){g(c());return}p.addEventListener("abort",()=>{i||g(c());},{once:true});}});try{return await Promise.race([u,f])}finally{i=true;}}var v=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 K(n,t,e,s){let o=s?.timeoutMs??ne,r=s?.pollMs??se;console.log(`[daytona] Snapshot "${t}" is inactive (unused for 2+ weeks) \u2014 reactivating...`);let a;try{a=await n.snapshot.activate(e);}catch(d){throw new v(t,`the activate call failed (${d instanceof Error?d.message:String(d)})`)}let i=Date.now()+o;for(;a?.state!=="active";){if(a?.state==="error"||a?.state==="build_failed")throw new v(t,`it entered state "${a.state}"`);if(Date.now()>=i)throw new v(t,`still "${a?.state??"unknown"}" after ${o}ms`);await S(r);try{a=await n.snapshot.get(t);}catch(d){throw new v(t,`the activation poll failed (${d instanceof Error?d.message:String(d)})`)}}return console.log(`[daytona] Snapshot "${t}" reactivated.`),a}var T=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;}},Et=Symbol("daytona-snapshot-gone"),kt=new Set(["pending","pulling","building","snapshotting"]),ce=3;function rt(n){let t=n;return t?.status??t?.statusCode??t?.response?.status}var St=new Set(["error","build_failed"]),ue=new Set(["latest","lts","stable"]);function X(n){let t=ot[n]??n;if(t.includes("@"))return /@[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[0-9a-f]{32,}$/i.test(t);let e=t.substring(t.lastIndexOf("/")+1),s=e.lastIndexOf(":");if(s<0)return false;let o=e.substring(s+1);return o===""?false:!ue.has(o.toLowerCase())}function V(n){let t=n.toLowerCase();return t.includes("not found")||t.includes("404")||t.includes("does not exist")}var _t=6e4,Mt=2e3;async function vt(n,t,e,s){let o=e.errorReason?`: ${e.errorReason}`:"";console.warn(`[daytona] Deleting dead snapshot "${t}" (state "${e.state??"unknown"}"${o}) before rebuilding it.`);try{await n.snapshot.delete(e);}catch(d){let u=d instanceof Error?d.message:String(d);if(!V(u))return console.warn(`[daytona] Could not delete dead snapshot "${t}" (${u}) \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 r=s?.timeoutMs??_t,a=s?.pollMs??Mt,i=Date.now()+r;for(;;){try{await n.snapshot.get(t);}catch(d){if(V(d instanceof Error?d.message:String(d)))return true}if(Date.now()>=i)return console.warn(`[daytona] Dead snapshot "${t}" still resolves ${r}ms after it was deleted \u2014 leaving the rebuild to the next run rather than racing the removal.`),false;await S(a);}}function Ot(n){if(rt(n)===409)return true;let t=(n instanceof Error?n.message:String(n)).toLowerCase();return t.includes("already exists")||t.includes("conflict")}function fe(n){let t=rt(n);if(t===401||t===403)return true;let e=(n instanceof Error?n.message:String(n)).toLowerCase();return e.includes("unauthorized")||e.includes("forbidden")||e.includes("status code 401")||e.includes("status code 403")}async function Ct(n,t,e){let s=e?.timeoutMs??$t,o=e?.pollMs??It;console.log(`[daytona] Snapshot "${t}" is already being created by another process \u2014 waiting for it (up to ${Math.round(s/1e3)}s) instead of pulling the image directly...`);let r=Date.now()+s,a,i="",d=0;for(;;){try{a=await n.snapshot.get(t),i="",d=0;}catch(u){a=void 0;let m=u instanceof Error?u.message:String(u);if(V(m))return console.log(`[daytona] Snapshot "${t}" no longer exists \u2014 the name is clear, building it.`),Et;if(fe(u))throw new T(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>=ce)throw new T(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&&!kt.has(a.state??""))return a;if(Date.now()>=r)throw new T(t,`it was still "${a?.state??"unknown"}" after ${s}ms \u2014 retry once that build finishes, or check the snapshot in the Daytona dashboard (Snapshots page)`);await S(o);}}function q(n,t){if(!t||t<=0)return n;let e=Buffer.from(n).toString("base64"),s=`/tmp/.evolve-cmd-${Date.now()}-${Math.random().toString(36).slice(2,8)}.sh`;return `sh -c '${`echo ${e} | base64 -d > ${s} && [ -s ${s} ] || { rm -f ${s}; exit 126; }; if command -v timeout >/dev/null 2>&1; then timeout -k 10 ${t} bash ${s}; else bash ${s}; fi; rc=$?; rm -f ${s}; exit $rc`}'`}function At(){return `EVOLVE-EOS-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Q(n,t){return n.trim()?`exec 9>&1 && { :
3
+ ${n}
4
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=$;
5
+ }; __evolve_eos=$?; printf '%s' '${t}' 2>/dev/null >&9; exec 9>&-; (exit $__evolve_eos)`:n}function Lt(n,t){return n.endsWith(`${t}
6
+ `)?n.slice(0,-(t.length+1)):n.endsWith(t)?n.slice(0,-t.length):n}function P(n,t){let e=Ht(n);return {stdout:Lt(e.stdout,t),stderr:e.stderr}}function J(n,t){let e=`${n}
7
+ `,s="",o=r=>{for(let a=Math.min(r.length,e.length);a>0;a--)if(e.startsWith(r.slice(r.length-a)))return a;return 0};return {push(r){s+=r;let a=o(s);a!==s.length&&(t(s.slice(0,s.length-a)),s=s.slice(s.length-a));},flush(){let r=s===e||s===n?"":s;s="",r&&t(r);}}}function Z(n,t,e,s){let o=n;return t&&(o=`cd '${t.replace(/'/g,"'\\''")}' && ${o}`),e&&Object.keys(e).length>0&&(o=`${Object.entries(e).filter(([,a])=>a!=null).map(([a,i])=>`export ${a}='${String(i).replace(/'/g,"'\\''")}'`).join("; ")}; ${o}`),s==="root"&&(o=`echo ${Buffer.from(o).toString("base64")} | base64 -d | sudo -n bash`),o}function Nt(n){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(n);return !(!t||[t[1],t[2],t[3],t[4]].some(e=>Number(e)>255)||t[5]!==void 0&&Number(t[5])>32)}function me(n){return /^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(n)&&!Nt(n)}function ge(n){return n.startsWith("[")?true:(n.match(/:/g)?.length??0)>=2}function pe(n){return /^[^:]+:\d+$/.test(n)}function he(n){return n.startsWith("*.")&&n.length>2&&!n.slice(2).includes("*")}function C(n){if(!n||n.outbound==="open"){if(n?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return n?{networkBlockAll:false}:{}}let t=n.allowedDestinations??[];if(t.length===0)return {networkBlockAll:true};for(let r of t){if(r.trim()==="")throw new b("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(r)}). 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).`,r);if(r.includes(","))throw new b("invalid-destination",`network.allowedDestinations entry "${r}" 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.`,r)}let e=[],s=[];for(let r of t)if(Nt(r))e.push(r.includes("/")?r:`${r}/32`);else {if(me(r))throw new b("invalid-ipv4",`"${r}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,r);if(ge(r))throw new b("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${r}".`,r);if(pe(r))throw new b("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${r}" and list just the host or IP.`,r);if(r.includes("*")&&!he(r))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 "${r}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,r);s.push(r);}if(e.length>0&&s.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: ${s.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(s.length>0){let r=[...new Set(s)];if(r.length>ht)throw new b("allowlist-too-large",`Daytona allows at most ${ht} entries in its domain allowlist; this policy names ${r.length} domains (${r.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return {networkBlockAll:false,domainAllowList:r.join(",")}}let o=[...new Set(e)];if(o.length>pt)throw new b("allowlist-too-large",`Daytona allows at most ${pt} entries in its network allowlist; this policy resolved to ${o.length} CIDRs (${o.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return {networkBlockAll:false,networkAllowList:o.join(",")}}function Rt(n){let t=C(n);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:false,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===true,networkAllowList:"",domainAllowList:""}}function Ut(n){let t=rt(n),e=(n instanceof Error?n.message:String(n)).toLowerCase(),s=e.includes("network policy")||e.includes("network settings")||e.includes("network configuration"),o=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)&&(o||s)?true:s&&o}function Ft(n){let t=n.indexOf("/");if(t<0)return;let e=n.substring(0,t);return e.includes(".")||e.includes(":")||e==="localhost"?e:void 0}function at(n){return {sandboxId:n.id,image:n.snapshot??"",name:n.name,metadata:n.labels??{},startedAt:n.createdAt??""}}function Bt(n){if(n==="started")return "running";if(n==="stopped"||n==="archived"||n==="paused")return "paused"}function Yt(n,t){if(!n||typeof n!="object")return;let e=n;if(typeof e.toolboxProxyUrl=="string"&&(e.toolboxProxyUrl=t),Array.isArray(e.items))for(let s of e.items)Yt(s,t);}function we(n,t){return new Proxy(n,{get(e,s,o){if(s==="getToolboxProxyUrl")return async()=>({data:{url:t}});let r=Reflect.get(e,s,o);return typeof r!="function"?r:function(...a){let i=r.apply(e,a);return i instanceof Promise?i.then(d=>(Yt(d?.data,t),d)):i}}})}var tt=class extends sdk.Daytona{constructor(t,e){super(t);let s=this;s.sandboxApi=we(s.sandboxApi,e);}};function ye(n,t){let e=new Uint8Array(new ArrayBuffer(n.length+t.length));return e.set(n,0),e.set(t,n.length),e}function Dt(n,t,e){t:for(let s=e;s+t.length<=n.length;s++){for(let o=0;o<t.length;o++)if(n[s+o]!==t[o])continue t;return s}return -1}function Gt(n,t){let e=new TextDecoder("utf-8"),s=new TextDecoder("utf-8"),o=new Uint8Array(0),r="stdout",a=i=>{i.length!==0&&(r==="stdout"?n(e.decode(i,{stream:true})):t(s.decode(i,{stream:true})));};return {push(i){for(o=ye(o,i);;){let d=Dt(o,sdk.STDOUT_PREFIX_BYTES,0),u=Dt(o,sdk.STDERR_PREFIX_BYTES,0),m=-1,c="stdout",f=0;if(d!==-1&&(u===-1||d<u)?(m=d,c="stdout",f=sdk.STDOUT_PREFIX_BYTES.length):u!==-1&&(m=u,c="stderr",f=sdk.STDERR_PREFIX_BYTES.length),m===-1){let l=Math.max(0,o.length-(sdk.MAX_PREFIX_LEN-1));a(o.subarray(0,l)),o=o.slice(l);return}a(o.subarray(0,m)),r=c,o=o.slice(m+f);}},flush(){a(o),o=new Uint8Array(0);let i=e.decode();i&&n(i);let d=s.decode();d&&t(d);}}}async function Wt(n,t,e,s,o,r,a){let i=`${n.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(e)}/command/${encodeURIComponent(s)}/logs?follow=true`,d=await fetch(i,{headers:{Authorization:`Bearer ${n.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 u=Gt(o,r),m=d.body.getReader();try{for(;;){let{done:c,value:f}=await m.read();if(c)break;f&&u.push(f);}}finally{u.flush(),await m.cancel().catch(()=>{});}}function Ht(n){let t=n.stdout||"",e=n.stderr||"",s=n.output||"";return !t&&!e&&s?{stdout:s,stderr:""}:{stdout:t,stderr:e}}var et=class{constructor(t,e,s){this.sandbox=t;this.user=e;this.managedStream=s;}streamTimings=oe;followLogs(t,e,s,o,r){return this.managedStream?Wt(this.managedStream,this.sandbox.id,t,e,s,o,r):this.sandbox.process.getSessionCommandLogs(t,e,s,o)}async run(t,e){let s=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,o=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(o);try{let r=!!(e?.onStdout||e?.onStderr),a=At(),i=await this.sandbox.process.executeSessionCommand(o,{command:q(Z(Q(t,a),e?.cwd,e?.envs,this.user),s),runAsync:r},s),d=i.cmdId;if(r&&!d)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(r&&d){let c="",f="",l=!0,g=Date.now(),p=J(a,h=>{c+=h,e?.onStdout?.(h);}),w=new AbortController,y=this.followLogs(o,d,h=>{l&&(g=Date.now(),p.push(h));},h=>{l&&(g=Date.now(),f+=h,e?.onStderr?.(h));},w.signal),x=!1,$,zt=y.then(()=>{},h=>{x||($=h);}),it;try{it=await this.awaitStreamedExit(o,d,y,()=>g,e?.timeoutMs);}finally{x=!0,w.abort(),await Promise.race([zt,S(this.streamTimings.drainMs)]),l=!1,$===void 0&&p.flush();}if($!==void 0){let h;try{let Kt=await this.sandbox.process.getSessionCommandLogs(o,d);h=P(Kt,a);}catch{throw $}if(!h.stdout.startsWith(c)||!h.stderr.startsWith(f))throw $;let I=h.stdout.slice(c.length),dt=h.stderr.slice(f.length);c=h.stdout,f=h.stderr,I&&e?.onStdout?.(I),dt&&e?.onStderr?.(dt);}else if(!c&&!f)try{let h=await this.sandbox.process.getSessionCommandLogs(o,d),I=P(h,a);c=I.stdout,f=I.stderr,c&&e?.onStdout?.(c),f&&e?.onStderr?.(f);}catch{}return {exitCode:it,stdout:c,stderr:f}}let{stdout:u,stderr:m}=P(i,a);if(!u&&!m&&d)try{let c=await this.sandbox.process.getSessionCommandLogs(o,d),f=P(c,a);u=f.stdout,m=f.stderr||m;}catch{}return {exitCode:i.exitCode??0,stdout:u,stderr:m}}finally{try{await this.sandbox.process.deleteSession(o);}catch{}}}async awaitStreamedExit(t,e,s,o,r){let a=this.streamTimings,i,d,u=s.then(()=>{i=Date.now();},f=>{i=Date.now(),d=f;}),m=r!==void 0&&r>0?Date.now()+r+a.killGraceMs:void 0,c=a.pollMinMs;for(;;){let f=await this.sandbox.process.getSessionCommand(t,e);if(f.exitCode!==void 0&&f.exitCode!==null){for(;i===void 0;){let p=Date.now()-o();if(p>=a.drainMs)break;await Promise.race([u,S(a.drainMs-p)]);}return f.exitCode}let l=i!==void 0?i+a.settleMs:void 0,g=m!==void 0&&l!==void 0?Math.min(m,l):m??l;if(g!==void 0&&Date.now()>=g)throw d!==void 0?d:new Error(`Daytona reported no exit code for command ${e} after `+(i!==void 0?"its log stream closed":`${r}ms`));await S(c),c=Math.min(c*2,a.pollMaxMs);}}async spawn(t,e){let s=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(s);let o=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,r=Date.now(),a=e?.timeoutMs,i=At(),u=(await this.sandbox.process.executeSessionCommand(s,{command:q(Z(Q(t,i),e?.cwd,e?.envs,this.user),o),runAsync:true},o)).cmdId;if(u&&(e?.onStdout||e?.onStderr)){let c=J(i,e.onStdout||(()=>{}));this.followLogs(s,u,f=>c.push(f),e.onStderr||(()=>{})).catch(()=>{}).finally(()=>c.flush());}let m=this.sandbox;return {processId:s,wait:async()=>{if(!u)return {exitCode:0,stdout:"",stderr:""};for(;;){if(a&&Date.now()-r>=a){try{await m.process.deleteSession(s);}catch{}return {exitCode:124,stdout:"",stderr:"operation timed out"}}try{let c=await m.process.getSessionCommand(s,u);if(c.exitCode!==void 0)try{let f=await m.process.getSessionCommandLogs(s,u);return {exitCode:c.exitCode,...P(f,i)}}catch{return {exitCode:c.exitCode,stdout:"",stderr:""}}}catch(c){let f=c instanceof Error?c.message.toLowerCase():String(c).toLowerCase();if(f.includes("not found")){let l=f.includes("sandbox");try{await m.refreshData(),l=!1;}catch(g){(g instanceof Error?g.message.toLowerCase():String(g).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(s),!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}}},Pt="%y\\0%s\\0%T@\\0%m\\0%u\\0%g\\0%l\\0%f\\0",Y=8,be=1800*1e3;function xe(n,t){let e=R(n),s=t==="children"?`[ -e ${e} ] || exit ${M}; [ -d ${e} ] || exit ${N};`:`[ -e ${e} ] || [ -L ${e} ] || exit ${M};`,o=t==="children"?`find -H ${e} -mindepth 1 -maxdepth 1 -printf '${Pt}'`:`find ${e} -maxdepth 0 -printf '${Pt}'`;return `sh -c ${R(`${s} ( ${o}; printf 'STATUS:%d' "$?" ) | base64`)}`}function Se(n,t,e){let o=Buffer.from(t.replace(/\s+/g,""),"base64").toString("utf-8").split("\0"),r=o.pop()??"",a=/^STATUS:(\d+)$/.exec(r);if(!a)throw new Error(`daytona: the listing of ${n} ended without find's status (${r.slice(0,40)})`);if(a[1]!=="0")throw new Error(`daytona: find exited ${a[1]} listing ${n}`);let i=[];for(let d=0;d+Y<=o.length;d+=Y){let[u,m,c,f,l,g,p,w]=o.slice(d,d+Y),y=u==="f"?"file":u==="d"?"dir":u==="l"?"symlink":"other",x={name:w,path:e==="children"?ut(n,w):n,type:y,size:Number(m),mtime:F(Number(c)),mode:ct(f),owner:l,group:g};y==="symlink"&&(x.target=p),i.push(x);}return i}var nt=class{constructor(t,e){this.sandbox=t;this.commands=e;}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 s;if(typeof e=="string")s=Buffer.from(e,"utf-8");else if(Buffer.isBuffer(e))s=e;else if(e instanceof ArrayBuffer)s=Buffer.from(e);else if(e instanceof Uint8Array)s=Buffer.from(e);else throw new Error(`Unsupported content type: ${typeof e}`);await this.sandbox.fs.uploadFile(s,t);}async writeBatch(t){let e=t.map(s=>{let o;if(typeof s.data=="string")o=Buffer.from(s.data,"utf-8");else if(Buffer.isBuffer(s.data))o=s.data;else if(s.data instanceof ArrayBuffer)o=Buffer.from(s.data);else if(s.data instanceof Uint8Array)o=Buffer.from(s.data);else throw new Error(`Unsupported content type: ${typeof s.data}`);return {source:o,destination:s.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=ae(t),s=ie(t);return (await this.sandbox.fs.listFiles(e)).some(r=>r.name===s)}catch{return false}}async list(t){return this.findListing(t,"children")}async stat(t){let[e]=await this.findListing(t,"self");if(!e)throw new A(t,"daytona");return e}async findListing(t,e){let s=await this.commands.run(xe(t,e));if(s.exitCode===M)throw new A(t,"daytona");if(s.exitCode===N)throw new Error(`daytona: ${t} is not a directory`);if(s.exitCode!==0)throw new Error(`daytona: listing ${t} failed (exit ${s.exitCode}): ${s.stderr.trim()}`);try{return Se(t,s.stdout,e)}catch(o){throw /printf|unrecognized|invalid option/i.test(s.stderr)?new E("files.list","daytona",`this image's find has no -printf (GNU findutils is needed to list entries as themselves): ${s.stderr.trim()}`):o}}async readRange(t,e){if(U(e),e.length===0)return new Uint8Array(0);let s=await this.sandbox.downloadUrl(t);return ft(s,e,{provider:"daytona",path:t,timeoutMs:be})}async watchDir(t,e,s){throw new E("files.watchDir","daytona","the Daytona SDK has no filesystem watcher; poll files.list() on the directories you have open")}async remove(t){await this.sandbox.fs.deleteFile(t,true);}async rename(t,e){await this.sandbox.fs.moveFiles(t,e);}},D=class{constructor(t,e,s){this.sandbox=t;let o=new et(t,e,s);this.commands=o,this.files=new nt(t,o);}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(),at(this.sandbox)}async metrics(){let t=await this.sandbox.getMetricsLatest();return {cpuPct:t.cpuUsedPct,memUsedMb:t.memUsed/G,memTotalMb:t.memTotal/G,diskUsedMb:t.diskUsed/G,sampledAt:F(t.timestamp),source:"daytona:getMetricsLatest"}}async updateNetwork(t){let e=Rt(t);try{await this.sandbox.updateNetworkSettings(e);}catch(s){throw Ut(s)?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: ${s instanceof Error?s.message:String(s)}).`):s}}async kill(){await this.sandbox.delete();}async pause(){await this.sandbox.stop();}},st=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:$t,pollMs:It};snapshotDeleteTiming={timeoutMs:_t,pollMs:Mt};constructor(t){let e={apiKey:t.apiKey,apiUrl:t.apiUrl,target:t.target,useDeprecatedPolling:true};this.client=t.managedToolboxUrl?new tt(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-${O}`);}async create(t){if(t.idleTimeoutMs!==void 0)throw new j;if(t.bootCommand!==void 0)throw new H;for(let l of t.phaseNetworkPolicies??[])C(l);let e=C(t.network),s=t.user,o=s&&s!=="root"?s:void 0,r=t.timeoutMs??this.defaultTimeoutMs,a=Math.max(1,Math.ceil(r/6e4)),i=t.image||this.snapshotName,d={envVars:t.envs,labels:t.metadata,autoStopInterval:a,autoDeleteInterval:ee,...o?{user:o}:{},...e},u,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 k(i);let l=await this.client.create({snapshot:i,...d},{timeout:600});return t.workingDirectory&&await l.fs.createFolder(t.workingDirectory,"755"),s&&this.sandboxUsers.set(l.id,s),new D(l,s,this.managedStream)}let c,f;try{let l=await this.client.snapshot.get(i),g=l?.state;if(l&&kt.has(g??"")&&(c=g),l&&(g==="active"||g==="inactive")&&m)throw new k(i);if(l&&g==="inactive"&&(g=(await K(this.client,i,l)).state),l&&St.has(g??"")&&(X(i)?f=await vt(this.client,i,l,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${i}" is dead (state "${g}") 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&&g==="active")console.log(`[daytona] Using cached snapshot: ${i}`),u=await this.client.create({snapshot:i,...d},{timeout:600});else throw new Error("Snapshot not active")}catch(l){if(l instanceof k||l instanceof v)throw l;let g=ot[i]??i,p=c!==void 0&&!m;p?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: ${g}`):(console.log(`[daytona] Snapshot "${i}" not found, building from image: ${g}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(f===!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(g),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(!p)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(!Ot(x)||m)throw x;await this.joinInFlightSnapshotBuild(i)&&await y();}u=await this.client.create({snapshot:i,...d},{timeout:600});}catch(w){if(w instanceof T||w instanceof v)throw w;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${w instanceof Error?w.message:w}`);try{u=await this.client.create({image:g,...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 Ft(g)?new W(g,y):y}}}return t.workingDirectory&&await u.fs.createFolder(t.workingDirectory,"755"),s&&this.sandboxUsers.set(u.id,s),new D(u,s,this.managedStream)}async joinInFlightSnapshotBuild(t){let e=await Ct(this.client,t,this.snapshotConflictTiming);if(e===Et)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 K(this.client,t,e),console.log(`[daytona] Snapshot "${t}" ready (built by another process) \u2014 reusing it.`),false;if(St.has(e.state??"")&&X(t)&&await vt(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 s=await this.client.get(t);return s.state!=="started"&&await s.start(),new D(s,this.sandboxUsers.get(t),this.managedStream)}async inspect(t,e){let s=await this.getSandboxRecord(t);if(s.state!=="started")throw new _(t,"daytona",s.state??"unknown");return new D(s,e?.user??this.sandboxUsers.get(t),this.managedStream)}async getSandboxRecord(t){return this.client.get(t)}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,...s}=await this.paginate(t);return s}async paginate(t){return jt(this.listStream(t),t)}listStream(t){let e=t?.state?ve(t.state):void 0,s={limit:re,...t?.metadata?{labels:t.metadata}:{},...e&&e.length>0?{states:e}:{}};return this.client.list(s)}};function ve(n){let t=[];for(let e of n)e==="running"&&t.push("started"),e==="paused"&&t.push("stopped","archived","paused");return t}async function jt(n,t){let e=t?.limit,s=[],o=0,r=new Set;try{for await(let a of n){if(e!==void 0&&s.length>=e)return {sandboxes:s,complete:!1,pagesFetched:o,stoppedAtLimit:!0,error:`stopped at the requested limit of ${e} with more sandboxes available`};if(o+=1,o>B)return {sandboxes:s,complete:!1,pagesFetched:B,stoppedAtLimit:!1,error:`sandbox list exceeded ${B} sandboxes scanned`};if(t?.state){let i=Bt(a.state);if(i===void 0||!t.state.includes(i))continue}r.has(a.id)||(r.add(a.id),s.push(at(a)));}}catch(a){return {sandboxes:s,complete:false,pagesFetched:o,stoppedAtLimit:false,error:`sandbox list failed: ${a instanceof Error?a.message:String(a)}`}}return {sandboxes:s,complete:true,pagesFetched:o,stoppedAtLimit:false}}var Le=jt;function Ne(n={}){let t=n.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 st({...n,apiKey:t})}var Re=Z,Ue=q,Fe=C,Be=Rt,Ye=Ut,Ge=Ft,We=at,He=Bt,je=K,ze=Ct,Ke=Ot,Xe=X,Ve=ot,qe=Q,Qe=Lt,Je=P,Ze=J,tn=Gt,en=Wt,nn=Ht,sn=D,G=1024*1024;
8
+ exports.DAYTONA_AUTO_DELETE_GRACE_MINUTES=ee;exports.DAYTONA_BOOT_LABEL=bt;exports.DAYTONA_BOOT_POLL_MS=le;exports.DAYTONA_LIST_PAGE_SIZE=re;exports.DAYTONA_MAX_DOMAIN_ALLOWLIST=ht;exports.DAYTONA_MAX_LIST_SCAN=B;exports.DAYTONA_MAX_NETWORK_ALLOWLIST=pt;exports.DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS=ne;exports.DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS=$t;exports.DAYTONA_SNAPSHOT_GONE=Et;exports.DAYTONA_STREAM_TIMINGS=oe;exports.DaytonaBootAbortedError=z;exports.DaytonaBootCommandError=H;exports.DaytonaCommands=et;exports.DaytonaFiles=nt;exports.DaytonaGpuTypeError=wt;exports.DaytonaIdleTimeoutError=j;exports.DaytonaImagePullError=W;exports.DaytonaNetworkPolicyError=b;exports.DaytonaProvider=st;exports.DaytonaResourcesError=k;exports.DaytonaSnapshotActivationError=v;exports.DaytonaSnapshotConflictError=T;exports.EVOLVE_IMAGE_VERSION=O;exports.SandboxFeatureUnsupportedError=E;exports.SandboxNotRunningError=_;exports.SandboxPathNotFoundError=A;exports._testActivateSnapshot=je;exports._testCollectSandboxStream=Le;exports._testCreateLogDemuxer=tn;exports._testCreateSentinelFilter=Ze;exports._testDaytonaSandboxImplCtor=sn;exports._testDaytonaStateToEvolveState=He;exports._testFollowManagedSessionLogs=en;exports._testImageMap=Ve;exports._testImageRegistryHost=Ge;exports._testIsNetworkPolicyTierRefusal=Ye;exports._testIsSnapshotNameConflict=Ke;exports._testMapNetworkPolicy=Fe;exports._testMapNetworkPolicyForUpdate=Be;exports._testProviderCanRebuildSnapshot=Xe;exports._testReadCommandStreams=nn;exports._testSettledStreams=Je;exports._testStripEndOfOutputSentinel=Qe;exports._testToSandboxInfo=We;exports._testWaitForSnapshotConflictWinner=ze;exports._testWithEndOfOutputSentinel=qe;exports._testWithInBoxTimeout=Ue;exports._testWrapCommand=Re;exports.createDaytonaProvider=Ne;exports.createSandboxObserved=Ce;exports.daytonaBootPhaseOf=yt;exports.isSandboxFeatureUnsupportedError=Xt;exports.isSandboxNotRunningError=qt;exports.isSandboxPathNotFoundError=Vt;exports.mapNetworkPolicy=C;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,32 @@
1
1
  import { CreateSandboxFromImageParams, CreateSandboxFromSnapshotParams, Sandbox, ListSandboxesQuery } from '@daytonaio/sdk';
2
2
 
3
+ /** A capability this provider lacks: `feature` in dotted form (`files.watchDir`), `provider` type, optional `reason`. */
4
+ declare class SandboxFeatureUnsupportedError extends Error {
5
+ readonly feature: string;
6
+ readonly provider: string;
7
+ readonly reason?: string;
8
+ constructor(feature: string, provider: string, reason?: string);
9
+ }
10
+ /** A path the sandbox does not have — never an empty success. */
11
+ declare class SandboxPathNotFoundError extends Error {
12
+ readonly path: string;
13
+ readonly provider: string;
14
+ constructor(path: string, provider: string);
15
+ }
16
+ /** An inspect refused because the sandbox is not running; `state` is the provider's own word (`paused`, `exited with code 137`). */
17
+ declare class SandboxNotRunningError extends Error {
18
+ readonly sandboxId: string;
19
+ readonly provider: string;
20
+ readonly state: string;
21
+ constructor(sandboxId: string, provider: string, state: string);
22
+ }
23
+ /** True for a SandboxFeatureUnsupportedError from ANY package's copy. */
24
+ declare function isSandboxFeatureUnsupportedError(err: unknown): err is SandboxFeatureUnsupportedError;
25
+ /** True for a SandboxPathNotFoundError from ANY package's copy. */
26
+ declare function isSandboxPathNotFoundError(err: unknown): err is SandboxPathNotFoundError;
27
+ /** True for a SandboxNotRunningError from ANY package's copy. */
28
+ declare function isSandboxNotRunningError(err: unknown): err is SandboxNotRunningError;
29
+
3
30
  /**
4
31
  * GENERATED — DO NOT EDIT. `npm run generate:image-version` (repo root)
5
32
  * rewrites this file from the evolve-all image build inputs under
@@ -791,11 +818,49 @@ interface SandboxInfo {
791
818
  /** End time (undefined for running sandboxes; Daytona never exposes one) */
792
819
  endAt?: string;
793
820
  }
794
- /** File or directory entry info */
821
+ /** The SDK contract's FileInfo (sdk-ts types.ts), the same entry on every provider. */
795
822
  interface FileInfo {
796
823
  name: string;
797
824
  path: string;
798
- type: "file" | "dir";
825
+ type: "file" | "dir" | "symlink" | "other";
826
+ size: number;
827
+ mtime: string;
828
+ mode: string;
829
+ owner: string;
830
+ group: string;
831
+ target?: string;
832
+ }
833
+ /** A byte range of a file (the SDK contract's FileRange). */
834
+ interface FileRange {
835
+ offset: number;
836
+ length: number;
837
+ }
838
+ /** One filesystem change from watchDir: an absolute path, four kinds. */
839
+ interface FilesystemEvent {
840
+ path: string;
841
+ type: "create" | "write" | "remove" | "rename";
842
+ }
843
+ /** Handle to stop watching a directory */
844
+ interface WatchHandle {
845
+ stop(): Promise<void>;
846
+ }
847
+ /** Options for watching a directory */
848
+ interface WatchOptions {
849
+ /** Also report changes in every subdirectory. Default false. */
850
+ recursive?: boolean;
851
+ }
852
+ /** One resource-usage sample (the SDK contract's SandboxMetrics). */
853
+ interface SandboxMetrics {
854
+ cpuPct: number;
855
+ memUsedMb: number;
856
+ memTotalMb: number;
857
+ diskUsedMb?: number;
858
+ sampledAt: string;
859
+ source: string;
860
+ }
861
+ /** Options for an inspect-only attach (the SDK contract's SandboxInspectOptions). */
862
+ interface SandboxInspectOptions {
863
+ user?: string;
799
864
  }
800
865
  /** Options for blocking sandbox command execution */
801
866
  interface SandboxRunOptions {
@@ -959,6 +1024,12 @@ interface SandboxFiles {
959
1024
  list(path: string): Promise<FileInfo[]>;
960
1025
  remove(path: string): Promise<void>;
961
1026
  rename(oldPath: string, newPath: string): Promise<void>;
1027
+ /** The entry at `path` itself; a symlink is never followed */
1028
+ stat(path: string): Promise<FileInfo>;
1029
+ /** Exactly the requested bytes, without moving the whole file when the range is small */
1030
+ readRange(path: string, range: FileRange): Promise<Uint8Array>;
1031
+ /** Always a typed refusal here: the Daytona SDK has no filesystem watcher */
1032
+ watchDir(path: string, onEvent: (event: FilesystemEvent) => void | Promise<void>, options?: WatchOptions): Promise<WatchHandle>;
962
1033
  }
963
1034
  /** Sandbox instance */
964
1035
  interface SandboxInstance {
@@ -968,6 +1039,8 @@ interface SandboxInstance {
968
1039
  getHost(port: number): Promise<string>;
969
1040
  isRunning(): Promise<boolean>;
970
1041
  getInfo(): Promise<SandboxInfo>;
1042
+ /** The newest resource-usage sample the daemon has */
1043
+ metrics(): Promise<SandboxMetrics | null>;
971
1044
  kill(): Promise<void>;
972
1045
  pause(): Promise<void>;
973
1046
  /** Replace the outbound network policy of the running sandbox. */
@@ -979,6 +1052,8 @@ interface SandboxProvider {
979
1052
  readonly name?: string;
980
1053
  create(options: SandboxCreateOptions): Promise<SandboxInstance>;
981
1054
  connect(sandboxId: string, timeoutMs?: number): Promise<SandboxInstance>;
1055
+ /** Attach to a STARTED sandbox for reads; never starts a stopped one */
1056
+ inspect(sandboxId: string, options?: SandboxInspectOptions): Promise<SandboxInstance>;
982
1057
  /** List sandboxes, paginating to exhaustion. `limit` bounds items returned. */
983
1058
  list(options?: SandboxListOptions): Promise<SandboxInfo[]>;
984
1059
  /** The same enumeration for fleet bookkeeping: never throws, reports completeness. */
@@ -1128,9 +1203,12 @@ declare class DaytonaCommands implements SandboxCommands {
1128
1203
  list(): Promise<ProcessInfo[]>;
1129
1204
  kill(processId: string): Promise<boolean>;
1130
1205
  }
1206
+ /** One blocking, whole-output run — what the file observation needs; a test passes a double. */
1207
+ type DaytonaCommandRunner = Pick<DaytonaCommands, "run">;
1131
1208
  declare class DaytonaFiles implements SandboxFiles {
1132
1209
  private sandbox;
1133
- constructor(sandbox: Sandbox);
1210
+ private commands;
1211
+ constructor(sandbox: Sandbox, commands: DaytonaCommandRunner);
1134
1212
  read(path: string): Promise<string | Uint8Array>;
1135
1213
  write(path: string, content: string | Buffer | ArrayBuffer | Uint8Array): Promise<void>;
1136
1214
  writeBatch(files: Array<{
@@ -1147,6 +1225,10 @@ declare class DaytonaFiles implements SandboxFiles {
1147
1225
  makeDir(path: string): Promise<void>;
1148
1226
  exists(path: string): Promise<boolean>;
1149
1227
  list(path: string): Promise<FileInfo[]>;
1228
+ stat(path: string): Promise<FileInfo>;
1229
+ private findListing;
1230
+ readRange(path: string, range: FileRange): Promise<Uint8Array>;
1231
+ watchDir(_path: string, _onEvent: (event: FilesystemEvent) => void | Promise<void>, _options?: WatchOptions): Promise<WatchHandle>;
1150
1232
  remove(path: string): Promise<void>;
1151
1233
  rename(oldPath: string, newPath: string): Promise<void>;
1152
1234
  }
@@ -1159,6 +1241,7 @@ declare class DaytonaSandboxImpl implements SandboxInstance {
1159
1241
  getHost(port: number): Promise<string>;
1160
1242
  isRunning(): Promise<boolean>;
1161
1243
  getInfo(): Promise<SandboxInfo>;
1244
+ metrics(): Promise<SandboxMetrics | null>;
1162
1245
  /**
1163
1246
  * Replace the running sandbox's outbound policy — Daytona's
1164
1247
  * `sandbox.updateNetworkSettings`, which "maps to the same mechanism as
@@ -1261,6 +1344,9 @@ declare class DaytonaProvider implements SandboxProvider {
1261
1344
  */
1262
1345
  private joinInFlightSnapshotBuild;
1263
1346
  connect(sandboxId: string, _timeoutMs?: number): Promise<SandboxInstance>;
1347
+ inspect(sandboxId: string, options?: SandboxInspectOptions): Promise<SandboxInstance>;
1348
+ /** A GET; seam for the unit test. */
1349
+ protected getSandboxRecord(sandboxId: string): Promise<Sandbox>;
1264
1350
  /**
1265
1351
  * List sandboxes, walking the cursor stream to exhaustion.
1266
1352
  *
@@ -1367,5 +1453,7 @@ declare const _testReadCommandStreams: typeof readCommandStreams;
1367
1453
  * the type (never the constructor) gives the seam the real methods to pin.
1368
1454
  */
1369
1455
  type _testDaytonaSandboxImpl = DaytonaSandboxImpl;
1456
+ /** The constructor, for the metrics unit test (a vendor sandbox double goes in). */
1457
+ declare const _testDaytonaSandboxImplCtor: typeof DaytonaSandboxImpl;
1370
1458
 
1371
- export { DAYTONA_AUTO_DELETE_GRACE_MINUTES, DAYTONA_BOOT_LABEL, DAYTONA_BOOT_POLL_MS, DAYTONA_LIST_PAGE_SIZE, DAYTONA_MAX_DOMAIN_ALLOWLIST, DAYTONA_MAX_LIST_SCAN, DAYTONA_MAX_NETWORK_ALLOWLIST, DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS, DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS, DAYTONA_SNAPSHOT_GONE, DAYTONA_STREAM_TIMINGS, DaytonaBootAbortedError, type DaytonaBootClient, DaytonaBootCommandError, type DaytonaBootPhase, type DaytonaBootProgress, DaytonaCommands, type DaytonaConfig, DaytonaFiles, DaytonaGpuTypeError, DaytonaIdleTimeoutError, DaytonaImagePullError, DaytonaNetworkPolicyError, type DaytonaNetworkPolicyReason, type DaytonaObservedCreateOptions, DaytonaProvider, DaytonaResourcesError, DaytonaSnapshotActivationError, DaytonaSnapshotConflictError, type DaytonaStreamTimings, EVOLVE_IMAGE_VERSION, type FileInfo, type ProcessInfo, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxCreateOptions, type SandboxFiles, type SandboxInfo, type SandboxInstance, type SandboxListOptions, type SandboxListPage, type SandboxProvider, type SandboxResources, type SandboxRunOptions, type SandboxSpawnOptions, _testActivateSnapshot, _testCollectSandboxStream, _testCreateLogDemuxer, _testCreateSentinelFilter, type _testDaytonaSandboxImpl, _testDaytonaStateToEvolveState, _testFollowManagedSessionLogs, _testImageMap, _testImageRegistryHost, _testIsNetworkPolicyTierRefusal, _testIsSnapshotNameConflict, _testMapNetworkPolicy, _testMapNetworkPolicyForUpdate, _testProviderCanRebuildSnapshot, _testReadCommandStreams, _testSettledStreams, _testStripEndOfOutputSentinel, _testToSandboxInfo, _testWaitForSnapshotConflictWinner, _testWithEndOfOutputSentinel, _testWithInBoxTimeout, _testWrapCommand, createDaytonaProvider, createSandboxObserved, daytonaBootPhaseOf, mapNetworkPolicy };
1459
+ export { DAYTONA_AUTO_DELETE_GRACE_MINUTES, DAYTONA_BOOT_LABEL, DAYTONA_BOOT_POLL_MS, DAYTONA_LIST_PAGE_SIZE, DAYTONA_MAX_DOMAIN_ALLOWLIST, DAYTONA_MAX_LIST_SCAN, DAYTONA_MAX_NETWORK_ALLOWLIST, DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS, DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS, DAYTONA_SNAPSHOT_GONE, DAYTONA_STREAM_TIMINGS, DaytonaBootAbortedError, type DaytonaBootClient, DaytonaBootCommandError, type DaytonaBootPhase, type DaytonaBootProgress, type DaytonaCommandRunner, DaytonaCommands, type DaytonaConfig, DaytonaFiles, DaytonaGpuTypeError, DaytonaIdleTimeoutError, DaytonaImagePullError, DaytonaNetworkPolicyError, type DaytonaNetworkPolicyReason, type DaytonaObservedCreateOptions, DaytonaProvider, DaytonaResourcesError, DaytonaSnapshotActivationError, DaytonaSnapshotConflictError, type DaytonaStreamTimings, EVOLVE_IMAGE_VERSION, type FileInfo, type FileRange, type FilesystemEvent, type ProcessInfo, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxCreateOptions, SandboxFeatureUnsupportedError, type SandboxFiles, type SandboxInfo, type SandboxInspectOptions, type SandboxInstance, type SandboxListOptions, type SandboxListPage, type SandboxMetrics, SandboxNotRunningError, SandboxPathNotFoundError, type SandboxProvider, type SandboxResources, type SandboxRunOptions, type SandboxSpawnOptions, type WatchHandle, type WatchOptions, _testActivateSnapshot, _testCollectSandboxStream, _testCreateLogDemuxer, _testCreateSentinelFilter, type _testDaytonaSandboxImpl, _testDaytonaSandboxImplCtor, _testDaytonaStateToEvolveState, _testFollowManagedSessionLogs, _testImageMap, _testImageRegistryHost, _testIsNetworkPolicyTierRefusal, _testIsSnapshotNameConflict, _testMapNetworkPolicy, _testMapNetworkPolicyForUpdate, _testProviderCanRebuildSnapshot, _testReadCommandStreams, _testSettledStreams, _testStripEndOfOutputSentinel, _testToSandboxInfo, _testWaitForSnapshotConflictWinner, _testWithEndOfOutputSentinel, _testWithInBoxTimeout, _testWrapCommand, createDaytonaProvider, createSandboxObserved, daytonaBootPhaseOf, isSandboxFeatureUnsupportedError, isSandboxNotRunningError, isSandboxPathNotFoundError, mapNetworkPolicy };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,32 @@
1
1
  import { CreateSandboxFromImageParams, CreateSandboxFromSnapshotParams, Sandbox, ListSandboxesQuery } from '@daytonaio/sdk';
2
2
 
3
+ /** A capability this provider lacks: `feature` in dotted form (`files.watchDir`), `provider` type, optional `reason`. */
4
+ declare class SandboxFeatureUnsupportedError extends Error {
5
+ readonly feature: string;
6
+ readonly provider: string;
7
+ readonly reason?: string;
8
+ constructor(feature: string, provider: string, reason?: string);
9
+ }
10
+ /** A path the sandbox does not have — never an empty success. */
11
+ declare class SandboxPathNotFoundError extends Error {
12
+ readonly path: string;
13
+ readonly provider: string;
14
+ constructor(path: string, provider: string);
15
+ }
16
+ /** An inspect refused because the sandbox is not running; `state` is the provider's own word (`paused`, `exited with code 137`). */
17
+ declare class SandboxNotRunningError extends Error {
18
+ readonly sandboxId: string;
19
+ readonly provider: string;
20
+ readonly state: string;
21
+ constructor(sandboxId: string, provider: string, state: string);
22
+ }
23
+ /** True for a SandboxFeatureUnsupportedError from ANY package's copy. */
24
+ declare function isSandboxFeatureUnsupportedError(err: unknown): err is SandboxFeatureUnsupportedError;
25
+ /** True for a SandboxPathNotFoundError from ANY package's copy. */
26
+ declare function isSandboxPathNotFoundError(err: unknown): err is SandboxPathNotFoundError;
27
+ /** True for a SandboxNotRunningError from ANY package's copy. */
28
+ declare function isSandboxNotRunningError(err: unknown): err is SandboxNotRunningError;
29
+
3
30
  /**
4
31
  * GENERATED — DO NOT EDIT. `npm run generate:image-version` (repo root)
5
32
  * rewrites this file from the evolve-all image build inputs under
@@ -791,11 +818,49 @@ interface SandboxInfo {
791
818
  /** End time (undefined for running sandboxes; Daytona never exposes one) */
792
819
  endAt?: string;
793
820
  }
794
- /** File or directory entry info */
821
+ /** The SDK contract's FileInfo (sdk-ts types.ts), the same entry on every provider. */
795
822
  interface FileInfo {
796
823
  name: string;
797
824
  path: string;
798
- type: "file" | "dir";
825
+ type: "file" | "dir" | "symlink" | "other";
826
+ size: number;
827
+ mtime: string;
828
+ mode: string;
829
+ owner: string;
830
+ group: string;
831
+ target?: string;
832
+ }
833
+ /** A byte range of a file (the SDK contract's FileRange). */
834
+ interface FileRange {
835
+ offset: number;
836
+ length: number;
837
+ }
838
+ /** One filesystem change from watchDir: an absolute path, four kinds. */
839
+ interface FilesystemEvent {
840
+ path: string;
841
+ type: "create" | "write" | "remove" | "rename";
842
+ }
843
+ /** Handle to stop watching a directory */
844
+ interface WatchHandle {
845
+ stop(): Promise<void>;
846
+ }
847
+ /** Options for watching a directory */
848
+ interface WatchOptions {
849
+ /** Also report changes in every subdirectory. Default false. */
850
+ recursive?: boolean;
851
+ }
852
+ /** One resource-usage sample (the SDK contract's SandboxMetrics). */
853
+ interface SandboxMetrics {
854
+ cpuPct: number;
855
+ memUsedMb: number;
856
+ memTotalMb: number;
857
+ diskUsedMb?: number;
858
+ sampledAt: string;
859
+ source: string;
860
+ }
861
+ /** Options for an inspect-only attach (the SDK contract's SandboxInspectOptions). */
862
+ interface SandboxInspectOptions {
863
+ user?: string;
799
864
  }
800
865
  /** Options for blocking sandbox command execution */
801
866
  interface SandboxRunOptions {
@@ -959,6 +1024,12 @@ interface SandboxFiles {
959
1024
  list(path: string): Promise<FileInfo[]>;
960
1025
  remove(path: string): Promise<void>;
961
1026
  rename(oldPath: string, newPath: string): Promise<void>;
1027
+ /** The entry at `path` itself; a symlink is never followed */
1028
+ stat(path: string): Promise<FileInfo>;
1029
+ /** Exactly the requested bytes, without moving the whole file when the range is small */
1030
+ readRange(path: string, range: FileRange): Promise<Uint8Array>;
1031
+ /** Always a typed refusal here: the Daytona SDK has no filesystem watcher */
1032
+ watchDir(path: string, onEvent: (event: FilesystemEvent) => void | Promise<void>, options?: WatchOptions): Promise<WatchHandle>;
962
1033
  }
963
1034
  /** Sandbox instance */
964
1035
  interface SandboxInstance {
@@ -968,6 +1039,8 @@ interface SandboxInstance {
968
1039
  getHost(port: number): Promise<string>;
969
1040
  isRunning(): Promise<boolean>;
970
1041
  getInfo(): Promise<SandboxInfo>;
1042
+ /** The newest resource-usage sample the daemon has */
1043
+ metrics(): Promise<SandboxMetrics | null>;
971
1044
  kill(): Promise<void>;
972
1045
  pause(): Promise<void>;
973
1046
  /** Replace the outbound network policy of the running sandbox. */
@@ -979,6 +1052,8 @@ interface SandboxProvider {
979
1052
  readonly name?: string;
980
1053
  create(options: SandboxCreateOptions): Promise<SandboxInstance>;
981
1054
  connect(sandboxId: string, timeoutMs?: number): Promise<SandboxInstance>;
1055
+ /** Attach to a STARTED sandbox for reads; never starts a stopped one */
1056
+ inspect(sandboxId: string, options?: SandboxInspectOptions): Promise<SandboxInstance>;
982
1057
  /** List sandboxes, paginating to exhaustion. `limit` bounds items returned. */
983
1058
  list(options?: SandboxListOptions): Promise<SandboxInfo[]>;
984
1059
  /** The same enumeration for fleet bookkeeping: never throws, reports completeness. */
@@ -1128,9 +1203,12 @@ declare class DaytonaCommands implements SandboxCommands {
1128
1203
  list(): Promise<ProcessInfo[]>;
1129
1204
  kill(processId: string): Promise<boolean>;
1130
1205
  }
1206
+ /** One blocking, whole-output run — what the file observation needs; a test passes a double. */
1207
+ type DaytonaCommandRunner = Pick<DaytonaCommands, "run">;
1131
1208
  declare class DaytonaFiles implements SandboxFiles {
1132
1209
  private sandbox;
1133
- constructor(sandbox: Sandbox);
1210
+ private commands;
1211
+ constructor(sandbox: Sandbox, commands: DaytonaCommandRunner);
1134
1212
  read(path: string): Promise<string | Uint8Array>;
1135
1213
  write(path: string, content: string | Buffer | ArrayBuffer | Uint8Array): Promise<void>;
1136
1214
  writeBatch(files: Array<{
@@ -1147,6 +1225,10 @@ declare class DaytonaFiles implements SandboxFiles {
1147
1225
  makeDir(path: string): Promise<void>;
1148
1226
  exists(path: string): Promise<boolean>;
1149
1227
  list(path: string): Promise<FileInfo[]>;
1228
+ stat(path: string): Promise<FileInfo>;
1229
+ private findListing;
1230
+ readRange(path: string, range: FileRange): Promise<Uint8Array>;
1231
+ watchDir(_path: string, _onEvent: (event: FilesystemEvent) => void | Promise<void>, _options?: WatchOptions): Promise<WatchHandle>;
1150
1232
  remove(path: string): Promise<void>;
1151
1233
  rename(oldPath: string, newPath: string): Promise<void>;
1152
1234
  }
@@ -1159,6 +1241,7 @@ declare class DaytonaSandboxImpl implements SandboxInstance {
1159
1241
  getHost(port: number): Promise<string>;
1160
1242
  isRunning(): Promise<boolean>;
1161
1243
  getInfo(): Promise<SandboxInfo>;
1244
+ metrics(): Promise<SandboxMetrics | null>;
1162
1245
  /**
1163
1246
  * Replace the running sandbox's outbound policy — Daytona's
1164
1247
  * `sandbox.updateNetworkSettings`, which "maps to the same mechanism as
@@ -1261,6 +1344,9 @@ declare class DaytonaProvider implements SandboxProvider {
1261
1344
  */
1262
1345
  private joinInFlightSnapshotBuild;
1263
1346
  connect(sandboxId: string, _timeoutMs?: number): Promise<SandboxInstance>;
1347
+ inspect(sandboxId: string, options?: SandboxInspectOptions): Promise<SandboxInstance>;
1348
+ /** A GET; seam for the unit test. */
1349
+ protected getSandboxRecord(sandboxId: string): Promise<Sandbox>;
1264
1350
  /**
1265
1351
  * List sandboxes, walking the cursor stream to exhaustion.
1266
1352
  *
@@ -1367,5 +1453,7 @@ declare const _testReadCommandStreams: typeof readCommandStreams;
1367
1453
  * the type (never the constructor) gives the seam the real methods to pin.
1368
1454
  */
1369
1455
  type _testDaytonaSandboxImpl = DaytonaSandboxImpl;
1456
+ /** The constructor, for the metrics unit test (a vendor sandbox double goes in). */
1457
+ declare const _testDaytonaSandboxImplCtor: typeof DaytonaSandboxImpl;
1370
1458
 
1371
- export { DAYTONA_AUTO_DELETE_GRACE_MINUTES, DAYTONA_BOOT_LABEL, DAYTONA_BOOT_POLL_MS, DAYTONA_LIST_PAGE_SIZE, DAYTONA_MAX_DOMAIN_ALLOWLIST, DAYTONA_MAX_LIST_SCAN, DAYTONA_MAX_NETWORK_ALLOWLIST, DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS, DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS, DAYTONA_SNAPSHOT_GONE, DAYTONA_STREAM_TIMINGS, DaytonaBootAbortedError, type DaytonaBootClient, DaytonaBootCommandError, type DaytonaBootPhase, type DaytonaBootProgress, DaytonaCommands, type DaytonaConfig, DaytonaFiles, DaytonaGpuTypeError, DaytonaIdleTimeoutError, DaytonaImagePullError, DaytonaNetworkPolicyError, type DaytonaNetworkPolicyReason, type DaytonaObservedCreateOptions, DaytonaProvider, DaytonaResourcesError, DaytonaSnapshotActivationError, DaytonaSnapshotConflictError, type DaytonaStreamTimings, EVOLVE_IMAGE_VERSION, type FileInfo, type ProcessInfo, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxCreateOptions, type SandboxFiles, type SandboxInfo, type SandboxInstance, type SandboxListOptions, type SandboxListPage, type SandboxProvider, type SandboxResources, type SandboxRunOptions, type SandboxSpawnOptions, _testActivateSnapshot, _testCollectSandboxStream, _testCreateLogDemuxer, _testCreateSentinelFilter, type _testDaytonaSandboxImpl, _testDaytonaStateToEvolveState, _testFollowManagedSessionLogs, _testImageMap, _testImageRegistryHost, _testIsNetworkPolicyTierRefusal, _testIsSnapshotNameConflict, _testMapNetworkPolicy, _testMapNetworkPolicyForUpdate, _testProviderCanRebuildSnapshot, _testReadCommandStreams, _testSettledStreams, _testStripEndOfOutputSentinel, _testToSandboxInfo, _testWaitForSnapshotConflictWinner, _testWithEndOfOutputSentinel, _testWithInBoxTimeout, _testWrapCommand, createDaytonaProvider, createSandboxObserved, daytonaBootPhaseOf, mapNetworkPolicy };
1459
+ export { DAYTONA_AUTO_DELETE_GRACE_MINUTES, DAYTONA_BOOT_LABEL, DAYTONA_BOOT_POLL_MS, DAYTONA_LIST_PAGE_SIZE, DAYTONA_MAX_DOMAIN_ALLOWLIST, DAYTONA_MAX_LIST_SCAN, DAYTONA_MAX_NETWORK_ALLOWLIST, DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS, DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS, DAYTONA_SNAPSHOT_GONE, DAYTONA_STREAM_TIMINGS, DaytonaBootAbortedError, type DaytonaBootClient, DaytonaBootCommandError, type DaytonaBootPhase, type DaytonaBootProgress, type DaytonaCommandRunner, DaytonaCommands, type DaytonaConfig, DaytonaFiles, DaytonaGpuTypeError, DaytonaIdleTimeoutError, DaytonaImagePullError, DaytonaNetworkPolicyError, type DaytonaNetworkPolicyReason, type DaytonaObservedCreateOptions, DaytonaProvider, DaytonaResourcesError, DaytonaSnapshotActivationError, DaytonaSnapshotConflictError, type DaytonaStreamTimings, EVOLVE_IMAGE_VERSION, type FileInfo, type FileRange, type FilesystemEvent, type ProcessInfo, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxCreateOptions, SandboxFeatureUnsupportedError, type SandboxFiles, type SandboxInfo, type SandboxInspectOptions, type SandboxInstance, type SandboxListOptions, type SandboxListPage, type SandboxMetrics, SandboxNotRunningError, SandboxPathNotFoundError, type SandboxProvider, type SandboxResources, type SandboxRunOptions, type SandboxSpawnOptions, type WatchHandle, type WatchOptions, _testActivateSnapshot, _testCollectSandboxStream, _testCreateLogDemuxer, _testCreateSentinelFilter, type _testDaytonaSandboxImpl, _testDaytonaSandboxImplCtor, _testDaytonaStateToEvolveState, _testFollowManagedSessionLogs, _testImageMap, _testImageRegistryHost, _testIsNetworkPolicyTierRefusal, _testIsSnapshotNameConflict, _testMapNetworkPolicy, _testMapNetworkPolicyForUpdate, _testProviderCanRebuildSnapshot, _testReadCommandStreams, _testSettledStreams, _testStripEndOfOutputSentinel, _testToSandboxInfo, _testWaitForSnapshotConflictWinner, _testWithEndOfOutputSentinel, _testWithInBoxTimeout, _testWrapCommand, createDaytonaProvider, createSandboxObserved, daytonaBootPhaseOf, isSandboxFeatureUnsupportedError, isSandboxNotRunningError, isSandboxPathNotFoundError, mapNetworkPolicy };
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import {STDOUT_PREFIX_BYTES,STDERR_PREFIX_BYTES,MAX_PREFIX_LEN,Daytona,Image}from'@daytonaio/sdk';import {randomUUID}from'crypto';var I="c-4bfce70a407f";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=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}
1
+ import {STDOUT_PREFIX_BYTES,STDERR_PREFIX_BYTES,MAX_PREFIX_LEN,Daytona,Image}from'@daytonaio/sdk';import {randomUUID}from'crypto';import'fs';var E=class extends Error{feature;provider;reason;constructor(t,e,s){super(`${e} does not support ${t}${s?`: ${s}`:""}`),this.name="SandboxFeatureUnsupportedError",this.feature=t,this.provider=e,this.reason=s;}},A=class extends Error{path;provider;constructor(t,e){super(`${e}: no such file or directory: ${t}`),this.name="SandboxPathNotFoundError",this.path=t,this.provider=e;}},_=class extends Error{sandboxId;provider;state;constructor(t,e,s){super(`${e} sandbox ${t} is not running (${s}); inspect never starts or resumes a sandbox`),this.name="SandboxNotRunningError",this.sandboxId=t,this.provider=e,this.state=s;}};function L(n,t){return !!n&&typeof n=="object"&&n.name===t}function Xt(n){return L(n,"SandboxFeatureUnsupportedError")}function Vt(n){return L(n,"SandboxPathNotFoundError")}function qt(n){return L(n,"SandboxNotRunningError")}var M=2,N=20;function R(n){return `'${n.replace(/'/g,"'\\''")}'`}function U(n){if(!Number.isInteger(n.offset)||n.offset<0)throw new RangeError(`offset must be a non-negative integer, got ${n.offset}`);if(!Number.isInteger(n.length)||n.length<0)throw new RangeError(`length must be a non-negative integer, got ${n.length}`)}function ct(n){if(typeof n=="number")return lt((n&4095).toString(8));if(/^[0-7]{1,4}$/.test(n))return lt(n);throw new RangeError(`not an octal mode: ${n}`)}function lt(n){return n.padStart(4,"0")}function F(n){let t=n instanceof Date?n:typeof n=="number"?new Date(n*1e3):new Date(n);if(Number.isNaN(t.getTime()))throw new RangeError(`not a timestamp: ${String(n)}`);return t.toISOString()}function ut(n,t){return n.endsWith("/")?`${n}${t}`:`${n}/${t}`}async function ft(n,t,e){if(U(t),t.length===0)return new Uint8Array(0);let s=t.offset+t.length-1,o=await fetch(n,{headers:{Range:`bytes=${t.offset}-${s}`},signal:AbortSignal.timeout(e.timeoutMs)});if(o.status===206){let r=new Uint8Array(await o.arrayBuffer());return r.length>t.length?r.subarray(0,t.length):r}if(o.status===200)return Qt(o,t);if(o.status===416)return await o.body?.cancel().catch(()=>{}),new Uint8Array(0);throw await o.body?.cancel().catch(()=>{}),o.status===404?new A(e.path,e.provider):new Error(`${e.provider}: range read of ${e.path} failed (HTTP ${o.status})`)}async function Qt(n,t){if(!n.body)return new Uint8Array(0);let e=n.body.getReader(),s=[],o=0,r=0,a=t.offset+t.length;try{for(;;){let{done:u,value:m}=await e.read();if(u)break;let c=o;if(o+=m.length,o>t.offset){let f=Math.max(0,t.offset-c),l=Math.min(m.length,a-c);l>f&&(s.push(m.subarray(f,l)),r+=l-f);}if(o>=a)break}}finally{await e.cancel().catch(()=>{});}let i=new Uint8Array(r),d=0;for(let u of s)i.set(u,d),d+=u.length;return i}var O="c-4bfce70a407f";var ot={[`evolve-all-${O}`]:`evolvingmachines/evolve-all:${O}`,"evolve-all":"evolvingmachines/evolve-all"},ee=10,pt=10,ht=20,ne=18e4,se=2e3,$t=6e5,It=5e3,oe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},S=n=>new Promise(t=>setTimeout(t,Math.max(0,n))),re=100,B=1e4;function ae(n){let t=n.lastIndexOf("/");return t>0?n.substring(0,t):"/"}function ie(n){let t=n.lastIndexOf("/");return t>=0?n.substring(t+1):n}var b=class extends Error{reason;destination;constructor(t,e,s){super(e),this.name="DaytonaNetworkPolicyError",this.reason=t,this.destination=s;}},W=class extends Error{image;constructor(t,e){let s=e instanceof Error?e.message:String(e??"unknown error");super(`Failed to pull image "${t}" on Daytona: ${s}. 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;}},wt=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;}},k=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;}},H=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";}},j=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";}},de=new Set(["pending_build","building_snapshot","pulling_snapshot"]);function yt(n){return n!=null&&de.has(n)?"image_pull":"boot"}var z=class extends Error{phase;state;sandboxId;constructor(t,e,s){super(`Daytona sandbox boot abandoned during ${t} (provider state ${e??"not yet reported"}, sandbox ${s??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=t,this.state=e,this.sandboxId=s;}},bt="evolve_boot",le=5e3,xt=30;async function Ce(n,t,e={}){let s=randomUUID(),o=e.pollMs??le,r=null,a=null,i=false,d=(l,g)=>{let p=l==="build_log"?"image_pull":yt(a);e.onProgress?.({signal:l,phase:p,state:a,sandboxId:r?.id??null,...g===void 0?{}:{line:g}});},u=n.create({...t,labels:{...t.labels??{},[bt]:s}},{timeout:0,onSnapshotCreateLogs:l=>{for(let g of l.split(`
2
+ `)){let p=g.trimEnd();p.length>0&&d("build_log",p);}}});(async()=>{for(;!i;){try{if(r===null)for await(let g of n.list({labels:{[bt]:s}})){r=g;break}else await r.refreshData();let l=r?.state??null;l!==a&&(a=l,d("state"));}catch{}i||await S(o);}})();let c=()=>{let l=new z(yt(a),a,r?.id??null);return u.then(g=>g.delete(xt).catch(()=>{}),()=>{}),r!==null&&r.delete(xt).catch(()=>{}),l},f=new Promise((l,g)=>{let p=e.signal;if(p){if(p.aborted){g(c());return}p.addEventListener("abort",()=>{i||g(c());},{once:true});}});try{return await Promise.race([u,f])}finally{i=true;}}var v=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 K(n,t,e,s){let o=s?.timeoutMs??ne,r=s?.pollMs??se;console.log(`[daytona] Snapshot "${t}" is inactive (unused for 2+ weeks) \u2014 reactivating...`);let a;try{a=await n.snapshot.activate(e);}catch(d){throw new v(t,`the activate call failed (${d instanceof Error?d.message:String(d)})`)}let i=Date.now()+o;for(;a?.state!=="active";){if(a?.state==="error"||a?.state==="build_failed")throw new v(t,`it entered state "${a.state}"`);if(Date.now()>=i)throw new v(t,`still "${a?.state??"unknown"}" after ${o}ms`);await S(r);try{a=await n.snapshot.get(t);}catch(d){throw new v(t,`the activation poll failed (${d instanceof Error?d.message:String(d)})`)}}return console.log(`[daytona] Snapshot "${t}" reactivated.`),a}var T=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;}},Et=Symbol("daytona-snapshot-gone"),kt=new Set(["pending","pulling","building","snapshotting"]),ce=3;function rt(n){let t=n;return t?.status??t?.statusCode??t?.response?.status}var St=new Set(["error","build_failed"]),ue=new Set(["latest","lts","stable"]);function X(n){let t=ot[n]??n;if(t.includes("@"))return /@[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[0-9a-f]{32,}$/i.test(t);let e=t.substring(t.lastIndexOf("/")+1),s=e.lastIndexOf(":");if(s<0)return false;let o=e.substring(s+1);return o===""?false:!ue.has(o.toLowerCase())}function V(n){let t=n.toLowerCase();return t.includes("not found")||t.includes("404")||t.includes("does not exist")}var _t=6e4,Mt=2e3;async function vt(n,t,e,s){let o=e.errorReason?`: ${e.errorReason}`:"";console.warn(`[daytona] Deleting dead snapshot "${t}" (state "${e.state??"unknown"}"${o}) before rebuilding it.`);try{await n.snapshot.delete(e);}catch(d){let u=d instanceof Error?d.message:String(d);if(!V(u))return console.warn(`[daytona] Could not delete dead snapshot "${t}" (${u}) \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 r=s?.timeoutMs??_t,a=s?.pollMs??Mt,i=Date.now()+r;for(;;){try{await n.snapshot.get(t);}catch(d){if(V(d instanceof Error?d.message:String(d)))return true}if(Date.now()>=i)return console.warn(`[daytona] Dead snapshot "${t}" still resolves ${r}ms after it was deleted \u2014 leaving the rebuild to the next run rather than racing the removal.`),false;await S(a);}}function Ot(n){if(rt(n)===409)return true;let t=(n instanceof Error?n.message:String(n)).toLowerCase();return t.includes("already exists")||t.includes("conflict")}function fe(n){let t=rt(n);if(t===401||t===403)return true;let e=(n instanceof Error?n.message:String(n)).toLowerCase();return e.includes("unauthorized")||e.includes("forbidden")||e.includes("status code 401")||e.includes("status code 403")}async function Ct(n,t,e){let s=e?.timeoutMs??$t,o=e?.pollMs??It;console.log(`[daytona] Snapshot "${t}" is already being created by another process \u2014 waiting for it (up to ${Math.round(s/1e3)}s) instead of pulling the image directly...`);let r=Date.now()+s,a,i="",d=0;for(;;){try{a=await n.snapshot.get(t),i="",d=0;}catch(u){a=void 0;let m=u instanceof Error?u.message:String(u);if(V(m))return console.log(`[daytona] Snapshot "${t}" no longer exists \u2014 the name is clear, building it.`),Et;if(fe(u))throw new T(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>=ce)throw new T(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&&!kt.has(a.state??""))return a;if(Date.now()>=r)throw new T(t,`it was still "${a?.state??"unknown"}" after ${s}ms \u2014 retry once that build finishes, or check the snapshot in the Daytona dashboard (Snapshots page)`);await S(o);}}function q(n,t){if(!t||t<=0)return n;let e=Buffer.from(n).toString("base64"),s=`/tmp/.evolve-cmd-${Date.now()}-${Math.random().toString(36).slice(2,8)}.sh`;return `sh -c '${`echo ${e} | base64 -d > ${s} && [ -s ${s} ] || { rm -f ${s}; exit 126; }; if command -v timeout >/dev/null 2>&1; then timeout -k 10 ${t} bash ${s}; else bash ${s}; fi; rc=$?; rm -f ${s}; exit $rc`}'`}function At(){return `EVOLVE-EOS-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Q(n,t){return n.trim()?`exec 9>&1 && { :
3
+ ${n}
4
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 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,STDOUT_PREFIX_BYTES,0),f=lt(r,STDERR_PREFIX_BYTES,0),m=-1,c="stdout",g=0;if(d!==-1&&(f===-1||d<f)?(m=d,c="stdout",g=STDOUT_PREFIX_BYTES.length):f!==-1&&(m=f,c="stderr",g=STDERR_PREFIX_BYTES.length),m===-1){let l=Math.max(0,r.length-(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 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: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
- export{Lt as DAYTONA_AUTO_DELETE_GRACE_MINUTES,ot as DAYTONA_BOOT_LABEL,Wt as DAYTONA_BOOT_POLL_MS,Ut as DAYTONA_LIST_PAGE_SIZE,et as DAYTONA_MAX_DOMAIN_ALLOWLIST,C as DAYTONA_MAX_LIST_SCAN,tt as DAYTONA_MAX_NETWORK_ALLOWLIST,Nt as DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS,ut as DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS,gt as DAYTONA_SNAPSHOT_GONE,Rt as DAYTONA_STREAM_TIMINGS,L as DaytonaBootAbortedError,O as DaytonaBootCommandError,j as DaytonaCommands,H as DaytonaFiles,nt as DaytonaGpuTypeError,E as DaytonaIdleTimeoutError,M as DaytonaImagePullError,b as DaytonaNetworkPolicyError,K as DaytonaProvider,T as DaytonaResourcesError,A as DaytonaSnapshotActivationError,D as DaytonaSnapshotConflictError,I as EVOLVE_IMAGE_VERSION,pe as _testActivateSnapshot,re as _testCollectSandboxStream,De as _testCreateLogDemuxer,ve as _testCreateSentinelFilter,me as _testDaytonaStateToEvolveState,Pe as _testFollowManagedSessionLogs,ye as _testImageMap,fe as _testImageRegistryHost,ue as _testIsNetworkPolicyTierRefusal,we as _testIsSnapshotNameConflict,le as _testMapNetworkPolicy,ce as _testMapNetworkPolicyForUpdate,be as _testProviderCanRebuildSnapshot,ke as _testReadCommandStreams,Ae as _testSettledStreams,Se as _testStripEndOfOutputSentinel,ge as _testToSandboxInfo,he as _testWaitForSnapshotConflictWinner,xe as _testWithEndOfOutputSentinel,de as _testWithInBoxTimeout,ie as _testWrapCommand,ae as createDaytonaProvider,oe as createSandboxObserved,st as daytonaBootPhaseOf,$ as mapNetworkPolicy};
5
+ }; __evolve_eos=$?; printf '%s' '${t}' 2>/dev/null >&9; exec 9>&-; (exit $__evolve_eos)`:n}function Lt(n,t){return n.endsWith(`${t}
6
+ `)?n.slice(0,-(t.length+1)):n.endsWith(t)?n.slice(0,-t.length):n}function P(n,t){let e=Ht(n);return {stdout:Lt(e.stdout,t),stderr:e.stderr}}function J(n,t){let e=`${n}
7
+ `,s="",o=r=>{for(let a=Math.min(r.length,e.length);a>0;a--)if(e.startsWith(r.slice(r.length-a)))return a;return 0};return {push(r){s+=r;let a=o(s);a!==s.length&&(t(s.slice(0,s.length-a)),s=s.slice(s.length-a));},flush(){let r=s===e||s===n?"":s;s="",r&&t(r);}}}function Z(n,t,e,s){let o=n;return t&&(o=`cd '${t.replace(/'/g,"'\\''")}' && ${o}`),e&&Object.keys(e).length>0&&(o=`${Object.entries(e).filter(([,a])=>a!=null).map(([a,i])=>`export ${a}='${String(i).replace(/'/g,"'\\''")}'`).join("; ")}; ${o}`),s==="root"&&(o=`echo ${Buffer.from(o).toString("base64")} | base64 -d | sudo -n bash`),o}function Nt(n){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(n);return !(!t||[t[1],t[2],t[3],t[4]].some(e=>Number(e)>255)||t[5]!==void 0&&Number(t[5])>32)}function me(n){return /^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(n)&&!Nt(n)}function ge(n){return n.startsWith("[")?true:(n.match(/:/g)?.length??0)>=2}function pe(n){return /^[^:]+:\d+$/.test(n)}function he(n){return n.startsWith("*.")&&n.length>2&&!n.slice(2).includes("*")}function C(n){if(!n||n.outbound==="open"){if(n?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return n?{networkBlockAll:false}:{}}let t=n.allowedDestinations??[];if(t.length===0)return {networkBlockAll:true};for(let r of t){if(r.trim()==="")throw new b("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(r)}). 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).`,r);if(r.includes(","))throw new b("invalid-destination",`network.allowedDestinations entry "${r}" 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.`,r)}let e=[],s=[];for(let r of t)if(Nt(r))e.push(r.includes("/")?r:`${r}/32`);else {if(me(r))throw new b("invalid-ipv4",`"${r}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,r);if(ge(r))throw new b("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${r}".`,r);if(pe(r))throw new b("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${r}" and list just the host or IP.`,r);if(r.includes("*")&&!he(r))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 "${r}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,r);s.push(r);}if(e.length>0&&s.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: ${s.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(s.length>0){let r=[...new Set(s)];if(r.length>ht)throw new b("allowlist-too-large",`Daytona allows at most ${ht} entries in its domain allowlist; this policy names ${r.length} domains (${r.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return {networkBlockAll:false,domainAllowList:r.join(",")}}let o=[...new Set(e)];if(o.length>pt)throw new b("allowlist-too-large",`Daytona allows at most ${pt} entries in its network allowlist; this policy resolved to ${o.length} CIDRs (${o.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return {networkBlockAll:false,networkAllowList:o.join(",")}}function Rt(n){let t=C(n);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:false,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===true,networkAllowList:"",domainAllowList:""}}function Ut(n){let t=rt(n),e=(n instanceof Error?n.message:String(n)).toLowerCase(),s=e.includes("network policy")||e.includes("network settings")||e.includes("network configuration"),o=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)&&(o||s)?true:s&&o}function Ft(n){let t=n.indexOf("/");if(t<0)return;let e=n.substring(0,t);return e.includes(".")||e.includes(":")||e==="localhost"?e:void 0}function at(n){return {sandboxId:n.id,image:n.snapshot??"",name:n.name,metadata:n.labels??{},startedAt:n.createdAt??""}}function Bt(n){if(n==="started")return "running";if(n==="stopped"||n==="archived"||n==="paused")return "paused"}function Yt(n,t){if(!n||typeof n!="object")return;let e=n;if(typeof e.toolboxProxyUrl=="string"&&(e.toolboxProxyUrl=t),Array.isArray(e.items))for(let s of e.items)Yt(s,t);}function we(n,t){return new Proxy(n,{get(e,s,o){if(s==="getToolboxProxyUrl")return async()=>({data:{url:t}});let r=Reflect.get(e,s,o);return typeof r!="function"?r:function(...a){let i=r.apply(e,a);return i instanceof Promise?i.then(d=>(Yt(d?.data,t),d)):i}}})}var tt=class extends Daytona{constructor(t,e){super(t);let s=this;s.sandboxApi=we(s.sandboxApi,e);}};function ye(n,t){let e=new Uint8Array(new ArrayBuffer(n.length+t.length));return e.set(n,0),e.set(t,n.length),e}function Dt(n,t,e){t:for(let s=e;s+t.length<=n.length;s++){for(let o=0;o<t.length;o++)if(n[s+o]!==t[o])continue t;return s}return -1}function Gt(n,t){let e=new TextDecoder("utf-8"),s=new TextDecoder("utf-8"),o=new Uint8Array(0),r="stdout",a=i=>{i.length!==0&&(r==="stdout"?n(e.decode(i,{stream:true})):t(s.decode(i,{stream:true})));};return {push(i){for(o=ye(o,i);;){let d=Dt(o,STDOUT_PREFIX_BYTES,0),u=Dt(o,STDERR_PREFIX_BYTES,0),m=-1,c="stdout",f=0;if(d!==-1&&(u===-1||d<u)?(m=d,c="stdout",f=STDOUT_PREFIX_BYTES.length):u!==-1&&(m=u,c="stderr",f=STDERR_PREFIX_BYTES.length),m===-1){let l=Math.max(0,o.length-(MAX_PREFIX_LEN-1));a(o.subarray(0,l)),o=o.slice(l);return}a(o.subarray(0,m)),r=c,o=o.slice(m+f);}},flush(){a(o),o=new Uint8Array(0);let i=e.decode();i&&n(i);let d=s.decode();d&&t(d);}}}async function Wt(n,t,e,s,o,r,a){let i=`${n.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(e)}/command/${encodeURIComponent(s)}/logs?follow=true`,d=await fetch(i,{headers:{Authorization:`Bearer ${n.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 u=Gt(o,r),m=d.body.getReader();try{for(;;){let{done:c,value:f}=await m.read();if(c)break;f&&u.push(f);}}finally{u.flush(),await m.cancel().catch(()=>{});}}function Ht(n){let t=n.stdout||"",e=n.stderr||"",s=n.output||"";return !t&&!e&&s?{stdout:s,stderr:""}:{stdout:t,stderr:e}}var et=class{constructor(t,e,s){this.sandbox=t;this.user=e;this.managedStream=s;}streamTimings=oe;followLogs(t,e,s,o,r){return this.managedStream?Wt(this.managedStream,this.sandbox.id,t,e,s,o,r):this.sandbox.process.getSessionCommandLogs(t,e,s,o)}async run(t,e){let s=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,o=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(o);try{let r=!!(e?.onStdout||e?.onStderr),a=At(),i=await this.sandbox.process.executeSessionCommand(o,{command:q(Z(Q(t,a),e?.cwd,e?.envs,this.user),s),runAsync:r},s),d=i.cmdId;if(r&&!d)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(r&&d){let c="",f="",l=!0,g=Date.now(),p=J(a,h=>{c+=h,e?.onStdout?.(h);}),w=new AbortController,y=this.followLogs(o,d,h=>{l&&(g=Date.now(),p.push(h));},h=>{l&&(g=Date.now(),f+=h,e?.onStderr?.(h));},w.signal),x=!1,$,zt=y.then(()=>{},h=>{x||($=h);}),it;try{it=await this.awaitStreamedExit(o,d,y,()=>g,e?.timeoutMs);}finally{x=!0,w.abort(),await Promise.race([zt,S(this.streamTimings.drainMs)]),l=!1,$===void 0&&p.flush();}if($!==void 0){let h;try{let Kt=await this.sandbox.process.getSessionCommandLogs(o,d);h=P(Kt,a);}catch{throw $}if(!h.stdout.startsWith(c)||!h.stderr.startsWith(f))throw $;let I=h.stdout.slice(c.length),dt=h.stderr.slice(f.length);c=h.stdout,f=h.stderr,I&&e?.onStdout?.(I),dt&&e?.onStderr?.(dt);}else if(!c&&!f)try{let h=await this.sandbox.process.getSessionCommandLogs(o,d),I=P(h,a);c=I.stdout,f=I.stderr,c&&e?.onStdout?.(c),f&&e?.onStderr?.(f);}catch{}return {exitCode:it,stdout:c,stderr:f}}let{stdout:u,stderr:m}=P(i,a);if(!u&&!m&&d)try{let c=await this.sandbox.process.getSessionCommandLogs(o,d),f=P(c,a);u=f.stdout,m=f.stderr||m;}catch{}return {exitCode:i.exitCode??0,stdout:u,stderr:m}}finally{try{await this.sandbox.process.deleteSession(o);}catch{}}}async awaitStreamedExit(t,e,s,o,r){let a=this.streamTimings,i,d,u=s.then(()=>{i=Date.now();},f=>{i=Date.now(),d=f;}),m=r!==void 0&&r>0?Date.now()+r+a.killGraceMs:void 0,c=a.pollMinMs;for(;;){let f=await this.sandbox.process.getSessionCommand(t,e);if(f.exitCode!==void 0&&f.exitCode!==null){for(;i===void 0;){let p=Date.now()-o();if(p>=a.drainMs)break;await Promise.race([u,S(a.drainMs-p)]);}return f.exitCode}let l=i!==void 0?i+a.settleMs:void 0,g=m!==void 0&&l!==void 0?Math.min(m,l):m??l;if(g!==void 0&&Date.now()>=g)throw d!==void 0?d:new Error(`Daytona reported no exit code for command ${e} after `+(i!==void 0?"its log stream closed":`${r}ms`));await S(c),c=Math.min(c*2,a.pollMaxMs);}}async spawn(t,e){let s=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(s);let o=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,r=Date.now(),a=e?.timeoutMs,i=At(),u=(await this.sandbox.process.executeSessionCommand(s,{command:q(Z(Q(t,i),e?.cwd,e?.envs,this.user),o),runAsync:true},o)).cmdId;if(u&&(e?.onStdout||e?.onStderr)){let c=J(i,e.onStdout||(()=>{}));this.followLogs(s,u,f=>c.push(f),e.onStderr||(()=>{})).catch(()=>{}).finally(()=>c.flush());}let m=this.sandbox;return {processId:s,wait:async()=>{if(!u)return {exitCode:0,stdout:"",stderr:""};for(;;){if(a&&Date.now()-r>=a){try{await m.process.deleteSession(s);}catch{}return {exitCode:124,stdout:"",stderr:"operation timed out"}}try{let c=await m.process.getSessionCommand(s,u);if(c.exitCode!==void 0)try{let f=await m.process.getSessionCommandLogs(s,u);return {exitCode:c.exitCode,...P(f,i)}}catch{return {exitCode:c.exitCode,stdout:"",stderr:""}}}catch(c){let f=c instanceof Error?c.message.toLowerCase():String(c).toLowerCase();if(f.includes("not found")){let l=f.includes("sandbox");try{await m.refreshData(),l=!1;}catch(g){(g instanceof Error?g.message.toLowerCase():String(g).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(s),!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}}},Pt="%y\\0%s\\0%T@\\0%m\\0%u\\0%g\\0%l\\0%f\\0",Y=8,be=1800*1e3;function xe(n,t){let e=R(n),s=t==="children"?`[ -e ${e} ] || exit ${M}; [ -d ${e} ] || exit ${N};`:`[ -e ${e} ] || [ -L ${e} ] || exit ${M};`,o=t==="children"?`find -H ${e} -mindepth 1 -maxdepth 1 -printf '${Pt}'`:`find ${e} -maxdepth 0 -printf '${Pt}'`;return `sh -c ${R(`${s} ( ${o}; printf 'STATUS:%d' "$?" ) | base64`)}`}function Se(n,t,e){let o=Buffer.from(t.replace(/\s+/g,""),"base64").toString("utf-8").split("\0"),r=o.pop()??"",a=/^STATUS:(\d+)$/.exec(r);if(!a)throw new Error(`daytona: the listing of ${n} ended without find's status (${r.slice(0,40)})`);if(a[1]!=="0")throw new Error(`daytona: find exited ${a[1]} listing ${n}`);let i=[];for(let d=0;d+Y<=o.length;d+=Y){let[u,m,c,f,l,g,p,w]=o.slice(d,d+Y),y=u==="f"?"file":u==="d"?"dir":u==="l"?"symlink":"other",x={name:w,path:e==="children"?ut(n,w):n,type:y,size:Number(m),mtime:F(Number(c)),mode:ct(f),owner:l,group:g};y==="symlink"&&(x.target=p),i.push(x);}return i}var nt=class{constructor(t,e){this.sandbox=t;this.commands=e;}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 s;if(typeof e=="string")s=Buffer.from(e,"utf-8");else if(Buffer.isBuffer(e))s=e;else if(e instanceof ArrayBuffer)s=Buffer.from(e);else if(e instanceof Uint8Array)s=Buffer.from(e);else throw new Error(`Unsupported content type: ${typeof e}`);await this.sandbox.fs.uploadFile(s,t);}async writeBatch(t){let e=t.map(s=>{let o;if(typeof s.data=="string")o=Buffer.from(s.data,"utf-8");else if(Buffer.isBuffer(s.data))o=s.data;else if(s.data instanceof ArrayBuffer)o=Buffer.from(s.data);else if(s.data instanceof Uint8Array)o=Buffer.from(s.data);else throw new Error(`Unsupported content type: ${typeof s.data}`);return {source:o,destination:s.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=ae(t),s=ie(t);return (await this.sandbox.fs.listFiles(e)).some(r=>r.name===s)}catch{return false}}async list(t){return this.findListing(t,"children")}async stat(t){let[e]=await this.findListing(t,"self");if(!e)throw new A(t,"daytona");return e}async findListing(t,e){let s=await this.commands.run(xe(t,e));if(s.exitCode===M)throw new A(t,"daytona");if(s.exitCode===N)throw new Error(`daytona: ${t} is not a directory`);if(s.exitCode!==0)throw new Error(`daytona: listing ${t} failed (exit ${s.exitCode}): ${s.stderr.trim()}`);try{return Se(t,s.stdout,e)}catch(o){throw /printf|unrecognized|invalid option/i.test(s.stderr)?new E("files.list","daytona",`this image's find has no -printf (GNU findutils is needed to list entries as themselves): ${s.stderr.trim()}`):o}}async readRange(t,e){if(U(e),e.length===0)return new Uint8Array(0);let s=await this.sandbox.downloadUrl(t);return ft(s,e,{provider:"daytona",path:t,timeoutMs:be})}async watchDir(t,e,s){throw new E("files.watchDir","daytona","the Daytona SDK has no filesystem watcher; poll files.list() on the directories you have open")}async remove(t){await this.sandbox.fs.deleteFile(t,true);}async rename(t,e){await this.sandbox.fs.moveFiles(t,e);}},D=class{constructor(t,e,s){this.sandbox=t;let o=new et(t,e,s);this.commands=o,this.files=new nt(t,o);}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(),at(this.sandbox)}async metrics(){let t=await this.sandbox.getMetricsLatest();return {cpuPct:t.cpuUsedPct,memUsedMb:t.memUsed/G,memTotalMb:t.memTotal/G,diskUsedMb:t.diskUsed/G,sampledAt:F(t.timestamp),source:"daytona:getMetricsLatest"}}async updateNetwork(t){let e=Rt(t);try{await this.sandbox.updateNetworkSettings(e);}catch(s){throw Ut(s)?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: ${s instanceof Error?s.message:String(s)}).`):s}}async kill(){await this.sandbox.delete();}async pause(){await this.sandbox.stop();}},st=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:$t,pollMs:It};snapshotDeleteTiming={timeoutMs:_t,pollMs:Mt};constructor(t){let e={apiKey:t.apiKey,apiUrl:t.apiUrl,target:t.target,useDeprecatedPolling:true};this.client=t.managedToolboxUrl?new tt(e,t.managedToolboxUrl):new 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-${O}`);}async create(t){if(t.idleTimeoutMs!==void 0)throw new j;if(t.bootCommand!==void 0)throw new H;for(let l of t.phaseNetworkPolicies??[])C(l);let e=C(t.network),s=t.user,o=s&&s!=="root"?s:void 0,r=t.timeoutMs??this.defaultTimeoutMs,a=Math.max(1,Math.ceil(r/6e4)),i=t.image||this.snapshotName,d={envVars:t.envs,labels:t.metadata,autoStopInterval:a,autoDeleteInterval:ee,...o?{user:o}:{},...e},u,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 k(i);let l=await this.client.create({snapshot:i,...d},{timeout:600});return t.workingDirectory&&await l.fs.createFolder(t.workingDirectory,"755"),s&&this.sandboxUsers.set(l.id,s),new D(l,s,this.managedStream)}let c,f;try{let l=await this.client.snapshot.get(i),g=l?.state;if(l&&kt.has(g??"")&&(c=g),l&&(g==="active"||g==="inactive")&&m)throw new k(i);if(l&&g==="inactive"&&(g=(await K(this.client,i,l)).state),l&&St.has(g??"")&&(X(i)?f=await vt(this.client,i,l,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${i}" is dead (state "${g}") 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&&g==="active")console.log(`[daytona] Using cached snapshot: ${i}`),u=await this.client.create({snapshot:i,...d},{timeout:600});else throw new Error("Snapshot not active")}catch(l){if(l instanceof k||l instanceof v)throw l;let g=ot[i]??i,p=c!==void 0&&!m;p?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: ${g}`):(console.log(`[daytona] Snapshot "${i}" not found, building from image: ${g}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(f===!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:Image.base(g),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(!p)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(!Ot(x)||m)throw x;await this.joinInFlightSnapshotBuild(i)&&await y();}u=await this.client.create({snapshot:i,...d},{timeout:600});}catch(w){if(w instanceof T||w instanceof v)throw w;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${w instanceof Error?w.message:w}`);try{u=await this.client.create({image:g,...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 Ft(g)?new W(g,y):y}}}return t.workingDirectory&&await u.fs.createFolder(t.workingDirectory,"755"),s&&this.sandboxUsers.set(u.id,s),new D(u,s,this.managedStream)}async joinInFlightSnapshotBuild(t){let e=await Ct(this.client,t,this.snapshotConflictTiming);if(e===Et)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 K(this.client,t,e),console.log(`[daytona] Snapshot "${t}" ready (built by another process) \u2014 reusing it.`),false;if(St.has(e.state??"")&&X(t)&&await vt(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 s=await this.client.get(t);return s.state!=="started"&&await s.start(),new D(s,this.sandboxUsers.get(t),this.managedStream)}async inspect(t,e){let s=await this.getSandboxRecord(t);if(s.state!=="started")throw new _(t,"daytona",s.state??"unknown");return new D(s,e?.user??this.sandboxUsers.get(t),this.managedStream)}async getSandboxRecord(t){return this.client.get(t)}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,...s}=await this.paginate(t);return s}async paginate(t){return jt(this.listStream(t),t)}listStream(t){let e=t?.state?ve(t.state):void 0,s={limit:re,...t?.metadata?{labels:t.metadata}:{},...e&&e.length>0?{states:e}:{}};return this.client.list(s)}};function ve(n){let t=[];for(let e of n)e==="running"&&t.push("started"),e==="paused"&&t.push("stopped","archived","paused");return t}async function jt(n,t){let e=t?.limit,s=[],o=0,r=new Set;try{for await(let a of n){if(e!==void 0&&s.length>=e)return {sandboxes:s,complete:!1,pagesFetched:o,stoppedAtLimit:!0,error:`stopped at the requested limit of ${e} with more sandboxes available`};if(o+=1,o>B)return {sandboxes:s,complete:!1,pagesFetched:B,stoppedAtLimit:!1,error:`sandbox list exceeded ${B} sandboxes scanned`};if(t?.state){let i=Bt(a.state);if(i===void 0||!t.state.includes(i))continue}r.has(a.id)||(r.add(a.id),s.push(at(a)));}}catch(a){return {sandboxes:s,complete:false,pagesFetched:o,stoppedAtLimit:false,error:`sandbox list failed: ${a instanceof Error?a.message:String(a)}`}}return {sandboxes:s,complete:true,pagesFetched:o,stoppedAtLimit:false}}var Le=jt;function Ne(n={}){let t=n.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 st({...n,apiKey:t})}var Re=Z,Ue=q,Fe=C,Be=Rt,Ye=Ut,Ge=Ft,We=at,He=Bt,je=K,ze=Ct,Ke=Ot,Xe=X,Ve=ot,qe=Q,Qe=Lt,Je=P,Ze=J,tn=Gt,en=Wt,nn=Ht,sn=D,G=1024*1024;
8
+ export{ee as DAYTONA_AUTO_DELETE_GRACE_MINUTES,bt as DAYTONA_BOOT_LABEL,le as DAYTONA_BOOT_POLL_MS,re as DAYTONA_LIST_PAGE_SIZE,ht as DAYTONA_MAX_DOMAIN_ALLOWLIST,B as DAYTONA_MAX_LIST_SCAN,pt as DAYTONA_MAX_NETWORK_ALLOWLIST,ne as DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS,$t as DAYTONA_SNAPSHOT_CONFLICT_TIMEOUT_MS,Et as DAYTONA_SNAPSHOT_GONE,oe as DAYTONA_STREAM_TIMINGS,z as DaytonaBootAbortedError,H as DaytonaBootCommandError,et as DaytonaCommands,nt as DaytonaFiles,wt as DaytonaGpuTypeError,j as DaytonaIdleTimeoutError,W as DaytonaImagePullError,b as DaytonaNetworkPolicyError,st as DaytonaProvider,k as DaytonaResourcesError,v as DaytonaSnapshotActivationError,T as DaytonaSnapshotConflictError,O as EVOLVE_IMAGE_VERSION,E as SandboxFeatureUnsupportedError,_ as SandboxNotRunningError,A as SandboxPathNotFoundError,je as _testActivateSnapshot,Le as _testCollectSandboxStream,tn as _testCreateLogDemuxer,Ze as _testCreateSentinelFilter,sn as _testDaytonaSandboxImplCtor,He as _testDaytonaStateToEvolveState,en as _testFollowManagedSessionLogs,Ve as _testImageMap,Ge as _testImageRegistryHost,Ye as _testIsNetworkPolicyTierRefusal,Ke as _testIsSnapshotNameConflict,Fe as _testMapNetworkPolicy,Be as _testMapNetworkPolicyForUpdate,Xe as _testProviderCanRebuildSnapshot,nn as _testReadCommandStreams,Je as _testSettledStreams,Qe as _testStripEndOfOutputSentinel,We as _testToSandboxInfo,ze as _testWaitForSnapshotConflictWinner,qe as _testWithEndOfOutputSentinel,Ue as _testWithInBoxTimeout,Re as _testWrapCommand,Ne as createDaytonaProvider,Ce as createSandboxObserved,yt as daytonaBootPhaseOf,Xt as isSandboxFeatureUnsupportedError,qt as isSandboxNotRunningError,Vt as isSandboxPathNotFoundError,C as mapNetworkPolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evolvingmachines/daytona",
3
- "version": "0.0.60",
3
+ "version": "0.0.61",
4
4
  "keywords": [
5
5
  "ai",
6
6
  "agents",
@@ -33,7 +33,7 @@
33
33
  "build": "tsup --minify",
34
34
  "dev": "tsup --watch",
35
35
  "type-check": "tsc --noEmit",
36
- "test:unit": "tsx tests/unit/daytona-commands.test.ts && tsx tests/unit/daytona-provider.test.ts && tsx tests/unit/daytona-managed.test.ts && tsx tests/unit/daytona-list-pagination.test.ts && tsx tests/unit/daytona-image-version.test.ts && tsx tests/unit/daytona-image-refresh.test.ts && tsx tests/unit/daytona-files-read.test.ts && tsx tests/unit/daytona-boot-observed.test.ts"
36
+ "test:unit": "tsx tests/unit/daytona-commands.test.ts && tsx tests/unit/daytona-provider.test.ts && tsx tests/unit/daytona-managed.test.ts && tsx tests/unit/daytona-list-pagination.test.ts && tsx tests/unit/daytona-image-version.test.ts && tsx tests/unit/daytona-image-refresh.test.ts && tsx tests/unit/daytona-files-read.test.ts && tsx tests/unit/daytona-boot-observed.test.ts && tsx tests/unit/daytona-files-observe.test.ts"
37
37
  },
38
38
  "dependencies": {
39
39
  "@daytonaio/sdk": "^0.203.0"