@opencoredev/sandbox-sdk 1.0.1 → 1.0.3
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/CHANGELOG.md +12 -0
- package/dist/ai.js +1 -1
- package/dist/chunk-11mbpwem.js +17 -0
- package/dist/{chunk-q5vqajhg.js → chunk-19gteae8.js} +2 -2
- package/dist/chunk-1k6yz176.js +1 -0
- package/dist/chunk-2z6fxyg5.js +2 -0
- package/dist/chunk-305dymgq.js +2 -0
- package/dist/chunk-348pdz09.js +5 -0
- package/dist/{chunk-k60b4r27.js → chunk-3zd78ha4.js} +2 -2
- package/dist/chunk-5gnqph3c.js +78 -0
- package/dist/chunk-6bemkxcx.js +290 -0
- package/dist/chunk-6nf686jb.js +26 -0
- package/dist/{chunk-nw845a93.js → chunk-c1wemt0y.js} +8 -8
- package/dist/{chunk-bd481sb7.js → chunk-drgkmewv.js} +1 -1
- package/dist/chunk-ea8y7y2p.js +2 -0
- package/dist/chunk-g0vk7g1k.js +2 -0
- package/dist/chunk-n7x9ha44.js +4 -0
- package/dist/{chunk-8786zrns.js → chunk-r8xnq6v3.js} +2 -2
- package/dist/{chunk-hzbssbep.js → chunk-rnksrxfc.js} +4 -4
- package/dist/chunk-tvw3kb8b.js +2 -0
- package/dist/http.d.ts +3 -0
- package/dist/index.js +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.js +1 -1
- package/dist/openai.js +1 -1
- package/dist/provider.d.ts +25 -0
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/index.js +11 -13
- package/dist/providers/daytona/index.js +15 -15
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/freestyle/execute.d.ts +3 -1
- package/dist/providers/freestyle/index.js +6 -15
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/execute.d.ts +3 -1
- package/dist/providers/superserve/index.js +21 -23
- package/dist/providers/tenki/index.js +14 -24
- package/dist/providers/upstash/index.js +10 -10
- package/dist/providers/upstash/provider.d.ts +1 -1
- package/dist/providers/vercel/index.js +1 -1
- package/dist/run.d.ts +9 -0
- package/dist/shared/guest.d.ts +28 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +5 -1
- package/package.json +1 -1
- package/dist/chunk-23tjmd39.js +0 -8
- package/dist/chunk-83avbjns.js +0 -2
- package/dist/chunk-8wq767xb.js +0 -17
- package/dist/chunk-9w9rddra.js +0 -2
- package/dist/chunk-ch71kvcp.js +0 -2
- package/dist/chunk-ckym4cht.js +0 -23
- package/dist/chunk-hgrwyjrb.js +0 -2
- package/dist/chunk-kk1hw8wa.js +0 -1
- package/dist/chunk-x2skgx3m.js +0 -5
- package/dist/chunk-x681p5d2.js +0 -68
- package/dist/chunk-xgxfy2n8.js +0 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{m}from"../../chunk-
|
|
2
|
-
${r.command}`,{cwd:r.cwd,env:r.env,timeoutMs:r.timeoutMs,signal:r.signal,output:{capture:"none"},onStdout(
|
|
1
|
+
import{m}from"../../chunk-drgkmewv.js";import{g}from"../../chunk-3zd78ha4.js";import{n}from"../../chunk-2ts3evzh.js";import{e,h,i,a}from"../../chunk-n7x9ha44.js";import{randomUUID as I}from"node:crypto";import{posix as V}from"node:path";function u(o,d="provider",p,l){return new e(`${o}. Check the agentOS runtime or use local() with Docker.`,{code:d,provider:"agentos",sandboxId:p,cause:l})}function E(o,d,p=!1){if(o instanceof e)return o;let{message:l}=m(o),w=/ENOENT|not found|no such file/i.test(l)?p?"file_not_found":"not_found":/limit|quota|ENOSPC/i.test(l)?"quota":/sidecar.*(exit|closed|missing)|cannot find package|module not found/i.test(l)?"unavailable":/EACCES|EPERM|invalid|EINVAL/i.test(l)?"invalid_argument":"provider",A=i(o,{code:w});return u(`agentOS operation failed: ${a(w,A.detail)}`,w,d,A.cause)}function D(){return{entries:new Map,keys:new Map,destroying:new Map}}var R="sha256:35ae142556050de3604342574494373c318adff3ac3b50ea6b7420c0a033d2d8",j=`https://releases.rivet.dev/agent-os/0.4.1/software/packages/git/${R.slice(7)}.aospkg`;function S(o){return{...o,labels:{...o.labels}}}function F(o,d){let p="file";if(d.isSymbolicLink)p="symlink";else if(d.isDirectory)p="directory";return{path:o,type:p,size:d.size,modifiedAt:d.mtimeMs}}function _(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)&&typeof o.size==="number"&&typeof o.modifiedAt==="number"}async function z(o,d,p){if(!(p??(d!=="/"&&(await o.filesystem.readdirEntries(V.dirname(d))).find((A)=>A.name===V.basename(d))?.isSymbolicLink)))return F(d,await o.filesystem.stat(d));let w=await o.javascript.evaluate(`(() => { const s = require("node:fs").lstatSync(${JSON.stringify(d)}); return { size: s.size, modifiedAt: s.mtimeMs }; })()`);if(w.outcome!=="succeeded"||!_(w.value))throw u("agentOS could not read symbolic link metadata","provider");return{path:d,type:"symlink",size:w.value.size,modifiedAt:w.value.modifiedAt}}async function q(o,d,p){let l=await o.javascript.evaluate(`(() => { require("node:fs").chmodSync(${JSON.stringify(d)}, ${p}); return true; })()`);if(l.outcome!=="succeeded"||l.value!==!0)throw u("agentOS could not set the file mode","provider")}function T(o,d,p){let{entries:l,keys:w,destroying:A}=p,L,N=()=>L??=g("@rivet-dev/agentos-core","agentos",d).catch((t)=>{throw u("Install @rivet-dev/agentos-core@0.4.1 and its platform sidecar package","unavailable",void 0,h(t))});function P(t){let r=l.get(t);if(!r)throw u("Sandbox does not exist in this application process","not_found",t);return r}async function b(t,r,s=!1){try{return await r(P(t).vm)}catch(c){throw E(c,t,s)}}let M={name:"agentos",inlineActivity:!0,keyMode:"exact",processMode:"unsupported",capabilities:new Set(["network-policy"]),async create(t){if(t.size!==void 0||t.from!==void 0)throw u("agentOS cannot enforce machine sizes or restore SDK snapshots","unsupported");if(t.idleTimeoutMs!==void 0||t.timeoutMs!==void 0)throw u("agentOS adapter does not enforce sandbox lifetime or idle deadlines","unsupported");if(t.signal?.aborted)throw u("Creation aborted","aborted");let r=t.network??"all",s={network:r==="none"?"deny":"allow"};if(r!=="all"&&r!=="none"){for(let f of r.allow)if(!/^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(f))throw u("Network allow-list entries must be literal hostnames","unsupported");s={network:{default:"deny",rules:r.allow.map((f)=>({mode:"allow",operations:["*"],patterns:[`dns://${f}`,`tcp://${f}:*`]}))}}}async function c(){let f;try{let{AgentOs:v}=await N(),y={permissions:s};if(Object.keys(t.env??{}).length)y.environment={PATH:"/opt/agentos/bin:/usr/local/bin:/usr/bin:/bin",HOME:"/home/agentos",...t.env};if(o.software?.length)y.software=o.software;if(o.mounts?.length)y.mounts=o.mounts;if(o.limits)y.limits=o.limits;if(f=await v.create(y),await f.software.install(o.gitPackagePath?{type:"path",path:o.gitPackagePath}:{type:"url",url:j,expectedDigest:R}),await f.filesystem.mkdir("/workspace",{recursive:!0}),t.signal?.aborted)throw u("Creation aborted","aborted");let C={id:`agentos-${I()}`,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"},state:"running",createdAt:Date.now()};return l.set(C.id,{vm:f,info:C}),S(C)}catch(v){if(f)await f.dispose().catch(()=>{});throw E(v)}}if(!t.key)return c();if(await M.find(t.key))throw u("Key already exists in this application process","invalid_argument");let O=w.get(t.key);if(O)throw await O,u("Key was created concurrently in this application process","invalid_argument");let x=c();w.set(t.key,x);try{return await x}finally{w.delete(t.key)}},async find(t){for(let r of l.values())if(r.info.key===t)return S(r.info);return},async connect(t){return S(P(t).info)},async list(t){return[...l.values()].flatMap((r)=>Object.entries(t).every(([s,c])=>r.info.labels[s]===c)?[S(r.info)]:[])},async destroy(t){if(!l.get(t))return;let s=A.get(t);if(s)return s;let c=b(t,(k)=>k.dispose()).then(()=>{l.delete(t)});A.set(t,c);try{await c}finally{A.delete(t)}},async exec(t,r){if(r.signal?.aborted)return{exitCode:null,timedOut:!0};return b(t,async(s)=>{let c=new TextDecoder,k=new TextDecoder,O=`/tmp/.sandbox-sdk/stdin-${I()}`;if(r.stdin!==void 0)await s.filesystem.mkdir("/tmp/.sandbox-sdk",{recursive:!0}),await s.filesystem.writeFile(O,r.stdin);try{if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let x=await s.process.exec(`exec < ${r.stdin===void 0?"/dev/null":n(O)}
|
|
2
|
+
${r.command}`,{cwd:r.cwd,env:r.env,timeoutMs:r.timeoutMs,signal:r.signal,output:{capture:"none"},onStdout(v){let y=c.decode(v,{stream:!0});if(y)r.onChunk({stream:"stdout",text:y})},onStderr(v){let y=k.decode(v,{stream:!0});if(y)r.onChunk({stream:"stderr",text:y})}});for(let[v,y]of[["stdout",c.decode()],["stderr",k.decode()]])if(y)r.onChunk({stream:v,text:y});let f=x.outcome==="timed_out"||x.outcome==="cancelled";if(!f&&x.exitCode===void 0)throw u("agentOS did not report a command exit","outcome_unknown",t);return{exitCode:f?null:x.exitCode??null,timedOut:f}}finally{if(r.stdin!==void 0)await s.filesystem.remove(O).catch(()=>{})}})},files:{writeCreatesParents:!0,writeSupportsMode:!0,transfer:"files",read:(t,r)=>b(t,async(s)=>new Uint8Array(await s.filesystem.readFile(r)),!0),write:(t,r,s,c)=>b(t,async(k)=>{if(await k.filesystem.mkdir(V.dirname(r),{recursive:!0}),await k.filesystem.writeFile(r,s),c?.mode!==void 0)await q(k,r,c.mode)},!0),stat:(t,r)=>b(t,async(s)=>z(s,r),!0),list:(t,r)=>b(t,async(s)=>Promise.all((await s.filesystem.readdirEntries(r)).map((c)=>z(s,V.join(r,c.name),c.isSymbolicLink))),!0),mkdir:(t,r)=>b(t,(s)=>s.filesystem.mkdir(r,{recursive:!0}),!0),remove:(t,r,s)=>b(t,(c)=>c.filesystem.remove(r,s),!0)},async previewUrl(t){throw P(t),u("Embedded agentOS has no preview URLs; forward HTTP with native.network.httpRequest","unsupported",t)},native(t){return P(t).vm}};return M}var U=D();function te(o={}){return T(o,()=>import("@rivet-dev/agentos-core"),U)}export{te as agentos};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-
|
|
1
|
+
import"../../chunk-6nf686jb.js";import{K}from"../../chunk-348pdz09.js";function o(e={}){return K(e).provider}export{o as boat};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{p,b,
|
|
1
|
+
import{p,j,b,N}from"../../chunk-6bemkxcx.js";import{D}from"../../chunk-19gteae8.js";import{m}from"../../chunk-drgkmewv.js";import{g}from"../../chunk-3zd78ha4.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,e,i,l,a}from"../../chunk-n7x9ha44.js";function u(d,f="provider",c,E){return new e(f==="auth"?d:f==="file_not_found"?`${d}. Check the path.`:`${d}. Check boxd configuration and retry.`,{code:f,provider:"boxd",sandboxId:c,cause:E})}var te=new Map([[1,"aborted"],[3,"invalid_argument"],[4,"timeout"],[5,"not_found"],[6,"invalid_argument"],[9,"invalid_argument"],[7,"auth"],[8,"quota"],[12,"unsupported"],[14,"unavailable"],[16,"auth"]]),re=new Map([["AuthenticationError","auth"],["PermissionDeniedError","auth"],["NotFoundError","not_found"],["RateLimitError","quota"],["APIConnectionError","unavailable"]]);function q(d,f){if(d instanceof e)return d;let c=m(d),E=c.grpcCode,k=(A,_)=>i(d,{code:A,known:_,status:E===void 0?void 0:`gRPC ${E}`,redact:l([process.env.BOXD_API_KEY])});if(c.name==="BoxdError"&&/^exec timed out after \d+ms$/.test(c.message))return u("boxd request timed out","timeout",f,k("timeout").cause);if(/\bno such file\b/i.test(c.message))return u("File does not exist","file_not_found",f,k("file_not_found").cause);let x=E===void 0?re.get(c.name)??"provider":te.get(E)??"provider",y=/permission denied/i.test(c.message),P=k(x,y||void 0);return u(y?"boxd guest filesystem permission denied":`boxd request failed: ${a(x,P.detail)}`,x,f,P.cause)}var se=`import sys,os,fcntl,select,_signal as signal
|
|
2
2
|
${b}
|
|
3
3
|
# Keep the output owner alive through native TERM grace. Caught handlers reset
|
|
4
4
|
# to the default disposition when the user shell execs.
|
|
5
5
|
signal.signal(signal.SIGTERM,lambda *_:None)
|
|
6
|
-
v=
|
|
6
|
+
v=eval(sys.stdin.buffer.read().decode(),{'__builtins__':{}})
|
|
7
7
|
if v.get('preparing'): print('SDK_PREPARED:',end='',flush=True)
|
|
8
8
|
a=v.get('activityPath')
|
|
9
9
|
m=v['pidPath']
|
|
@@ -22,14 +22,12 @@ try:
|
|
|
22
22
|
print(str(e),file=sys.stderr); sys.exit(127)
|
|
23
23
|
# Keep the supervisor and marker until inherited output pipes close, even
|
|
24
24
|
# after the direct shell exits and only background descendants remain.
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
if data: key.data.write(data); key.data.flush()
|
|
32
|
-
else: sel.unregister(key.fileobj); key.fileobj.close()
|
|
25
|
+
streams={p.stdout.fileno():(p.stdout,sys.stdout.buffer),p.stderr.fileno():(p.stderr,sys.stderr.buffer)}
|
|
26
|
+
while streams:
|
|
27
|
+
for fd in select.select(list(streams),[],[])[0]:
|
|
28
|
+
data=os.read(fd,16384)
|
|
29
|
+
if data: streams[fd][1].write(data); streams[fd][1].flush()
|
|
30
|
+
else: streams.pop(fd)[0].close()
|
|
33
31
|
code=p.wait()
|
|
34
32
|
sys.exit(code if code>=0 else 128-code)
|
|
35
33
|
finally:
|
|
@@ -57,7 +55,7 @@ finally:
|
|
|
57
55
|
if a:
|
|
58
56
|
try: os.unlink(a)
|
|
59
57
|
except FileNotFoundError: pass
|
|
60
|
-
`,
|
|
58
|
+
`,ie=j(se),ne=`import os,sys,signal,time,fcntl
|
|
61
59
|
p=sys.argv[1]
|
|
62
60
|
with open(p+'.lock','a') as lock:
|
|
63
61
|
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
@@ -82,7 +80,7 @@ while time.monotonic()<end:
|
|
|
82
80
|
except FileNotFoundError: pass
|
|
83
81
|
print('confirmed'); sys.exit(0)
|
|
84
82
|
time.sleep(.01)
|
|
85
|
-
sys.exit(1)`;async function Z(d,f,l,E="",k){if(l.signal?.aborted)return{exitCode:null,timedOut:!0};let v=`/tmp/sandbox-sdk-${crypto.randomUUID()}.pid`,x=d.machines.streamExec(f,{command:E+p(te)}),P=!1,D=!1,T=x.wait().then((s)=>({kind:"exit",exitCode:s}),(s)=>({kind:"error",cause:s})),S={stdout:new TextDecoder,stderr:new TextDecoder},K=!E,A="";for(let s of["stdout","stderr"])x[s].push=(h)=>{let w=S[s].decode(h,{stream:!0});if(s==="stdout"&&!K){if(A+=w,"SDK_PREPARED:".startsWith(A)&&A.length<13)return;if(A.startsWith("SDK_PREPARED:"))K=!0,k?.(),w=A.slice(13);else w=A;A=""}if(w)l.onChunk({stream:s,text:w})};let j=()=>{},W=new Promise((s)=>{j=s}),U=()=>{if(P)return;P=!0,x.close(),j()},z=setTimeout(U,l.timeoutMs);l.signal?.addEventListener("abort",U,{once:!0});try{x.write(JSON.stringify({pidPath:v,preparing:Boolean(E),command:l.command,cwd:l.cwd,env:l.env,stdin:l.stdin??"",activityPath:l.activityPath})),x.end();let s=await Promise.race([T,W.then(()=>({kind:"cancel"}))]);if(P){let h,w=await Promise.race([T.then((y)=>y.kind==="exit"&&y.exitCode>=0?!0:new Promise(()=>{})),new Promise((y)=>{h=setTimeout(()=>y(!1),1000)})]);if(clearTimeout(h),!w){let y=await d.machines.exec(f,{command:p(re,v),timeout:5000});if(y.exitCode!==0||y.stdout.trim()!=="confirmed")throw u("Process termination could not be confirmed","outcome_unknown",f)}}else if(s.kind==="error")throw s.cause;for(let h of["stdout","stderr"]){let w=S[h].decode();if(w)l.onChunk({stream:h,text:w})}return{exitCode:P?null:s.kind==="exit"?s.exitCode:null,timedOut:P}}catch(s){if(D=!0,P)throw u("Process termination could not be confirmed","outcome_unknown",f);throw x.close(),s}finally{if(clearTimeout(z),l.signal?.removeEventListener("abort",U),(P||D)&&l.activityPath)await d.machines.exec(f,{command:`rm -f -- ${n(l.activityPath)} ${n(v)}`,timeout:5000}).catch((s)=>{if(!D)throw s})}}var se="import os,sys,base64; os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True); f=open(sys.argv[1],'wb'); f.write(base64.b64decode(sys.stdin.buffer.read())); f.close()",ie="import sys; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); sys.stdout.buffer.write(f.read(int(sys.argv[3])))",Y="/var/lib/sandbox-sdk/metadata.json";function oe(d){if(d===void 0)return;if(t(d))return{small:1,medium:2,large:4}[d];if(![1,2,4,8].includes(d.cpu))throw u("boxd sizes are 1 vCPU / 4 GiB, 2 / 8, 4 / 16, or 8 / 32, each with 100 GB disk","unsupported");if(d.memoryMb!==d.cpu*4096||(d.diskGb??100)!==100)throw u(`boxd gives ${d.cpu} vCPU / ${d.cpu*4} GiB memory / 100 GB disk; CPU and memory cannot be selected independently`,"unsupported");return d.cpu}function J(d,f){if(d===void 0)return;if(!Number.isSafeInteger(d)||d<=0)throw u(`${f} must be a positive integer of milliseconds`,"invalid_argument");return Math.ceil(d/1000)}function ne(d){if(d===void 0||d==="all")return;if(d==="none"||!d.allow.length)throw u("boxd cannot block all egress (an empty allow-list means unrestricted); pass network: { allow: [...] } with at least one entry","unsupported");for(let f of d.allow)if(!/^(\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?|(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$/.test(f))throw u("Network allow entries must be hostnames, *.wildcards, or public IPv4 addresses and CIDRs","unsupported");return[...new Set(d.allow)]}function V(d,f,l){let E,k,v,x=new Map;async function P(){return E??=(async()=>{if(d.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(d.requestTimeoutMs)||d.requestTimeoutMs<=0))throw u("requestTimeoutMs must be a positive integer","invalid_argument");let s=d.apiKey??process.env.BOXD_API_KEY;if(!s?.trim())throw u("boxd API key is missing. Authentication is required. Set BOXD_API_KEY or pass apiKey.","auth");let{Boxd:h}=await g("@boxd-sh/sdk","boxd",f);return k=new h({apiKey:s,baseURL:d.baseUrl??d.baseURL,timeout:d.requestTimeoutMs??30000,maxRetries:0})})()}async function D(){return await P(),v??=l({apiKey:d.apiKey??process.env.BOXD_API_KEY,baseURL:d.baseUrl??d.baseURL,timeout:d.requestTimeoutMs??30000,maxRetries:0},d.fileTransferSignal)}async function T(s,h){try{return await h()}catch(w){throw q(w,s)}}let S=new Map;function K(s){return`if ! mkdir -p /workspace /var/lib/sandbox-sdk 2>/dev/null || [ ! -w /workspace ] || [ ! -w /var/lib/sandbox-sdk ]; then sudo -n install -d -o "$(id -u)" -g "$(id -g)" /workspace /var/lib/sandbox-sdk; fi && test -w /workspace && test -w /var/lib/sandbox-sdk && mkdir -p /tmp/.sandbox-sdk && printf %s ${n(s)} > ${n(Y)} && `}function A(s){return S.get(s)??""}async function j(s){let h=await P();return{name:"boxd",raw:async(w)=>{let y=A(s),M="SDK_PREPARED:",C=await h.machines.exec(s,{command:y?y+`printf %s ${n("SDK_PREPARED:")} && `+w:w,timeout:d.requestTimeoutMs??30000}),B=y&&C.stdout.startsWith("SDK_PREPARED:");if(B)S.delete(s);if(C.exitCode!==0)throw u("Guest operation failed","provider",s);return B?C.stdout.slice(13):C.stdout},upload:async(w,y)=>{let M=A(s);if(M){if((await Z(h,s,{command:p(se,w),cwd:"/",env:{},stdin:Buffer.from(y).toString("base64"),timeoutMs:d.requestTimeoutMs??30000,onChunk(){}},M,()=>S.delete(s))).exitCode!==0)throw u("File upload failed","provider",s);return}if(await(await D()).upload(s,w,y)!==y.length)throw u("Incomplete file upload","provider",s)},read:async(w,y)=>{if(!y)return(await D()).download(s,w);let M=await h.machines.exec(s,{command:p(ie,w,String(y.offset),String(y.length)),encoding:"buffer",timeout:d.requestTimeoutMs??30000});if(M.exitCode!==0)throw u("File does not exist","file_not_found",s);return new Uint8Array(M.stdout)}}}async function W(s){if(!s.name.startsWith("sbxsdk-"))throw u("Not an SDK machine","not_found",s.id);let h,w=!1;try{h=new TextDecoder().decode(await(await D()).download(s.id,Y))}catch(B){if(!["not_found","file_not_found"].includes(q(B).code))throw B;let O=s.name.split("-");if(O[1]!=="v2"||!["0","1"].includes(O[2]??""))throw u("SDK metadata is missing","not_found",s.id);let L=Number.parseInt(O[3]??"",36);if(!Number.isFinite(L)||L<=0)throw u("Invalid SDK metadata","not_found",s.id);h=JSON.stringify({key:null,labels:O[2]==="1"?{"sandbox-sdk":"1"}:{},createdAt:L}),w=!0}let y=(B)=>{throw u(`Invalid SDK ${B}`,"not_found",s.id)},M=N(h,y),C=M.createdAt??y("metadata");if(M.key===void 0)y("metadata");if(w&&!S.has(s.id))S.set(s.id,K(h));return{id:s.id,key:M.key??void 0,labels:M.labels,createdAt:s.createdAt?.getTime()??C,state:s.status==="running"?"running":["suspended","hibernated"].includes(s.status)?"paused":"stopped"}}let U={name:"boxd",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","size","snapshot","network-policy"]),create:(s)=>T(void 0,async()=>{let h=ne(s.network),w=J(s.timeoutMs,"timeoutMs"),y=J(s.idleTimeoutMs,"idleTimeoutMs")??0;if(s.from!==void 0&&!s.from.trim())throw u("Snapshot restore requires a nonempty snapshot ID or name","invalid_argument");if(s.from!==void 0&&(s.size!==void 0||Object.keys(s.env??{}).length>0||d.image!==void 0||d.volumes?.length))throw u("boxd snapshot restore inherits size, image, volumes and environment; overrides are not supported","unsupported");let M=oe(s.size);if(s.signal?.aborted)throw u("Creation aborted","aborted");let C=await P(),B=Date.now(),O=JSON.stringify({key:s.key??null,labels:s.labels,createdAt:B}),L=s.key===void 0&&Object.keys(s.labels).every((I)=>I==="sandbox-sdk"&&s.labels[I]==="1")&&s.from===void 0,_;try{let I=L?`sbxsdk-v2-${s.labels["sandbox-sdk"]==="1"?"1":"0"}-${B.toString(36)}-${crypto.randomUUID()}`:`sbxsdk-${crypto.randomUUID()}`,F=s.from!==void 0?{autoSuspendTimeout:y}:{autoSuspendTimeout:y,autoDestroyTimeout:0,vcpu:M};if(s.from===void 0&&d.volumes?.length)F.volumes=d.volumes;let G=s.from!==void 0?{name:I,fromSnapshot:s.from,isolated:!0,config:F}:{name:I,image:d.image,env:s.env,isolated:!0,config:F};if(w!==void 0)G.deleteAfter=w;_=await C.machines.create(G)}catch(I){let F=q(I);if(F.code==="unavailable"||F.code==="timeout")throw u("Machine creation outcome is unknown; inspect the account before retrying","outcome_unknown");throw I}try{if(s.signal?.aborted)throw u("Creation aborted","aborted");if(_.status!=="running")_=await C.machines.waitUntilReady(_.id,{timeout:d.requestTimeoutMs??90000});if(h){let F=await C.machines.setEgressAllow(_.id,h);if(F.length!==h.length||h.some((G)=>!F.includes(G)))throw u("boxd did not confirm the requested egress allow-list","unsupported",_.id)}let I={id:_.id,key:s.key,labels:s.labels,createdAt:_.createdAt?.getTime()??B,state:"running"};if(S.set(_.id,K(O)),x.set(_.id,_),!L)await(await j(_.id)).raw("true");return I}catch(I){throw await C.machines.delete(_.id),I}}),list:(s)=>T(void 0,async()=>{try{let h=[];for(let w of await(await P()).machines.list()){if(!w.name.startsWith("sbxsdk-")||w.status==="destroyed")continue;try{let y=await W(w);if(Object.entries(s).every(([M,C])=>y.labels[M]===C))h.push(y)}catch(y){if(q(y).code!=="not_found")throw y}}return h}finally{if(!x.size)await v?.releaseIdle()}}),async find(s){let h=(await U.list({})).find((w)=>w.key===s);return h?U.connect(h.id):void 0},connect:(s)=>T(s,async()=>{try{let h=await(await P()).machines.get(s),w=await W(h);return x.set(s,h),w}finally{if(!x.size)await v?.releaseIdle()}}),destroy:(s)=>T(s,async()=>{try{await(await P()).machines.delete(s)}catch(h){if(q(h).code!=="not_found")throw h}if(x.delete(s),S.delete(s),await v?.closeMachine(s),!x.size)await v?.releaseIdle()}),async close(s){if(x.delete(s),await v?.closeMachine(s),!x.size)await v?.releaseIdle()},exec:(s,h)=>T(s,async()=>{let w=A(s);return await Z(await P(),s,h,w,()=>S.delete(s))}),files:R(j,T),previewUrl:(s,h)=>T(s,async()=>{let w=await P(),y=(await w.machines.proxies.list(s)).find((M)=>M.isDefault);if(!y)throw u("Default proxy is not ready","unavailable",s);return await w.machines.proxies.setPort(s,h),await w.machines.setBotProtection(s,"off"),{url:`https://${y.domain}`}}),pause:(s)=>T(s,async()=>{await(await P()).machines.pause(s)}),resume:(s)=>T(s,async()=>{await(await P()).machines.resume(s)}),snapshot:(s,h)=>T(s,async()=>{if(h?.expiresInMs)throw u("boxd keeps snapshots until they are deleted; omit expiresInMs","unsupported",s);let w=await P(),y=`sbxsdk-${crypto.randomUUID()}`,M=Date.now()+(d.requestTimeoutMs??90000);try{await w.snapshots.create(s,y);while(Date.now()<M){let C=await w.snapshots.get(y);if(C.status==="ready")return{id:y};if(C.status==="failed")throw u("boxd snapshot capture failed","provider",s);await new Promise((B)=>setTimeout(B,250))}throw u("boxd snapshot did not become ready","timeout",s)}catch(C){try{await w.snapshots.delete(y)}catch(B){if(q(B,s).code!=="not_found")throw u(`Snapshot ${y} cleanup is unconfirmed after ${q(C,s).code}; inspect and remove it before retrying`,"outcome_unknown",s)}throw C}}),native(s){let h=x.get(s);if(!h)throw u("Connect the machine first","not_found",s);if(!E)throw u("Client is detached","not_found",s);return{machine:h,client:z()}}};function z(){if(!k)throw u("Client is detached","not_found");return k}return U}import{createRequire as ae}from"node:module";import{isAbsolute as de,join as ce}from"node:path";import{pathToFileURL as H}from"node:url";import{Worker as le}from"node:worker_threads";function ue(d){return r(d)&&"requestId"in d&&o(d.requestId)}var me=`import("node:worker_threads").then(async ({ parentPort, workerData }) => {
|
|
83
|
+
sys.exit(1)`;async function X(d,f,c,E="",k){if(c.signal?.aborted)return{exitCode:null,timedOut:!0};let x=`/tmp/sandbox-sdk-${crypto.randomUUID()}.pid`,y=d.machines.streamExec(f,{command:E+p(ie)}),P=!1,A=!1,_=y.wait().then((s)=>({kind:"exit",exitCode:s}),(s)=>({kind:"error",cause:s})),B={stdout:new TextDecoder,stderr:new TextDecoder},K=!E,S="";for(let s of["stdout","stderr"])y[s].push=(w)=>{let h=B[s].decode(w,{stream:!0});if(s==="stdout"&&!K){if(S+=h,"SDK_PREPARED:".startsWith(S)&&S.length<13)return;if(S.startsWith("SDK_PREPARED:"))K=!0,k?.(),h=S.slice(13);else h=S;S=""}if(h)c.onChunk({stream:s,text:h})};let W=()=>{},z=new Promise((s)=>{W=s}),U=()=>{if(P)return;P=!0,y.close(),W()},Z=setTimeout(U,c.timeoutMs);c.signal?.addEventListener("abort",U,{once:!0});try{let s={pidPath:x,preparing:E?1:0,command:c.command,cwd:c.cwd,env:c.env,stdin:c.stdin??"",activityPath:c.activityPath};y.write(JSON.stringify(s)),y.end();let w=await Promise.race([_,z.then(()=>({kind:"cancel"}))]);if(P){let h,v=await Promise.race([_.then((C)=>C.kind==="exit"&&C.exitCode>=0?!0:new Promise(()=>{})),new Promise((C)=>{h=setTimeout(()=>C(!1),1000)})]);if(clearTimeout(h),!v){let C=await d.machines.exec(f,{command:p(ne,x),timeout:5000});if(C.exitCode!==0||C.stdout.trim()!=="confirmed")throw u("Process termination could not be confirmed","outcome_unknown",f)}}else if(w.kind==="error")throw w.cause;for(let h of["stdout","stderr"]){let v=B[h].decode();if(v)c.onChunk({stream:h,text:v})}return{exitCode:P?null:w.kind==="exit"?w.exitCode:null,timedOut:P}}catch(s){if(A=!0,P)throw u("Process termination could not be confirmed","outcome_unknown",f);throw y.close(),s}finally{if(clearTimeout(Z),c.signal?.removeEventListener("abort",U),(P||A)&&c.activityPath)await d.machines.exec(f,{command:`rm -f -- ${n(c.activityPath)} ${n(x)}`,timeout:5000}).catch((s)=>{if(!A)throw s})}}var oe="import os,sys,base64; os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True); f=open(sys.argv[1],'wb'); f.write(base64.b64decode(sys.stdin.buffer.read())); f.close()",ae="import sys; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); sys.stdout.buffer.write(f.read(int(sys.argv[3])))",J="/var/lib/sandbox-sdk/metadata.json";function de(d){if(d===void 0)return;if(t(d))return{small:1,medium:2,large:4}[d];if(![1,2,4,8].includes(d.cpu))throw u("boxd sizes are 1 vCPU / 4 GiB, 2 / 8, 4 / 16, or 8 / 32, each with 100 GB disk","unsupported");if(d.memoryMb!==d.cpu*4096||(d.diskGb??100)!==100)throw u(`boxd gives ${d.cpu} vCPU / ${d.cpu*4} GiB memory / 100 GB disk; CPU and memory cannot be selected independently`,"unsupported");return d.cpu}function H(d,f){if(d===void 0)return;if(!Number.isSafeInteger(d)||d<=0)throw u(`${f} must be a positive integer of milliseconds`,"invalid_argument");return Math.ceil(d/1000)}function ce(d){if(d===void 0||d==="all")return;if(d==="none"||!d.allow.length)throw u("boxd cannot block all egress (an empty allow-list means unrestricted); pass network: { allow: [...] } with at least one entry","unsupported");for(let f of d.allow)if(!/^(\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?|(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)$/.test(f))throw u("Network allow entries must be hostnames, *.wildcards, or public IPv4 addresses and CIDRs","unsupported");return[...new Set(d.allow)]}function Q(d,f,c){let E,k,x,y=new Map;async function P(){return E??=(async()=>{if(d.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(d.requestTimeoutMs)||d.requestTimeoutMs<=0))throw u("requestTimeoutMs must be a positive integer","invalid_argument");let s=d.apiKey??process.env.BOXD_API_KEY;if(!s?.trim())throw u("boxd API key is missing. Authentication is required. Set BOXD_API_KEY or pass apiKey.","auth");let{Boxd:w}=await g("@boxd-sh/sdk","boxd",f);return k=new w({apiKey:s,baseURL:d.baseUrl??d.baseURL,timeout:d.requestTimeoutMs??30000,maxRetries:0})})()}async function A(){return await P(),x??=c({apiKey:d.apiKey??process.env.BOXD_API_KEY,baseURL:d.baseUrl??d.baseURL,timeout:d.requestTimeoutMs??30000,maxRetries:0},d.fileTransferSignal)}async function _(s,w){try{return await w()}catch(h){throw q(h,s)}}let B=new Map;function K(s){return`if ! mkdir -p /workspace /var/lib/sandbox-sdk 2>/dev/null || [ ! -w /workspace ] || [ ! -w /var/lib/sandbox-sdk ]; then sudo -n install -d -o "$(id -u)" -g "$(id -g)" /workspace /var/lib/sandbox-sdk; fi && test -w /workspace && test -w /var/lib/sandbox-sdk && mkdir -p /tmp/.sandbox-sdk && printf %s ${n(s)} > ${n(J)} && `}function S(s){return B.get(s)??""}async function W(s){let w=await P();return{name:"boxd",raw:async(h)=>{let v=S(s),C="SDK_PREPARED:",M=await w.machines.exec(s,{command:v?v+`printf %s ${n("SDK_PREPARED:")} && `+h:h,timeout:d.requestTimeoutMs??30000}),I=v&&M.stdout.startsWith("SDK_PREPARED:");if(I)B.delete(s);if(M.exitCode!==0)throw u("Guest operation failed","provider",s);return I?M.stdout.slice(13):M.stdout},upload:async(h,v)=>{let C=S(s);if(C){if((await X(w,s,{command:p(oe,h),cwd:"/",env:{},stdin:Buffer.from(v).toString("base64"),timeoutMs:d.requestTimeoutMs??30000,onChunk(){}},C,()=>B.delete(s))).exitCode!==0)throw u("File upload failed","provider",s);return}if(await(await A()).upload(s,h,v)!==v.length)throw u("Incomplete file upload","provider",s)},read:async(h,v)=>{if(!v)return(await A()).download(s,h);let C=await w.machines.exec(s,{command:p(ae,h,String(v.offset),String(v.length)),encoding:"buffer",timeout:d.requestTimeoutMs??30000});if(C.exitCode!==0)throw u("File does not exist","file_not_found",s);return new Uint8Array(C.stdout)}}}async function z(s){if(!s.name.startsWith("sbxsdk-"))throw u("Not an SDK machine","not_found",s.id);let w,h=!1;try{w=new TextDecoder().decode(await(await A()).download(s.id,J))}catch(I){if(!["not_found","file_not_found"].includes(q(I).code))throw I;let O=s.name.split("-");if(O[1]!=="v2"||!["0","1"].includes(O[2]??""))throw u("SDK metadata is missing","not_found",s.id);let L=Number.parseInt(O[3]??"",36);if(!Number.isFinite(L)||L<=0)throw u("Invalid SDK metadata","not_found",s.id);w=JSON.stringify({key:null,labels:O[2]==="1"?{"sandbox-sdk":"1"}:{},createdAt:L}),h=!0}let v=(I)=>{throw u(`Invalid SDK ${I}`,"not_found",s.id)},C=D(w,v),M=C.createdAt??v("metadata");if(C.key===void 0)v("metadata");if(h&&!B.has(s.id))B.set(s.id,K(w));return{id:s.id,key:C.key??void 0,labels:C.labels,createdAt:s.createdAt?.getTime()??M,state:s.status==="running"?"running":["suspended","hibernated"].includes(s.status)?"paused":"stopped"}}let U={name:"boxd",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","size","snapshot","network-policy"]),create:(s)=>_(void 0,async()=>{let w=ce(s.network),h=H(s.timeoutMs,"timeoutMs"),v=H(s.idleTimeoutMs,"idleTimeoutMs")??0;if(s.from!==void 0&&!s.from.trim())throw u("Snapshot restore requires a nonempty snapshot ID or name","invalid_argument");if(s.from!==void 0&&(s.size!==void 0||Object.keys(s.env??{}).length>0||d.image!==void 0||d.volumes?.length))throw u("boxd snapshot restore inherits size, image, volumes and environment; overrides are not supported","unsupported");let C=de(s.size);if(s.signal?.aborted)throw u("Creation aborted","aborted");let M=await P(),I=Date.now(),O=JSON.stringify({key:s.key??null,labels:s.labels,createdAt:I}),L=s.key===void 0&&Object.keys(s.labels).every((T)=>T==="sandbox-sdk"&&s.labels[T]==="1")&&s.from===void 0,R;try{let T=L?`sbxsdk-v2-${s.labels["sandbox-sdk"]==="1"?"1":"0"}-${I.toString(36)}-${crypto.randomUUID()}`:`sbxsdk-${crypto.randomUUID()}`,F=s.from!==void 0?{autoSuspendTimeout:v}:{autoSuspendTimeout:v,autoDestroyTimeout:0,vcpu:C};if(s.from===void 0&&d.volumes?.length)F.volumes=d.volumes;let G=s.from!==void 0?{name:T,fromSnapshot:s.from,isolated:!0,config:F}:{name:T,image:d.image,env:s.env,isolated:!0,config:F};if(h!==void 0)G.deleteAfter=h;R=await M.machines.create(G)}catch(T){let F=q(T);if(F.code==="unavailable"||F.code==="timeout")throw u("Machine creation outcome is unknown; inspect the account before retrying","outcome_unknown");throw T}try{if(s.signal?.aborted)throw u("Creation aborted","aborted");if(R.status!=="running")R=await M.machines.waitUntilReady(R.id,{timeout:d.requestTimeoutMs??90000});let T=R.id,F={id:T,key:s.key,labels:s.labels,createdAt:R.createdAt?.getTime()??I,state:"running"};if(B.set(T,K(O)),y.set(T,R),w){let G=await M.machines.setEgressAllow(T,w);if(G.length!==w.length||w.some((ee)=>!G.includes(ee)))throw u("boxd did not confirm the requested egress allow-list","unsupported",T)}if(!L)await(await W(T)).raw("true");return F}catch(T){try{await M.machines.delete(R.id)}finally{if(y.delete(R.id),B.delete(R.id),await x?.closeMachine(R.id),!y.size)await x?.releaseIdle()}throw T}}),list:(s)=>_(void 0,async()=>{try{let w=[];for(let h of await(await P()).machines.list()){if(!h.name.startsWith("sbxsdk-")||h.status==="destroyed")continue;try{let v=await z(h);if(Object.entries(s).every(([C,M])=>v.labels[C]===M))w.push(v)}catch(v){if(q(v).code!=="not_found")throw v}}return w}finally{if(!y.size)await x?.releaseIdle()}}),async find(s){let w=(await U.list({})).find((h)=>h.key===s);return w?U.connect(w.id):void 0},connect:(s)=>_(s,async()=>{try{let w=await(await P()).machines.get(s),h=await z(w);return y.set(s,w),h}finally{if(!y.size)await x?.releaseIdle()}}),destroy:(s)=>_(s,async()=>{try{await(await P()).machines.delete(s)}catch(w){if(q(w).code!=="not_found")throw w}if(y.delete(s),B.delete(s),await x?.closeMachine(s),!y.size)await x?.releaseIdle()}),async close(s){if(y.delete(s),await x?.closeMachine(s),!y.size)await x?.releaseIdle()},exec:(s,w)=>_(s,async()=>{let h=S(s);return await X(await P(),s,w,h,()=>B.delete(s))}),files:N(W,_),previewUrl:(s,w)=>_(s,async()=>{let h=await P(),v=(await h.machines.proxies.list(s)).find((C)=>C.isDefault);if(!v)throw u("Default proxy is not ready","unavailable",s);return await h.machines.proxies.setPort(s,w),await h.machines.setBotProtection(s,"off"),{url:`https://${v.domain}`}}),pause:(s)=>_(s,async()=>{await(await P()).machines.pause(s)}),resume:(s)=>_(s,async()=>{await(await P()).machines.resume(s)}),snapshot:(s,w)=>_(s,async()=>{if(w?.expiresInMs)throw u("boxd keeps snapshots until they are deleted; omit expiresInMs","unsupported",s);let h=await P(),v=`sbxsdk-${crypto.randomUUID()}`,C=Date.now()+(d.requestTimeoutMs??90000);try{await h.snapshots.create(s,v);while(Date.now()<C){let M=await h.snapshots.get(v);if(M.status==="ready")return{id:v};if(M.status==="failed")throw u("boxd snapshot capture failed","provider",s);await new Promise((I)=>setTimeout(I,250))}throw u("boxd snapshot did not become ready","timeout",s)}catch(M){try{await h.snapshots.delete(v)}catch(I){if(q(I,s).code!=="not_found")throw u(`Snapshot ${v} cleanup is unconfirmed after ${q(M,s).code}; inspect and remove it before retrying`,"outcome_unknown",s)}throw M}}),native(s){let w=y.get(s);if(!w)throw u("Connect the machine first","not_found",s);if(!E)throw u("Client is detached","not_found",s);return{machine:w,client:Z()}}};function Z(){if(!k)throw u("Client is detached","not_found");return k}return U}import{createRequire as le}from"node:module";import{isAbsolute as ue,join as me}from"node:path";import{pathToFileURL as V}from"node:url";import{Worker as fe}from"node:worker_threads";function pe(d){return r(d)&&"requestId"in d&&o(d.requestId)}var he=`import("node:worker_threads").then(async ({ parentPort, workerData }) => {
|
|
86
84
|
const { Boxd } = await import(workerData.moduleURL);
|
|
87
85
|
const client = new Boxd(workerData.options);
|
|
88
86
|
parentPort.on("message", async request => {
|
|
@@ -102,4 +100,4 @@ sys.exit(1)`;async function Z(d,f,l,E="",k){if(l.signal?.aborted)return{exitCode
|
|
|
102
100
|
} });
|
|
103
101
|
}
|
|
104
102
|
});
|
|
105
|
-
});`;function
|
|
103
|
+
});`;function we(){let d=import.meta;for(let f of[d.url,V(me(process.cwd(),"index.js")).href]){if(!t(f))continue;try{let c=le(f).resolve("@boxd-sh/sdk/web");if(t(c)&&ue(c))return V(c).href}catch{}}return}class Y{options;signal;workers=new Set;idle=[];stopping=new Map;nextId=0;pending=new Map;moduleURL;inline;constructor(d,f){this.options=d;this.signal=f}start(d){let f=this.idle.pop();if(f)return f;let c=new fe(he,{eval:!0,workerData:{moduleURL:d,options:this.options}});return this.workers.add(c),c.on("message",(E)=>{let k=E;if(!this.workers.has(c))return;if(!pe(k)){this.stop(c,u("Invalid file transfer response"));return}let x=this.pending.get(k.requestId);if(!x||x.worker!==c)return;if(this.pending.delete(k.requestId),x.cleanup(),"value"in k&&(o(k.value)||k.value instanceof Uint8Array))x.resolve(k.value);else if("error"in k&&r(k.error)){let y=k.error,P="permissionDenied"in y&&y.permissionDenied===!0?"permission denied":("missingFile"in y)&&y.missingFile===!0?"no such file":"File transfer failed";x.reject(q(Object.assign(Error(P),{name:"name"in y&&t(y.name)?y.name:"Error",grpcCode:"grpcCode"in y&&o(y.grpcCode)?y.grpcCode:void 0}),x.machine))}else x.reject(u("Invalid file transfer response","provider",x.machine));this.idle.push(c),c.unref()}),c.on("error",()=>{if(this.workers.has(c))this.stop(c,u("File transfer worker failed","unavailable"))}),c.on("exit",()=>{if(this.workers.has(c))this.stop(c,u("File transfer worker exited","unavailable"))}),c.unref(),c}stop(d,f){let c=this.stopping.get(d);if(c)return c.promise;this.workers.delete(d),this.idle=this.idle.filter((x)=>x!==d);let E=[...this.pending].filter(([,x])=>x.worker===d);for(let[x,y]of E)this.pending.delete(x),y.cleanup();let k=d.terminate().then(()=>{for(let[,x]of E)x.reject(f);this.stopping.delete(d)});return this.stopping.set(d,{machine:E[0]?.[1].machine,promise:k}),k}async transfer(d){if(this.signal?.aborted)throw u("File transfer aborted","aborted",d.machine);if(this.moduleURL===void 0)this.moduleURL=we()??null;if(this.moduleURL===null)return this.direct(d);let f=this.start(this.moduleURL);f.ref();let c=this.nextId++;return new Promise((E,k)=>{let x=()=>{this.stop(f,u("File transfer aborted","aborted",d.machine))},y=setTimeout(()=>{this.stop(f,u("File transfer deadline exceeded; check the destination before retrying a write","timeout",d.machine))},this.options.timeout??30000),P=()=>{clearTimeout(y),this.signal?.removeEventListener("abort",x)};if(this.pending.set(c,{worker:f,machine:d.machine,resolve:E,reject:k,cleanup:P}),this.signal?.addEventListener("abort",x,{once:!0}),this.signal?.aborted){x();return}try{f.postMessage({...d,requestId:c})}catch{this.stop(f,u("Could not submit file transfer","unavailable",d.machine))}})}async direct(d){let f=await(this.inline??=g("@boxd-sh/sdk/web","boxd",()=>import("@boxd-sh/sdk/web")).then(({Boxd:y})=>new y(this.options))),c=d.kind==="upload"?f.machines.files.upload(d.machine,d.path,d.bytes):f.machines.files.download(d.machine,d.path),E,k=()=>{},x=new Promise((y,P)=>{if(E=setTimeout(()=>P(u("File transfer deadline exceeded; check the destination before retrying a write","timeout",d.machine)),this.options.timeout??30000),k=()=>P(u("File transfer aborted","aborted",d.machine)),this.signal?.addEventListener("abort",k,{once:!0}),this.signal?.aborted)k()});try{return await Promise.race([c.catch((y)=>{throw q(y,d.machine)}),x])}finally{clearTimeout(E),this.signal?.removeEventListener("abort",k)}}async upload(d,f,c){let E=await this.transfer({kind:"upload",machine:d,path:f,bytes:c});if(!o(E))throw u("Invalid upload response","provider",d);return E}async download(d,f){let c=await this.transfer({kind:"download",machine:d,path:f});if(!(c instanceof Uint8Array))throw u("Invalid download response","provider",d);return c}async closeMachine(d){let f=new Set;for(let c of this.pending.values())if(c.machine===d)f.add(c.worker);await Promise.all([...f].map((c)=>this.stop(c,u("File transfers closed","aborted",d)))),await Promise.all([...this.stopping.values()].flatMap((c)=>c.machine===d?[c.promise]:[]))}async releaseIdle(){let d=this.idle.splice(0);await Promise.all(d.map((f)=>this.stop(f,u("Idle file transfer worker closed","aborted")))),await Promise.all([...this.stopping.values()].map((f)=>f.promise))}async close(){await Promise.all([...this.workers].map((d)=>this.stop(d,u("File transfers closed","aborted")))),await Promise.all([...this.stopping.values()].map((d)=>d.promise))}}function Ke(d={}){return Q(d,()=>import("@boxd-sh/sdk"),(f,c)=>new Y(f,c))}export{Ke as boxd};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{T,w,v,k}from"../../chunk-2z6fxyg5.js";import{d,y,x}from"../../chunk-305dymgq.js";import{t,o,r,e,i,l,a}from"../../chunk-n7x9ha44.js";import{posix as We}from"node:path";var Fe=new Set(["FILE_NOT_FOUND","QUOTA_EXCEEDED"]),je=/^(?:[a-f0-9]{16,64}|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/i,Ue=/^(request|create|restore|list|connect|destroy|exec|process|preview|snapshot|files)$/,qe=(n)=>n instanceof Error&&typeof("operation"in n?n.operation:void 0)==="string";function Z(n,c,h=!1,E=h?"files":"request",A=process.env.DAYTONA_API_KEY,g=[]){let L=Ue.test(E)?E:"request";if(n instanceof e){if(!qe(n.cause)||n.cause.operation===L)return n;let{status:R,providerCode:q,requestId:H,source:O,native:j}=n.cause,z={operation:L};if(R!==void 0)z.status=R;if(q!==void 0)z.providerCode=q;if(H!==void 0)z.requestId=H;if(O!==void 0)z.source=O;if(j!==void 0)z.native=j;return new e(n.message,{code:n.code,provider:n.provider,sandboxId:n.sandboxId,retryable:n.retryable,hint:n.hint,cause:Object.assign(Error(JSON.stringify(z)),z)})}let D=n&&r(n)&&"statusCode"in n?n.statusCode:void 0,f=n&&r(n)&&"code"in n?n.code:void 0,S=n instanceof Error?n.name:"",u=h&&D===400&&n instanceof Error&&/(?:\bENOENT\b|no such file or directory|\bnot found\b|\bdoes not exist\b)/i.test(n.message),m="provider";if(D===401||D===403)m="auth";else if(f==="FILE_NOT_FOUND"||h&&D===404||u)m="file_not_found";else if(D===404||D===410)m="not_found";else if(D===429||D===402||f==="QUOTA_EXCEEDED")m="quota";else if(D===408||D===504||S.includes("Timeout"))m="timeout";else if(o(D)&&D>=500||S.includes("Connection"))m="unavailable";else if(D===400||D===422||S.includes("InvalidArgument"))m="invalid_argument";let b={operation:L},P=[...g,A,process.env.DAYTONA_API_KEY].filter((R)=>typeof R==="string"&&R.length>0),M=(R,q)=>typeof R==="string"&&q.test(R)&&!P.some((H)=>R.includes(H));if(o(D)&&Number.isInteger(D)&&D>=100&&D<=599)b.status=D;if(M(f,/^[A-Z_]{1,64}$/)&&Fe.has(f))b.providerCode=f;if(n&&r(n)){if("source"in n&&M(n.source,/^DAYTONA_(API|DAEMON|PROXY)$/))b.source=n.source;if("headers"in n&&n.headers&&r(n.headers)){let R=n.headers;for(let q of["x-request-id"in R?R["x-request-id"]:void 0,"x-daytona-request-id"in R?R["x-daytona-request-id"]:void 0])if(M(q,je)){b.requestId=q;break}}}let{detail:N}=i(n,{code:m,status:D===void 0?void 0:String(D),redact:l(P)});if(N!==void 0)b.native=N;let U=Object.assign(Error(JSON.stringify(b)),b);return new e(`Daytona request failed: ${a(m,b.native)}. Check the sandbox and provider configuration.`,{code:m,provider:"daytona",sandboxId:c,cause:U,retryable:["quota","unavailable","timeout"].includes(m),hint:"Check Daytona credentials, quotas, sandbox state, and request options before retrying."})}function ze(n){return n.plane==="toolbox"&&/^[A-Z]+ \/files(?:\/|$)/.test(n.operation)}function Ke(n){let c=n.body.json,h=r(c)?"source"in c?c.source:void 0:void 0,E={};for(let A of["x-request-id","x-daytona-request-id"]){let g=n.headers.get(A);if(g!==null)E[A]=g}return Object.assign(Error(n.body.message??""),{statusCode:n.status,code:n.body.code,source:h,headers:E})}function Te(n){let c=(h,E)=>h.kind==="status"?Z(Ke(h),E.sandboxId,ze(E),"request",void 0,n()):void 0;return{mapError:(h,E)=>c(h,E)?.code,cause:(h,E)=>{let A=c(h,E)?.cause;return A instanceof Error?A:void 0}}}function re(n){throw new e(`${n}. Daytona cannot enforce this request. Choose supported settings.`,{code:"unsupported",provider:"daytona"})}var ye=new TextEncoder,pe=ye.encode(`\r
|
|
2
2
|
\r
|
|
3
|
-
`);function Ee(n){if(!n||!/^multipart\//i.test(n.trim()))return;let
|
|
4
|
-
--${
|
|
5
|
-
`)){let j=
|
|
3
|
+
`);function Ee(n){if(!n||!/^multipart\//i.test(n.trim()))return;let c=/;\s*boundary=(?:"([^"]{1,70})"|([^\s;"]{1,70}))/i.exec(n);return c?.[1]??c?.[2]}function ce(n,c,h=0){let E=c[0];for(let A=n.indexOf(E??0,h);A>=0&&A+c.length<=n.length;A=n.indexOf(E??0,A+1)){let g=!0;for(let L=1;L<c.length;L++)if(n[A+L]!==c[L]){g=!1;break}if(g)return A}return-1}function Be(n,c){if(!n.byteLength)return c;let h=new Uint8Array(n.byteLength+c.byteLength);return h.set(n),h.set(c,n.byteLength),h}function Ie(n,c){return(new RegExp(`(?:^|;)\\s*${c}="([^"]*)"`,"i").exec(n)??new RegExp(`(?:^|;)\\s*${c}=([^;\\s]*)`,"i").exec(n))?.[1]}async function Ae(n,c,h){let E=(m,b)=>new e(`${b}. The ${h.provider} download response ${m?"ended early":"is not valid multipart"}. Retry the read.`,{code:m?"unavailable":"provider",provider:h.provider,sandboxId:h.sandboxId,retryable:m}),A=h.maxHeaderBytes??16384,g=ye.encode(`--${c}`),L=ye.encode(`\r
|
|
4
|
+
--${c}`),D=n.getReader(),f=new Uint8Array,S=!1,u=async()=>{let m=await D.read();if(m.done)return S=!0,!1;return f=Be(f,m.value),!0};try{let m;while((m=ce(f,g))<0||f.length<m+g.length+2){if(f.length>A)throw E(!1,"No part delimiter in the first bytes");if(!await u())throw E(!0,"The body ended before the first part")}if(f[m+g.length]===45&&f[m+g.length+1]===45)throw E(!1,"The body has no parts");let b;while((b=ce(f,pe.subarray(0,2),m+g.length))<0){if(f.length>A)throw E(!1,"The part delimiter line is too long");if(!await u())throw E(!0,"The body ended in the part delimiter")}let P;while((P=ce(f,pe,b))<0){if(f.length-b>A)throw E(!1,"The part headers are too large");if(!await u())throw E(!0,"The body ended in the part headers")}let M={};for(let O of new TextDecoder().decode(f.subarray(b+2,P)).split(`\r
|
|
5
|
+
`)){let j=O.indexOf(":");if(j>0)M[O.slice(0,j).trim().toLowerCase()]=O.slice(j+1).trim()}let N=M["content-disposition"]??"",U=M["content-length"]===void 0?void 0:Number(M["content-length"]);if(U!==void 0&&!(Number.isSafeInteger(U)&&U>=0))throw E(!1,"The part has an invalid Content-Length");f=f.subarray(P+pe.length);let R=0,q=!1,H=new ReadableStream({async pull(O){try{for(;;){let j=ce(f,L),z=!1;while(j>=0){let s=j+L.length;if(f.length<s+2){z=!0;break}if(f[s]===45&&f[s+1]===45||f[s]===13&&f[s+1]===10)break;j=ce(f,L,j+1)}if(j>=0&&!z){if(j)O.enqueue(f.slice(0,j));if(R+=j,q=!0,U!==void 0&&U!==R)throw E(!1,`The part has ${R} bytes but declares ${U}`);await D.cancel().catch(()=>{}),O.close();return}let B=z?j:f.length-(L.length+1);if(B>0){if(O.enqueue(f.slice(0,B)),R+=B,f=f.subarray(B),U!==void 0&&R>U)throw E(!1,`The part is longer than its declared ${U} bytes`);return}if(S||!await u())throw E(!0,"The body ended inside the part")}}catch(j){throw q=!0,await D.cancel().catch(()=>{}),j}},async cancel(O){if(!q)await D.cancel(O).catch(()=>{})}},{highWaterMark:0});return{name:Ie(N,"name"),filename:Ie(N,"filename"),headers:M,body:H}}catch(m){throw await D.cancel().catch(()=>{}),m}}async function we(n){let c=n.getReader(),h=[],E=0;try{for(;;){let{done:L,value:D}=await c.read();if(L)break;h.push(D),E+=D.byteLength}}finally{c.releaseLock()}let A=new Uint8Array(E),g=0;for(let L of h)A.set(L,g),g+=L.byteLength;return A}var W=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n),Q=(n,c)=>c(n)?n:void 0,J=(n)=>typeof n==="string",se=(n)=>typeof n==="number"&&Number.isFinite(n),Ce=(n)=>typeof n==="boolean";function te(n,c){return new e(`Daytona returned ${n} the adapter cannot read. Check the Daytona API version.`,{code:"provider",provider:"daytona",sandboxId:c})}function ue(n){if(!W(n)||!J(n.id)||!n.id)throw te("a sandbox");let c=W(n.labels)?Object.fromEntries(Object.entries(n.labels).filter((h)=>typeof h[1]==="string")):{};return{id:n.id,labels:c,state:Q(n.state,J),createdAt:Q(n.createdAt,J),public:Q(n.public,Ce),cpu:Q(n.cpu,se),memory:Q(n.memory,se),disk:Q(n.disk,se),toolboxProxyUrl:Q(n.toolboxProxyUrl,J)}}function Se(n,c){if(!W(n)||!J(n.name)||!Ce(n.isDir))throw te("file information",c);return{name:n.name,isDir:n.isDir,size:Q(n.size,se),mode:Q(n.mode,J),modifiedAt:Q(n.modifiedAt,J),modTime:Q(n.modTime,J)}}var Ge=new Set(["error","build_failed"]),Ye=(n,c)=>n<5000?100:Math.min(c*1.1,1000);function _e(n){let c=new Map,h=(u)=>{if(u.toolboxProxyUrl)c.set(u.id,u.toolboxProxyUrl);return u},E=()=>{let{apiKey:u,jwtToken:m,organizationId:b}=n.credentials();return u?{authorization:`Bearer ${u}`}:{authorization:`Bearer ${m??""}`,"x-daytona-organization-id":b??""}},A=x({provider:"daytona",label:"Daytona",defaultPlane:"api",timeoutMs:n.requestTimeoutMs,fetch:n.fetch,authHint:"Set DAYTONA_API_KEY to a valid Daytona API key, or DAYTONA_JWT_TOKEN with DAYTONA_ORGANIZATION_ID.",secrets:()=>{let{apiKey:u,jwtToken:m}=n.credentials();return[u,m,...n.secrets()]},...Te(()=>{let{apiKey:u,jwtToken:m}=n.credentials();return[u,m,...n.secrets()].filter(J)}),planes:{api:{baseUrl:n.baseUrl,auth:E,headers:{accept:"application/json"}},toolbox:{async baseUrl({sandboxId:u,signal:m}){if(u===void 0)throw new e("The toolbox plane belongs to one sandbox. Use box.native, or pass the sandbox to a sandbox-bound client.",{code:"invalid_argument",provider:"daytona"});let b=c.get(u);if(b===void 0){let P=await A.json({method:"GET",path:"/sandbox/{sandboxId}/toolbox-proxy-url",params:{sandboxId:u},sandboxId:u,signal:m});if(!W(P)||!J(P.url)||!P.url)throw te("a toolbox proxy URL",u);b=P.url,c.set(u,b)}return`${b.replace(/\/+$/,"")}/${encodeURIComponent(u)}`},auth:E}}});async function g(u,m){return h(ue(await A.json({method:"GET",path:"/sandbox/{sandboxId}",params:{sandboxId:u},sandboxId:u,deadline:m})))}async function L(u,m,b,P,M=!1){let N=Date.now(),U=100;for(;;){let R;try{R=await g(u,b)}catch(q){if(M&&q instanceof e&&q.code==="not_found")return;throw q}if(R.state!==void 0&&Ge.has(R.state))throw new e(`Sandbox ${P} failed with state ${R.state}. Inspect the sandbox in the Daytona dashboard.`,{code:"provider",provider:"daytona",sandboxId:u});if(m(R.state))return R;U=Ye(Date.now()-N,U),await y(Math.min(U,Math.max(1,b.remaining())),b,"daytona")}}let D=(u,m)=>d(u,m),f=async(u,m,b,P)=>h(ue(await A.json({method:"POST",path:`/sandbox/{sandboxId}/${m}`,params:{sandboxId:u},sandboxId:u,body:P,deadline:b}))),S={get:g,waitFor:L,async create(u,m){return h(ue(await A.json({method:"POST",path:"/sandbox",body:u,deadline:m})))},async*list(u){let m;do{let b=await A.json({method:"GET",path:"/sandbox",query:{labels:JSON.stringify(u),cursor:m}});if(!W(b)||!Array.isArray(b.items))throw te("a sandbox list");for(let P of b.items)yield h(ue(P));m=J(b.nextCursor)&&b.nextCursor?b.nextCursor:void 0}while(m!==void 0)},async remove(u,m,b=60000){let P=D(b),M=await A.json({method:"DELETE",path:"/sandbox/{sandboxId}",params:{sandboxId:u},sandboxId:u,deadline:P});if(c.delete(u),!m||W(M)&&M.state==="destroyed")return;await L(u,(N)=>N==="destroyed",P,"deletion",!0)},async cleanup(u){await A.cleanup({method:"DELETE",path:"/sandbox/{sandboxId}",params:{sandboxId:u},sandboxId:u}),c.delete(u)},async stop(u,m=60000){let b=D(m),P=await f(u,"stop",b);if(P.state!=="stopped"&&P.state!=="destroyed")await L(u,(M)=>M==="stopped"||M==="destroyed",b,"stop",!0)},async start(u,m=60000){let b=D(m);if((await f(u,"start",b)).state!=="started")await L(u,(M)=>M==="started",b,"start")},async resize(u,m,b=60000){let P=D(b);if((await f(u,"resize",P,m)).state==="resizing")await L(u,(N)=>N!=="resizing",P,"resize")},async snapshot(u,m,b){let P=D(b);await f(u,"snapshot",P,{name:m}),await L(u,(M)=>M!=="snapshotting",P,"snapshot")},async previewLink(u,m){let b=await A.json({method:"GET",path:"/sandbox/{sandboxId}/ports/{port}/preview-url",params:{sandboxId:u,port:m},sandboxId:u});if(!W(b)||!J(b.url)||!J(b.token))throw te("a preview link",u);return{url:b.url,token:b.token}}};return{http:A,control:S,toolbox:(u)=>Je(A,S,u,n.requestTimeoutMs)}}var Pe=5000;function Je(n,c,h,E){let A={plane:"toolbox",sandboxId:h},g=(f,S,u={})=>n.request({...A,method:f,path:S,...u}),L=(f)=>{if(!W(f))throw te("a command result",h);return{exitCode:se(f.exitCode)?f.exitCode:0,result:J(f.result)?f.result:""}};async function D(f,S={}){let u=await n.stream({...A,method:"POST",path:"/files/bulk-download",body:{paths:[f]},readOnly:!0,signal:S.signal,timeoutMs:S.timeoutMs}),m=Ee(u.headers.get("content-type"));if(!m||!u.body)throw await u.body?.cancel().catch(()=>{}),te("a download that is not multipart",h);let b=await Ae(u.body,m,{provider:"daytona",sandboxId:h});if(b.name==="file")return b.body;if(b.name!=="error")throw await b.body.cancel().catch(()=>{}),te(`a download part named ${JSON.stringify(b.name??"").slice(0,32)}`,h);let P=new TextDecoder().decode((await we(b.body)).subarray(0,65536)),M;try{M=JSON.parse(P)}catch{M=void 0}let N=W(M)&&se(M.statusCode)?M.statusCode:500,U=W(M)&&J(M.code)?M.code:void 0,R=W(M)&&J(M.message)?M.message:P,q=U==="FILE_NOT_FOUND"||N===404||N===400&&/no such file or directory|\bnot found\b/i.test(R);throw new e(`Daytona POST /files/bulk-download failed (HTTP ${N}${U&&/^[A-Z_]{1,64}$/.test(U)?` ${U}`:""}).`,{code:q?"file_not_found":N===400?"invalid_argument":N===401||N===403?"auth":"provider",provider:"daytona",sandboxId:h})}return{id:h,fs:{async upload(f,S){let u=new FormData;u.append("files[0].path",S),u.append("files[0].file",new Blob([Uint8Array.from(f)]),S),await g("POST","/files/bulk-upload",{body:u})},async download(f){return we(await D(f,{timeoutMs:E}))},downloadStream:(f,S)=>D(f,S),async deleteFile(f,S){await g("DELETE","/files",{query:{path:f,recursive:S}})},async createFolder(f,S){await g("POST","/files/folder",{query:{path:f,mode:S}})},async setFilePermissions(f,S){await g("POST","/files/permissions",{query:{path:f,mode:S}})},async getFileDetails(f){return Se((await g("GET","/files/info",{query:{path:f}})).json(),h)},async listFiles(f){let S=(await g("GET","/files",{query:{path:f}})).json();if(!Array.isArray(S))throw te("a file list",h);return S.map((u)=>Se(u,h))}},process:{async executeCommand(f,S,u,m){return L((await g("POST","/process/execute",{body:{command:f,cwd:S,timeout:m,envs:u&&Object.keys(u).length?u:void 0},timeoutMs:m?m*1000+Pe:void 0})).json())},async codeRun(f,S){return L((await g("POST","/process/code-run",{body:{code:f,language:"python",timeout:S},timeoutMs:S*1000+Pe})).json())},async createSession(f){await g("POST","/process/session",{body:{sessionId:f}})},async executeSessionCommand(f,S){let u=(await g("POST","/process/session/{session}/exec",{params:{session:f},body:S})).json();return{cmdId:W(u)&&J(u.cmdId)?u.cmdId:void 0}},async getSessionCommand(f,S){let u=(await g("GET","/process/session/{session}/command/{command}",{params:{session:f,command:S}})).json();return{exitCode:W(u)&&se(u.exitCode)?u.exitCode:void 0}},async followSessionCommandLogs(f,S,u,m){let b=await n.stream({...A,method:"GET",path:"/process/session/{session}/command/{command}/logs",params:{session:f,command:S},query:{follow:!0},signal:m,startupTimeoutMs:2147483647});if(!b.body)return;let P=new TextDecoder,M=b.body.getReader();try{for(;;){let{done:U,value:R}=await M.read();if(U)break;let q=P.decode(R,{stream:!0});if(q)u(q)}let N=P.decode();if(N)u(N)}finally{await M.cancel().catch(()=>{})}},async deleteSession(f){await g("DELETE","/process/session/{session}",{params:{session:f}})}},stop:()=>c.stop(h)}}var He=`import base64,os,selectors,signal,subprocess,sys,time,shutil,fcntl
|
|
6
6
|
command,directory,cwd,limit,activity=sys.argv[1:]
|
|
7
7
|
if activity:
|
|
8
8
|
os.makedirs(os.path.dirname(activity),exist_ok=True)
|
|
@@ -64,9 +64,9 @@ for attempt in range(3):
|
|
|
64
64
|
break
|
|
65
65
|
except FileNotFoundError:
|
|
66
66
|
if attempt==2: raise
|
|
67
|
-
`;async function Oe(n,
|
|
68
|
-
`),
|
|
69
|
-
`))>=0)q(
|
|
67
|
+
`;async function Oe(n,c,h=ae,E){if(c.signal?.aborted)return{exitCode:null,timedOut:!0};let A=Date.now()+c.timeoutMs,g=new AbortController,L,D=!1,f=()=>{},S=new Promise((O)=>{f=O}),u=`/tmp/.sandbox-sdk/exec/sdk-${crypto.randomUUID()}`,m=!0,b=!1,P,M,N=()=>{if(D=!0,f(),g.abort(),L?.cancel().catch(()=>{}),b)return;P??=n.process.executeCommand(`python3 -c ${Y(Ve)} ${Y(u)}`,"/",void 0,10).then((O)=>{if(O.exitCode!==0)throw Error("Cancellation failed")}).catch((O)=>{M=O})},U={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},R=()=>new e("Buffered output is incomplete or malformed. Daytona did not confirm exact output and exit. Inspect or destroy the sandbox before retrying.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id}),q=(O)=>{let j=/^(O|E):([A-Za-z0-9+/]*={0,2})$/.exec(O);if(!j||O.length>5466||Buffer.from(j[2]??"","base64").toString("base64")!==j[2])throw R();let z=j[1]==="O"?"stdout":"stderr",B=U[z].decode(Buffer.from(j[2]??"","base64"),{stream:!0});if(B)c.onChunk({stream:z,text:B})};c.signal?.addEventListener("abort",N,{once:!0});let H=setTimeout(N,Math.max(0,A-Date.now()));try{let O=await n.process.executeCommand(`${h?`${h} && `:""}python3 -u -c ${Y(He)} ${Y(c.command)} ${Y(u)} ${Y(c.cwd)} ${Y(String(c.timeoutMs/1000))} ${Y(c.activityPath??"")}`,"/",c.env,Math.ceil(c.timeoutMs/1000)+15),j=O.result.trimEnd().split(`
|
|
68
|
+
`),z=/^R:(\d+):([01]):([01])$/.exec(j.pop()??"");if(O.exitCode!==0||!z)throw R();b=!0,E?.(),m=z[3]==="1";for(let s of j)if(s)q(s);if(z[3]==="1"){let s=A-Date.now();if(s<=0)N();if(!D){let I=(async()=>{let C=(await n.fs.downloadStream(`${u}/output`,{signal:g.signal,timeoutMs:Math.max(1,s)})).getReader();if(L=C,D){await C.cancel().catch(()=>{});return}let G="";for(;;){let{done:V,value:X}=await C.read();if(V)break;if(D)return;G+=Buffer.from(X).toString("ascii");let ne;while((ne=G.indexOf(`
|
|
69
|
+
`))>=0)q(G.slice(0,ne)),G=G.slice(ne+1);if(G.length>5466)throw R()}if(G)throw R()})();I.catch(()=>{}),await Promise.race([I,S])}if(D)return{exitCode:null,timedOut:!0}}for(let s of["stdout","stderr"]){let p=U[s].decode();if(p)c.onChunk({stream:s,text:p})}if(await P,M!==void 0)throw R();let B=z[2]==="1"||D;return{exitCode:B?null:Number(z[1]),timedOut:B}}catch(O){if(b&&D)return{exitCode:null,timedOut:!0};if(!b)N(),await P,await n.stop();if(await P,M!==void 0)throw R();throw O}finally{if(clearTimeout(H),c.signal?.removeEventListener("abort",N),await P,P||m)await n.fs.deleteFile(u,!0).catch(()=>{});if(c.activityPath&&P)await n.fs.deleteFile(c.activityPath,!0).catch(()=>{})}}var Y=(n)=>`'${n.replace(/'/g,"'\\''")}'`,Ze=`import base64,os,selectors,subprocess,sys,shutil
|
|
70
70
|
a=sys.argv[3]
|
|
71
71
|
if a:
|
|
72
72
|
os.makedirs(os.path.dirname(a),exist_ok=True)
|
|
@@ -84,13 +84,13 @@ code=p.wait()
|
|
|
84
84
|
if a: shutil.rmtree(a,ignore_errors=True)
|
|
85
85
|
print("X:",flush=True)
|
|
86
86
|
sys.exit(code if code>=0 else 128-code)
|
|
87
|
-
`,fe=(n)=>new Promise((
|
|
88
|
-
`))>=0){let
|
|
89
|
-
`});continue}let de=/^(O|E):([A-Za-z0-9+/]*={0,2})$/.exec(
|
|
90
|
-
`}
|
|
91
|
-
subprocess.run(["sh","-c",${JSON.stringify(
|
|
87
|
+
`,fe=(n)=>new Promise((c)=>setTimeout(c,n)),ae='if [ ! -w /workspace ]; then sudo -n install -d -o "$(id -u)" -g "$(id -g)" -m 755 /workspace; fi; test -w /workspace';async function be(n,c,h,E=ae){let A=`sdk-${crypto.randomUUID()}`,g=`/tmp/.sandbox-sdk/exec/${A}`,L=`${g}/pid`,D=c.signal?.aborted??!1,f,S,u=!1,m=!1,b=!1,P=!1,M=h===void 0,N=()=>{D=!0},U=new AbortController,R=h===void 0?void 0:setTimeout(N,h);c.signal?.addEventListener("abort",N,{once:!0});async function q(O){if(f===void 0)return;if((await n.process.executeCommand(`/bin/kill -${O} -- -${f} 2>/dev/null || ! /bin/kill -0 -- -${f} 2>/dev/null`,"/",void 0,10)).exitCode!==0)throw new e("Remote process group could not be killed. Cancellation is unconfirmed. Destroy the sandbox before retrying.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id})}async function H(){if(clearTimeout(R),c.signal?.removeEventListener("abort",N),c.activityPath&&!P)await n.fs.deleteFile(c.activityPath,!0).catch(()=>{});if(U.abort(),u)try{await n.process.deleteSession(A)}catch(O){if(Z(O).code!=="not_found")throw O}try{await n.fs.deleteFile(g,!0)}catch(O){if(Z(O,n.id,!0).code!=="file_not_found")throw O}}try{if(c.stdin!==void 0)await n.fs.createFolder(g,"700"),await n.fs.upload(Buffer.from(c.stdin),`${g}/stdin`);if(D)return await H(),{pid:0,wait:async()=>({exitCode:null,signal:"SIGKILL"}),stop:async()=>{},detach(){}};await n.process.createSession(A),u=!0;let O=Object.entries(c.env).map(([_,K])=>Y(`${_}=${K}`)).join(" "),j=`umask 077; mkdir -p ${Y(g)} || exit 1; echo $$ > ${Y(`${L}.tmp`)}; mv ${Y(`${L}.tmp`)} ${Y(L)}; cd ${Y(c.cwd)} || exit 1; exec env ${O} python3 -u -c ${Y(Ze)} ${Y(c.command)} ${Y(c.stdin===void 0?"/dev/null":`${g}/stdin`)} ${Y(c.activityPath??"")}`;if(S=(await n.process.executeSessionCommand(A,{command:`${E?`${E} && `:""}setsid --wait sh -c ${Y(j)}`,runAsync:!0,suppressInputEcho:!0})).cmdId,!S)throw new e("Session command has no ID. Daytona did not confirm launch. Inspect or destroy the sandbox.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id});let B="",s,p=!1,I={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},F=(_)=>{B+=_;let K;while((K=B.indexOf(`
|
|
88
|
+
`))>=0){let ee=B.slice(0,K).replace(/\r$/,"");if(B=B.slice(K+1),!ee)continue;if(p)throw new e("Session output continued after completion. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});if(ee==="X:"){p=!0,P=!0;for(let ke of["stdout","stderr"]){let De=I[ke].decode();if(!m&&De)c.onChunk({stream:ke,text:De})}continue}if(!/^[OE]:/.test(ee)){if(!m)c.onChunk({stream:"stderr",text:`${ee}
|
|
89
|
+
`});continue}let de=/^(O|E):([A-Za-z0-9+/]*={0,2})$/.exec(ee);if(!de||ee.length>5466||Buffer.from(de[2]??"","base64").toString("base64")!==de[2])throw new e("Session output is malformed. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});let xe=de[1]==="O"?"stdout":"stderr",ve=I[xe].decode(Buffer.from(de[2]??"","base64"),{stream:!0});if(!m&&ve)c.onChunk({stream:xe,text:ve})}if(p&&B.length)throw new e("Session output continued after completion. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});if(B.length>5466)throw new e("Session output frame is too large. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id})},C=(_)=>{try{if(s===void 0)F(_)}catch(K){s=K}},G=M?Promise.resolve():n.process.followSessionCommandLogs(A,S,C,U.signal).then(()=>{if(s===void 0&&B.trim()&&!p&&!/^[OEX]/.test(B)){if(!m)c.onChunk({stream:"stderr",text:B});B=""}if(B.trim())throw new e("Session output is incomplete. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});for(let _ of["stdout","stderr"]){let K=I[_].decode();if(!m&&K)c.onChunk({stream:_,text:K})}}),V=!1;G.then(()=>{V=!0},(_)=>{s=_,V=!0});let X=Date.now();while(f===void 0)try{let _=Number(Buffer.from(await n.fs.download(L)).toString());if(!Number.isSafeInteger(_)||_<=1)throw new e("Invalid process group ID. Remote launch was not confirmed. Destroy the sandbox.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id});f=_}catch(_){if(!(_ instanceof e)||_.code!=="file_not_found"&&_.code!=="unavailable")throw _;if((await n.process.getSessionCommand(A,S)).exitCode!==void 0){f=0;break}if(Date.now()-X>1e4)throw new e("Process launch was not confirmed. No PID arrived in ten seconds. Destroy the sandbox.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id});await fe(10)}let ne=S,oe=(async()=>{try{let _;while(!0){if(b)await new Promise(()=>{});if(s!==void 0&&!D)throw s;if(D&&f)await q("KILL");let K;try{K=await n.process.getSessionCommand(A,ne)}catch(ee){if(!M||D)throw ee;if(Z(ee).code==="not_found")return{exitCode:137,signal:"SIGKILL"};await fe(1000);continue}if(s!==void 0&&!D)throw s;if(K.exitCode!==void 0){if(D)_??=Date.now();if(V||p||_!==void 0&&Date.now()-_>=1000)return{exitCode:D?null:K.exitCode,signal:D?"SIGKILL":null}}await fe(20)}}catch(_){if(f&&!M)await q("KILL");throw _}finally{m=!0,await H().catch(()=>{})}})();oe.catch(()=>{});let ie=!1;return{pid:f,wait:()=>oe,detach(){b=!0},async stop({graceMs:_}){if(ie)return;if(f)await q("TERM");if(await fe(_),f)await q("KILL");await oe,ie=!0}}}catch(O){try{if(f)await q("KILL");else if(u)await n.stop()}finally{await H()}throw O}}async function Me(n,c,h=ae,E){if(c.streaming!==!0&&c.stdin===void 0)return Oe(n,c,h,E);let A=await be(n,c,c.timeoutMs,h);if(A.pid>0)E?.();let g=await A.wait();return{exitCode:g.exitCode,timedOut:g.signal==="SIGKILL"}}var $e={"sandbox-sdk":"1"},le="sandbox-sdk-key",ge="sandbox-sdk-create",Re="code-toolbox-language",Xe=new Set([le,ge,Re]),Qe=1e4,et={small:{cpu:1,memoryMb:1024,diskGb:10},medium:{cpu:2,memoryMb:4096,diskGb:10},large:{cpu:4,memoryMb:8192,diskGb:10}};function tt(n){let c=t(n)?et[n]:n,h=c?.diskGb??10;if(!c||!Number.isInteger(c.cpu)||c.cpu<=0||!Number.isInteger(c.memoryMb)||c.memoryMb<=0||c.memoryMb%1024||!Number.isInteger(h)||h<=0)re("Size requires positive integer CPUs, whole GiB memory (memoryMb divisible by 1024), and integer diskGb");return{cpu:c.cpu,memory:c.memoryMb/1024,disk:h}}function he(n,c=!1){if(!Number.isFinite(n)||n<0||n===0&&!c)throw new e(`Timeout must be ${c?"zero or positive":"positive"}. Invalid milliseconds supplied. Use a ${c?"non-negative":"positive"} finite duration.`,{code:"invalid_argument",provider:"daytona"});return Math.ceil(n/60000)}function nt(n){if(!r(n))return{networkBlockAll:n==="none"};if(!n.allow.length)return{networkBlockAll:!0};if(n.allow.some((c)=>!/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(c)||c.length>253))re("Network allow entries must be DNS hostnames without schemes, ports, commas, or wildcards");return{networkBlockAll:!1,domainAllowList:n.allow.join(",")}}function me(n,c){let h=Date.parse(n.createdAt??"")||c;if(h===void 0||!Number.isFinite(h))throw new e("Sandbox creation time is missing. Daytona returned incomplete metadata. Refresh the sandbox metadata.",{code:"provider",provider:"daytona",sandboxId:n.id});return{id:n.id,key:n.labels[le],labels:Object.fromEntries(Object.entries(n.labels).filter(([E])=>!Xe.has(E))),createdAt:h,state:n.state==="started"?"running":n.state==="paused"?"paused":"stopped"}}async function Le(n){let c;await Promise.race([n.catch(()=>{}),new Promise((h)=>{c=setTimeout(h,Qe),c.unref?.()})]),clearTimeout(c)}async function ot(n,c){let h=!1,E=!1;return await Le((async()=>{for(let A=0;A<5&&!h;A++){for await(let g of n.list({[ge]:c})){await n.cleanup(g.id),E=!0;return}await new Promise((g)=>setTimeout(g,1000))}})()),h=!0,E}function Ne(n,c){return{path:n,type:c.isDir?"directory":c.mode?.startsWith("L")||c.mode?.startsWith("l")?"symlink":"file",size:c.size??0,modifiedAt:Date.parse(c.modifiedAt||c.modTime||"")||0}}function Pt(n={}){let c=new Set,h=(s={})=>{for(let p of Object.values(s))if(p)c.add(p)},E=new Map,A=new Map,g=new Set,L=ae,D=new Map,f=new Map,S=new Map;for(let s of[n.jwtToken,process.env.DAYTONA_JWT_TOKEN])if(s)c.add(s);let u=()=>n.baseUrl??n.apiUrl??process.env.DAYTONA_API_URL??process.env.DAYTONA_SERVER_URL??"https://app.daytona.io/api",m=()=>n.target??process.env.DAYTONA_TARGET??"us",b;function P(){if(b)return b;let s=n.apiKey??(n.jwtToken?void 0:process.env.DAYTONA_API_KEY),p=s?void 0:n.jwtToken??process.env.DAYTONA_JWT_TOKEN,I=n.organizationId??process.env.DAYTONA_ORGANIZATION_ID;if(p&&!I)throw new e("Daytona organization is missing. JWT authentication needs an organization ID. Set DAYTONA_ORGANIZATION_ID or pass organizationId.",{code:"auth",provider:"daytona"});if(!s&&!p)throw new e("Daytona API key is missing. Authentication is required. Set DAYTONA_API_KEY or pass apiKey.",{code:"auth",provider:"daytona"});return b=s?{apiKey:s}:{jwtToken:p,organizationId:I}}let{http:M,control:N,toolbox:U}=_e({baseUrl:u,credentials:P,requestTimeoutMs:n.requestTimeoutMs??30000,secrets:()=>c}),R=!1;function q(){if(R)return;if(!Number.isSafeInteger(n.snapshotTimeoutMs??600000)||(n.snapshotTimeoutMs??600000)<=0||(n.snapshotTimeoutMs??600000)>900000)throw new e("snapshotTimeoutMs must be an integer from 1 to 900000.",{code:"invalid_argument",provider:"daytona"});if(n.createTimeoutMs!==void 0&&(!Number.isSafeInteger(n.createTimeoutMs)||n.createTimeoutMs<=0))throw new e("createTimeoutMs must be a positive integer.",{code:"invalid_argument",provider:"daytona"});P(),R=!0}let H={package:"@daytonaio/sdk",async connect(s,p){let{apiKey:I,jwtToken:F,organizationId:C}=P(),G=v(s,"Daytona",[{...I?{apiKey:I}:{jwtToken:F,organizationId:C},apiUrl:u(),target:m()}],"@daytonaio/sdk");return p===void 0?G:T(await k(G,"get",[p],"@daytonaio/sdk"),"Daytona.get","@daytonaio/sdk")}};async function O(s,p,I=!1,F=I?"files":"request"){try{return q(),await s()}catch(C){throw Z(C,p,I,F,n.apiKey??process.env.DAYTONA_API_KEY,c)}}async function j(s){let p=E.get(s);if(p)return p;let I=await N.get(s);return E.set(s,I),g.add(s),I}let z=(s,p)=>O(async()=>(await j(s),p(U(s))),s,!0),B={name:"daytona",inlineActivity:!0,keyMode:"best-effort",capabilities:new Set(["snapshot","size","network-policy"]),api:w({http:M,placeholder:"sandboxId",sdk:H}),async create(s){return h(s.env),O(async()=>{if(n.image&&n.snapshot)re("Choose either image or snapshot");let p=s.from===void 0?n.image:void 0,I=s.size===void 0?void 0:tt(s.size);if(s.timeoutMs!==void 0&&(s.timeoutMs<60000||!Number.isFinite(s.timeoutMs)))re("Daytona hard lifetime must be at least one minute");let F=crypto.randomUUID(),C={...s.labels,...$e};if(delete C[le],s.key!==void 0)C[le]=s.key;C[ge]=F,C[Re]="python";let G=p?void 0:s.from??n.snapshot??(I?.cpu===4&&I.memory===8&&I.disk===10?"daytona-large":void 0),V=p?I:void 0,X={snapshot:G,buildInfo:p?{dockerfileContent:`FROM ${p}
|
|
90
|
+
`}:void 0,cpu:V?.cpu,memory:V?.memory,disk:V?.disk,env:s.env??{},labels:C,public:n.public??!1,target:m(),...nt(s.network),autoStopInterval:s.idleTimeoutMs===void 0?void 0:he(s.idleTimeoutMs),autoPauseInterval:0,autoArchiveInterval:n.autoArchiveMs===void 0?void 0:he(n.autoArchiveMs),autoDeleteInterval:n.autoDeleteMs===void 0?void 0:he(n.autoDeleteMs,!0),volumes:n.volumes,outboundProxyUrl:n.outboundProxyUrl,ttlMinutes:s.timeoutMs===void 0?void 0:Math.floor(s.timeoutMs/60000)},ne=Date.now(),oe=n.createTimeoutMs??60000,ie=d(oe),_;try{_=await N.create(X,ie)}catch(K){if(!(K instanceof e)||K.code!=="outcome_unknown"||!await ot(N,F))throw K;throw new e(`Sandbox creation did not answer within ${Math.ceil(oe/1000)} seconds. The sandbox it made was deleted. Retry, or raise createTimeoutMs.`,{code:"timeout",provider:"daytona",retryable:!0})}try{if(_.state!=="started")try{_=await N.waitFor(_.id,(K)=>K==="started",d(ie.remaining(),s.signal),"start")??_}catch(K){if(!(K instanceof e)||K.code!=="timeout")throw K;throw new e(`Sandbox did not start within ${Math.ceil(oe/1000)} seconds. It was deleted. Retry, or raise createTimeoutMs.`,{code:"timeout",provider:"daytona",sandboxId:_.id,retryable:!0})}if(s.signal?.aborted)throw new e("Creation aborted. The caller cancelled. Retry when ready.",{code:"aborted",provider:"daytona"});if(I&&!p&&(I.cpu!==_.cpu||I.memory!==_.memory||I.disk!==_.disk)){if(I.disk<(_.disk??0))re("Snapshot disk cannot shrink; choose diskGb at least as large as the snapshot");await N.stop(_.id),await N.resize(_.id,I),await N.start(_.id),_=await N.get(_.id)}return E.set(_.id,_),g.add(_.id),D.set(_.id,{expiresAt:Date.now()+30000}),me(_,ne)}catch(K){throw await Le(N.remove(_.id,!0)),E.delete(_.id),D.delete(_.id),K}},void 0,!1,s.from?"restore":"create")},async list(s){return O(async()=>{let p={...s,...$e},I=(C)=>Object.entries(p).every(([G,V])=>C.labels[G]===V),F=new Map;for await(let C of N.list(p))if(I(C)){if(!E.has(C.id))g.add(C.id);E.set(C.id,C),F.set(C.id,me(C)),D.delete(C.id)}for(let[C,G]of D){if(Date.now()>=G.expiresAt){D.delete(C);continue}let V=E.get(C);if(!V||!I(V))continue;try{let X=await N.get(C);if(D.get(C)!==G||f.has(C)||Date.now()>=G.expiresAt)continue;if(I(X))E.set(C,X),F.set(C,me(X))}catch(X){if(Z(X).code!=="not_found")throw X;D.delete(C),E.delete(C)}}return[...F.values()]},void 0,!1,"list")},async find(s){return(await B.list({[le]:s}))[0]},async connect(s){return O(async()=>{let p=await N.get(s);return E.set(s,p),g.add(s),me(p)},s,!1,"connect")},async destroy(s){let p=f.get(s);if(p)return p;let I=O(async()=>{try{await N.remove(s,!0)}catch(F){if(Z(F).code!=="not_found")throw F}finally{E.delete(s),A.delete(s),D.delete(s),g.delete(s)}},s,!1,"destroy");f.set(s,I);try{await I}finally{f.delete(s)}},exec:(s,p)=>(h(p.env),O(async()=>(await j(s),Me(U(s),p,g.has(s)?L:"",()=>g.delete(s))),s,!1,"exec")),startProcess:(s,p)=>(h(p.env),O(async()=>{await j(s);let I=await be(U(s),p,void 0,g.has(s)?L:"");if(I.pid>0)g.delete(s);let F=S.get(s);if(!F)F=new Set,S.set(s,F);return F.add(I.detach),I.wait().finally(()=>F.delete(I.detach)).catch(()=>{}),{pid:I.pid,wait:()=>O(I.wait,s,!1,"process"),stop:(C)=>O(()=>I.stop(C),s,!1,"process")}},s,!1,"process")),async close(s){for(let p of S.get(s)??[])p();S.delete(s)},files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(s,p)=>z(s,(I)=>I.fs.download(p)),write:(s,p,I,F)=>z(s,async(C)=>{let G=F?.mode;if(!g.has(s)){if(await C.fs.upload(I,p),G!==void 0)await C.fs.setFilePermissions(p,G.toString(8));return}if((await C.process.codeRun(`import os,base64,subprocess
|
|
91
|
+
subprocess.run(["sh","-c",${JSON.stringify(L)}],check=True)
|
|
92
92
|
p=${JSON.stringify(p)}
|
|
93
93
|
os.makedirs(os.path.dirname(p),exist_ok=True)
|
|
94
|
-
fd=os.open(p,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,${
|
|
95
|
-
os.fchmod(fd,${
|
|
96
|
-
with os.fdopen(fd,"wb") as f: f.write(base64.b64decode(${JSON.stringify(Buffer.from(
|
|
94
|
+
fd=os.open(p,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,${G??438})${G===void 0?"":`
|
|
95
|
+
os.fchmod(fd,${G})`}
|
|
96
|
+
with os.fdopen(fd,"wb") as f: f.write(base64.b64decode(${JSON.stringify(Buffer.from(I).toString("base64"))}))`,120)).exitCode!==0)throw new e("File write failed. Workspace setup or the native code operation failed. Check guest permissions.",{code:"provider",provider:"daytona",sandboxId:s});g.delete(s)}),list:(s,p)=>z(s,async(I)=>{try{return(await I.fs.listFiles(p)).map((F)=>Ne(We.join(p,F.name),F))}catch(F){if(p!=="/workspace"||!g.has(s)||Z(F,s,!0).code!=="file_not_found")throw F;return[]}}),stat:(s,p)=>z(s,async(I)=>{try{return Ne(p,await I.fs.getFileDetails(p))}catch(F){if(p!=="/workspace"||!g.has(s)||Z(F,s,!0).code!=="file_not_found")throw F;return{path:p,type:"directory",size:0,modifiedAt:Date.parse(E.get(s)?.createdAt??"")||Date.now()}}}),remove:(s,p,I)=>z(s,async(F)=>{try{await F.fs.deleteFile(p,I.recursive)}catch(C){if(p!=="/workspace"||!g.has(s)||Z(C,s,!0).code!=="file_not_found")throw C}if(p==="/workspace")g.delete(s)}),mkdir:(s,p)=>z(s,async(I)=>{if(!g.has(s))return I.fs.createFolder(p,"755");if((await I.process.executeCommand(`${L} && mkdir -p ${Y(p)}`,"/",void 0,10)).exitCode!==0)throw new e("Directory creation failed. Check guest permissions.",{code:"provider",provider:"daytona",sandboxId:s});g.delete(s)})},previewUrl:(s,p)=>O(async()=>{let I=await j(s),F=await N.previewLink(s,p),C={url:F.url};if(!I.public)C.headers={"X-Daytona-Preview-Token":F.token};return C},s,!1,"preview"),snapshot:(s,p)=>O(async()=>{if(p?.expiresInMs)re("Snapshot expiry is unavailable; Daytona keeps snapshots until you delete them. Omit expiresInMs, or pass 0");let I=`sdk-${crypto.randomUUID()}`;await j(s);try{await N.snapshot(s,I,n.snapshotTimeoutMs??600000)}catch(F){let C=Z(F,s,!1,"snapshot",n.apiKey??process.env.DAYTONA_API_KEY,c);throw new e(`Snapshot ${I} did not complete. It may still be creating. Inspect or delete this name with the native snapshot API before retrying.`,{code:C.code,cause:C.cause,provider:"daytona",sandboxId:s,retryable:!1,hint:`Recover snapshot ${I} from source sandbox ${s}.`})}return{id:I}},s,!1,"snapshot"),native(s){if(!E.has(s))throw new e("Sandbox is not connected. No local native object exists. Connect the sandbox first.",{code:"not_found",provider:"daytona",sandboxId:s});let p=A.get(s);if(!p)p=w({http:M,placeholder:"sandboxId",sandboxId:s,sdk:H}),A.set(s,p);return p}};return B}export{Pt as daytona};
|