@evolvingmachines/daytona 0.0.51 → 0.0.52-launch-round-1.20260803.cb1be5b

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,2 +1,7 @@
1
- 'use strict';var sdk=require('@daytonaio/sdk');var h={"evolve-all":"evolvingmachines/evolve-all"},S=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".pdf",".zip",".tar",".gz",".7z",".rar",".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".mp3",".wav",".ogg",".flac",".aac",".mp4",".avi",".mov",".mkv",".webm",".woff",".woff2",".ttf",".otf",".eot",".exe",".dll",".so",".dylib",".sqlite",".db",".pickle",".pkl",".parquet"]);function w(r){let e=r.substring(r.lastIndexOf(".")).toLowerCase();return S.has(e)}function v(r){let e=r.lastIndexOf("/");return e>0?r.substring(0,e):"/"}function P(r){let e=r.lastIndexOf("/");return e>=0?r.substring(e+1):r}function g(r,e,t){let s=r;return e&&(s=`cd '${e.replace(/'/g,"'\\''")}' && ${s}`),t&&Object.keys(t).length>0&&(s=`${Object.entries(t).filter(([,a])=>a!=null).map(([a,o])=>`export ${a}='${o.replace(/'/g,"'\\''")}'`).join("; ")}; ${s}`),s}var C=g,f=class{constructor(e){this.sandbox=e;}async run(e,t){let s=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,n=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);try{let a=await this.sandbox.process.executeSessionCommand(n,{command:g(e,t?.cwd,t?.envs),runAsync:!1},s),o=a.cmdId;o&&(t?.onStdout||t?.onStderr)&&await this.sandbox.process.getSessionCommandLogs(n,o,t.onStdout||(()=>{}),t.onStderr||(()=>{}));let d=a.stdout??a.output??"",i=a.stderr??"";if(!d&&o&&!t?.onStdout)try{let m=await this.sandbox.process.getSessionCommandLogs(n,o);d=m.stdout??m.output??"",i=m.stderr??i;}catch{}return {exitCode:a.exitCode??0,stdout:d,stderr:i}}finally{try{await this.sandbox.process.deleteSession(n);}catch{}}}async spawn(e,t){let s=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(s);let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),o=t?.timeoutMs,i=(await this.sandbox.process.executeSessionCommand(s,{command:g(e,t?.cwd,t?.envs),runAsync:true},n)).cmdId;i&&(t?.onStdout||t?.onStderr)&&this.sandbox.process.getSessionCommandLogs(s,i,t.onStdout||(()=>{}),t.onStderr||(()=>{})).catch(()=>{});let m=this.sandbox;return {processId:s,wait:async()=>{if(!i)return {exitCode:0,stdout:"",stderr:""};for(;;){if(o&&Date.now()-a>=o){try{await m.process.deleteSession(s);}catch{}return {exitCode:-1,stdout:"",stderr:"operation timed out"}}try{let c=await m.process.getSessionCommand(s,i);if(c.exitCode!==void 0)try{let l=await m.process.getSessionCommandLogs(s,i);return {exitCode:c.exitCode,stdout:l.stdout??l.output??"",stderr:l.stderr??""}}catch{return {exitCode:c.exitCode,stdout:"",stderr:""}}}catch(c){if((c instanceof Error?c.message.toLowerCase():String(c).toLowerCase()).includes("not found"))return {exitCode:-1,stdout:"",stderr:"session terminated"};throw c}await new Promise(c=>setTimeout(c,500));}},kill:async()=>{try{return await m.process.deleteSession(s),!0}catch{return false}}}}async list(){try{return (await this.sandbox.process.listSessions()).map(t=>({processId:t.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return []}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return false}}},p=class{constructor(e){this.sandbox=e;}async read(e){let t=await this.sandbox.fs.downloadFile(e);return w(e)?new Uint8Array(t):t.toString("utf-8")}async write(e,t){let s;if(typeof t=="string")s=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))s=t;else if(t instanceof ArrayBuffer)s=Buffer.from(t);else if(t instanceof Uint8Array)s=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(s,e);}async writeBatch(e){let t=e.map(s=>{let n;if(typeof s.data=="string")n=Buffer.from(s.data,"utf-8");else if(Buffer.isBuffer(s.data))n=s.data;else if(s.data instanceof ArrayBuffer)n=Buffer.from(s.data);else if(s.data instanceof Uint8Array)n=Buffer.from(s.data);else throw new Error(`Unsupported content type: ${typeof s.data}`);return {source:n,destination:s.path}});await this.sandbox.fs.uploadFiles(t);}async makeDir(e){await this.sandbox.fs.createFolder(e,"755");}async exists(e){try{let t=v(e),s=P(e);return (await this.sandbox.fs.listFiles(t)).some(a=>a.name===s)}catch{return false}}async list(e){return (await this.sandbox.fs.listFiles(e)).map(s=>({name:s.name,path:e.endsWith("/")?`${e}${s.name}`:`${e}/${s.name}`,type:s.isDir?"dir":"file"}))}async remove(e){await this.sandbox.fs.deleteFile(e,true);}async rename(e,t){await this.sandbox.fs.moveFiles(e,t);}},u=class{constructor(e){this.sandbox=e;this.commands=new f(e),this.files=new p(e);}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return (await this.sandbox.getPreviewLink(e)).url}async isRunning(){return this.sandbox.state==="started"}async getInfo(){return {sandboxId:this.sandbox.id,image:this.sandbox.snapshot||"unknown",name:this.sandbox.name,metadata:this.sandbox.labels||{},startedAt:new Date().toISOString()}}async kill(){await this.sandbox.delete();}async pause(){await this.sandbox.stop();}},x=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;constructor(e){this.client=new sdk.Daytona({apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??"evolve-all";}async create(e){let t=e.timeoutMs??this.defaultTimeoutMs,s=Math.max(1,Math.ceil(t/6e4)),n=e.image||this.snapshotName,a;try{let o=await this.client.snapshot.get(n);if(o&&o.state==="active")console.log(`[daytona] Using cached snapshot: ${n}`),a=await this.client.create({snapshot:n,envVars:e.envs,labels:e.metadata,autoStopInterval:s},{timeout:600});else throw new Error("Snapshot not active")}catch{let o=h[n]??n;console.log(`[daytona] Snapshot "${n}" not found, building from image: ${o}`),console.log("[daytona] First run will take a few minutes (this only happens once)...");try{await this.client.snapshot.create({name:n,image:sdk.Image.base(o),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10}},{onLogs:d=>console.log(`[daytona] ${d}`)}),console.log(`[daytona] Snapshot "${n}" ready.`),a=await this.client.create({snapshot:n,envVars:e.envs,labels:e.metadata,autoStopInterval:s},{timeout:600});}catch(d){console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${d instanceof Error?d.message:d}`),a=await this.client.create({image:o,envVars:e.envs,labels:e.metadata,autoStopInterval:s,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10}},{timeout:600,onSnapshotCreateLogs:i=>console.log(`[daytona] ${i}`)});}}return e.workingDirectory&&await a.fs.createFolder(e.workingDirectory,"755"),new u(a)}async connect(e,t){let s=await this.client.get(e);return s.state!=="started"&&await s.start(),new u(s)}async list(e){let t=e?.limit??100;return (await this.client.list(e?.metadata,1,t)).items.map(n=>({sandboxId:n.id,image:n.snapshot||"unknown",name:n.name,metadata:n.labels||{},startedAt:new Date().toISOString()}))}};function A(r={}){let e=r.apiKey??process.env.DAYTONA_API_KEY;if(!e)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 x({...r,apiKey:e})}
2
- exports.DaytonaProvider=x;exports._testWrapCommand=C;exports.createDaytonaProvider=A;
1
+ 'use strict';var sdk=require('@daytonaio/sdk'),promises=require('dns/promises');var A="c-6cd57962a3d9";var X={[`evolve-all-${A}`]:`evolvingmachines/evolve-all:${A}`,"evolve-all":"evolvingmachines/evolve-all"},mt=10,G=10,ft=18e4,gt=2e3,pt={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},v=s=>new Promise(t=>setTimeout(t,Math.max(0,s))),V=100,I=100;function ht(s){let t=s.lastIndexOf("/");return t>0?s.substring(0,t):"/"}function bt(s){let t=s.lastIndexOf("/");return t>=0?s.substring(t+1):s}var h=class extends Error{reason;destination;constructor(t,e,n){super(e),this.name="DaytonaNetworkPolicyError",this.reason=t,this.destination=n;}},C=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 (e.g. AWS ECR) require registry credentials pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret. 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;}},P=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;}},$=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";}},b=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 J(s,t,e,n){let o=n?.timeoutMs??ft,l=n?.pollMs??gt;console.log(`[daytona] Snapshot "${t}" is inactive (unused for 2+ weeks) \u2014 reactivating...`);let r;try{r=await s.snapshot.activate(e);}catch(i){throw new b(t,`the activate call failed (${i instanceof Error?i.message:String(i)})`)}let a=Date.now()+o;for(;r?.state!=="active";){if(r?.state==="error"||r?.state==="build_failed")throw new b(t,`it entered state "${r.state}"`);if(Date.now()>=a)throw new b(t,`still "${r?.state??"unknown"}" after ${o}ms`);await v(l);try{r=await s.snapshot.get(t);}catch(i){throw new b(t,`the activation poll failed (${i instanceof Error?i.message:String(i)})`)}}return console.log(`[daytona] Snapshot "${t}" reactivated.`),r}function M(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 j(){return `EVOLVE-EOS-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function k(s,t){return s.trim()?`{ :
2
+ ${s}
3
+
4
+ }; __evolve_eos=$?; printf '%s' '${t}'; (exit $__evolve_eos)`:s}function Z(s,t){return s.endsWith(`${t}
5
+ `)?s.slice(0,-(t.length+1)):s.endsWith(t)?s.slice(0,-t.length):s}function x(s,t){let e=ot(s);return {stdout:Z(e.stdout,t),stderr:e.stderr}}function T(s,t){let e=`${s}
6
+ `,n="",o=l=>{for(let r=Math.min(l.length,e.length);r>0;r--)if(e.startsWith(l.slice(l.length-r)))return r;return 0};return {push(l){n+=l;let r=o(n);r!==n.length&&(t(n.slice(0,n.length-r)),n=n.slice(n.length-r));},flush(){let l=n===e||n===s?"":n;n="",l&&t(l);}}}function E(s,t,e,n){let o=s;return t&&(o=`cd '${t.replace(/'/g,"'\\''")}' && ${o}`),e&&Object.keys(e).length>0&&(o=`${Object.entries(e).filter(([,r])=>r!=null).map(([r,a])=>`export ${r}='${String(a).replace(/'/g,"'\\''")}'`).join("; ")}; ${o}`),n==="root"&&(o=`echo ${Buffer.from(o).toString("base64")} | base64 -d | sudo -n bash`),o}var wt=s=>promises.resolve4(s);function Q(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 xt(s){return /^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(s)&&!Q(s)}function yt(s){return s.startsWith("[")?true:(s.match(/:/g)?.length??0)>=2}function St(s){return /^[^:]+:\d+$/.test(s)}async function tt(s,t=wt){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 e=s.allowedDestinations??[];if(e.length===0)return {networkBlockAll:true};let n=[],o=[];for(let r of e)if(Q(r))n.push(r.includes("/")?r:`${r}/32`);else {if(xt(r))throw new h("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(yt(r))throw new h("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${r}".`,r);if(St(r))throw new h("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("*"))throw new h("wildcard-hostname",`Daytona cannot enforce wildcard hostname "${r}": its allowlist is kernel-level IPv4 CIDR filtering with no DNS/domain layer. List concrete hostnames or IPv4 CIDRs instead.`,r);o.push(r);}for(let r of o){let a=[];try{a=await t(r);}catch(i){throw new h("unresolvable-hostname",`Cannot pin hostname "${r}" to stable IPv4 addresses at create time (${i instanceof Error?i.message:String(i)}). Daytona enforces IPv4 CIDRs only; use an IPv4 CIDR for this destination instead.`,r)}if(a.length===0)throw new h("unresolvable-hostname",`Hostname "${r}" resolved to no IPv4 addresses. Daytona enforces IPv4 CIDRs only; use an IPv4 CIDR for this destination instead.`,r);console.warn(`[daytona] Network allowlist: pinning "${r}" to [${a.join(", ")}] (DNS resolved at create time). Daytona enforces IPv4 CIDRs only \u2014 if this host rotates DNS (CDNs and cloud APIs often do), traffic to its new IPs will be BLOCKED for the sandbox's lifetime.`);for(let i of a)n.push(`${i}/32`);}let l=[...new Set(n)];if(l.length>G)throw new h("allowlist-too-large",`Daytona allows at most ${G} entries in its network allowlist; this policy resolved to ${l.length} CIDRs (${l.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return {networkBlockAll:false,networkAllowList:l.join(",")}}function et(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 U(s){return {sandboxId:s.id,image:s.snapshot??"",name:s.name,metadata:s.labels??{},startedAt:s.createdAt??""}}function nt(s){if(s==="started")return "running";if(s==="stopped"||s==="archived")return "paused"}var _=class extends sdk.Daytona{constructor(e,n){super(e);this.managedToolboxUrl=n;}async getProxyToolboxUrl(){return this.managedToolboxUrl}};function vt(s,t){let e=new Uint8Array(new ArrayBuffer(s.length+t.length));return e.set(s,0),e.set(t,s.length),e}function z(s,t,e){t:for(let n=e;n+t.length<=s.length;n++){for(let o=0;o<t.length;o++)if(s[n+o]!==t[o])continue t;return n}return -1}function st(s,t){let e=new TextDecoder("utf-8"),n=new TextDecoder("utf-8"),o=new Uint8Array(0),l="stdout",r=a=>{a.length!==0&&(l==="stdout"?s(e.decode(a,{stream:true})):t(n.decode(a,{stream:true})));};return {push(a){for(o=vt(o,a);;){let i=z(o,sdk.STDOUT_PREFIX_BYTES,0),u=z(o,sdk.STDERR_PREFIX_BYTES,0),m=-1,d="stdout",c=0;if(i!==-1&&(u===-1||i<u)?(m=i,d="stdout",c=sdk.STDOUT_PREFIX_BYTES.length):u!==-1&&(m=u,d="stderr",c=sdk.STDERR_PREFIX_BYTES.length),m===-1){let f=Math.max(0,o.length-(sdk.MAX_PREFIX_LEN-1));r(o.subarray(0,f)),o=o.slice(f);return}r(o.subarray(0,m)),l=d,o=o.slice(m+c);}},flush(){r(o),o=new Uint8Array(0);let a=e.decode();a&&s(a);let i=n.decode();i&&t(i);}}}async function rt(s,t,e,n,o,l,r){let a=`${s.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(e)}/command/${encodeURIComponent(n)}/logs?follow=true`,i=await fetch(a,{headers:{Authorization:`Bearer ${s.apiKey}`,accept:"application/octet-stream"},...r?{signal:r}:{}});if(!i.ok)throw new Error(`Daytona managed log follow failed: ${i.status} ${await i.text()}`);if(!i.body)return;let u=st(o,l),m=i.body.getReader();try{for(;;){let{done:d,value:c}=await m.read();if(d)break;c&&u.push(c);}}finally{u.flush(),await m.cancel().catch(()=>{});}}function ot(s){let t=s.stdout||"",e=s.stderr||"",n=s.output||"";return !t&&!e&&n?{stdout:n,stderr:""}:{stdout:t,stderr:e}}var R=class{constructor(t,e,n){this.sandbox=t;this.user=e;this.managedStream=n;}streamTimings=pt;followLogs(t,e,n,o,l){return this.managedStream?rt(this.managedStream,this.sandbox.id,t,e,n,o,l):this.sandbox.process.getSessionCommandLogs(t,e,n,o)}async run(t,e){let n=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 l=!!(e?.onStdout||e?.onStderr),r=j(),a=await this.sandbox.process.executeSessionCommand(o,{command:M(E(k(t,r),e?.cwd,e?.envs,this.user),n),runAsync:l},n),i=a.cmdId;if(l&&!i)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(l&&i){let d="",c="",f=!0,p=Date.now(),w=T(r,g=>{d+=g,e?.onStdout?.(g);}),B=new AbortController,N=this.followLogs(o,i,g=>{f&&(p=Date.now(),w.push(g));},g=>{f&&(p=Date.now(),c+=g,e?.onStderr?.(g));},B.signal),F=!1,y,it=N.then(()=>{},g=>{F||(y=g);}),K;try{K=await this.awaitStreamedExit(o,i,N,()=>p,e?.timeoutMs);}finally{F=!0,B.abort(),await Promise.race([it,v(this.streamTimings.drainMs)]),f=!1,y===void 0&&w.flush();}if(y!==void 0){let g;try{let dt=await this.sandbox.process.getSessionCommandLogs(o,i);g=x(dt,r);}catch{throw y}if(!g.stdout.startsWith(d)||!g.stderr.startsWith(c))throw y;let S=g.stdout.slice(d.length),H=g.stderr.slice(c.length);d=g.stdout,c=g.stderr,S&&e?.onStdout?.(S),H&&e?.onStderr?.(H);}else if(!d&&!c)try{let g=await this.sandbox.process.getSessionCommandLogs(o,i),S=x(g,r);d=S.stdout,c=S.stderr,d&&e?.onStdout?.(d),c&&e?.onStderr?.(c);}catch{}return {exitCode:K,stdout:d,stderr:c}}let{stdout:u,stderr:m}=x(a,r);if(!u&&!m&&i)try{let d=await this.sandbox.process.getSessionCommandLogs(o,i),c=x(d,r);u=c.stdout,m=c.stderr||m;}catch{}return {exitCode:a.exitCode??0,stdout:u,stderr:m}}finally{try{await this.sandbox.process.deleteSession(o);}catch{}}}async awaitStreamedExit(t,e,n,o,l){let r=this.streamTimings,a,i,u=n.then(()=>{a=Date.now();},c=>{a=Date.now(),i=c;}),m=l!==void 0&&l>0?Date.now()+l+r.killGraceMs:void 0,d=r.pollMinMs;for(;;){let c=await this.sandbox.process.getSessionCommand(t,e);if(c.exitCode!==void 0&&c.exitCode!==null){for(;a===void 0;){let w=Date.now()-o();if(w>=r.drainMs)break;await Promise.race([u,v(r.drainMs-w)]);}return c.exitCode}let f=a!==void 0?a+r.settleMs:void 0,p=m!==void 0&&f!==void 0?Math.min(m,f):m??f;if(p!==void 0&&Date.now()>=p)throw i!==void 0?i:new Error(`Daytona reported no exit code for command ${e} after `+(a!==void 0?"its log stream closed":`${l}ms`));await v(d),d=Math.min(d*2,r.pollMaxMs);}}async spawn(t,e){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let o=e?.timeoutMs?Math.floor(e.timeoutMs/1e3):void 0,l=Date.now(),r=e?.timeoutMs,a=j(),u=(await this.sandbox.process.executeSessionCommand(n,{command:M(E(k(t,a),e?.cwd,e?.envs,this.user),o),runAsync:true},o)).cmdId;if(u&&(e?.onStdout||e?.onStderr)){let d=T(a,e.onStdout||(()=>{}));this.followLogs(n,u,c=>d.push(c),e.onStderr||(()=>{})).catch(()=>{}).finally(()=>d.flush());}let m=this.sandbox;return {processId:n,wait:async()=>{if(!u)return {exitCode:0,stdout:"",stderr:""};for(;;){if(r&&Date.now()-l>=r){try{await m.process.deleteSession(n);}catch{}return {exitCode:124,stdout:"",stderr:"operation timed out"}}try{let d=await m.process.getSessionCommand(n,u);if(d.exitCode!==void 0)try{let c=await m.process.getSessionCommandLogs(n,u);return {exitCode:d.exitCode,...x(c,a)}}catch{return {exitCode:d.exitCode,stdout:"",stderr:""}}}catch(d){let c=d instanceof Error?d.message.toLowerCase():String(d).toLowerCase();if(c.includes("not found")){let f=c.includes("sandbox");try{await m.refreshData(),f=!1;}catch(p){(p instanceof Error?p.message.toLowerCase():String(p).toLowerCase()).includes("not found")&&(f=true);}return {exitCode:-1,stdout:"",stderr:f?"sandbox deleted during run":"session terminated"}}throw d}await v(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}}},L=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 o;if(typeof n.data=="string")o=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))o=n.data;else if(n.data instanceof ArrayBuffer)o=Buffer.from(n.data);else if(n.data instanceof Uint8Array)o=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return {source:o,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=ht(t),n=bt(t);return (await this.sandbox.fs.listFiles(e)).some(l=>l.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);}},D=class{constructor(t,e,n){this.sandbox=t;this.commands=new R(t,e,n),this.files=new L(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(),U(this.sandbox)}async kill(){await this.sandbox.delete();}async pause(){await this.sandbox.stop();}},O=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;constructor(t){let e={apiKey:t.apiKey,apiUrl:t.apiUrl,target:t.target};this.client=t.managedToolboxUrl?new _(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-${A}`);}async create(t){if(t.idleTimeoutMs!==void 0)throw new $;let e=await tt(t.network),n=t.user,o=n&&n!=="root"?n:void 0,l=t.timeoutMs??this.defaultTimeoutMs,r=Math.max(1,Math.ceil(l/6e4)),a=t.image||this.snapshotName,i={envVars:t.envs,labels:t.metadata,autoStopInterval:r,autoDeleteInterval:mt,...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);if(this.managedStream){if(m)throw new P(a);let d=await this.client.create({snapshot:a,...i},{timeout:600});return t.workingDirectory&&await d.fs.createFolder(t.workingDirectory,"755"),n&&this.sandboxUsers.set(d.id,n),new D(d,n,this.managedStream)}try{let d=await this.client.snapshot.get(a),c=d?.state;if(d&&(c==="active"||c==="inactive")&&m)throw new P(a);if(d&&c==="inactive"&&(c=(await J(this.client,a,d)).state),d&&c==="active")console.log(`[daytona] Using cached snapshot: ${a}`),u=await this.client.create({snapshot:a,...i},{timeout:600});else throw new Error("Snapshot not active")}catch(d){if(d instanceof P||d instanceof b)throw d;let c=X[a]??a;console.log(`[daytona] Snapshot "${a}" not found, building from image: ${c}`),console.log("[daytona] First run will take a few minutes (this only happens once)...");try{await this.client.snapshot.create({name:a,image:sdk.Image.base(c),resources:{cpu:t.resources?.cpu??4,memory:t.resources?.memory??4,disk:t.resources?.disk??10}},{onLogs:f=>console.log(`[daytona] ${f}`)}),console.log(`[daytona] Snapshot "${a}" ready.`),u=await this.client.create({snapshot:a,...i},{timeout:600});}catch(f){console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${f instanceof Error?f.message:f}`);try{u=await this.client.create({image:c,...i,resources:{cpu:t.resources?.cpu??4,memory:t.resources?.memory??4,disk:t.resources?.disk??10}},{timeout:600,onSnapshotCreateLogs:p=>console.log(`[daytona] ${p}`)});}catch(p){throw et(c)?new C(c,p):p}}}return t.workingDirectory&&await u.fs.createFolder(t.workingDirectory,"755"),n&&this.sandboxUsers.set(u.id,n),new D(u,n,this.managedStream)}async connect(t,e){let n=await this.client.get(t);return n.state!=="started"&&await n.start(),new D(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 at(e=>this.listPage(t,e),t)}async listPage(t,e){let n=t?.state?Pt(t.state):void 0;if(n&&n.length>0){let o=this.client.sandboxApi;if(typeof o?.listSandboxesPaginated=="function")try{let l=await o.listSandboxesPaginated(void 0,e,V,void 0,void 0,t?.metadata?JSON.stringify(t.metadata):void 0,void 0,n);return {items:l.data.items,totalPages:l.data.totalPages}}catch{}}return this.client.list(t?.metadata,e,V)}};function Pt(s){let t=[];for(let e of s)e==="running"&&t.push("started"),e==="paused"&&t.push("stopped","archived");return t}async function at(s,t){let e=t?.limit,n=[],o=0,l=new Set;for(let r=1;r<=I;r+=1){let a;try{a=await s(r);}catch(u){return {sandboxes:n,complete:false,pagesFetched:o,stoppedAtLimit:false,error:`sandbox list failed: ${u instanceof Error?u.message:String(u)}`}}o+=1;for(let u of a.items){if(t?.state){let m=nt(u.state);if(m===void 0||!t.state.includes(m))continue}if(!l.has(u.id)){if(e!==void 0&&n.length>=e)return {sandboxes:n,complete:false,pagesFetched:o,stoppedAtLimit:true,error:`stopped at the requested limit of ${e} with more sandboxes available`};l.add(u.id),n.push(U(u));}}let i=a.items.length===0||typeof a.totalPages=="number"&&r>=a.totalPages;if(e!==void 0&&n.length>=e&&!i)return {sandboxes:n,complete:false,pagesFetched:o,stoppedAtLimit:true,error:`stopped at the requested limit of ${e} with more sandboxes available`};if(i)break;if(r===I)return {sandboxes:n,complete:false,pagesFetched:o,stoppedAtLimit:false,error:`sandbox list exceeded ${I} pages`}}return {sandboxes:n,complete:true,pagesFetched:o,stoppedAtLimit:false}}var $t=at;function Mt(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 O({...s,apiKey:t})}var kt=E,Tt=M,Et=tt,_t=et,Rt=U,Lt=nt,Ot=J,Ut=X,Bt=k,Nt=Z,Ft=x,Kt=T,Ht=st,Yt=rt,Wt=ot;
7
+ exports.DAYTONA_AUTO_DELETE_GRACE_MINUTES=mt;exports.DAYTONA_LIST_PAGE_SIZE=V;exports.DAYTONA_MAX_LIST_PAGES=I;exports.DAYTONA_MAX_NETWORK_ALLOWLIST=G;exports.DAYTONA_SNAPSHOT_ACTIVATE_TIMEOUT_MS=ft;exports.DAYTONA_STREAM_TIMINGS=pt;exports.DaytonaCommands=R;exports.DaytonaFiles=L;exports.DaytonaIdleTimeoutError=$;exports.DaytonaImagePullError=C;exports.DaytonaNetworkPolicyError=h;exports.DaytonaProvider=O;exports.DaytonaResourcesError=P;exports.DaytonaSnapshotActivationError=b;exports.EVOLVE_IMAGE_VERSION=A;exports._testActivateSnapshot=Ot;exports._testCollectSandboxPages=$t;exports._testCreateLogDemuxer=Ht;exports._testCreateSentinelFilter=Kt;exports._testDaytonaStateToEvolveState=Lt;exports._testFollowManagedSessionLogs=Yt;exports._testImageMap=Ut;exports._testImageRegistryHost=_t;exports._testMapNetworkPolicy=Et;exports._testReadCommandStreams=Wt;exports._testSettledStreams=Ft;exports._testStripEndOfOutputSentinel=Nt;exports._testToSandboxInfo=Rt;exports._testWithEndOfOutputSentinel=Bt;exports._testWithInBoxTimeout=Tt;exports._testWrapCommand=kt;exports.createDaytonaProvider=Mt;