@opencoredev/sandbox-sdk 1.0.2 → 1.1.0
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 +23 -0
- package/README.md +9 -6
- package/dist/ai.js +1 -1
- package/dist/chunk-0eeyc0aq.js +4 -0
- package/dist/chunk-0wp6x4wb.js +2 -0
- package/dist/chunk-2999xbh7.js +2 -0
- package/dist/chunk-3h6c1ack.js +2 -0
- package/dist/{chunk-q5vqajhg.js → chunk-7rkcx5cx.js} +2 -2
- package/dist/{chunk-hzbssbep.js → chunk-7s9pxk1v.js} +4 -4
- package/dist/chunk-aek8n3a4.js +78 -0
- package/dist/{chunk-8786zrns.js → chunk-aq6fmgdx.js} +2 -2
- package/dist/chunk-drhcb2hx.js +2 -0
- package/dist/chunk-ek44atpe.js +2 -0
- package/dist/chunk-g5n5xcmp.js +0 -0
- package/dist/chunk-kdecey83.js +290 -0
- package/dist/{chunk-bd481sb7.js → chunk-pdgnaxp9.js} +2 -2
- package/dist/{chunk-k60b4r27.js → chunk-qfhee1t8.js} +2 -2
- package/dist/chunk-rx9318sh.js +5 -0
- package/dist/chunk-sjnk17y5.js +26 -0
- package/dist/chunk-w8nk1xf2.js +17 -0
- package/dist/{chunk-bfzdkjjw.js → chunk-x05t86n3.js} +2 -2
- package/dist/{chunk-nw845a93.js → chunk-x4rrgmxf.js} +10 -10
- package/dist/chunk-xqtzts2q.js +1 -0
- package/dist/errors.d.ts +19 -9
- package/dist/files.d.ts +2 -5
- package/dist/http.d.ts +3 -0
- package/dist/index.d.ts +24 -3
- 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 +127 -7
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/baseten/errors.d.ts +6 -0
- package/dist/providers/baseten/execute.d.ts +68 -0
- package/dist/providers/baseten/index.d.ts +3 -0
- package/dist/providers/baseten/index.js +97 -0
- package/dist/providers/baseten/provider.d.ts +39 -0
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/errors.d.ts +25 -3
- package/dist/providers/boxd/index.js +14 -14
- package/dist/providers/boxd/provider.d.ts +16 -2
- package/dist/providers/daytona/api.d.ts +2 -2
- package/dist/providers/daytona/index.js +15 -15
- package/dist/providers/e2b/envd.d.ts +32 -2
- package/dist/providers/e2b/errors.d.ts +1 -2
- package/dist/providers/e2b/index.d.ts +40 -4
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/e2b/narrow.d.ts +7 -0
- package/dist/providers/freestyle/execute.d.ts +3 -1
- package/dist/providers/freestyle/index.js +7 -16
- package/dist/providers/instabox/api.d.ts +56 -0
- package/dist/providers/instabox/errors.d.ts +49 -0
- package/dist/providers/instabox/index.d.ts +4 -0
- package/dist/providers/instabox/index.js +7 -0
- package/dist/providers/instabox/provider.d.ts +28 -0
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/modal/errors.d.ts +4 -0
- package/dist/providers/modal/index.d.ts +14 -0
- package/dist/providers/modal/index.js +2 -0
- package/dist/providers/modal/provider.d.ts +94 -0
- package/dist/providers/modal/transport.d.ts +50 -0
- 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 +22 -24
- package/dist/providers/tenki/deadline.d.ts +1 -1
- package/dist/providers/tenki/index.js +16 -26
- package/dist/providers/tenki/provider.d.ts +12 -12
- package/dist/providers/tenki/records.d.ts +1 -1
- package/dist/providers/upstash/index.js +11 -11
- package/dist/providers/upstash/provider.d.ts +1 -1
- package/dist/providers/vercel/index.js +1 -1
- package/dist/providers/vercel/transport.d.ts +1 -1
- package/dist/run.d.ts +9 -0
- package/dist/shared/guest.d.ts +28 -1
- package/dist/shared/native-error.d.ts +2 -0
- package/dist/streams.d.ts +2 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +37 -14
- package/dist/version.d.ts +4 -0
- package/package.json +28 -4
- package/dist/chunk-23tjmd39.js +0 -8
- package/dist/chunk-6a3wkj84.js +0 -2
- package/dist/chunk-8wq767xb.js +0 -17
- package/dist/chunk-9w9rddra.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-vz47a139.js +0 -5
- package/dist/chunk-x681p5d2.js +0 -68
- package/dist/chunk-xgxfy2n8.js +0 -4
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import{m,R,g,C,_}from"../../chunk-kdecey83.js";import{h}from"../../chunk-qfhee1t8.js";import{t,o,r,e,i,a,F}from"../../chunk-0eeyc0aq.js";import{createHash as me}from"node:crypto";function p(s,b="provider",w){return new e(b==="auth"||b==="file_not_found"?s:`${s}. Check Baseten and retry.`,{code:b,provider:"baseten",sandboxId:w})}function K(s){if(!(s instanceof Error)||!r(s)||!("status"in s))return;return o(s.status)?s.status:void 0}function S(s,b){if(s instanceof e)return s;let w=K(s),k=s instanceof Error?s.name:void 0,y=w!==void 0?F(w):k==="AbortError"?"aborted":k==="SandboxProcessWaitTimeoutError"?"timeout":s instanceof TypeError?"unavailable":"provider",E=i(s,{code:y,known:!0,status:w===void 0?void 0:`HTTP ${w}`});return new e(`Baseten request failed: ${a(y,E.detail)}. Check Baseten and retry.`,{code:y,provider:"baseten",sandboxId:b,cause:E.cause})}var ne=`def alive(g):
|
|
2
|
+
for name in os.listdir('/proc'):
|
|
3
|
+
if not name.isdigit(): continue
|
|
4
|
+
try:
|
|
5
|
+
with open('/proc/'+name+'/stat') as f: fields=f.read().rsplit(')',1)[1].split()
|
|
6
|
+
if int(fields[2])==g and fields[0]!='Z': return True
|
|
7
|
+
except (FileNotFoundError,ProcessLookupError,IndexError,ValueError): pass
|
|
8
|
+
return False`,ce=`import os,sys,json,fcntl,select,time,base64,_signal as signal
|
|
9
|
+
${g}
|
|
10
|
+
${C}
|
|
11
|
+
f=os.environ.pop('SANDBOX_SDK_SPEC_FILE',None)
|
|
12
|
+
if f:
|
|
13
|
+
with open(f) as h: v=json.load(h)
|
|
14
|
+
os.unlink(f)
|
|
15
|
+
else: v=json.loads(os.environ.pop('SANDBOX_SDK_SPEC'))
|
|
16
|
+
out=sys.stdout.buffer
|
|
17
|
+
${ne}
|
|
18
|
+
def sweep(m):
|
|
19
|
+
# Removes records whose group has no live member left, under each record's lock so it never
|
|
20
|
+
# races a launcher spawning or a kill program reading. Runs only when this launcher keeps its
|
|
21
|
+
# own record, so at most one stale record per background-leaving command waits for the next.
|
|
22
|
+
d=os.path.dirname(m)
|
|
23
|
+
for name in os.listdir(d):
|
|
24
|
+
q=os.path.join(d,name)
|
|
25
|
+
if q==m or not name.startswith('exec-') or not name.endswith('.pid'): continue
|
|
26
|
+
try:
|
|
27
|
+
with open(q+'.lock','a') as lock:
|
|
28
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
29
|
+
if not os.path.exists(q):
|
|
30
|
+
os.unlink(q+'.lock'); continue
|
|
31
|
+
with open(q) as h: g=int(h.read())
|
|
32
|
+
if not alive(g):
|
|
33
|
+
for r in [q,q+'.lock']:
|
|
34
|
+
try: os.unlink(r)
|
|
35
|
+
except FileNotFoundError: pass
|
|
36
|
+
except (OSError,ValueError): pass
|
|
37
|
+
def emit(s,d):
|
|
38
|
+
out.write(b'O' if s=='stdout' else b'E'); out.write(base64.b64encode(d)); out.write(b'.'); out.flush()
|
|
39
|
+
a=v.get('activityPath')
|
|
40
|
+
m=v['pidPath']
|
|
41
|
+
os.makedirs(os.path.dirname(m),exist_ok=True)
|
|
42
|
+
with stdin_file() as i:
|
|
43
|
+
i.write(v.get('stdin','').encode()); i.seek(0)
|
|
44
|
+
with open(m+'.lock','a') as lock:
|
|
45
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
46
|
+
if os.path.exists(m+'.cancel'): out.write(b'T.'); out.flush(); sys.exit(0)
|
|
47
|
+
if a:
|
|
48
|
+
os.makedirs(os.path.dirname(a),exist_ok=True)
|
|
49
|
+
with open(a,'w') as h: h.write('1')
|
|
50
|
+
try: p=Process(v,{**os.environ,**v['env']},i,True)
|
|
51
|
+
except OSError as e:
|
|
52
|
+
if a:
|
|
53
|
+
try: os.unlink(a)
|
|
54
|
+
except FileNotFoundError: pass
|
|
55
|
+
emit('stderr',(str(e)+'\\n').encode()); out.write(b'X127.'); out.flush(); sys.exit(0)
|
|
56
|
+
with open(m,'w') as h: h.write(str(p.pid))
|
|
57
|
+
try:
|
|
58
|
+
timed=pump(p,emit,time.monotonic()+v['timeoutMs']/1000)
|
|
59
|
+
code=p.wait()
|
|
60
|
+
finally:
|
|
61
|
+
# A background child with its output redirected can outlive the shell and its pipes.
|
|
62
|
+
# Keep the pid record while any live member of the group remains, so a later abort
|
|
63
|
+
# still finds and kills it. Baseten's PID 1 never reaps, so zombies do not count.
|
|
64
|
+
g=p.pid
|
|
65
|
+
if alive(g): sweep(m)
|
|
66
|
+
else:
|
|
67
|
+
for q in [m,m+'.lock']:
|
|
68
|
+
try: os.unlink(q)
|
|
69
|
+
except FileNotFoundError: pass
|
|
70
|
+
if a:
|
|
71
|
+
try: os.unlink(a)
|
|
72
|
+
except FileNotFoundError: pass
|
|
73
|
+
if timed: out.write(b'T.')
|
|
74
|
+
else: out.write(b'X'+str(code if code>=0 else 128-code).encode()+b'.')
|
|
75
|
+
out.flush()
|
|
76
|
+
`,ue=m(R(ce)),le=`import os,sys,signal,time,fcntl
|
|
77
|
+
p=sys.argv[1]
|
|
78
|
+
os.makedirs(os.path.dirname(p),exist_ok=True)
|
|
79
|
+
with open(p+'.lock','a') as lock:
|
|
80
|
+
fcntl.flock(lock,fcntl.LOCK_EX)
|
|
81
|
+
with open(p+'.cancel','w') as f: f.write('1')
|
|
82
|
+
try:
|
|
83
|
+
with open(p) as f: pgid=int(f.read())
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
print('confirmed'); sys.exit(0)
|
|
86
|
+
try: os.killpg(pgid,signal.SIGKILL)
|
|
87
|
+
except ProcessLookupError: pass
|
|
88
|
+
${ne}
|
|
89
|
+
end=time.monotonic()+2
|
|
90
|
+
while time.monotonic()<end:
|
|
91
|
+
if not alive(pgid):
|
|
92
|
+
for q in [p,p+'.cancel']:
|
|
93
|
+
try: os.unlink(q)
|
|
94
|
+
except FileNotFoundError: pass
|
|
95
|
+
print('confirmed'); sys.exit(0)
|
|
96
|
+
time.sleep(.01)
|
|
97
|
+
sys.exit(1)`,fe=98304;class oe{#e="";push(s){let b=[];this.#e+=s.replace(/\n/g,"");let w=this.#e.indexOf(".");while(w!==-1){let k=this.#e.slice(0,w);this.#e=this.#e.slice(w+1);let y=k[0],E=k.slice(1);if(y==="O"||y==="E")b.push({kind:"output",stream:y==="O"?"stdout":"stderr",bytes:Buffer.from(E,"base64")});else if(y==="T"&&E==="")b.push({kind:"timeout"});else if(y==="X"&&/^\d{1,3}$/.test(E))b.push({kind:"exit",code:Number(E)});else throw p("Baseten command output was malformed","provider");w=this.#e.indexOf(".")}return b}get empty(){return this.#e===""}}var M={exitCode:null,timedOut:!0};async function re({processes:s,sandboxId:b,input:w,uploadSpec:k,removeSpec:y}){if(w.signal?.aborted)return M;let E=`/tmp/.sandbox-sdk/exec-${crypto.randomUUID()}.pid`,q=JSON.stringify({pidPath:E,command:w.command,cwd:w.cwd,env:w.env,stdin:w.stdin??"",timeoutMs:w.timeoutMs,activityPath:w.activityPath}),B=new AbortController,I=new oe,O={stdout:new TextDecoder,stderr:new TextDecoder},j=!1,A,N=!1,T=!1,L,G=()=>{T=!0,B.abort()},n=async()=>{try{let d=await s.exec({command:m(le,E),waitForCompletion:!0,timeoutMs:1e4});return d.exitCode===0&&d.stdout.trim()==="confirmed"}catch{return!1}},c=()=>p("Process termination could not be confirmed","outcome_unknown",b);w.signal?.addEventListener("abort",G,{once:!0});try{let d;if(Buffer.byteLength(q,"utf8")>fe){let f=AbortSignal.any([B.signal,AbortSignal.timeout(w.timeoutMs+5000)]);try{d=await k(q,f)}catch(v){if(T)return M;if(f.aborted)throw p("Uploading the command's input timed out","timeout",b);throw v}if(T)return await y(d).catch(()=>{}),M}if(T)return M;L=setTimeout(G,w.timeoutMs+5000);let u=!1;try{for await(let f of s.execStream({command:ue,workingDir:"/",env:d===void 0?{SANDBOX_SDK_SPEC:q}:{SANDBOX_SDK_SPEC_FILE:d},timeoutMs:0,callOptions:{signal:B.signal}})){if(f.type==="exit"){if(f.process.exitCode!==0)N=!0;break}if(f.stream==="stderr"){N=!0;continue}for(let v of I.push(f.text))if(v.kind==="output"){let V=O[v.stream].decode(v.bytes,{stream:!0});if(V)w.onChunk({stream:v.stream,text:V})}else if(v.kind==="timeout")j=!0;else A=v.code}}catch{if(!T)u=!0}let l=async()=>{if(d!==void 0)await y(d).catch(()=>{})};if(T||u){if(!await n())throw c();if(await l(),u)throw p("Baseten command stream broke; the command was stopped and its outcome is unknown","outcome_unknown",b);return M}for(let f of["stdout","stderr"]){let v=O[f].decode();if(v)w.onChunk({stream:f,text:v})}if(j)return M;if(A===void 0||N||!I.empty){if(!await n())throw c();throw await l(),p("Baseten command launcher failed; the sandbox needs python3","provider",b)}return{exitCode:A,timedOut:!1}}finally{clearTimeout(L),w.signal?.removeEventListener("abort",G)}}var U="sbxsdk-",H=2048;function pe(s){if(s===void 0)return;if(t(s))return{small:2048,medium:4096,large:8192}[s];if(![1,2,4].includes(s.cpu)||s.memoryMb!==s.cpu*H)throw p(`Baseten sets CPU from memory; the sizes known to match are 1 vCPU / ${H} MiB, 2 / ${2*H} and 4 / ${4*H}`,"unsupported");if(s.diskGb!==void 0)throw p("Baseten keeps files in memory and has no disk size option","unsupported");return s.memoryMb}var J=(s)=>`${s}-v`,ie=(s)=>new Promise((b)=>setTimeout(b,s));function ae(s){return`${U}k${me("sha256").update(s).digest("hex").slice(0,40)}`}function we(s){let b=[];if(s.timeoutMs!==void 0)b.push({type:"TTL_MAX_AGE",afterMs:s.timeoutMs});if(s.idleTimeoutMs!==void 0)b.push({type:"TTL_IDLE",afterMs:s.idleTimeoutMs});return b.length?{expirationPolicies:b}:void 0}var Z=new Set(["FAILED","DELETING","TERMINATED","DEACTIVATING"]);function he(s){if(Z.has(s))return;if(["DEACTIVATED","ARCHIVING","ARCHIVED"].includes(s))return"paused";return"running"}var Q="sandbox-sdk-attempt";function Y(s){if(!s.name.startsWith(U))return;let b=he(s.status);if(b===void 0)return;let{[Q]:w,...k}=s.labels;return{id:s.name,key:s.externalId||void 0,labels:k,state:b,createdAt:s.createdAt.getTime()}}function be(s,b){return Object.entries(b).every(([w,k])=>s.labels[w]===k)}var ye="import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); sys.stdout.write(base64.b64encode(f.read(int(sys.argv[3]))).decode())";function se(s,b){let w,k,y=new Map,E=new Set;async function q(n,c){let d=y.get(c);if(d)return d.previews;let u;try{u=await n.getInfo({name:c})}catch(l){if(S(l,c).code!=="not_found")throw l;u={name:c,status:"TERMINATED",envs:{},labels:{},ports:[],volumes:[],createdAt:new Date(0)}}return(await n.get({info:{...u,url:u.url??"https://pending.invalid"}})).previews}async function B(){return w??=(async()=>{let n=s.apiKey??process.env.BASETEN_API_KEY;if(!n?.trim())throw p("Baseten API key is missing. Authentication is required. Set BASETEN_API_KEY or pass apiKey.","auth");let{SandboxClient:c}=await h("@basetenlabs/sandbox","baseten",b),d={apiKey:n,teamId:s.teamId};if(!t(import.meta.url))d.nodeUndici=!1;return k=new c(d)})()}async function I(n,c){try{return await c()}catch(d){throw S(d,n)}}async function O(n){let c=y.get(n);if(c)return c;let d=await B(),u=await d.getInfo({name:n});if(!Y(u))throw p("Sandbox not found","not_found",n);let l=await N(d,u),f=await d.get({info:l});return y.set(n,f),f}async function j(n){let c=await O(n);return{name:"baseten",raw:async(d)=>{let u=await c.process.exec({command:d,waitForCompletion:!0,timeoutMs:60000});if(u.exitCode!==0)throw p("Guest operation failed","provider",n);return u.stdout},upload:async(d,u)=>{await c.fs.writeBytes({path:d,content:u})},read:async(d,u)=>{if(!u)try{return await c.fs.readBytes({path:d})}catch(f){let v=S(f,n);if(v.code==="not_found")throw p("File does not exist","file_not_found",n);if(!(f instanceof Error&&f.message.endsWith("is a directory, not a file")))throw v}let l=await c.process.exec({command:m(ye,d,String(u?.offset??0),String(u?.length??-1)),waitForCompletion:!0,timeoutMs:60000});if(l.exitCode!==0)throw p("File does not exist","file_not_found",n);return new Uint8Array(Buffer.from(l.stdout,"base64"))}}}async function A(n){try{let c=await B(),d=await c.getInfo({name:n}),u=Y(d);if(u&&d.url)y.set(n,await c.get({info:d}));return u}catch(c){if(S(c,n).code==="not_found")return;throw c}}async function N(n,c){let d=Date.now()+(s.readyTimeoutMs??120000),u=c;while(u.status!=="DEPLOYED"||!u.url){if(Z.has(u.status))throw p(`Sandbox did not deploy (${u.status})`,"provider",c.name);if(Date.now()>d)throw p("Sandbox did not deploy in time","timeout");await new Promise((l)=>setTimeout(l,250)),u=await n.getInfo({name:c.name})}return u}async function T(n,c,d){let u=Date.now()+(s.readyTimeoutMs??120000),l=c;while(l.status!=="DEPLOYED"){if(["FAILED","DELETING"].includes(l.status))throw p(`Volume did not deploy (${l.status})`);if(Date.now()>u)throw p("Volume did not deploy in time","timeout");if(d?.aborted)throw p("Creation aborted","aborted");await ie(250),l=await n.volumes.getInfo({name:c.name})}return l}async function L(n,c){let d=Date.now()+120000;for(;;){try{return await n.volumes.delete({name:c}),!0}catch(u){let{code:l}=S(u);if(l==="not_found")return!0;if(!(K(u)===409||(K(u)??0)>=500||["unavailable","timeout"].includes(l))||Date.now()>d)return!1}await ie(1000)}}return{name:"baseten",keyMode:"exact",inlineActivity:!0,capabilities:new Set(["size"]),create:(n)=>I(void 0,async()=>{if(n.from!==void 0)throw p("Baseten adapter has no snapshot restore","unsupported");if(n.network!==void 0&&n.network!=="all")throw p("Baseten adapter has no network policy","unsupported");if(s.volume&&n.key!==void 0)throw p("Baseten volumes cannot be combined with a key","unsupported");let c=pe(n.size);if(n.signal?.aborted)throw p("Creation aborted","aborted");let d=await B(),u=crypto.randomUUID(),l=n.key===void 0?`${U}${crypto.randomUUID()}`:ae(n.key),f;if(s.volume){let x=J(l);try{f=await T(d,await d.volumes.create({name:x,size:`${s.volume.sizeGiB}Gi`,region:s.region,callOptions:{signal:n.signal}}),n.signal)}catch(P){if(!await L(d,x))throw p(`Volume ${x} may exist and could not be deleted; delete it before retrying`,"outcome_unknown");throw S(P)}}let v=async(x)=>{if(f&&!await L(d,f.name))return p(`Sandbox creation failed and volume ${f.name} could not be deleted; delete it`,"outcome_unknown");return x},V={name:l,image:s.image,memory:c,region:f?.region??s.region,envs:Object.fromEntries(Object.entries(n.env??{}).map(([x,P])=>[x,{value:P,secret:!0}])),labels:{...n.labels,[Q]:u},externalId:n.key,lifecycle:we(n),callOptions:{signal:n.signal}};if(f&&s.volume)V.volumes=[{name:f.name,mountPath:s.volume.mountPath}];let X,W;try{W=await d.create(V),X=W.info}catch(x){let P=S(x);if(K(x)===void 0||["unavailable","timeout"].includes(P.code)){let D=await d.getInfo({name:l}).catch((te)=>{if(S(te).code==="not_found")return;throw p(`Sandbox creation outcome is unknown; delete ${l}${f?` and volume ${f.name}`:""} if they exist before retrying`,"outcome_unknown")}),z=D?.labels[Q],ee=P.code==="aborted"||n.signal?.aborted===!0;if(D&&z===u&&!ee&&!Z.has(D.status))X=D;else{if(!(D===void 0||z!==void 0&&(z!==u||await d.delete({name:l}).then(()=>!0,(de)=>S(de).code==="not_found"))))throw p(`Sandbox creation outcome is unknown; delete ${l}${f?` and volume ${f.name}`:""} if they exist before retrying`,"outcome_unknown");throw await v(ee?p("Creation aborted","aborted"):P)}}else throw await v(P)}try{let x=await N(d,X);y.set(x.name,W&&x===X?W:await d.get({info:x}));let P=Y(x);if(!P)throw p("Created sandbox is not usable","provider",x.name);if(!f)E.add(x.name);return P}catch(x){if(y.delete(l),!await d.delete({name:l}).then(()=>!0,(D)=>S(D).code==="not_found"))throw p(`Sandbox ${l} did not become usable and could not be deleted; delete it${f?` and volume ${f.name}`:""} before retrying`,"outcome_unknown",l);throw await v(S(x,l))}}),find:(n)=>I(void 0,()=>A(ae(n))),connect:(n)=>I(n,async()=>{if(!n.startsWith(U))throw p("Not an SDK sandbox","not_found",n);let c=await A(n);if(!c)throw p("Sandbox not found","not_found",n);return c}),list:(n)=>I(void 0,async()=>{let c=[];for await(let d of(await B()).list({}))if(d.name.startsWith(U)){let u=Y(d);if(u&&be(u,n))c.push(u)}return c}),destroy:(n)=>I(n,async()=>{let c=await B();try{let d=await q(c,n);for await(let u of d.list())try{await d.delete({name:u.name})}catch(l){if(S(l,n).code!=="not_found")throw l}}catch(d){if(S(d,n).code!=="not_found")throw d}try{await c.delete({name:n})}catch(d){if(S(d,n).code!=="not_found")throw d}if(y.delete(n),!E.has(n)&&!await L(c,J(n)))throw p(`Volume ${J(n)} could not be deleted; delete it`,"provider",n);E.delete(n)}),async close(n){y.delete(n)},exec:(n,c)=>I(n,async()=>{let d=await O(n);return re({processes:d.process,sandboxId:n,input:c,uploadSpec:async(u,l)=>{let f=`/tmp/.sandbox-sdk/spec-${crypto.randomUUID()}.json`;return await d.fs.writeBytes({path:f,content:new TextEncoder().encode(u),callOptions:{signal:l}}),f},removeSpec:async(u)=>{await d.fs.remove({path:u})}})}),files:_(j,I),previewUrl:(n,c)=>I(n,async()=>({url:(await(await O(n)).previews.create({port:c,name:`port-${c}`,createIfNotExists:!0,public:!0})).url})),native(n){let c=y.get(n);if(!c)throw p("Connect the sandbox first","not_found",n);if(!k)throw p("Client is detached","not_found",n);return{sandbox:c,client:k}}}}function Ae(s={}){return se(s,()=>import("@basetenlabs/sandbox"))}export{Ae as baseten};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Sandbox, SandboxClient, SandboxClientOptions } from "@basetenlabs/sandbox";
|
|
2
|
+
import type { Provider } from "../../provider.js";
|
|
3
|
+
export interface BasetenOptions {
|
|
4
|
+
/** Defaults to BASETEN_API_KEY. */
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
/** Team to act in. Unset uses the key's only team. */
|
|
7
|
+
teamId?: string;
|
|
8
|
+
/** Image reference with its tag. Defaults to Baseten's `baseten/base-image:latest`. */
|
|
9
|
+
image?: string;
|
|
10
|
+
/** Region to run in. Unset lets Baseten pick the closest. */
|
|
11
|
+
region?: string;
|
|
12
|
+
/** How long create waits for a sandbox (and its volume) to deploy. Default: 120 s. */
|
|
13
|
+
readyTimeoutMs?: number;
|
|
14
|
+
/**
|
|
15
|
+
* A persistent volume made for each sandbox, mounted at `mountPath` and deleted with the
|
|
16
|
+
* sandbox. Baseten holds a sandbox's files in its memory, so a large workspace competes with
|
|
17
|
+
* processes for RAM; a volume puts those files on disk. Not available with `key`.
|
|
18
|
+
*/
|
|
19
|
+
volume?: BasetenVolume;
|
|
20
|
+
}
|
|
21
|
+
export interface BasetenVolume {
|
|
22
|
+
/** Whole GiB. Baseten caps the size per account (8 GiB on the bench's account, 2026-11-16). */
|
|
23
|
+
sizeGiB: number;
|
|
24
|
+
/** Absolute path the volume is mounted at. */
|
|
25
|
+
mountPath: string;
|
|
26
|
+
}
|
|
27
|
+
export interface BasetenNative {
|
|
28
|
+
sandbox: Sandbox;
|
|
29
|
+
client: SandboxClient;
|
|
30
|
+
}
|
|
31
|
+
type BasetenCapability = "size";
|
|
32
|
+
export type BasetenProvider = Provider<BasetenNative, BasetenCapability>;
|
|
33
|
+
/** The `@basetenlabs/sandbox` module, or a test fixture with the same shape. */
|
|
34
|
+
export interface BasetenModule {
|
|
35
|
+
SandboxClient: new (options: SandboxClientOptions) => SandboxClient;
|
|
36
|
+
}
|
|
37
|
+
/** @internal The adapter behind `baseten()`. `load` imports the Baseten SDK; tests pass a fixture. */
|
|
38
|
+
export declare function createBasetenProvider(options: BasetenOptions, load: () => Promise<BasetenModule>): BasetenProvider;
|
|
39
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-
|
|
1
|
+
import"../../chunk-sjnk17y5.js";import{Y}from"../../chunk-rx9318sh.js";function o(e={}){return Y(e).provider}export{o as boat};
|
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
import { SandboxError, type ErrorCode } from "../../errors.js";
|
|
2
|
-
export declare function failure(message: string, code?: ErrorCode, sandboxId?: string, cause?:
|
|
3
|
-
|
|
1
|
+
import { SandboxError, type ErrorCode, type NativeEvidence } from "../../errors.js";
|
|
2
|
+
export declare function failure(message: string, code?: ErrorCode, sandboxId?: string, cause?: unknown): SandboxError;
|
|
3
|
+
/**
|
|
4
|
+
* The boxd control-plane calls the adapter names in a failure's evidence. Their errors name
|
|
5
|
+
* machines and snapshots, never guest paths, so boxd's own message is kept for them.
|
|
6
|
+
*/
|
|
7
|
+
export type BoxdCall = "machines.create" | "machines.waitUntilReady" | "machines.get" | "machines.list" | "machines.delete" | "machines.pause" | "machines.resume" | "machines.setEgressAllow" | "machines.proxies" | "snapshots.create" | "snapshots.get" | "snapshots.delete";
|
|
8
|
+
/** Where a failure happened. */
|
|
9
|
+
export interface BoxdContext {
|
|
10
|
+
/** The sandbox the error belongs to. Never set while creating: an ID on a failed create claims ownership. */
|
|
11
|
+
sandboxId?: string;
|
|
12
|
+
/** The control-plane call that failed. */
|
|
13
|
+
call?: BoxdCall;
|
|
14
|
+
/** The machine that call touched, for evidence only; defaults to `sandboxId`. */
|
|
15
|
+
machineId?: string;
|
|
16
|
+
}
|
|
17
|
+
/** boxd's evidence: the shared fields, plus the machine a failed call touched. */
|
|
18
|
+
export type BoxdEvidence = NativeEvidence & {
|
|
19
|
+
machineId?: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Maps a boxd failure to a SandboxError with evidence in its cause. `secrets` are values to redact
|
|
23
|
+
* besides `BOXD_API_KEY`, such as an `apiKey` passed to the provider.
|
|
24
|
+
*/
|
|
25
|
+
export declare function boxdError(cause: unknown, context?: BoxdContext, secrets?: readonly (string | undefined)[]): SandboxError;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{
|
|
2
|
-
${
|
|
1
|
+
import{m,R,g,_}from"../../chunk-kdecey83.js";import{j}from"../../chunk-7rkcx5cx.js";import{u}from"../../chunk-pdgnaxp9.js";import{h}from"../../chunk-qfhee1t8.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,e,I,i,T,d,a}from"../../chunk-0eeyc0aq.js";function w(s,f="provider",l,E){return new e(f==="auth"?s:f==="file_not_found"?`${s}. Check the path.`:`${s}. Check boxd configuration and retry.`,{code:f,provider:"boxd",sandboxId:l,cause:E})}var pe=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"]]),he=["OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","UNAUTHENTICATED"],oe=new Map([["AuthenticationError","auth"],["PermissionDeniedError","auth"],["NotFoundError","not_found"],["RateLimitError","quota"],["APIConnectionError","unavailable"]]),we=new Set([...oe.keys(),"BoxdError","ConflictError","APIStatusError","AgentOutdatedError","FilesystemError"]),ee=/^[A-Za-z0-9_.:-]{1,128}$/,ge=["x-request-id","x-boxd-request-id","request-id","x-trace-id","traceparent"];function ie(s){if(s.requestId!==void 0)return s.requestId;for(let f of ge){let l=s.metadata.get(f)??s.headers.get(f);if(l!==void 0)return l}return}function xe(s,f,l,E){let P=(B)=>E.some((D)=>B.includes(D)),p={};if(f.call!==void 0)p.operation=f.call;let x=f.machineId??f.sandboxId;if(f.call!==void 0&&x!==void 0&&ee.test(x))p.machineId=x;let k=s.grpcCode;if(k!==void 0){let B=he[k];if(p.providerCode=k,B!==void 0)p.providerStatus=B}if(we.has(s.name))p.nativeName=s.name;let q=s.reason??u(s.cause).reason;if(q!==void 0&&ee.test(q)&&!P(q))p.providerReason=q;let C=ie(s)??ie(u(s.cause));if(C!==void 0&&ee.test(C)&&!P(C))p.requestId=C;if(f.call!==void 0&&s.message)p.providerMessage=I(d(E)(s.message),Number.POSITIVE_INFINITY);if(l!==void 0&&!(p.providerMessage&&l.includes(p.providerMessage.slice(0,80))))p.native=l;return p}function K(s,f={},l=[]){if(s instanceof e)return s;let{sandboxId:E}=f,P=[process.env.BOXD_API_KEY,...l].filter((N)=>N!==void 0&&N!==""),p=u(s),x=p.grpcCode,k=(N,G)=>i(s,{code:N,known:G,status:x===void 0?void 0:`gRPC ${x}`,redact:d(P)}),q=(N)=>T(xe(p,f,N,P));if(p.name==="BoxdError"&&/^exec timed out after \d+ms$/.test(p.message))return w("boxd request timed out","timeout",E,q());if(/\bno such file\b/i.test(p.message))return w("File does not exist","file_not_found",E,q());let C=x===void 0?oe.get(p.name)??"provider":pe.get(x)??"provider",B=/permission denied/i.test(p.message),D=k(C,B||void 0);return w(B?"boxd guest filesystem permission denied":`boxd request failed: ${a(C,D.detail)}`,C,E,q(D.detail))}var ye=`import sys,os,fcntl,select,_signal as signal
|
|
2
|
+
${g}
|
|
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
|
+
`,be=R(ye),ve=`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 te(s,f,l,E="",P){if(l.signal?.aborted)return{exitCode:null,timedOut:!0};let p=`/tmp/sandbox-sdk-${crypto.randomUUID()}.pid`,x=s.machines.streamExec(f,{command:E+m(be)}),k=!1,q=!1,C=x.wait().then((A)=>({kind:"exit",exitCode:A}),(A)=>({kind:"error",cause:A})),B={stdout:new TextDecoder,stderr:new TextDecoder},D=!E,N="";for(let A of["stdout","stderr"])x[A].push=(z)=>{let F=B[A].decode(z,{stream:!0});if(A==="stdout"&&!D){if(N+=F,"SDK_PREPARED:".startsWith(N)&&N.length<13)return;if(N.startsWith("SDK_PREPARED:"))D=!0,P?.(),F=N.slice(13);else F=N;N=""}if(F)l.onChunk({stream:A,text:F})};let G=()=>{},V=new Promise((A)=>{G=A}),X=()=>{if(k)return;k=!0,x.close(),G()},H=setTimeout(X,l.timeoutMs);l.signal?.addEventListener("abort",X,{once:!0});try{let A={pidPath:p,preparing:E?1:0,command:l.command,cwd:l.cwd,env:l.env,stdin:l.stdin??"",activityPath:l.activityPath};x.write(JSON.stringify(A)),x.end();let z=await Promise.race([C,V.then(()=>({kind:"cancel"}))]);if(k){let F,J=await Promise.race([C.then((c)=>c.kind==="exit"&&c.exitCode>=0?!0:new Promise(()=>{})),new Promise((c)=>{F=setTimeout(()=>c(!1),1000)})]);if(clearTimeout(F),!J){let c=await s.machines.exec(f,{command:m(ve,p),timeout:5000});if(c.exitCode!==0||c.stdout.trim()!=="confirmed")throw w("Process termination could not be confirmed","outcome_unknown",f)}}else if(z.kind==="error")throw z.cause;for(let F of["stdout","stderr"]){let J=B[F].decode();if(J)l.onChunk({stream:F,text:J})}return{exitCode:k?null:z.kind==="exit"?z.exitCode:null,timedOut:k}}catch(A){if(q=!0,k)throw w("Process termination could not be confirmed","outcome_unknown",f);throw x.close(),A}finally{if(clearTimeout(H),l.signal?.removeEventListener("abort",X),(k||q)&&l.activityPath)await s.machines.exec(f,{command:`rm -f -- ${n(l.activityPath)} ${n(p)}`,timeout:5000}).catch((A)=>{if(!q)throw A})}}var ke="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()",Pe="import sys; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); sys.stdout.buffer.write(f.read(int(sys.argv[3])))",ae="/var/lib/sandbox-sdk/metadata.json";function re(s){let f=s.split("-");return f[1]==="v2"&&["0","1"].includes(f[2]??"")}function Ee(s){if(!re(s.name))return null;let f=s.name.split("-"),l=Number.parseInt(f[3]??"",36);if(!Number.isFinite(l)||l<=0)throw w("Invalid SDK metadata","not_found",s.id);return JSON.stringify({key:null,labels:f[2]==="1"?{"sandbox-sdk":"1"}:{},createdAt:l})}function de(s){return s.status!=="running"&&!re(s.name)}function le(s){return["suspended","hibernated"].includes(s)?"paused":"stopped"}function Ie(s){return s==="running"?"running":le(s)}function Ce(s){throw w("SDK metadata is missing","not_found",s)}function Me(s){if(s===void 0)return;if(t(s))return{small:1,medium:2,large:4}[s];if(![1,2,4,8].includes(s.cpu))throw w("boxd sizes are 1 vCPU / 4 GiB, 2 / 8, 4 / 16, or 8 / 32, each with 100 GB disk","unsupported");if(s.memoryMb!==s.cpu*4096||(s.diskGb??100)!==100)throw w(`boxd gives ${s.cpu} vCPU / ${s.cpu*4} GiB memory / 100 GB disk; CPU and memory cannot be selected independently`,"unsupported");return s.cpu}function ce(s,f){if(s===void 0)return;if(!Number.isSafeInteger(s)||s<=0)throw w(`${f} must be a positive integer of milliseconds`,"invalid_argument");return Math.ceil(s/1000)}function Te(s){if(s===void 0||s==="all")return;if(s==="none"||!s.allow.length)throw w("boxd cannot block all egress (an empty allow-list means unrestricted); pass network: { allow: [...] } with at least one entry","unsupported");for(let f of s.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 w("Network allow entries must be hostnames, *.wildcards, or public IPv4 addresses and CIDRs","unsupported");return[...new Set(s.allow)]}function ue(s,f,l){let E,P,p,x=new Map;async function k(){return E??=(async()=>{if(s.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(s.requestTimeoutMs)||s.requestTimeoutMs<=0))throw w("requestTimeoutMs must be a positive integer","invalid_argument");let c=s.apiKey??process.env.BOXD_API_KEY;if(!c?.trim())throw w("boxd API key is missing. Authentication is required. Set BOXD_API_KEY or pass apiKey.","auth");let{Boxd:b}=await h("@boxd-sh/sdk","boxd",f);return P=new b({apiKey:c,baseURL:s.baseUrl??s.baseURL,timeout:s.requestTimeoutMs??30000,maxRetries:0})})()}async function q(){return await k(),p??=l({apiKey:s.apiKey??process.env.BOXD_API_KEY,baseURL:s.baseUrl??s.baseURL,timeout:s.requestTimeoutMs??30000,maxRetries:0},s.fileTransferSignal)}async function C(c,b){try{return await b()}catch(y){throw K(y,{sandboxId:c},[s.apiKey])}}async function B(c,b){try{return await b()}catch(y){throw K(y,c,[s.apiKey])}}let D=new Map;function N(c){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(c)} > ${n(ae)} && `}function G(c){return D.get(c)??""}async function V(c){let b=await k();return{name:"boxd",raw:async(y)=>{let v=G(c),S="SDK_PREPARED:",M=await b.machines.exec(c,{command:v?v+`printf %s ${n("SDK_PREPARED:")} && `+y:y,timeout:s.requestTimeoutMs??30000}),O=v&&M.stdout.startsWith("SDK_PREPARED:");if(O)D.delete(c);if(M.exitCode!==0)throw w("Guest operation failed","provider",c);return O?M.stdout.slice(13):M.stdout},upload:async(y,v)=>{let S=G(c);if(S){if((await te(b,c,{command:m(ke,y),cwd:"/",env:{},stdin:Buffer.from(v).toString("base64"),timeoutMs:s.requestTimeoutMs??30000,onChunk(){}},S,()=>D.delete(c))).exitCode!==0)throw w("File upload failed","provider",c);return}if(await(await q()).upload(c,y,v)!==v.length)throw w("Incomplete file upload","provider",c)},read:async(y,v)=>{if(!v)return(await q()).download(c,y);let S=await b.machines.exec(c,{command:m(Pe,y,String(v.offset),String(v.length)),encoding:"buffer",timeout:s.requestTimeoutMs??30000});if(S.exitCode!==0)throw w("File does not exist","file_not_found",c);return new Uint8Array(S.stdout)}}}async function X(c,{attach:b}){if(!c.name.startsWith("sbxsdk-"))throw w("Not an SDK machine","not_found",c.id);let y=()=>Ee(c)??Ce(c.id),v,S=!1;if(re(c.name))v=y(),S=!0;else try{v=new TextDecoder().decode(await(await q()).download(c.id,ae))}catch(Z){if(!["not_found","file_not_found"].includes(K(Z).code))throw Z;v=y(),S=!0}let M=(Z)=>{throw w(`Invalid SDK ${Z}`,"not_found",c.id)},O=j(v,M),Y=O.createdAt??M("metadata");if(O.key===void 0)M("metadata");if(b&&S&&!D.has(c.id))D.set(c.id,N(v));return{id:c.id,key:O.key??void 0,labels:O.labels,createdAt:c.createdAt?.getTime()??Y,state:Ie(c.status)}}async function H(c){try{return await X(c,{attach:!1})}catch(b){if(K(b).code!=="not_found")throw b;return null}}async function A(){try{let c=[],b=[];for(let y of await(await k()).machines.list()){if(!y.name.startsWith("sbxsdk-")||y.status==="destroyed")continue;if(de(y)){b.push(y);continue}let v=await H(y);if(v!==null)c.push(v)}return{known:c,asleep:b}}finally{if(!x.size)await p?.releaseIdle()}}let z={name:"boxd",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","size","snapshot","network-policy"]),create:(c)=>C(void 0,async()=>{let b=Te(c.network),y=ce(c.timeoutMs,"timeoutMs"),v=ce(c.idleTimeoutMs,"idleTimeoutMs")??0;if(c.from!==void 0&&!c.from.trim())throw w("Snapshot restore requires a nonempty snapshot ID or name","invalid_argument");if(c.from!==void 0&&(c.size!==void 0||Object.keys(c.env??{}).length>0||s.image!==void 0||s.volumes?.length))throw w("boxd snapshot restore inherits size, image, volumes and environment; overrides are not supported","unsupported");let S=Me(c.size);if(c.signal?.aborted)throw w("Creation aborted","aborted");let M=await k(),O=Date.now(),Y=JSON.stringify({key:c.key??null,labels:c.labels,createdAt:O}),Z=c.key===void 0&&Object.keys(c.labels).every((L)=>L==="sandbox-sdk"&&c.labels[L]==="1")&&c.from===void 0,W;try{let L=Z?`sbxsdk-v2-${c.labels["sandbox-sdk"]==="1"?"1":"0"}-${O.toString(36)}-${crypto.randomUUID()}`:`sbxsdk-${crypto.randomUUID()}`,U=c.from!==void 0?{autoSuspendTimeout:v}:{autoSuspendTimeout:v,autoDestroyTimeout:0,vcpu:S};if(c.from===void 0&&s.volumes?.length)U.volumes=s.volumes;let Q=c.from!==void 0?{name:L,fromSnapshot:c.from,isolated:!0,config:U}:{name:L,image:s.image,env:c.env,isolated:!0,config:U};if(y!==void 0)Q.deleteAfter=y;W=await M.machines.create(Q)}catch(L){let U=K(L,{call:"machines.create"},[s.apiKey]);if(U.code==="unavailable"||U.code==="timeout")throw w("Machine creation outcome is unknown; inspect the account before retrying","outcome_unknown",void 0,U.cause);throw U}try{if(c.signal?.aborted)throw w("Creation aborted","aborted");let L=W;if(L.status!=="running")W=await B({call:"machines.waitUntilReady",machineId:L.id},()=>M.machines.waitUntilReady(L.id,{timeout:s.requestTimeoutMs??90000}));let U=W.id,Q={id:U,key:c.key,labels:c.labels,createdAt:W.createdAt?.getTime()??O,state:"running"};if(D.set(U,N(Y)),x.set(U,W),b){let se=await B({call:"machines.setEgressAllow",machineId:U},()=>M.machines.setEgressAllow(U,b));if(se.length!==b.length||b.some((fe)=>!se.includes(fe)))throw w("boxd did not confirm the requested egress allow-list","unsupported",U)}if(!Z)await(await V(U)).raw("true");return Q}catch(L){try{await M.machines.delete(W.id)}finally{if(x.delete(W.id),D.delete(W.id),await p?.closeMachine(W.id),!x.size)await p?.releaseIdle()}throw L}}),list:(c)=>C(void 0,async()=>(await A()).known.filter((b)=>Object.entries(c).every(([y,v])=>b.labels[y]===v))),find:(c)=>C(void 0,async()=>{let{known:b,asleep:y}=await A(),v=b.find((S)=>S.key===c);try{for(let S of y){if(v)break;let M=await H(S);if(M?.key===c)v=M}}finally{if(!x.size)await p?.releaseIdle()}return v?z.connect(v.id):void 0}),connect:(c)=>C(c,async()=>{try{let b=await k(),y=await B({call:"machines.get",sandboxId:c},()=>b.machines.get(c)),v=await X(y,{attach:!0});return x.set(c,y),v}finally{if(!x.size)await p?.releaseIdle()}}),destroy:(c)=>C(c,async()=>{try{await(await k()).machines.delete(c)}catch(b){let y=K(b,{call:"machines.delete",sandboxId:c},[s.apiKey]);if(y.code!=="not_found")throw y}if(x.delete(c),D.delete(c),await p?.closeMachine(c),!x.size)await p?.releaseIdle()}),async close(c){if(x.delete(c),await p?.closeMachine(c),!x.size)await p?.releaseIdle()},exec:(c,b)=>C(c,async()=>{let y=G(c);return await te(await k(),c,b,y,()=>D.delete(c))}),files:_(V,C),previewUrl:(c,b)=>C(c,async()=>{let y=await k(),v=(await y.machines.proxies.list(c)).find((S)=>S.isDefault);if(!v)throw w("Default proxy is not ready","unavailable",c);return await y.machines.proxies.setPort(c,b),await y.machines.setBotProtection(c,"off"),{url:`https://${v.domain}`}}),pause:(c)=>C(c,async()=>{let b=await k();await B({call:"machines.pause",sandboxId:c},()=>b.machines.pause(c))}),resume:(c)=>C(c,async()=>{let b=await k();await B({call:"machines.resume",sandboxId:c},()=>b.machines.resume(c))}),snapshot:(c,b)=>C(c,async()=>{if(b?.expiresInMs)throw w("boxd keeps snapshots until they are deleted; omit expiresInMs","unsupported",c);let y=await k(),v=`sbxsdk-${crypto.randomUUID()}`,S=Date.now()+(s.requestTimeoutMs??90000);try{await B({call:"snapshots.create",sandboxId:c},()=>y.snapshots.create(c,v));while(Date.now()<S){let M=await B({call:"snapshots.get",sandboxId:c},()=>y.snapshots.get(v));if(M.status==="ready")return{id:v};if(M.status==="failed")throw w("boxd snapshot capture failed","provider",c);await new Promise((O)=>setTimeout(O,250))}throw w("boxd snapshot did not become ready","timeout",c)}catch(M){try{await y.snapshots.delete(v)}catch(O){let Y=K(O,{call:"snapshots.delete",sandboxId:c},[s.apiKey]);if(Y.code!=="not_found")throw w(`Snapshot ${v} cleanup is unconfirmed after ${K(M,{sandboxId:c}).code}; inspect and remove it before retrying`,"outcome_unknown",c,Y.cause)}throw M}}),native(c){let b=x.get(c);if(!b)throw w("Connect the machine first","not_found",c);if(!E)throw w("Client is detached","not_found",c);return{machine:b,client:F()}}};function F(){if(!P)throw w("Client is detached","not_found");return P}return Object.assign(z,{listSleeping:()=>C(void 0,async()=>(await B({call:"machines.list"},async()=>(await k()).machines.list())).filter((c)=>c.name.startsWith("sbxsdk-")&&c.status!=="destroyed"&&de(c)).map((c)=>({id:c.id,name:c.name,state:le(c.status),createdAt:c.createdAt?.getTime()??null})))})}import{createRequire as Se}from"node:module";import{isAbsolute as Be,join as Ae}from"node:path";import{pathToFileURL as me}from"node:url";import{Worker as _e}from"node:worker_threads";function Re(s){return r(s)&&"requestId"in s&&o(s.requestId)}var De=`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 => {
|
|
@@ -97,9 +95,11 @@ sys.exit(1)`;async function Z(d,f,l,E="",k){if(l.signal?.aborted)return{exitCode
|
|
|
97
95
|
parentPort.postMessage({ requestId: request.requestId, error: {
|
|
98
96
|
name: error instanceof Error ? error.name : "Error",
|
|
99
97
|
grpcCode: typeof error === "object" && error !== null && typeof error.grpcCode === "number" ? error.grpcCode : undefined,
|
|
98
|
+
// boxd's machine-readable reason (0.3.x): an opaque token, never free text.
|
|
99
|
+
reason: typeof error === "object" && error !== null && typeof error.reason === "string" && /^[A-Za-z0-9_.:-]{1,128}$/.test(error.reason) ? error.reason : undefined,
|
|
100
100
|
permissionDenied: /permission denied/i.test(message),
|
|
101
101
|
missingFile: /\\bno such file\\b/i.test(message),
|
|
102
102
|
} });
|
|
103
103
|
}
|
|
104
104
|
});
|
|
105
|
-
});`;function
|
|
105
|
+
});`;function Ne(){let s=import.meta;for(let f of[s.url,me(Ae(process.cwd(),"index.js")).href]){if(!t(f))continue;try{let l=Se(f).resolve("@boxd-sh/sdk/web");if(t(l)&&Be(l))return me(l).href}catch{}}return}class ne{options;signal;workers=new Set;idle=[];stopping=new Map;nextId=0;pending=new Map;moduleURL;inline;constructor(s,f){this.options=s;this.signal=f}start(s){let f=this.idle.pop();if(f)return f;let l=new _e(De,{eval:!0,workerData:{moduleURL:s,options:this.options}});return this.workers.add(l),l.on("message",(E)=>{let P=E;if(!this.workers.has(l))return;if(!Re(P)){this.stop(l,w("Invalid file transfer response"));return}let p=this.pending.get(P.requestId);if(!p||p.worker!==l)return;if(this.pending.delete(P.requestId),p.cleanup(),"value"in P&&(o(P.value)||P.value instanceof Uint8Array))p.resolve(P.value);else if("error"in P&&r(P.error)){let x=P.error,k="permissionDenied"in x&&x.permissionDenied===!0?"permission denied":("missingFile"in x)&&x.missingFile===!0?"no such file":"File transfer failed";p.reject(K(Object.assign(Error(k),{name:"name"in x&&t(x.name)?x.name:"Error",grpcCode:"grpcCode"in x&&o(x.grpcCode)?x.grpcCode:void 0,reason:"reason"in x&&t(x.reason)?x.reason:void 0}),{sandboxId:p.machine},[this.options.apiKey]))}else p.reject(w("Invalid file transfer response","provider",p.machine));this.idle.push(l),l.unref()}),l.on("error",()=>{if(this.workers.has(l))this.stop(l,w("File transfer worker failed","unavailable"))}),l.on("exit",()=>{if(this.workers.has(l))this.stop(l,w("File transfer worker exited","unavailable"))}),l.unref(),l}stop(s,f){let l=this.stopping.get(s);if(l)return l.promise;this.workers.delete(s),this.idle=this.idle.filter((p)=>p!==s);let E=[...this.pending].filter(([,p])=>p.worker===s);for(let[p,x]of E)this.pending.delete(p),x.cleanup();let P=s.terminate().then(()=>{for(let[,p]of E)p.reject(f);this.stopping.delete(s)});return this.stopping.set(s,{machine:E[0]?.[1].machine,promise:P}),P}async transfer(s){if(this.signal?.aborted)throw w("File transfer aborted","aborted",s.machine);if(this.moduleURL===void 0)this.moduleURL=Ne()??null;if(this.moduleURL===null)return this.direct(s);let f=this.start(this.moduleURL);f.ref();let l=this.nextId++;return new Promise((E,P)=>{let p=()=>{this.stop(f,w("File transfer aborted","aborted",s.machine))},x=setTimeout(()=>{this.stop(f,w("File transfer deadline exceeded; check the destination before retrying a write","timeout",s.machine))},this.options.timeout??30000),k=()=>{clearTimeout(x),this.signal?.removeEventListener("abort",p)};if(this.pending.set(l,{worker:f,machine:s.machine,resolve:E,reject:P,cleanup:k}),this.signal?.addEventListener("abort",p,{once:!0}),this.signal?.aborted){p();return}try{f.postMessage({...s,requestId:l})}catch{this.stop(f,w("Could not submit file transfer","unavailable",s.machine))}})}async direct(s){let f=await(this.inline??=h("@boxd-sh/sdk/web","boxd",()=>import("@boxd-sh/sdk/web")).then(({Boxd:x})=>new x(this.options))),l=s.kind==="upload"?f.machines.files.upload(s.machine,s.path,s.bytes):f.machines.files.download(s.machine,s.path),E,P=()=>{},p=new Promise((x,k)=>{if(E=setTimeout(()=>k(w("File transfer deadline exceeded; check the destination before retrying a write","timeout",s.machine)),this.options.timeout??30000),P=()=>k(w("File transfer aborted","aborted",s.machine)),this.signal?.addEventListener("abort",P,{once:!0}),this.signal?.aborted)P()});try{return await Promise.race([l.catch((x)=>{throw K(x,{sandboxId:s.machine},[this.options.apiKey])}),p])}finally{clearTimeout(E),this.signal?.removeEventListener("abort",P)}}async upload(s,f,l){let E=await this.transfer({kind:"upload",machine:s,path:f,bytes:l});if(!o(E))throw w("Invalid upload response","provider",s);return E}async download(s,f){let l=await this.transfer({kind:"download",machine:s,path:f});if(!(l instanceof Uint8Array))throw w("Invalid download response","provider",s);return l}async closeMachine(s){let f=new Set;for(let l of this.pending.values())if(l.machine===s)f.add(l.worker);await Promise.all([...f].map((l)=>this.stop(l,w("File transfers closed","aborted",s)))),await Promise.all([...this.stopping.values()].flatMap((l)=>l.machine===s?[l.promise]:[]))}async releaseIdle(){let s=this.idle.splice(0);await Promise.all(s.map((f)=>this.stop(f,w("Idle file transfer worker closed","aborted")))),await Promise.all([...this.stopping.values()].map((f)=>f.promise))}async close(){await Promise.all([...this.workers].map((s)=>this.stop(s,w("File transfers closed","aborted")))),await Promise.all([...this.stopping.values()].map((s)=>s.promise))}}function at(s={}){return ue(s,()=>import("@boxd-sh/sdk"),(f,l)=>new ne(f,l))}export{at as boxd};
|
|
@@ -27,7 +27,21 @@ export interface BoxdNative {
|
|
|
27
27
|
client: Boxd;
|
|
28
28
|
}
|
|
29
29
|
type BoxdCapability = "pause" | "size" | "snapshot" | "network-policy";
|
|
30
|
-
|
|
30
|
+
/** A suspended or hibernated SDK machine whose labels are only in its guest, so `list()` leaves it out. */
|
|
31
|
+
export interface BoxdSleepingMachine {
|
|
32
|
+
id: string;
|
|
33
|
+
name: string;
|
|
34
|
+
state: "paused" | "stopped";
|
|
35
|
+
createdAt: number | null;
|
|
36
|
+
}
|
|
37
|
+
export interface BoxdExtras {
|
|
38
|
+
/**
|
|
39
|
+
* The sleeping SDK machines `list()` leaves out, read from boxd's machine list only, so none is
|
|
40
|
+
* woken. `connect(id)` reads one's labels and key, which wakes it.
|
|
41
|
+
*/
|
|
42
|
+
listSleeping(): Promise<BoxdSleepingMachine[]>;
|
|
43
|
+
}
|
|
44
|
+
export type BoxdProvider = Provider<BoxdNative, BoxdCapability> & BoxdExtras;
|
|
31
45
|
/** The parts of a boxd client the adapter uses. */
|
|
32
46
|
export interface BoxdClient {
|
|
33
47
|
machines: {
|
|
@@ -70,5 +84,5 @@ export type OpenTransfers = (options: BoxdClientOptions, signal?: AbortSignal) =
|
|
|
70
84
|
export declare function createBoxdProvider<C extends BoxdClient>(options: BoxdOptions, load: () => Promise<BoxdModule<C>>, openTransfers: OpenTransfers): Provider<{
|
|
71
85
|
machine: Machine;
|
|
72
86
|
client: C;
|
|
73
|
-
}, BoxdCapability
|
|
87
|
+
}, BoxdCapability> & BoxdExtras;
|
|
74
88
|
export {};
|
|
@@ -82,10 +82,10 @@ export interface Toolbox {
|
|
|
82
82
|
upload(data: Uint8Array, path: string): Promise<void>;
|
|
83
83
|
/** Reads the absolute `path`. A missing file is `file_not_found`. */
|
|
84
84
|
download(path: string): Promise<Uint8Array>;
|
|
85
|
-
/** Streams the absolute `path`. The signal and
|
|
85
|
+
/** Streams the absolute `path`. The signal, and `timeoutMs` when given, cover the whole body. */
|
|
86
86
|
downloadStream(path: string, options: {
|
|
87
87
|
signal: AbortSignal;
|
|
88
|
-
timeoutMs
|
|
88
|
+
timeoutMs?: number;
|
|
89
89
|
}): Promise<ReadableStream<Uint8Array>>;
|
|
90
90
|
deleteFile(path: string, recursive?: boolean): Promise<void>;
|
|
91
91
|
createFolder(path: string, mode: string): Promise<void>;
|