@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
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import type { ExecInput, ExecResult } from "../../provider.js";
|
|
2
2
|
import { type PagedGuest } from "../../shared/paged-exec.js";
|
|
3
3
|
export declare const supervisorPath = "/var/lib/sandbox-sdk-exec-v2.py";
|
|
4
|
-
export declare const supervisor = "import os,sys,marshal,_signal as signal,select,time,fcntl\ndef stdin_file():\n try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')\n except (AttributeError,OSError):\n import tempfile\n return tempfile.TemporaryFile()\nclass Process:\n # A missing cwd fails the command, not the supervisor: the shell reports it on stderr and exits 2.\n def argv(self,v):\n try: os.chdir(v['cwd']); return ['sh','-c',v['command']]\n except OSError: return ['sh','-c','cd \"$1\" || exit 2','sh',v['cwd']]\n def __init__(self,v,env,stdin,session=False):\n if not all(hasattr(os,name) for name in ['posix_spawn','waitstatus_to_exitcode']):\n self.legacy(v,env,stdin,session); return\n directory=os.open('.',os.O_RDONLY)\n r,w=os.pipe(); e,x=os.pipe()\n try:\n argv=self.argv(v)\n error=FileNotFoundError(2,os.strerror(2),'sh')\n signals=[getattr(signal,s) for s in ['SIGPIPE','SIGXFZ','SIGXFSZ'] if hasattr(signal,s)]\n for path in os.get_exec_path(env):\n try:\n self.pid=os.posix_spawn(os.path.join(path,'sh'),argv,env,file_actions=[(os.POSIX_SPAWN_DUP2,stdin.fileno(),0),(os.POSIX_SPAWN_DUP2,w,1),(os.POSIX_SPAWN_DUP2,x,2)],setsid=session,setsigdef=signals)\n break\n except (FileNotFoundError,NotADirectoryError): pass\n except OSError as failure:\n if failure.errno==38: raise NotImplementedError()\n error=failure\n else: raise error\n except NotImplementedError:\n os.close(r); os.close(e)\n self.legacy(v,env,stdin,session); return\n except BaseException:\n os.close(r); os.close(e); raise\n finally:\n os.fchdir(directory); os.close(directory); os.close(w); os.close(x)\n self.stdout=os.fdopen(r,'rb',buffering=0); self.stderr=os.fdopen(e,'rb',buffering=0)\n self.code=None\n def legacy(self,v,env,stdin,session):\n import subprocess\n directory=os.open('.',os.O_RDONLY)\n try: self.child=subprocess.Popen(self.argv(v),env=env,stdin=stdin,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=session)\n finally: os.fchdir(directory); os.close(directory)\n self.pid=self.child.pid; self.stdout=self.child.stdout; self.stderr=self.child.stderr\n def poll(self):\n if hasattr(self,'child'): return self.child.poll()\n if self.code is None:\n pid,status=os.waitpid(self.pid,os.WNOHANG)\n if pid: self.code=os.waitstatus_to_exitcode(status)\n return self.code\n def wait(self):\n if hasattr(self,'child'): return self.child.wait()\n if self.code is None: self.code=os.waitstatus_to_exitcode(os.waitpid(self.pid,0)[1])\n return self.code\n\nroot=sys.argv[1]\nv=marshal.loads(bytes.fromhex(sys.stdin.read()))\nif v.get('files') is not None:\n previous_umask=os.umask(0o077)\n os.makedirs('/workspace',exist_ok=True)\n os.makedirs('/tmp/.sandbox-sdk',exist_ok=True)\n for path,content in v['files']:\n os.makedirs(os.path.dirname(path),exist_ok=True)\n tmp=path+'.'+str(os.getpid())\n try:\n with open(tmp,'w') as f: f.write(content)\n os.replace(tmp,path)\n finally:\n if os.path.exists(tmp): os.unlink(tmp)\n os.umask(previous_umask)\nos.makedirs(root,mode=0o700,exist_ok=True)\n# Keep small completed responses until their request deadline has passed.\n# Sweep expired responses inline, so no ack RPC or background daemon is needed.\nwith open(os.path.dirname(root)+'/.sweep','a') as sweep:\n try: fcntl.flock(sweep,fcntl.LOCK_EX|fcntl.LOCK_NB)\n except BlockingIOError: pass\n else:\n if time.time()-os.fstat(sweep.fileno()).st_mtime>30:\n os.utime(sweep.fileno(),None)\n for entry in os.scandir(os.path.dirname(root)):\n if not entry.name.startswith('run-') or entry.path==root: continue\n try:\n with open(entry.path+'/expires') as f: expired=time.time()>float(f.read())\n if expired:\n import shutil\n shutil.rmtree(entry.path,ignore_errors=True)\n except (FileNotFoundError,NotADirectoryError): pass\na=v.get('activityPath')\ntimed=False\ncode=127\ntry:\n if a:\n os.makedirs(os.path.dirname(a),exist_ok=True)\n with open(a,'w') as f: f.write('1')\n try:\n with open('/var/lib/sandbox-sdk-env.json') as f:\n import json\n saved=json.load(f)\n except FileNotFoundError: saved={}\n env={**os.environ,**saved,**v['env']}\n with stdin_file() as f, open(root+'/out','wb',buffering=0) as out:\n f.write(v.get('stdin','').encode()); f.seek(0)\n with open(root+'/lock','w') as lock:\n fcntl.flock(lock,fcntl.LOCK_EX)\n if os.path.exists(root+'/cancelled'): timed=True; p=None\n else:\n try: p=Process(v,env,f,True)\n except OSError as e:\n out.write(('[\"stderr\",\"'+str(e).encode().hex()+'\"]\\n').encode()); p=None\n if p:\n with open(root+'/pid','w') as m: m.write(str(p.pid))\n if p:\n
|
|
4
|
+
export declare const supervisor = "import os,sys,marshal,_signal as signal,select,time,fcntl\ndef stdin_file():\n try: return os.fdopen(os.memfd_create('sandbox-sdk-stdin'),'w+b')\n except (AttributeError,OSError):\n import tempfile\n return tempfile.TemporaryFile()\nclass Process:\n # A missing cwd fails the command, not the supervisor: the shell reports it on stderr and exits 2.\n def argv(self,v):\n try: os.chdir(v['cwd']); return ['sh','-c',v['command']]\n except OSError: return ['sh','-c','cd \"$1\" || exit 2','sh',v['cwd']]\n def __init__(self,v,env,stdin,session=False):\n if not all(hasattr(os,name) for name in ['posix_spawn','waitstatus_to_exitcode']):\n self.legacy(v,env,stdin,session); return\n directory=os.open('.',os.O_RDONLY)\n r,w=os.pipe(); e,x=os.pipe()\n try:\n argv=self.argv(v)\n error=FileNotFoundError(2,os.strerror(2),'sh')\n signals=[getattr(signal,s) for s in ['SIGPIPE','SIGXFZ','SIGXFSZ'] if hasattr(signal,s)]\n for path in os.get_exec_path(env):\n # A missing candidate would cost a whole spawn and failed exec; skip it with one stat.\n if not os.path.exists(os.path.join(path,'sh')): continue\n try:\n self.pid=os.posix_spawn(os.path.join(path,'sh'),argv,env,file_actions=[(os.POSIX_SPAWN_DUP2,stdin.fileno(),0),(os.POSIX_SPAWN_DUP2,w,1),(os.POSIX_SPAWN_DUP2,x,2)],setsid=session,setsigdef=signals)\n break\n except (FileNotFoundError,NotADirectoryError): pass\n except OSError as failure:\n if failure.errno==38: raise NotImplementedError()\n error=failure\n else: raise error\n except NotImplementedError:\n os.close(r); os.close(e)\n self.legacy(v,env,stdin,session); return\n except BaseException:\n os.close(r); os.close(e); raise\n finally:\n os.fchdir(directory); os.close(directory); os.close(w); os.close(x)\n self.stdout=os.fdopen(r,'rb',buffering=0); self.stderr=os.fdopen(e,'rb',buffering=0)\n self.code=None\n def legacy(self,v,env,stdin,session):\n import subprocess\n directory=os.open('.',os.O_RDONLY)\n try: self.child=subprocess.Popen(self.argv(v),env=env,stdin=stdin,stdout=subprocess.PIPE,stderr=subprocess.PIPE,start_new_session=session)\n finally: os.fchdir(directory); os.close(directory)\n self.pid=self.child.pid; self.stdout=self.child.stdout; self.stderr=self.child.stderr\n def poll(self):\n if hasattr(self,'child'): return self.child.poll()\n if self.code is None:\n pid,status=os.waitpid(self.pid,os.WNOHANG)\n if pid: self.code=os.waitstatus_to_exitcode(status)\n return self.code\n def wait(self):\n if hasattr(self,'child'): return self.child.wait()\n if self.code is None: self.code=os.waitstatus_to_exitcode(os.waitpid(self.pid,0)[1])\n return self.code\n\ndef pump(p,emit,end):\n r,w=os.pipe(); os.set_blocking(w,False)\n signal.set_wakeup_fd(w,warn_on_full_buffer=False)\n signal.signal(signal.SIGCHLD,lambda *_:None)\n streams={p.stdout.fileno():('stdout',p.stdout),p.stderr.fileno():('stderr',p.stderr)}\n timed=False\n while streams or p.poll() is None:\n left=end-time.monotonic()\n if not timed and left<=0:\n timed=True\n try: os.killpg(p.pid,signal.SIGKILL)\n except ProcessLookupError: pass\n for fd in select.select(list(streams)+[r],[],[],None if timed else max(left,0))[0]:\n if fd==r: os.read(r,512); continue\n data=os.read(fd,8192)\n if data: emit(streams[fd][0],data)\n else: streams.pop(fd)[1].close()\n return timed\n\nroot=sys.argv[1]\nv=marshal.loads(bytes.fromhex(sys.stdin.read()))\nif v.get('files') is not None:\n previous_umask=os.umask(0o077)\n os.makedirs('/workspace',exist_ok=True)\n os.makedirs('/tmp/.sandbox-sdk',exist_ok=True)\n for path,content in v['files']:\n os.makedirs(os.path.dirname(path),exist_ok=True)\n tmp=path+'.'+str(os.getpid())\n try:\n with open(tmp,'w') as f: f.write(content)\n os.replace(tmp,path)\n finally:\n if os.path.exists(tmp): os.unlink(tmp)\n os.umask(previous_umask)\nos.makedirs(root,mode=0o700,exist_ok=True)\n# Keep small completed responses until their request deadline has passed.\n# Sweep expired responses inline, so no ack RPC or background daemon is needed.\nwith open(os.path.dirname(root)+'/.sweep','a') as sweep:\n try: fcntl.flock(sweep,fcntl.LOCK_EX|fcntl.LOCK_NB)\n except BlockingIOError: pass\n else:\n if time.time()-os.fstat(sweep.fileno()).st_mtime>30:\n os.utime(sweep.fileno(),None)\n for entry in os.scandir(os.path.dirname(root)):\n if not entry.name.startswith('run-') or entry.path==root: continue\n try:\n with open(entry.path+'/expires') as f: expired=time.time()>float(f.read())\n if expired:\n import shutil\n shutil.rmtree(entry.path,ignore_errors=True)\n except (FileNotFoundError,NotADirectoryError): pass\na=v.get('activityPath')\ntimed=False\ncode=127\ntry:\n if a:\n os.makedirs(os.path.dirname(a),exist_ok=True)\n with open(a,'w') as f: f.write('1')\n try:\n with open('/var/lib/sandbox-sdk-env.json') as f:\n import json\n saved=json.load(f)\n except FileNotFoundError: saved={}\n env={**os.environ,**saved,**v['env']}\n with stdin_file() as f, open(root+'/out','wb',buffering=0) as out:\n f.write(v.get('stdin','').encode()); f.seek(0)\n with open(root+'/lock','w') as lock:\n fcntl.flock(lock,fcntl.LOCK_EX)\n if os.path.exists(root+'/cancelled'): timed=True; p=None\n else:\n try: p=Process(v,env,f,True)\n except OSError as e:\n out.write(('[\"stderr\",\"'+str(e).encode().hex()+'\"]\\n').encode()); p=None\n if p:\n with open(root+'/pid','w') as m: m.write(str(p.pid))\n if p:\n timed=pump(p,lambda name,data: out.write(('[\"'+name+'\",\"'+data.hex()+'\"]\\n').encode()),time.monotonic()+v['timeoutMs']/1000)\n code=p.wait()\n timed=timed or os.path.exists(root+'/cancelled')\n result='{\"exitCode\":%s,\"timedOut\":%s}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower())\n with open(root+'/exit','w') as f: f.write(result)\n size=os.path.getsize(root+'/out')\n with open(root+'/out','rb') as f:\n chunks=[line.decode().strip() for _,line in zip(range(3),f)]\n offset=f.tell()\n if offset==size and not timed:\n with open(root+'/expires','w') as f: f.write(str(time.time()+v['timeoutMs']/1000+5))\n if timed and not p:\n import shutil\n shutil.rmtree(root)\n print('{\"result\":%s,\"chunks\":[%s],\"offset\":%d,\"size\":%d}'%(result,','.join(chunks),offset,size))\nfinally:\n if a:\n try: os.unlink(a)\n except FileNotFoundError: pass\n";
|
|
5
5
|
export interface ExecutionGuest extends PagedGuest {
|
|
6
|
+
/** The sandbox ID. */
|
|
7
|
+
readonly id: string;
|
|
6
8
|
exec(command: string, stdin: string, timeoutMs: number, signal?: AbortSignal): Promise<string>;
|
|
7
9
|
}
|
|
8
10
|
export declare function execute(g: ExecutionGuest, input: ExecInput, files?: [string, string][]): Promise<ExecResult>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import{U}from"../../chunk-hzbssbep.js";import{T}from"../../chunk-8786zrns.js";import{p,b,R}from"../../chunk-x681p5d2.js";import{d,y,x,_,h,v,k}from"../../chunk-6a3wkj84.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,e,i,c,a}from"../../chunk-xgxfy2n8.js";import{createHash as He}from"node:crypto";import{AsyncLocalStorage as Me}from"node:async_hooks";import{createHash as _e}from"node:crypto";import{AsyncLocalStorage as Ae}from"node:async_hooks";import{AsyncLocalStorage as Pe}from"node:async_hooks";var re=new Pe,Fe=new Set(["v5","vms","fs","read","write","uploads","commit","dir","mkdir","remove","exists","stat","exec-await","firewall","rules","tls","pause","start","snapshot","snapshots","background-requests"]);function me(u){return(u.split("?")[0]??"").split("/").map((m)=>Fe.has(m)?m:m?":id":"").join("/")}function ye(u,m="GET",w){let E=re.getStore();if(!E)return;if(w&&!E.deniedValues?.includes(w))E.deniedValues=[...E.deniedValues??[],w];let F=new URL(u instanceof Request?u.url:u).pathname;if(!F.startsWith("/v5/background-requests/")||!E.operation)E.operation=`${/^(GET|POST|PUT|DELETE|PATCH|HEAD)$/.test(m)?m:"REQUEST"} ${me(F)}`,delete E.backgroundRequestId;delete E.status,delete E.requestId}function he(u,m){let w=re.getStore();if(!w)return;w.status=u.status;let E=u.headers.get("x-freestyle-background-request-id"),F=(O)=>O&&/^[A-Za-z0-9_-]{1,128}$/.test(O)&&!O.includes(m)&&!w.deniedValues?.some((D)=>O.includes(D))?O:void 0;if(F(E))w.backgroundRequestId=F(E);w.requestId=F(u.headers.get("x-request-id"))??F(u.headers.get("x-freestyle-request-id"))??w.backgroundRequestId}function P(u,m="provider",w,E){return new e(m==="auth"?u:`${u}. Check Freestyle configuration and retry.`,{code:m,provider:"freestyle",sandboxId:w,cause:E})}class ne extends Error{status;code;path;backgroundRequestId;name="FreestyleApiError";constructor(u,m,w,E,F){super(w||`Freestyle API error: ${m??u}`);this.status=u;this.code=m;this.path=E;this.backgroundRequestId=F}}var Re=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[402,"quota"],[408,"timeout"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),Te=(u,m)=>u===404&&/no such file or directory|\bos error 2\b/i.test(m??""),ue=(u,m)=>Te(u,m)?"file_not_found":Re.get(u)??"provider";function te(u,m){if(u instanceof e)return u;let w=r(u)&&"status"in u?u.status:void 0,E=re.getStore(),F={};if(o(w)&&Number.isInteger(w)&&w>=100&&w<=599)F.status=w;if(r(u)){if("code"in u&&t(u.code)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(u.code)){let J=u.code;if(!E?.deniedValues?.some((A)=>J.includes(A)))F.providerCode=J}if("path"in u&&t(u.path))F.operation=me(u.path)}if(E?.operation)F.operation=E.operation;if(E?.status===w&&E?.requestId)F.requestId=E.requestId;let O=o(w)?ue(w,u instanceof Error?u.message:void 0):u instanceof Error&&(u.name==="TimeoutError"||u.name==="AbortError")?u.name==="TimeoutError"?"timeout":"aborted":u instanceof Error&&u.name==="FreestyleTransportError"?"unavailable":"provider",{detail:D}=i(u,{code:O,status:w===void 0?void 0:String(w),redact:c([process.env.FREESTYLE_API_KEY,...E?.deniedValues??[]])});if(D!==void 0)F.native=D;let B=Object.keys(F).length?Object.assign(Error(JSON.stringify(F)),F):void 0;return P(`Freestyle request failed: ${a(O,F.native)}`,O,m,B)}var X=new Ae;async function ge(u,m,w){if(w?.aborted)throw P("Operation aborted","aborted");let E=d(m,w),F=()=>E.parent?.aborted&&!E.timeout.aborted?P("Operation aborted","aborted"):P("Native operation timed out","timeout"),O=()=>{},D=new Promise((B,J)=>{if(O=()=>J(F()),E.signal.addEventListener("abort",O,{once:!0}),E.signal.aborted)O()});try{if(E.signal.aborted)throw F();return await Promise.race([X.run(E,u),D])}finally{E.signal.removeEventListener("abort",O)}}var ve="https://api.freestyle.sh",Oe="x-freestyle-background-after-secs",we="x-freestyle-background-request-id",oe={afterSecs:5,pollMs:2000,unavailableMs:300000,hopMs:30000},Ce=new Set([408,429,502,503,504]),Ve=8388608,qe=16777216,De=5,be={"content-type":"application/octet-stream"},Ne=4294967296,Y=(u)=>typeof u==="object"&&u!==null&&!Array.isArray(u);function Q(u,m){throw P(`Freestyle returned an unexpected ${u}`,"provider",m)}function ae(u){return u===void 0||u===null||typeof u==="number"}function le(u,m){if(!Y(u)||!t(u.id)||!t(u.state))Q("VM record",m);let w={};if(u.metadata!==void 0&&u.metadata!==null){if(!Y(u.metadata))Q("VM record",m);for(let[J,A]of Object.entries(u.metadata))if(t(A))Object.defineProperty(w,J,{value:A,enumerable:!0})}let{idleTimeoutSeconds:E,ttlSeconds:F,autoDeleteSeconds:O,vpcs:D,createdAt:B}=u;if(!ae(E)||!ae(F)||!ae(O)||D!==void 0&&!Array.isArray(D)||B!==void 0&&!t(B))Q("VM record",m);return{id:u.id,state:u.state,metadata:w,createdAt:B??"",idleTimeoutSeconds:E,ttlSeconds:F,autoDeleteSeconds:O,vpcs:D}}function je(u){if(u===void 0||u===null)return[];if(!Array.isArray(u))Q("firewall rule list");return u.map((m)=>{if(!Y(m)||!t(m.action)||!Y(m.source)||!Y(m.destination))Q("firewall rule");return{action:m.action,source:m.source,destination:m.destination}})}function Ue(u,m){if(!Y(u)||!ae(u.statusCode)||u.stdout!==void 0&&u.stdout!==null&&!t(u.stdout)||u.stderr!==void 0&&u.stderr!==null&&!t(u.stderr))Q("command result",m);return{statusCode:u.statusCode??null,stdout:u.stdout,stderr:u.stderr}}function ce(u,m){if(!Y(u)||!t(u.uploadId)||!Number.isSafeInteger(u.receivedBytes))Q("upload session",m);return{uploadId:u.uploadId,receivedBytes:Number(u.receivedBytes)}}var ie=(u,m)=>{let w=Y(u)?u[m]:void 0;return t(w)&&w?w:void 0};function xe(u){let m=new Me,w,E=()=>(w=u.apiKey(),{authorization:`Bearer ${w}`}),F=x({provider:"freestyle",label:"Freestyle",defaultPlane:"api",planes:{api:{baseUrl:u.baseUrl,auth:E}},timeoutMs:u.requestTimeoutMs,secrets:()=>[process.env.FREESTYLE_API_KEY,w],authHint:"Set FREESTYLE_API_KEY to a valid Freestyle API key, or pass apiKey.",async fetch(l,I){ye(l,I.method,w);let M=await globalThis.fetch(l,I);if(w!==void 0)he(M,w);return M},mapError(l){let I=m.getStore();if(I)I.failure=l;return l.kind==="status"?ue(l.status,l.body.message):void 0}});async function O(l){let I={};try{return await m.run(I,()=>F.request(l))}catch(M){let C=I.failure;if(C?.kind!=="status")throw M;throw new ne(C.status,C.body.code,C.body.message,l.path,C.headers.get(we)??void 0)}}let D=()=>X.getStore()??d(u.requestTimeoutMs),B=(l)=>l instanceof ne?Ce.has(l.status)&&l.backgroundRequestId===void 0:l instanceof e&&(l.code==="unavailable"||l.code==="timeout");async function J(l,I,M){let C;try{C=l.json()}catch{C=void 0}let H=l.headers.get(we)??ie(C,"requestId"),j=ie(C,"resultUrl")??(H===void 0?void 0:`/v5/background-requests/${encodeURIComponent(H)}`);if(j===void 0||/[{}]/.test(j))throw new ne(l.status,"BACKGROUND_PROTOCOL_ERROR","202 Accepted carried no background request id",I);let s;for(;;){await y(oe.pollMs,M,"freestyle");try{let g=d(Math.min(oe.hopMs,M.remaining()),M.signal),f=await O({method:"GET",path:j,deadline:g});if(f.status!==202)return f;s=void 0}catch(g){if(M.signal.aborted||!B(g))throw g;if(s??=Date.now(),Date.now()-s>=oe.unavailableMs)throw g}}}async function A(l){let I=D(),M={...l,deadline:I},C=await O({...M,headers:{...l.headers,[Oe]:String(oe.afterSecs)}});if(C.status!==202)return C;try{return await J(C,l.path,I)}catch(H){if(l.method==="GET"&&H instanceof ne&&H.code==="BACKGROUND_RESULT_UNSTORABLE")return await O(M);throw H}}let z=(l)=>({params:{id:l},sandboxId:l});async function de(l,I,M,C){let H={path:"/v5/vms/{id}/fs/uploads/{upload}",params:{id:l,upload:I},sandboxId:l};for(let j=1;;j++)try{return ce((await A({...H,method:"PUT",query:{offset:C},body:M,headers:be})).json(),l)}catch(s){let g=s instanceof ne?s.status>=500||s.status===408||s.status===409||s.status===429:B(s),f=D();if(!g||f.signal.aborted||j>=De)throw s;await y(Math.min(500*2**(j-1),8000),f,"freestyle");let S=await A({...H,method:"GET"}).then((V)=>ce(V.json(),l),()=>{return});if(S&&S.receivedBytes>C)return S}}return{http:F,async createVm(l){let I=(await A({method:"POST",path:"/v5/vms",body:l})).json();return{data:le(I),firewallRules:je(Y(I)?I.firewallRules:void 0),tlsRules:Y(I)&&Array.isArray(I.tlsRules)?I.tlsRules:[]}},async listVms(l,I){let M=(await A({method:"GET",path:"/v5/vms",query:{limit:l,offset:I}})).json();if(!Y(M)||!Array.isArray(M.vms)||!Number.isSafeInteger(M.totalCount))Q("VM list");return{vms:M.vms.map((C)=>le(C)),totalCount:Number(M.totalCount)}},async getVm(l){return le((await A({method:"GET",path:"/v5/vms/{id}",...z(l)})).json(),l)},async deleteVm(l){await A({method:"DELETE",path:"/v5/vms/{id}",...z(l)})},async exec(l,I){return Ue((await A({method:"POST",path:"/v5/vms/{id}/exec-await",...z(l),body:{...I,linuxUser:"root"}})).json(),l)},async lifecycle(l,I){await A({method:"POST",path:`/v5/vms/{id}/${I}`,...z(l),body:{}})},async snapshot(l,I){let M=(await A({method:"POST",path:"/v5/vms/{id}/snapshot",...z(l),body:I})).json(),C=ie(M,"snapshotId");if(C===void 0)Q("snapshot result",l);return C},async createTlsRule(l){let I=ie((await A({method:"POST",path:"/v5/tls",body:l})).json(),"domain");if(I===void 0)Q("TLS rule");return{domain:I}},async readFile(l,I,M){let C=M?{range:`bytes=${M.offset}-${M.offset+M.length-1}`}:void 0;return(await O({method:"GET",path:"/v5/vms/{id}/fs/read",...z(l),query:{path:I},deadline:D(),maxBytes:Ne,headers:C})).body},async writeFile(l,I,M,C){let H=_e("sha256").update(M).digest("hex");if(M.byteLength<=Ve){await A({method:"PUT",path:"/v5/vms/{id}/fs/write",...z(l),query:{path:I,mode:C,sha256:H},body:M,headers:be});return}let j=M.byteLength,s=ce((await A({method:"POST",path:"/v5/vms/{id}/fs/uploads",...z(l),body:{path:I,size:j,sha256:H,mode:C}})).json(),l),g={id:l,upload:s.uploadId};try{let f=s.receivedBytes;while(f<j){let S=(await de(l,s.uploadId,M.subarray(f,Math.min(f+qe,j)),f)).receivedBytes;if(S<=f)throw P("Freestyle upload made no progress","provider",l);f=S}await A({method:"POST",path:"/v5/vms/{id}/fs/uploads/{upload}/commit",params:g,sandboxId:l,body:{}})}catch(f){throw await F.cleanup({method:"DELETE",path:"/v5/vms/{id}/fs/uploads/{upload}",params:g,sandboxId:l}).catch(()=>{}),f}}}}var fe=`import os,sys,marshal,_signal as signal,select,time,fcntl
|
|
2
|
-
${
|
|
1
|
+
import{H}from"../../chunk-7s9pxk1v.js";import{A}from"../../chunk-aq6fmgdx.js";import{m,J,g,C,_}from"../../chunk-kdecey83.js";import{N,b,S,P}from"../../chunk-ek44atpe.js";import{f,w,v}from"../../chunk-2999xbh7.js";import{t,o,r,e,i,d,a}from"../../chunk-0eeyc0aq.js";import{createHash as Je}from"node:crypto";import{AsyncLocalStorage as _e}from"node:async_hooks";import{createHash as Oe}from"node:crypto";import{AsyncLocalStorage as Me}from"node:async_hooks";import{AsyncLocalStorage as Ie}from"node:async_hooks";var ne=new Ie,Re=new Set(["v5","vms","fs","read","write","uploads","commit","dir","mkdir","remove","exists","stat","exec-await","firewall","rules","tls","pause","start","snapshot","snapshots","background-requests"]);function ye(s){return(s.split("?")[0]??"").split("/").map((c)=>Re.has(c)?c:c?":id":"").join("/")}function he(s,c="GET",y){let x=ne.getStore();if(!x)return;if(y&&!x.deniedValues?.includes(y))x.deniedValues=[...x.deniedValues??[],y];let F=new URL(s instanceof Request?s.url:s).pathname;if(!F.startsWith("/v5/background-requests/")||!x.operation)x.operation=`${/^(GET|POST|PUT|DELETE|PATCH|HEAD)$/.test(c)?c:"REQUEST"} ${ye(F)}`,delete x.backgroundRequestId;delete x.status,delete x.requestId}function ge(s,c){let y=ne.getStore();if(!y)return;y.status=s.status;let x=s.headers.get("x-freestyle-background-request-id"),F=(T)=>T&&/^[A-Za-z0-9_-]{1,128}$/.test(T)&&!T.includes(c)&&!y.deniedValues?.some((q)=>T.includes(q))?T:void 0;if(F(x))y.backgroundRequestId=F(x);y.requestId=F(s.headers.get("x-request-id"))??F(s.headers.get("x-freestyle-request-id"))??y.backgroundRequestId}function E(s,c="provider",y,x){return new e(c==="auth"?s:`${s}. Check Freestyle configuration and retry.`,{code:c,provider:"freestyle",sandboxId:y,cause:x})}class se extends Error{status;code;path;backgroundRequestId;name="FreestyleApiError";constructor(s,c,y,x,F){super(y||`Freestyle API error: ${c??s}`);this.status=s;this.code=c;this.path=x;this.backgroundRequestId=F}}var Te=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[402,"quota"],[408,"timeout"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),Ae=(s,c)=>s===404&&/no such file or directory|\bos error 2\b/i.test(c??""),le=(s,c)=>Ae(s,c)?"file_not_found":Te.get(s)??"provider";function re(s,c){if(s instanceof e)return s;let y=r(s)&&"status"in s?s.status:void 0,x=ne.getStore(),F={};if(o(y)&&Number.isInteger(y)&&y>=100&&y<=599)F.status=y;if(r(s)){if("code"in s&&t(s.code)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.code)){let G=s.code;if(!x?.deniedValues?.some((I)=>G.includes(I)))F.providerCode=G}if("path"in s&&t(s.path))F.operation=ye(s.path)}if(x?.operation)F.operation=x.operation;if(x?.status===y&&x?.requestId)F.requestId=x.requestId;let T=o(y)?le(y,s instanceof Error?s.message:void 0):s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError")?s.name==="TimeoutError"?"timeout":"aborted":s instanceof Error&&s.name==="FreestyleTransportError"?"unavailable":"provider",{detail:q}=i(s,{code:T,status:y===void 0?void 0:String(y),redact:d([process.env.FREESTYLE_API_KEY,...x?.deniedValues??[]])});if(q!==void 0)F.native=q;let L=Object.keys(F).length?Object.assign(Error(JSON.stringify(F)),F):void 0;return E(`Freestyle request failed: ${a(T,F.native)}`,T,c,L)}var Q=new Me;async function we(s,c,y){if(y?.aborted)throw E("Operation aborted","aborted");let x=f(c,y),F=()=>x.parent?.aborted&&!x.timeout.aborted?E("Operation aborted","aborted"):E("Native operation timed out","timeout"),T=()=>{},q=new Promise((L,G)=>{if(T=()=>G(F()),x.signal.addEventListener("abort",T,{once:!0}),x.signal.aborted)T()});try{if(x.signal.aborted)throw F();return await Promise.race([Q.run(x,s),q])}finally{x.signal.removeEventListener("abort",T)}}var xe="https://api.freestyle.sh",Ce="x-freestyle-background-after-secs",be="x-freestyle-background-request-id",ie={afterSecs:5,pollMs:2000,unavailableMs:300000,hopMs:30000},Ve=new Set([408,429,502,503,504]),qe=8388608,De=16777216,je=5,ve={"content-type":"application/octet-stream"},Ne=4294967296,Z=(s)=>typeof s==="object"&&s!==null&&!Array.isArray(s);function ee(s,c){throw E(`Freestyle returned an unexpected ${s}`,"provider",c)}function de(s){return s===void 0||s===null||typeof s==="number"}function ce(s,c){if(!Z(s)||!t(s.id)||!t(s.state))ee("VM record",c);let y={};if(s.metadata!==void 0&&s.metadata!==null){if(!Z(s.metadata))ee("VM record",c);for(let[G,I]of Object.entries(s.metadata))if(t(I))Object.defineProperty(y,G,{value:I,enumerable:!0})}let{idleTimeoutSeconds:x,ttlSeconds:F,autoDeleteSeconds:T,vpcs:q,createdAt:L}=s;if(!de(x)||!de(F)||!de(T)||q!==void 0&&!Array.isArray(q)||L!==void 0&&!t(L))ee("VM record",c);return{id:s.id,state:s.state,metadata:y,createdAt:L??"",idleTimeoutSeconds:x,ttlSeconds:F,autoDeleteSeconds:T,vpcs:q}}function Ue(s){if(s===void 0||s===null)return[];if(!Array.isArray(s))ee("firewall rule list");return s.map((c)=>{if(!Z(c)||!t(c.action)||!Z(c.source)||!Z(c.destination))ee("firewall rule");return{action:c.action,source:c.source,destination:c.destination}})}function He(s,c){if(!Z(s)||!de(s.statusCode)||s.stdout!==void 0&&s.stdout!==null&&!t(s.stdout)||s.stderr!==void 0&&s.stderr!==null&&!t(s.stderr))ee("command result",c);return{statusCode:s.statusCode??null,stdout:s.stdout,stderr:s.stderr}}function fe(s,c){if(!Z(s)||!t(s.uploadId)||!Number.isSafeInteger(s.receivedBytes))ee("upload session",c);return{uploadId:s.uploadId,receivedBytes:Number(s.receivedBytes)}}var ae=(s,c)=>{let y=Z(s)?s[c]:void 0;return t(y)&&y?y:void 0};function ke(s){let c=new _e,y,x=()=>(y=s.apiKey(),{authorization:`Bearer ${y}`}),F=v({provider:"freestyle",label:"Freestyle",defaultPlane:"api",planes:{api:{baseUrl:s.baseUrl,auth:x}},timeoutMs:s.requestTimeoutMs,secrets:()=>[process.env.FREESTYLE_API_KEY,y],authHint:"Set FREESTYLE_API_KEY to a valid Freestyle API key, or pass apiKey.",async fetch(u,k){he(u,k.method,y);let R=await globalThis.fetch(u,k);if(y!==void 0)ge(R,y);return R},mapError(u){let k=c.getStore();if(k)k.failure=u;return u.kind==="status"?le(u.status,u.body.message):void 0}});async function T(u){let k={};try{return await c.run(k,()=>F.request(u))}catch(R){let M=k.failure;if(M?.kind!=="status")throw R;throw new se(M.status,M.body.code,M.body.message,u.path,M.headers.get(be)??void 0)}}let q=()=>Q.getStore()??f(s.requestTimeoutMs),L=(u)=>u instanceof se?Ve.has(u.status)&&u.backgroundRequestId===void 0:u instanceof e&&(u.code==="unavailable"||u.code==="timeout");async function G(u,k,R){let M;try{M=u.json()}catch{M=void 0}let U=u.headers.get(be)??ae(M,"requestId"),j=ae(M,"resultUrl")??(U===void 0?void 0:`/v5/background-requests/${encodeURIComponent(U)}`);if(j===void 0||/[{}]/.test(j))throw new se(u.status,"BACKGROUND_PROTOCOL_ERROR","202 Accepted carried no background request id",k);let n;for(;;){await w(ie.pollMs,R,"freestyle");try{let p=f(Math.min(ie.hopMs,R.remaining()),R.signal),l=await T({method:"GET",path:j,deadline:p});if(l.status!==202)return l;n=void 0}catch(p){if(R.signal.aborted||!L(p))throw p;if(n??=Date.now(),Date.now()-n>=ie.unavailableMs)throw p}}}async function I(u){let k=q(),R={...u,deadline:k},M=await T({...R,headers:{...u.headers,[Ce]:String(ie.afterSecs)}});if(M.status!==202)return M;try{return await G(M,u.path,k)}catch(U){if(u.method==="GET"&&U instanceof se&&U.code==="BACKGROUND_RESULT_UNSTORABLE")return await T(R);throw U}}let Y=(u)=>({params:{id:u},sandboxId:u});async function ue(u,k,R,M){let U={path:"/v5/vms/{id}/fs/uploads/{upload}",params:{id:u,upload:k},sandboxId:u};for(let j=1;;j++)try{return fe((await I({...U,method:"PUT",query:{offset:M},body:R,headers:ve})).json(),u)}catch(n){let p=n instanceof se?n.status>=500||n.status===408||n.status===409||n.status===429:L(n),l=q();if(!p||l.signal.aborted||j>=je)throw n;await w(Math.min(500*2**(j-1),8000),l,"freestyle");let h=await I({...U,method:"GET"}).then((O)=>fe(O.json(),u),()=>{return});if(h&&h.receivedBytes>M)return h}}return{http:F,async createVm(u){let k=(await I({method:"POST",path:"/v5/vms",body:u})).json();return{data:ce(k),firewallRules:Ue(Z(k)?k.firewallRules:void 0),tlsRules:Z(k)&&Array.isArray(k.tlsRules)?k.tlsRules:[]}},async listVms(u,k){let R=(await I({method:"GET",path:"/v5/vms",query:{limit:u,offset:k}})).json();if(!Z(R)||!Array.isArray(R.vms)||!Number.isSafeInteger(R.totalCount))ee("VM list");return{vms:R.vms.map((M)=>ce(M)),totalCount:Number(R.totalCount)}},async getVm(u){return ce((await I({method:"GET",path:"/v5/vms/{id}",...Y(u)})).json(),u)},async deleteVm(u){await I({method:"DELETE",path:"/v5/vms/{id}",...Y(u)})},async exec(u,k){return He((await I({method:"POST",path:"/v5/vms/{id}/exec-await",...Y(u),body:{...k,linuxUser:"root"}})).json(),u)},async lifecycle(u,k){await I({method:"POST",path:`/v5/vms/{id}/${k}`,...Y(u),body:{}})},async snapshot(u,k){let R=(await I({method:"POST",path:"/v5/vms/{id}/snapshot",...Y(u),body:k})).json(),M=ae(R,"snapshotId");if(M===void 0)ee("snapshot result",u);return M},async createTlsRule(u){let k=ae((await I({method:"POST",path:"/v5/tls",body:u})).json(),"domain");if(k===void 0)ee("TLS rule");return{domain:k}},async readFile(u,k,R){let M=R?{range:`bytes=${R.offset}-${R.offset+R.length-1}`}:void 0;return(await T({method:"GET",path:"/v5/vms/{id}/fs/read",...Y(u),query:{path:k},deadline:q(),maxBytes:Ne,headers:M})).body},async writeFile(u,k,R,M){let U=Oe("sha256").update(R).digest("hex");if(R.byteLength<=qe){await I({method:"PUT",path:"/v5/vms/{id}/fs/write",...Y(u),query:{path:k,mode:M,sha256:U},body:R,headers:ve});return}let j=R.byteLength,n=fe((await I({method:"POST",path:"/v5/vms/{id}/fs/uploads",...Y(u),body:{path:k,size:j,sha256:U,mode:M}})).json(),u),p={id:u,upload:n.uploadId};try{let l=n.receivedBytes;while(l<j){let h=(await ue(u,n.uploadId,R.subarray(l,Math.min(l+De,j)),l)).receivedBytes;if(h<=l)throw E("Freestyle upload made no progress","provider",u);l=h}await I({method:"POST",path:"/v5/vms/{id}/fs/uploads/{upload}/commit",params:p,sandboxId:u,body:{}})}catch(l){throw await F.cleanup({method:"DELETE",path:"/v5/vms/{id}/fs/uploads/{upload}",params:p,sandboxId:u}).catch(()=>{}),l}}}}var pe=`import os,sys,marshal,_signal as signal,select,time,fcntl
|
|
2
|
+
${g}
|
|
3
|
+
${C}
|
|
3
4
|
root=sys.argv[1]
|
|
4
5
|
v=marshal.loads(bytes.fromhex(sys.stdin.read()))
|
|
5
6
|
if v.get('files') is not None:
|
|
@@ -57,17 +58,7 @@ try:
|
|
|
57
58
|
if p:
|
|
58
59
|
with open(root+'/pid','w') as m: m.write(str(p.pid))
|
|
59
60
|
if p:
|
|
60
|
-
|
|
61
|
-
end=time.monotonic()+v['timeoutMs']/1000
|
|
62
|
-
while streams or p.poll() is None:
|
|
63
|
-
if not timed and time.monotonic()>=end:
|
|
64
|
-
timed=True
|
|
65
|
-
try: os.killpg(p.pid,signal.SIGKILL)
|
|
66
|
-
except ProcessLookupError: pass
|
|
67
|
-
for fd in select.select(list(streams),[],[],.01 if streams else .001)[0]:
|
|
68
|
-
data=os.read(fd,8192)
|
|
69
|
-
if data: out.write(('["'+streams[fd]+'","'+data.hex()+'"]\\n').encode())
|
|
70
|
-
else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()
|
|
61
|
+
timed=pump(p,lambda name,data: out.write(('["'+name+'","'+data.hex()+'"]\\n').encode()),time.monotonic()+v['timeoutMs']/1000)
|
|
71
62
|
code=p.wait()
|
|
72
63
|
timed=timed or os.path.exists(root+'/cancelled')
|
|
73
64
|
result='{"exitCode":%s,"timedOut":%s}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower())
|
|
@@ -86,7 +77,7 @@ finally:
|
|
|
86
77
|
if a:
|
|
87
78
|
try: os.unlink(a)
|
|
88
79
|
except FileNotFoundError: pass
|
|
89
|
-
|
|
80
|
+
`,Be=J(pe);async function Se(s,c,y){return H({guest:s,input:c,fail:(x,F)=>E(x,F),launch:(x,F)=>s.exec(Be.command(s.id,x),A({files:y,command:c.command,env:c.env,cwd:c.cwd,stdin:c.stdin??"",timeoutMs:c.timeoutMs,activityPath:c.activityPath}).toString("hex"),c.timeoutMs+5000,F)})}var me="/var/lib/sandbox-sdk.json",Ee=Je("sha256").update(pe).digest("hex"),oe="sandbox-sdk-info";function Ke(s){let y=Buffer.from(JSON.stringify({key:s.key??null,labels:s.labels})).toString("base64url").match(/.{1,63}/g)??[];if(y.length>62)throw E("Key and labels exceed Freestyle's native metadata budget","unsupported");return{"sandbox-sdk":"1",[oe]:String(y.length),...Object.fromEntries(y.map((x,F)=>[`${oe}-${F}`,x]))}}var Le="/var/lib/sandbox-sdk-env.json";function Pe(s,c){if(s===void 0)return;if(!Number.isSafeInteger(s)||s<=0)throw E("Timeout must be a positive integer","invalid_argument");if(c&&s<1000)throw E("Hard lifetime requires at least one second","unsupported");return c?Math.floor(s/1000):Math.ceil(s/1000)}function $e(s){if(s.network==="none"||r(s.network)&&s.network.allow.length===0)return[];if(r(s.network))throw E("Host allow lists are not implemented; use all or none","unsupported");return[{action:"allow",source:{},destination:{public:!0}}]}function kt(s={}){let c=new Set,y=new Map,x=new Map,F=new Map,T=s.requestTimeoutMs??30000;if(s.autoDeleteMs!==void 0&&(!Number.isSafeInteger(s.autoDeleteMs)||s.autoDeleteMs<0))throw E("autoDeleteMs must be a non-negative integer of milliseconds","invalid_argument");let q=s.autoDeleteMs===void 0?void 0:Math.ceil(s.autoDeleteMs/1000),L=s.baseUrl??xe;function G(){if(!Number.isSafeInteger(T)||T<=0)throw E("requestTimeoutMs must be a positive integer","invalid_argument");let n=s.apiKey??process.env.FREESTYLE_API_KEY;if(!n?.trim())throw E("Freestyle API key is missing. Authentication is required. Set FREESTYLE_API_KEY or pass apiKey.","auth");return n}let I=ke({baseUrl:L,apiKey:G,requestTimeoutMs:Number.isSafeInteger(T)&&T>0?T:30000}),Y={package:"freestyle",async connect(n,p){let l=S(n,"Freestyle",[{apiKey:G(),baseUrl:L}],"freestyle");if(p===void 0)return l;return N(await P(l.vms,"ref",[p],"freestyle"),"vms.ref","freestyle")}},ue=b({http:I.http,placeholder:["vmId","vmIdOrSlug"],sdk:Y});async function u(n,p,l,h=T){return ne.run({deniedValues:ne.getStore()?.deniedValues},async()=>{try{return await we(p,h,l??Q.getStore()?.signal)}catch(O){throw re(O,n)}})}async function k(n,p,l,h){let O=y.get(n);if(!O)return I.exec(n,{command:p,stdin:l,timeoutMs:h});let V=await I.exec(n,{command:m(`import os,sys,json,tempfile,base64
|
|
90
81
|
v=json.load(sys.stdin)
|
|
91
82
|
for path in ['/workspace','/tmp/.sandbox-sdk']:
|
|
92
83
|
os.makedirs(path,exist_ok=True)
|
|
@@ -101,5 +92,5 @@ for path,content in v['files']:
|
|
|
101
92
|
with tempfile.TemporaryFile() as f:
|
|
102
93
|
f.write(base64.b64decode(v.get('stdin') or '')); f.seek(0); os.dup2(f.fileno(),0)
|
|
103
94
|
print('SDK_PREPARED:',end='',flush=True)
|
|
104
|
-
os.execvp('sh',['sh','-c',v['command']])`),stdin:Buffer.from(JSON.stringify({files:
|
|
105
|
-
if m is not None: os.chmod(p,m)`,
|
|
95
|
+
os.execvp('sh',['sh','-c',v['command']])`),stdin:Buffer.from(JSON.stringify({files:O,command:p,stdin:l})).toString("base64"),timeoutMs:h});if(V.stdout?.startsWith("SDK_PREPARED:"))return y.delete(n),{...V,stdout:V.stdout.slice(13)};return V}async function R(n){return{name:"freestyle",raw:async(p)=>{let l=await u(n,()=>k(n,p,void 0,T));if(l.statusCode!==0)throw E("Guest operation failed",l.statusCode===null?"timeout":"provider",n);return l.stdout??""},upload:(p,l,h)=>u(n,async()=>{if(y.has(n)){if((await k(n,m(`import os,sys; p=sys.argv[1]; os.makedirs(os.path.dirname(p),exist_ok=True); m=int(sys.argv[2],8) if sys.argv[2] else None; f=open(p,'wb'); f.write(sys.stdin.buffer.read()); f.close()
|
|
96
|
+
if m is not None: os.chmod(p,m)`,p,h===void 0?"":h.toString(8)),Buffer.from(l).toString("base64"),T)).statusCode!==0)throw E("File upload failed","provider",n)}else await I.writeFile(n,p,l,h)}),read:(p,l)=>u(n,()=>I.readFile(n,p,l))}}async function M(n,p=!1){if(n.metadata["sandbox-sdk"]!=="1")throw E("Not an SDK VM","not_found",n.id);let l;if(p&&n.metadata[oe]!==void 0){let D=Number(n.metadata[oe]);if(!Number.isInteger(D)||D<1||D>62)throw E("Invalid SDK metadata","not_found",n.id);let B="";for(let K=0;K<D;K++){let W=n.metadata[`${oe}-${K}`];if(!W||!/^[A-Za-z0-9_-]{1,63}$/.test(W))throw E("Invalid SDK metadata","not_found",n.id);B+=W}l=Buffer.from(B,"base64url").toString()}else l=new TextDecoder().decode(await I.readFile(n.id,me));let h;try{h=JSON.parse(l)}catch{throw E("Invalid SDK metadata","not_found",n.id)}if(!h||!r(h)||!("key"in h)||h.key!==null&&!t(h.key)||!("labels"in h)||!h.labels||!r(h.labels)||Array.isArray(h.labels))throw E("Invalid SDK metadata","not_found",n.id);let O={};for(let[D,B]of Object.entries(h.labels)){if(!t(B))throw E("Invalid SDK label","not_found",n.id);Object.defineProperty(O,D,{value:B,enumerable:!0})}let V=Date.parse(n.createdAt);if(!Number.isFinite(V))throw E("Invalid VM creation time","provider",n.id);return{supervisorHash:"supervisorHash"in h&&t(h.supervisorHash)?h.supervisorHash:void 0,info:{id:n.id,key:h.key??void 0,labels:O,createdAt:V,state:n.state==="running"?"running":n.state==="paused"||n.state==="pausing"?"paused":"stopped"}}}async function U(n,p=!1){return(await M(n,p)).info}let j={name:"freestyle",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","snapshot","network-policy"]),create:(n)=>u(void 0,async()=>{let p=ne.getStore();if(p)p.deniedValues=Object.values(n.env??{}).filter(Boolean);if(n.size!==void 0)throw E("Explicit sizes are not implemented; select a base snapshot instead","unsupported");let l=$e(n),h=Pe(n.idleTimeoutMs,!1),O=Pe(n.timeoutMs,!0);if(n.signal?.aborted||Q.getStore()?.signal.aborted)throw E("Creation aborted","aborted");let V={snapshotId:n.from??s.snapshotId??"freestyle/ubuntu",metadata:Ke(n),firewall:{rules:l},tls:{rules:[]},vpcs:[],idleTimeoutSeconds:h??-1,ttlSeconds:O,autoDeleteSeconds:q},D,B=Date.now();G();try{let z=Q.getStore();D=z?await Q.run({signal:z.timeout,timeout:z.timeout,remaining:z.remaining},()=>I.createVm(V)):await I.createVm(V)}catch(z){let X=re(z);if(X.code==="unavailable"||X.code==="timeout")throw E("VM creation outcome is unknown; inspect the account before retrying","outcome_unknown",void 0,X.cause);throw z}let{data:K,firewallRules:W,tlsRules:Fe}=D,te=K.id;c.add(te);try{if(n.signal?.aborted||Q.getStore()?.signal.aborted)throw E("Creation aborted","aborted");if(h!==void 0&&K.idleTimeoutSeconds!==h||O!==void 0&&K.ttlSeconds!==O||q!==void 0&&K.autoDeleteSeconds!==q)throw E("Freestyle did not confirm requested limits","unsupported",te);if(!Array.isArray(K.vpcs)||K.vpcs.length||W.length!==l.length||W.some((X)=>X.action!=="allow"||Object.keys(X.source).length!==1||X.source.vmId!==te||Object.keys(X.destination).length!==1||X.destination.public!==!0))throw E("Freestyle did not confirm the requested firewall","unsupported",te);if(Fe.length)throw E("Unexpected TLS egress grants","unsupported",te);let z=[[me,JSON.stringify({key:n.key??null,labels:n.labels,supervisorHash:Ee})]];if(Object.keys(n.env??{}).length||n.from!==void 0||s.snapshotId!==void 0)z.push([Le,JSON.stringify(n.env??{})]);if(y.set(te,z),Object.keys(n.env??{}).length||n.from!==void 0||s.snapshotId!==void 0){if((await k(te,"true",void 0,T)).statusCode!==0)throw E("Guest setup failed","provider",te)}return await U({...K,createdAt:K.createdAt||new Date(B).toISOString(),state:"running"},!0)}catch(z){throw await Q.exit(()=>j.destroy(te)),z}},n.signal).catch((p)=>{let l=re(p);if(l.code==="timeout")throw E("VM creation outcome is unknown; inspect the account before retrying","outcome_unknown",void 0,l.cause);throw l}),list:(n)=>u(void 0,async()=>{let p=[],l=0;while(!0){let h=await I.listVms(100,l);for(let O of h.vms){if(O.metadata["sandbox-sdk"]!=="1")continue;try{let V=await U(O,!0);if(Object.entries(n).every(([D,B])=>V.labels[D]===B))p.push(V)}catch(V){if(re(V,O.id).code!=="not_found")throw V}}if(l+=h.vms.length,l>=h.totalCount)break;if(!h.vms.length)throw E("VM list ended before all pages were returned")}return p}),async find(n){let p=(await j.list({})).find((l)=>l.key===n);if(!p)return;try{return await j.connect(p.id)}catch(l){if(re(l,p.id).code!=="not_found")throw l;return}},connect:(n)=>u(n,async()=>{let p=await I.getVm(n);c.add(n);let l;try{l=await M(p)}catch(h){if(!["file_not_found","not_found"].includes(re(h,n).code))throw h;l=await M(p,!0),y.set(n,[[me,JSON.stringify({key:l.info.key??null,labels:l.info.labels,supervisorHash:Ee})]])}return l.info}),destroy:(n)=>u(n,async()=>{try{await I.deleteVm(n)}catch(p){if(re(p).code!=="not_found")throw p}c.delete(n),F.delete(n),y.delete(n);for(let p of x.keys())if(p.startsWith(n+":"))x.delete(p)}),async close(n){c.delete(n),F.delete(n)},exec:async(n,p)=>{try{if(!c.has(n))await j.connect(n);let l=await R(n),h=y.get(n),O=await Se({id:n,raw:l.raw,read:(V,D,B)=>u(n,()=>I.readFile(n,V,D),B),exec:(V,D,B,K)=>u(n,async()=>{let W=await I.exec(n,{command:V,stdin:Buffer.from(D).toString("base64"),timeoutMs:B});if(W.statusCode!==0||!W.stdout)throw E("Guest execution failed","provider",n);return W.stdout},K,B)},p,h);if(!O.timedOut&&y.get(n)===h)y.delete(n);return O}catch(l){throw re(l,n)}},files:{..._(R,u),writeSupportsMode:!0},previewUrl:(n,p)=>u(n,async()=>{let l=`${n}:${p}`,h=x.get(l);if(h)return{url:h};let O=`sdk-${crypto.randomUUID()}.style.dev`,V=await I.createTlsRule({action:"allow",domain:O,source:{public:!0},destination:{vmId:n,port:p}});if(V.domain!==O)throw E("Freestyle returned a different preview domain","provider",n);let D=`https://${V.domain}`;return x.set(l,D),{url:D}}),pause:(n)=>u(n,async()=>{await I.lifecycle(n,"pause")}),resume:(n)=>u(n,async()=>{await I.lifecycle(n,"start")}),snapshot:(n,p)=>u(n,async()=>{let l=p?.expiresInMs;if(l!==void 0&&(!Number.isSafeInteger(l)||l<0))throw E("expiresInMs must be a non-negative integer","invalid_argument",n);return{id:await I.snapshot(n,l?{ttlSeconds:Math.ceil(l/1000)}:{})}}),native(n){if(!c.has(n))throw E("Connect the VM first","not_found",n);let p=F.get(n);if(!p)p=b({http:I.http,placeholder:["vmId","vmIdOrSlug"],sandboxId:n,sdk:Y}),F.set(n,p);return p},api:ue};return j}export{kt as freestyle};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { FileInfo, Labels, SandboxInfo } from "../../provider.js";
|
|
2
|
+
import { type JsonValue } from "../../shared/json.js";
|
|
3
|
+
/** The label that carries the SDK's sandbox key in a machine's metadata. */
|
|
4
|
+
export declare const keyLabel = "sandbox-sdk-key";
|
|
5
|
+
/** A member of a JSON object, or undefined. */
|
|
6
|
+
export declare const field: (raw: JsonValue | undefined, key: string) => JsonValue | undefined;
|
|
7
|
+
export interface Machine {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
state: string;
|
|
11
|
+
metadata: Labels;
|
|
12
|
+
createdAt: number;
|
|
13
|
+
}
|
|
14
|
+
export declare function parseMachine(raw: JsonValue | undefined): Machine;
|
|
15
|
+
export interface Operation {
|
|
16
|
+
id: string;
|
|
17
|
+
machineId: string;
|
|
18
|
+
/** Instabox's state; anything but `succeeded` and `failed` is still in progress. */
|
|
19
|
+
state: string;
|
|
20
|
+
errorCode: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
export declare function parseOperation(raw: JsonValue | undefined): Operation;
|
|
23
|
+
export declare function isFinished(op: Operation): boolean;
|
|
24
|
+
export interface MachinePage {
|
|
25
|
+
machines: Machine[];
|
|
26
|
+
nextCursor: string | null;
|
|
27
|
+
}
|
|
28
|
+
export declare function parseMachinePage(raw: JsonValue | undefined): MachinePage;
|
|
29
|
+
export interface Snapshot {
|
|
30
|
+
id: string;
|
|
31
|
+
status: string;
|
|
32
|
+
}
|
|
33
|
+
export declare function parseSnapshot(raw: JsonValue | undefined): Snapshot;
|
|
34
|
+
export type ExecEvent = {
|
|
35
|
+
kind: "stdout";
|
|
36
|
+
text: string;
|
|
37
|
+
} | {
|
|
38
|
+
kind: "stderr";
|
|
39
|
+
text: string;
|
|
40
|
+
} | {
|
|
41
|
+
kind: "exit";
|
|
42
|
+
exitCode: number | null;
|
|
43
|
+
timedOut: boolean;
|
|
44
|
+
} | {
|
|
45
|
+
kind: "error";
|
|
46
|
+
code: string;
|
|
47
|
+
};
|
|
48
|
+
/** One server-sent event from `POST /v1/machines/{id}/exec`; unknown events are skipped. */
|
|
49
|
+
export declare function parseExecEvent(event: string, data: string): ExecEvent | undefined;
|
|
50
|
+
export declare function parseEntry(dir: string, raw: JsonValue | undefined): FileInfo;
|
|
51
|
+
/** A machine as the SDK sees it: the key label moves to `key`, the state to running, paused or stopped. */
|
|
52
|
+
export declare function toInfo(machine: Machine): SandboxInfo;
|
|
53
|
+
/** `stat -c '%F|%s|%.3Y'` output as a FileInfo. */
|
|
54
|
+
export declare function statLine(path: string, line: string): FileInfo;
|
|
55
|
+
/** `find -printf '%P\0%y\0%s\0%T@\0'` output as FileInfo entries of `path`. */
|
|
56
|
+
export declare function findEntries(path: string, stdout: string): FileInfo[];
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { SandboxError, type ErrorCode } from "../../errors.js";
|
|
2
|
+
import { type JsonValue } from "../../shared/json.js";
|
|
3
|
+
interface FailOptions {
|
|
4
|
+
sandboxId?: string | undefined;
|
|
5
|
+
retryable?: boolean;
|
|
6
|
+
cause?: unknown;
|
|
7
|
+
}
|
|
8
|
+
/** An error this adapter writes itself; the message never holds text from Instabox. */
|
|
9
|
+
export declare function fail(message: string, code?: ErrorCode, options?: FailOptions): SandboxError;
|
|
10
|
+
/**
|
|
11
|
+
* The machine-readable part of Instabox's error envelope (`{"error": {"code", "message",
|
|
12
|
+
* "requestId", "retryable", "retryAfterSeconds"}}`). The message is never kept: it can echo
|
|
13
|
+
* paths, commands or request bodies.
|
|
14
|
+
*/
|
|
15
|
+
export interface ApiErrorBody {
|
|
16
|
+
code: string;
|
|
17
|
+
retryable: boolean;
|
|
18
|
+
retryAfterSeconds: number | undefined;
|
|
19
|
+
requestId: string | undefined;
|
|
20
|
+
}
|
|
21
|
+
export declare function parseErrorBody(raw: JsonValue | undefined): ApiErrorBody | undefined;
|
|
22
|
+
/** Instabox's error code first, then the HTTP status. */
|
|
23
|
+
export declare function errorCode(status: number, code: string): ErrorCode;
|
|
24
|
+
/** A non-2xx answer from the API, kept as its status and allowlisted envelope fields. */
|
|
25
|
+
export declare class ApiFailure extends Error {
|
|
26
|
+
readonly status: number;
|
|
27
|
+
readonly body: ApiErrorBody;
|
|
28
|
+
constructor(status: number, body: ApiErrorBody);
|
|
29
|
+
}
|
|
30
|
+
/** Any failure from a request as a SandboxError, keeping only Instabox's status and code. */
|
|
31
|
+
export declare function instaboxError(cause: unknown, operation: string, sandboxId?: string): SandboxError;
|
|
32
|
+
/** A failed asynchronous operation: its code, never its message. */
|
|
33
|
+
export declare function operationError(input: {
|
|
34
|
+
operationId: string;
|
|
35
|
+
errorCode: string | undefined;
|
|
36
|
+
sandboxId: string;
|
|
37
|
+
}): SandboxError;
|
|
38
|
+
export type CreateStage = "operation" | "prepare" | "read";
|
|
39
|
+
/**
|
|
40
|
+
* A create that failed after this call's POST /v1/machines admitted a machine. The evidence
|
|
41
|
+
* names the machine, so the bench can recover it by its labels if the adapter's own delete
|
|
42
|
+
* (`cleanupCode`) failed too.
|
|
43
|
+
*/
|
|
44
|
+
export declare function createError(cause: unknown, context: {
|
|
45
|
+
sandboxId: string;
|
|
46
|
+
stage: CreateStage;
|
|
47
|
+
cleanupCode?: ErrorCode;
|
|
48
|
+
}): SandboxError;
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type InstaboxOptions, type InstaboxProvider } from "./provider.js";
|
|
2
|
+
export type { InstaboxCapability, InstaboxNative, InstaboxOptions, InstaboxProvider, } from "./provider.js";
|
|
3
|
+
/** Instabox (https://instabox.sh) through its REST API: no other package to install. */
|
|
4
|
+
export declare function instabox(options?: InstaboxOptions): InstaboxProvider;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{x}from"../../chunk-drhcb2hx.js";import{c}from"../../chunk-0wp6x4wb.js";import{t,o,e,i,T,a,F}from"../../chunk-0eeyc0aq.js";import{randomUUID as Q}from"node:crypto";import{posix as fe}from"node:path";var V="instabox";function p(r,u="provider",f={}){return new e(`Instabox: ${r}`,{code:u,provider:V,...f})}var ne=/^[a-z][a-z0-9_]{0,47}$/,ue=/^[A-Za-z0-9_-]{1,64}$/;function q(r){let u=c(r)?r.error:void 0;if(!c(u))return;let{code:f,retryAfterSeconds:h,requestId:y}=u;return{code:t(f)&&ne.test(f)?f:"unknown",retryable:u.retryable===!0,retryAfterSeconds:o(h)?h:void 0,requestId:t(y)&&ue.test(y)?y:void 0}}function K(r,u){switch(u){case"missing_key":case"malformed_key":case"invalid_key":case"expired_key":case"revoked_key":case"missing_scope":case"permission_denied":return"auth";case"quota_exceeded":case"rate_limited":case"no_capacity":return"quota";case"spec_not_allowed":case"template_not_allowed":return"unsupported";case"host_unavailable":return"unavailable";case"not_found":return"not_found";default:return r===0?"provider":F(r)}}class N extends Error{status;body;constructor(r,u){super(`Instabox HTTP ${r} ${u.code}`);this.status=r;this.body=u;this.name="InstaboxApiFailure"}}function Ee(r,u){let f={operation:r,status:u.status};if(u.body.code!=="unknown")f.providerCode=u.body.code;if(u.body.requestId)f.requestId=u.body.requestId;return f}function B(r,u,f){if(r instanceof e)return r;if(r instanceof N){let y=K(r.status,r.body.code);return new e(`Instabox ${u} failed: ${a(y)}`,{code:y,provider:V,sandboxId:f,retryable:r.body.retryable||r.status===429,cause:T(Ee(u,r))})}let h=i(r,{code:"provider",known:!0});return new e(`Instabox ${u} failed: ${a("provider")}`,{code:"provider",provider:V,sandboxId:f,cause:h.cause})}function me(r){let u=r.errorCode&&ne.test(r.errorCode)?r.errorCode:void 0,f=K(0,u??""),h={operation:"operation"};if(u)h.providerCode=u;return new e(`Instabox operation ${r.operationId} failed: ${a(f)}`,{code:f,provider:V,sandboxId:r.sandboxId,cause:T(h)})}function ke(r){if(!(r instanceof Error))return{};let u={};if("status"in r&&o(r.status))u.status=r.status;if("providerCode"in r&&t(r.providerCode)&&ne.test(r.providerCode))u.providerCode=r.providerCode;if("requestId"in r&&t(r.requestId)&&ue.test(r.requestId))u.requestId=r.requestId;return u}function le(r,u){let f=B(r,"create",u.sandboxId),h={operation:"create",admittedByThisCall:!0,stage:u.stage,...ke(f.cause)};if(/^m_[a-z0-9]{1,64}$/.test(u.sandboxId))h.sandboxId=u.sandboxId;if(u.cleanupCode!==void 0)h.cleanupCode=u.cleanupCode;return new e(f.message,{code:f.code,provider:V,sandboxId:u.sandboxId,retryable:f.retryable,cause:T(h)})}var W="sandbox-sdk-key",Se=new Set(["suspended","suspending"]),_e=new Set(["running","creating","starting","resuming"]),w=(r,u)=>c(r)?r[u]:void 0;function Me(r){let u={};if(c(r)){for(let[f,h]of Object.entries(r))if(t(h))u[f]=h}return u}function re(r){let u=w(r,"id"),f=w(r,"name"),h=w(r,"state"),y=w(r,"createdAt");if(!t(u)||!t(f)||!t(h)||!t(y))throw p("unexpected machine object from the API");let A=Date.parse(y);if(!Number.isFinite(A))throw p("machine has no valid creation time","provider",{sandboxId:u});return{id:u,name:f,state:h,metadata:Me(w(r,"metadata")),createdAt:A}}function H(r){let u=w(r,"id"),f=w(r,"machineId"),h=w(r,"state");if(!t(u)||!t(f)||!t(h))throw p("unexpected operation object from the API");let y=w(r,"error");return{id:u,machineId:f,state:h,errorCode:y===void 0?void 0:q({error:y})?.code}}function X(r){return r.state==="succeeded"||r.state==="failed"}function pe(r){let u=w(r,"machines");if(!Array.isArray(u))throw p("unexpected machine list from the API");let f=w(r,"nextCursor");return{machines:u.map(re),nextCursor:t(f)?f:null}}function oe(r){let u=w(r,"id"),f=w(r,"status");if(!t(u)||!t(f))throw p("unexpected snapshot object from the API");return{id:u,status:f}}function he(r,u){let f;try{f=JSON.parse(u)}catch{throw p(`exec stream sent invalid JSON in a ${r} event`)}if(!c(f))throw p(`exec stream sent a non-object ${r} event`);switch(r){case"stdout":case"stderr":{let h=w(f,"data");return{kind:r,text:t(h)?h:""}}case"exit":{let h=w(f,"exitCode"),y=w(f,"timedOut")===!0;return{kind:"exit",exitCode:!y&&o(h)?h:null,timedOut:y}}case"error":return{kind:"error",code:(q(f)??q({error:f}))?.code??"unknown"};default:return}}function Ae(r){if(r==="dir"||r==="directory")return"directory";if(r==="symlink")return"symlink";return"file"}function be(r,u){let f=w(u,"name"),h=w(u,"type");if(!t(f)||!t(h))throw p("unexpected directory entry from the API");let y=w(u,"size"),A=w(u,"modTime"),P=t(A)?Date.parse(A):Number.NaN;return{path:fe.join(r,f),type:Ae(h),size:o(y)?y:0,modifiedAt:Number.isFinite(P)?P:0}}function z(r){let{[W]:u,...f}=r.metadata,h=Se.has(r.state)?"paused":_e.has(r.state)?"running":"stopped";return u===void 0?{id:r.id,labels:f,state:h,createdAt:r.createdAt}:{id:r.id,key:u,labels:f,state:h,createdAt:r.createdAt}}function ye(r,u){let[f="",h="0",y="0"]=u.split("|");return{path:r,type:f==="directory"?"directory":f==="symbolic link"?"symlink":"file",size:Number(h),modifiedAt:Math.round(Number(y)*1000)}}function xe(r,u){let f=u.split("\x00"),h=[];for(let y=0;y+3<f.length;y+=4){let[A="",P="f",U="0",E="0"]=f.slice(y,y+4);h.push({path:fe.join(r,A),type:P==="d"?"directory":P==="l"?"symlink":"file",size:Number(U),modifiedAt:Math.round(Number(E)*1000)})}return h}var $e="instabox",we="/data/workspace",Te={small:{vcpus:2,memMiB:4096},medium:{vcpus:4,memMiB:8192},large:{vcpus:8,memMiB:16384}},Pe=["set -e",`if [ ! -e /workspace ]; then mkdir -p ${we}; sudo -n ln -s ${we} /workspace; fi`,"test -w /workspace/","mkdir -p /tmp/.sandbox-sdk","command -v python3 git tar nohup setsid >/dev/null"].join("; "),Oe=new Set(["BASH_ENV","ENV","HOME","HOSTNAME","IFS","LOGNAME","OLDPWD","PATH","PWD","SHELL","SHLVL","USER","BASHOPTS","BASH_VERSINFO","EUID","PPID","SHELLOPTS","UID","TERM","XDG_RUNTIME_DIR","DBUS_SESSION_BUS_ADDRESS","SSL_CERT_FILE","SSL_CERT_DIR","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","NODE_EXTRA_CA_CERTS"]);function Re(r){return Oe.has(r)||r.startsWith("INSTABOX_")||r.startsWith("SSH_")}function Ie(r){return`'${r.replaceAll("'",`'"'"'`)}'`}function D(r){if(!r.startsWith("/"))throw p(`path must be absolute: ${r}`,"invalid_argument");return r}function Ne(r){if(r===void 0)return{};if(t(r))return Te[r];if(r.diskGb!==void 0)throw p("the disk size comes with the machine size (20 GiB); omit diskGb and resize it later","unsupported");return{vcpus:r.cpu,memMiB:r.memoryMb}}function De(r){let u=Math.ceil(r/60000)*60;if(u<300||u>1800)throw p("idleTimeoutMs must be between 5 and 30 minutes","unsupported");return u}function Ue(r){let u=Math.ceil(r/1000);if(u<60||u>86400)throw p("timeoutMs must be between 1 minute and 24 hours","unsupported");return u}function se(r,u){return new Promise((f)=>{let h=setTimeout(f,r);u?.addEventListener("abort",()=>{clearTimeout(h),f()},{once:!0})})}function ge(r={}){let u=(r.baseUrl??process.env.INSTABOX_API_URL??"https://api.instabox.sh").replace(/\/+$/,""),f=r.requestTimeoutMs??60000,h=r.operationTimeoutMs??300000,y=new Map;function A(){let n=r.apiKey??process.env.INSTABOX_API_KEY;if(!n?.trim())throw p("no API key; set INSTABOX_API_KEY or pass apiKey","auth",{retryable:!1});return n.trim()}function P(n,s){let d=new URL(u+n);for(let[m,l]of Object.entries(s??{}))if(l!==void 0)d.searchParams.set(m,l);return d}async function U(n){let s=n.idempotent?Q():void 0,d=Date.now()+(n.timeoutMs??f),m=n.method==="POST"||n.method==="PATCH",l=!m||!!s;for(let b=0;;b++){let I=new Headers({"X-API-Key":A(),"User-Agent":x});if(s)I.set("Idempotency-Key",s);if(n.confirmDelete)I.set("X-Confirm-Delete",n.confirmDelete);if(n.accept)I.set("Accept",n.accept);let S;if(n.raw!==void 0)I.set("Content-Type","application/octet-stream"),S=new Uint8Array(n.raw);else if(n.body!==void 0)I.set("Content-Type","application/json"),S=JSON.stringify(n.body);let k=AbortSignal.timeout(Math.max(1,d-Date.now())),v=n.signal?AbortSignal.any([n.signal,k]):k,g;try{g=await fetch(P(n.path,n.query),{method:n.method,headers:I,body:S,signal:v,redirect:"error"})}catch(ee){let te=i(ee,{code:"outcome_unknown",known:!0});if(n.signal?.aborted)throw p(`${n.operation} aborted`,"aborted",{sandboxId:n.sandboxId,cause:te.cause});if(k.aborted)throw p(`${n.operation} timed out`,m?"outcome_unknown":"timeout",{sandboxId:n.sandboxId,retryable:!m,cause:te.cause});if(l&&b<4){await se(250*2**b,n.signal);continue}throw p(`${n.operation}: the connection failed`,m?"outcome_unknown":"unavailable",{sandboxId:n.sandboxId,retryable:!m,cause:te.cause})}if(g.ok)return g;let C="";try{C=await g.text()}catch(ee){if(m&&g.status>=500)throw p(`${n.operation}: the error answer broke off`,"outcome_unknown",{sandboxId:n.sandboxId,cause:i(ee,{code:"outcome_unknown",known:!0}).cause})}let _;try{_=JSON.parse(C)}catch{_=void 0}let R=q(_)??{code:"unknown",retryable:g.status>=500,retryAfterSeconds:void 0,requestId:void 0},G=g.status===429||l&&(R.retryable||[502,503,504].includes(g.status)),L=Number(g.headers.get("retry-after")),M=1000*(R.retryAfterSeconds??(Number.isFinite(L)?L:0)),O=Math.max(M,500*2**Math.min(b,5));if(G&&b<8&&Date.now()+O<d){if(await se(O,n.signal),n.signal?.aborted)throw p(`${n.operation} aborted`,"aborted");continue}if(m&&g.status===504)throw p(`${n.operation} timed out at the gateway`,"outcome_unknown",{sandboxId:n.sandboxId});throw new N(g.status,R)}}async function E(n){try{let s=await U(n),d;try{d=await s.text()}catch(l){let b=n.method==="POST"||n.method==="PATCH";throw p(`${n.operation}: the answer broke off`,b?"outcome_unknown":"unavailable",{sandboxId:n.sandboxId,retryable:!b,cause:i(l,{code:"unavailable",known:!0}).cause})}let m;try{m=d?JSON.parse(d):void 0}catch{throw p(`${n.operation} returned invalid JSON`,"provider",{sandboxId:n.sandboxId})}return m}catch(s){throw B(s,n.operation,n.sandboxId)}}async function Y(n,s){let d=n,m=Date.now()+h;while(!X(d)){if(Date.now()>m)throw p(`operation ${d.id} did not finish in time`,"timeout",{sandboxId:s,retryable:!0});let l=m-Date.now();if(d=H(await E({method:"GET",path:`/v1/operations/${encodeURIComponent(d.id)}`,operation:"operation status",query:{wait:`${Math.max(1,Math.min(25,Math.floor(l/1000)))}s`},sandboxId:s,timeoutMs:Math.max(1,Math.min(40000,l))})),!X(d)&&Date.now()>m)break}if(!X(d))throw p(`operation ${d.id} did not finish in time`,"timeout",{sandboxId:s,retryable:!0});if(d.state==="failed")throw me({operationId:d.id,errorCode:d.errorCode,sandboxId:s});return d}async function Z(n){return re(await E({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}`,operation:"connect",sandboxId:n}))}async function ae(n){let s=[],d=null;do{let m=P("/v1/machines");for(let[b,I]of Object.entries(n))m.searchParams.append("metadata",`${b}:${I}`);if(m.searchParams.set("limit","200"),d)m.searchParams.set("cursor",d);let l=pe(await E({method:"GET",path:m.pathname+m.search,operation:"list"}));s.push(...l.machines),d=l.nextCursor}while(d);return s.filter((m)=>m.state!=="deleting"&&Object.entries(n).every(([l,b])=>m.metadata[l]===b))}async function ie(n,s){let d=await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/${s}`,operation:s==="suspend"?"pause":s,idempotent:!0,sandboxId:n});await Y(H(d),n)}async function de(n,s,d,m){let l={path:D(s),parents:"true",mode:m.mode===void 0?void 0:`0${(m.mode&4095).toString(8)}`};try{await U({method:"PUT",path:`/v1/machines/${encodeURIComponent(n)}/files`,operation:"write file",query:l,raw:d,sandboxId:n,signal:m.signal,timeoutMs:m.timeoutMs})}catch(b){if(b instanceof N&&b.body.code==="not_a_file")throw p(`${s} is a directory`,"invalid_argument",{sandboxId:n});throw B(b,"write file",n)}}async function J(n,s,d){let m=new AbortController,l=setTimeout(()=>m.abort(),d.timeoutMs),b=d.signal?AbortSignal.any([d.signal,m.signal]):m.signal,I;try{I=await U({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/exec`,operation:"exec",body:{...s,timeoutSeconds:Math.min(600,Math.max(1,Math.ceil(d.timeoutMs/1000)+1))},accept:"text/event-stream",sandboxId:n,signal:b,timeoutMs:d.timeoutMs+30000})}catch(C){if(clearTimeout(l),b.aborted)return{exitCode:null,timedOut:!0};throw B(C,"exec",n)}let S=I.body?.getReader();if(!S)throw clearTimeout(l),p("exec returned no stream","provider",{sandboxId:n});let k=new TextDecoder,v="",g=!1;try{for(;;){let C;try{C=await S.read()}catch(R){if(b.aborted)return{exitCode:null,timedOut:!0};throw p("exec stream broke","outcome_unknown",{sandboxId:n,cause:i(R,{code:"outcome_unknown",known:!0}).cause})}if(C.done){g=!0;break}v+=k.decode(C.value,{stream:!0});let _=v.indexOf(`
|
|
2
|
+
|
|
3
|
+
`);while(_>=0){let R=v.slice(0,_);v=v.slice(_+2),_=v.indexOf(`
|
|
4
|
+
|
|
5
|
+
`);let G="message",L=[];for(let O of R.split(`
|
|
6
|
+
`))if(O.startsWith("event:"))G=O.slice(6).trim();else if(O.startsWith("data:"))L.push(O.slice(5).replace(/^ /,""));if(!L.length)continue;let M=he(G,L.join(`
|
|
7
|
+
`));if(!M)continue;switch(M.kind){case"stdout":case"stderr":if(M.text)d.onChunk({stream:M.kind,text:M.text});break;case"exit":return g=await ve(S),{exitCode:M.exitCode,timedOut:M.timedOut};case"error":throw p(`exec failed (${M.code})`,K(0,M.code),{sandboxId:n});default:throw p(`unknown exec event ${String(M)}`)}}}if(b.aborted)return{exitCode:null,timedOut:!0};throw p("exec stream ended without an exit event","outcome_unknown",{sandboxId:n})}finally{if(clearTimeout(l),!g)await S.cancel().catch(()=>{return})}}async function ve(n){let s=Date.now()+1000;try{while(Date.now()<s){let d=new Promise((l)=>setTimeout(()=>l("timeout"),Math.max(1,s-Date.now()))),m=await Promise.race([n.read(),d]);if(m==="timeout")return!1;if(m.done)return!0}}catch{return!1}return!1}async function j(n,s,d=[0]){let m="",l="",b=await J(n,{argv:s},{timeoutMs:60000,onChunk(I){if(I.stream==="stdout")m+=I.text;else l+=I.text}});if(b.timedOut)throw p(`${s[0]} timed out`,"timeout",{sandboxId:n});if(b.exitCode===null||!d.includes(b.exitCode))throw p(`${s[0]} failed (exit ${b.exitCode}): ${l.trim().slice(0,300)}`,"provider",{sandboxId:n});return{exitCode:b.exitCode,stdout:m}}async function ce(n){try{let s=await E({method:"DELETE",path:`/v1/machines/${encodeURIComponent(n)}`,operation:"destroy",idempotent:!0,confirmDelete:n,sandboxId:n});await Y(H(s),n)}catch(s){if(s instanceof e&&s.code==="not_found")return;throw s}finally{for(let s of y.keys())if(s.startsWith(`${n}:`))y.delete(s)}}async function Ce(n,s,d){let m;try{await ce(n)}catch(l){m=l instanceof e?l.code:"provider"}throw le(d,{sandboxId:n,stage:s,cleanupCode:m})}return{name:$e,keyMode:"best-effort",commandShell:"bash",capabilities:new Set(["pause","snapshot","snapshot-delete","size"]),async create(n){if(n.network!==void 0&&n.network!=="all")throw p("network policies are not supported","unsupported");let s={...n.labels};if(n.key!==void 0)s[W]=n.key;if(Object.keys(s).length>32)throw p("at most 32 labels (one is used for the key)","unsupported");let d=n.from?.startsWith("sn_")?n.from:void 0,m=d?void 0:n.from??r.template,l=Ne(n.size),b={name:`sbx-${Q().slice(0,13).replace("-","")}`,metadata:s,...l};if(d)b.snapshotId=d;else if(m)b.templateId=m;if(n.idleTimeoutMs!==void 0)b.autoSuspendAfterSeconds=De(n.idleTimeoutMs);if(n.timeoutMs!==void 0)b.deleteAfterSeconds=Ue(n.timeoutMs);let I=Object.fromEntries(Object.entries(n.env??{}).filter(([C])=>!Re(C)));if(Object.keys(I).length>0)b.env=I;let S=H(await E({method:"POST",path:"/v1/machines",operation:"create",body:b,idempotent:!0})),k=S.machineId,v="operation",g=()=>p("create aborted","aborted",{sandboxId:k});try{if(await Y(S,k),n.signal?.aborted)throw g();if(v="prepare",await j(k,["bash","-c",Pe]),n.signal?.aborted)throw g();return v="read",z(await Z(k))}catch(C){return Ce(k,v,C)}},async find(n){let[s]=await ae({[W]:n});return s?z(s):void 0},async connect(n){return z(await Z(n))},async list(n){return(await ae(n)).map(z)},destroy:ce,async exec(n,s){let d={cmd:s.command,cwd:s.cwd,envs:s.env};if(s.stdin!==void 0){let m=new TextEncoder().encode(s.stdin);if(m.byteLength<=1048576)return J(n,{...d,stdin:s.stdin},s);let l=`/tmp/.sandbox-sdk/stdin-${Q()}`,b=Date.now(),I=new AbortController,S=setTimeout(()=>I.abort(),s.timeoutMs),k=s.signal?AbortSignal.any([s.signal,I.signal]):I.signal,v=()=>J(n,{argv:["rm","-f","--",l]},{timeoutMs:1e4,onChunk:()=>{return}}).catch(()=>{return});try{await de(n,l,m,{signal:k,timeoutMs:s.timeoutMs})}catch(_){if(await v(),k.aborted)return{exitCode:null,timedOut:!0};throw _}finally{clearTimeout(S)}let g=`exec < ${Ie(l)}; rm -f ${Ie(l)}; ${s.command}`,C;try{C=await J(n,{...d,cmd:g},{...s,timeoutMs:Math.max(1,s.timeoutMs-(Date.now()-b))})}catch(_){throw await v(),_}if(C.exitCode===null)await v();return C}return J(n,d,s)},files:{writeCreatesParents:!0,writeSupportsMode:!0,async read(n,s){try{let d=await U({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}/files/content`,operation:"read file",query:{path:D(s)},sandboxId:n,timeoutMs:300000});return new Uint8Array(await d.arrayBuffer())}catch(d){if(d instanceof N&&d.status===404)throw p(`no such file: ${s}`,"file_not_found",{sandboxId:n});if(d instanceof N&&d.body.code==="not_a_file")throw p(`${s} is a directory`,"invalid_argument",{sandboxId:n});throw B(d,"read file",n)}},async write(n,s,d,m){await de(n,s,d,{mode:m?.mode,timeoutMs:300000})},async list(n,s){let d;try{d=await E({method:"GET",path:`/v1/machines/${encodeURIComponent(n)}/files`,operation:"list files",query:{path:D(s)},sandboxId:n})}catch(l){if(l instanceof e&&l.code==="not_found")throw p(`no such directory: ${s}`,"file_not_found",{sandboxId:n});throw l}if(w(d,"type")!=="dir")throw p(`${s} is not a directory`,"invalid_argument",{sandboxId:n});let m=w(d,"entries");if(!Array.isArray(m))throw p("directory listing has no entries","provider",{sandboxId:n});if(m.length>=5000){let{stdout:l}=await j(n,["find","-H",D(s),"-mindepth","1","-maxdepth","1","-printf","%P\\0%y\\0%s\\0%T@\\0"]);return xe(s,l)}return m.map((l)=>be(s,l))},async stat(n,s){let d=D(s),m=d==="/workspace"||d==="/workspace/"?["-L"]:[],{exitCode:l,stdout:b}=await j(n,["stat",...m,"-c","%F|%s|%.3Y","--",d],[0,1]);if(l!==0)throw p(`no such file: ${s}`,"file_not_found",{sandboxId:n});return ye(s,b.trim())},async remove(n,s,d){let m=D(s),{exitCode:l}=await j(n,["bash","-c",'test -e "$1" || test -L "$1" || exit 3; rm -f $2 -- "$1"',"remove",m,d.recursive?"-r":"-d"],[0,3]);if(l===3)throw p(`no such file: ${s}`,"file_not_found",{sandboxId:n})},async mkdir(n,s){await j(n,["mkdir","-p","--",D(s)])}},async previewUrl(n,s){let d=y.get(`${n}:${s}`);if(d)return{url:d};let m=await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/ports`,operation:"publish port",body:{port:s},sandboxId:n}),l=w(m,"url");if(!t(l))throw p("publishing the port returned no URL","provider",{sandboxId:n});return y.set(`${n}:${s}`,l),{url:l}},native(n){return{machineId:n,request:({method:s,path:d,body:m})=>{let l=s.toUpperCase();if(l!=="GET"&&l!=="POST"&&l!=="PUT"&&l!=="PATCH"&&l!=="DELETE")throw p(`unsupported method ${s}`,"invalid_argument");return E({method:l,path:d,operation:"native request",body:m,idempotent:l!=="GET",sandboxId:n})}}},async pause(n){await ie(n,"suspend")},async resume(n){let s=await Z(n);await ie(n,s.state==="stopped"?"start":"resume")},async snapshot(n,s){if(s?.expiresInMs)throw p("snapshots are kept until deleted; omit expiresInMs","unsupported",{sandboxId:n});let d=oe(await E({method:"POST",path:`/v1/machines/${encodeURIComponent(n)}/snapshots`,operation:"snapshot",body:{name:`sbx-${Q()}`},idempotent:!0,sandboxId:n,timeoutMs:h})),m=Date.now()+h;while(d.status==="pending"){if(Date.now()>m)throw p(`snapshot ${d.id} is still pending`,"timeout",{sandboxId:n});await se(500),d=oe(await E({method:"GET",path:`/v1/snapshots/${encodeURIComponent(d.id)}`,operation:"snapshot status",sandboxId:n}))}if(d.status!=="ready")throw p(`snapshot ${d.id} ended ${d.status}`,"provider",{sandboxId:n});return{id:d.id}},async deleteSnapshot(n){try{return await E({method:"DELETE",path:`/v1/snapshots/${encodeURIComponent(n)}`,operation:"delete snapshot",idempotent:!0,confirmDelete:n}),!0}catch(s){if(s instanceof e&&s.code==="not_found")return!1;throw s}}}}function nt(r={}){return ge(r)}export{nt as instabox};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Provider } from "../../provider.js";
|
|
2
|
+
import type { JsonValue } from "../../shared/json.js";
|
|
3
|
+
export type InstaboxCapability = "pause" | "snapshot" | "snapshot-delete" | "size";
|
|
4
|
+
export interface InstaboxOptions {
|
|
5
|
+
/** Defaults to INSTABOX_API_KEY. Needs the images:write and images:delete scopes for snapshots. */
|
|
6
|
+
apiKey?: string;
|
|
7
|
+
/** Default: INSTABOX_API_URL, else https://api.instabox.sh. */
|
|
8
|
+
baseUrl?: string;
|
|
9
|
+
/** Template for new machines, optionally pinned as `id@version`. Default: Instabox's default, `agent-browser`. */
|
|
10
|
+
template?: string;
|
|
11
|
+
/** Deadline for each control-plane request. Default: 60 seconds. */
|
|
12
|
+
requestTimeoutMs?: number;
|
|
13
|
+
/** Deadline for create, start, pause, resume, delete and snapshot operations. Default: 5 minutes. */
|
|
14
|
+
operationTimeoutMs?: number;
|
|
15
|
+
}
|
|
16
|
+
/** `box.native`: the machine ID and an authenticated request to Instabox's API. */
|
|
17
|
+
export interface InstaboxNative {
|
|
18
|
+
readonly machineId: string;
|
|
19
|
+
/** Calls `https://api.instabox.sh<path>` with this adapter's key. Writes get an `Idempotency-Key`. */
|
|
20
|
+
request(input: {
|
|
21
|
+
method: string;
|
|
22
|
+
path: string;
|
|
23
|
+
body?: JsonValue;
|
|
24
|
+
}): Promise<JsonValue | undefined>;
|
|
25
|
+
}
|
|
26
|
+
export type InstaboxProvider = Provider<InstaboxNative, InstaboxCapability>;
|
|
27
|
+
/** Instabox through its REST API. Machines are Firecracker microVMs; `/workspace` links to the persistent `/data` disk. */
|
|
28
|
+
export declare function createInstaboxProvider(options?: InstaboxOptions): InstaboxProvider;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)){let w=g(j(I));if(w.error)throw c(`Image pull: ${T(w.error)}`)}return}return j(v.toString())}async exec(s,a,l){let L=g(await this.call("POST",`/containers/${k(s)}/exec`,{Cmd:a,WorkingDir:l.cwd??"/",User:l.user,Env:Object.entries(l.env??{}).map(([w,b])=>`${w}=${b}`),AttachStdout:!0,AttachStderr:!0,AttachStdin:l.stdin!==void 0,Tty:!1})),v=T(L.Id);await new Promise((w,b)=>{let h=new G(l.onChunk),C=z({agent:this.pool(),socketPath:this.socketPath,path:`/v1.44/exec/${k(v)}/start`,method:"POST",headers:{"Content-Type":"application/json",Connection:"Upgrade",Upgrade:"tcp"}}),x=(S)=>{S.on("data",(D)=>{try{h.push(D)}catch(P){S.destroy(),b(P)}}),S.on("error",(D)=>b(c(D.message,"unavailable"))),S.on("end",()=>{try{h.end(),w()}catch(D){b(D)}})};C.on("upgrade",(S,D,P)=>{if(D.setTimeout(0),x(D),P.length)try{h.push(P)}catch(r){D.destroy(),b(r);return}D.end(l.stdin??"")}),C.on("response",(S)=>{if((S.statusCode??500)>=400){S.resume(),b(c(`Exec attach HTTP ${S.statusCode}`));return}x(S)}),C.on("error",(S)=>b(c(S.message,"unavailable"))),C.setTimeout(30000,()=>C.destroy(c("Exec attach timed out","timeout"))),C.end(JSON.stringify({Detach:!1,Tty:!1}))});let I=g(await this.call("GET",`/exec/${k(v)}/json`));if(I.Running)throw c("Exec attachment ended before the process exited","outcome_unknown");return R(I.ExitCode)}}var F="sandbox-sdk.local.deadline",H="sandbox-sdk.local.idle-ms",_="/tmp/.sandbox-sdk-activity",U="sandbox-sdk.local.key",Y="sandbox-sdk.local.snapshot",oe=["for d in /tmp/.sandbox-sdk/procs/*/",'do [ -d "$d" ] || continue','rm -rf "$d"lock','[ ! -f "$d"spec.json ] || [ -f "$d"exit ] || printf 137 > "$d"exit || exit 1',"done","rm -rf /tmp/.sandbox-sdk/runs/*"].join("; "),se=new Set([F,H,U,Y]),Z=(s)=>Object.fromEntries(Object.entries(s).filter(([a])=>!se.has(a))),V=(s)=>`sandbox-sdk-${re("sha256").update(s).digest("hex")}`,ie={small:{cpu:1,memoryMb:1024},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}};function ae(s){if(!s)return{};if(!t(s)&&s.diskGb!==void 0)throw c("Docker cannot enforce diskGb portably; pass only cpu and memoryMb, or use small, medium, or large","unsupported");let a=t(s)?ie[s]:s;if(!a)throw c("Unknown size preset","unsupported");if(!(a.cpu>0)||!Number.isFinite(a.cpu)||!Number.isSafeInteger(a.memoryMb)||a.memoryMb<6)throw c("Custom sizes need cpu above 0 and memoryMb of at least 6","invalid_argument");return{NanoCpus:Math.round(a.cpu*1e9),Memory:a.memoryMb*1024*1024,MemorySwap:a.memoryMb*1024*1024}}function ce(s,a){let l=g(s);return a.startsWith(`${String(l.Os)}/${String(l.Architecture)}`)}var X=(s,a)=>{if(s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw c(`${a} must be a positive integer`,"invalid_argument")};function de(s){X(s.pidsLimit,"pidsLimit"),X(s.shmSizeMb,"shmSizeMb");let a=s.networkMode;if(a!==void 0&&(!a||a==="host"||a==="none"||a.startsWith("container:")))throw c("networkMode must name a bridge-style network; host and container modes break localhost previews and network: none","unsupported");for(let l of s.mounts??[]){if(!["bind","volume","tmpfs"].includes(l.type)||!l.target.startsWith("/"))throw c("Mounts need type bind, volume or tmpfs and an absolute target","invalid_argument");if(l.type==="bind"?!l.source?.startsWith("/"):l.type==="tmpfs"&&l.source!==void 0)throw c("Bind mounts need an absolute host source; tmpfs mounts take none","invalid_argument")}return{Runtime:s.runtime,Mounts:s.mounts?.length?s.mounts.map((l)=>({Type:l.type,Target:l.target,Source:l.source,ReadOnly:l.readOnly??!1})):void 0,PidsLimit:s.pidsLimit,ShmSize:s.shmSizeMb===void 0?void 0:s.shmSizeMb*1024*1024,CapAdd:s.capAdd?.length?s.capAdd:void 0,CapDrop:s.capDrop?.length?s.capDrop:void 0,SecurityOpt:s.securityOpt?.length?s.securityOpt:void 0}}function ee(s){let a=g(s),l=g(a.Config),L=g(a.State),v=Object.fromEntries(Object.entries(g(l.Labels??{})).map(([I,w])=>[I,T(w)]));if(v["sandbox-sdk"]!=="1")throw c("Container was not created by Sandbox SDK","not_found");return{info:{id:T(a.Id),key:v[U]||void 0,labels:Z(v),state:L.Paused?"paused":L.Running?"running":"stopped",createdAt:Date.parse(T(a.Created))},labels:v}}var Q=(s)=>ee(s).info;function xe(s={}){let a=new B(s.dockerHost),l=s.image??"node:22-bookworm",L=de(s),v=s.platform?`&platform=${k(s.platform)}`:"",I=new Map,w=new Set,b=new Map,h=(r)=>a.call("GET",`/containers/${k(r)}/json`);async function C(r,i,d){let u="",p="",m=w.has(r)?["sh","-c",`touch ${_}; "$@"; code=$?; touch ${_}; exit "$code"`,"sh",...i]:i,M=await a.exec(r,m,{stdin:d,onChunk(O){if(O.stream==="stdout")u+=O.text;else p+=O.text}});if(M!==0)throw c(`Container operation exited ${M}: ${p}`,p.includes("ENOENT")||p.includes("No such file")?"file_not_found":"provider");return u}let x=(r,i,d=[],u)=>C(r,["node","-e",i,...d],u),S="const fs=require('fs'); const p=require('path'); const stat=x=>{const s=fs.lstatSync(x);return {path:x,type:s.isSymbolicLink()?'symlink':s.isDirectory()?'directory':'file',size:s.size,modifiedAt:s.mtimeMs}};";function D(r){let i=g(r),d=i.type;if(d!=="file"&&d!=="directory"&&d!=="symlink")throw c("Invalid file type");return{path:T(i.path),type:d,size:R(i.size),modifiedAt:R(i.modifiedAt)}}let P={name:"local",keyMode:"exact",capabilities:new Set(["pause","snapshot","size","network-policy"]),async create(r){if(r.network!==void 0&&r.network!=="all"&&r.network!=="none")throw c("Network allow-lists cannot be enforced by this Docker adapter","unsupported");for(let y of[r.idleTimeoutMs,r.timeoutMs])if(y!==void 0&&(!Number.isFinite(y)||y<=0))throw c("Timeouts must be positive milliseconds","invalid_argument");let i=ae(r.size);if(r.signal?.aborted)throw c("Creation aborted","aborted");let d={},u=performance.now(),p=r.from??l,m;try{let y=await a.call("GET",`/images/${k(p)}/json`);m=!s.platform||r.from!==void 0||ce(y,s.platform)}catch(y){if(!(y instanceof e)||y.code!=="not_found")throw y;if(r.from)throw c("Snapshot image not found","not_found");m=!1}if(!m)await a.call("POST",`/images/create?fromImage=${k(p)}${v}`);if(d.createInspectMs=performance.now()-u,r.signal?.aborted)throw c("Creation aborted after image pull","aborted");let M=[...new Set(r.ports??[3000])],O=Object.fromEntries(M.map((y)=>[`${y}/tcp`,[{HostIp:"127.0.0.1",HostPort:""}]]));u=performance.now();let A=Date.now(),N={...r.labels,"sandbox-sdk":"1",[U]:r.key??"",[F]:r.timeoutMs===void 0?"":String(A+r.timeoutMs),[H]:r.idleTimeoutMs===void 0?"":String(r.idleTimeoutMs)},E=g(await a.call("POST",`/containers/create?name=${k(r.key?V(r.key):`sandbox-sdk-${K()}`)}${r.from===void 0?v:""}`,{Image:p,WorkingDir:"/workspace",Cmd:["sh","-c","exec sleep infinity"],User:s.user,Env:Object.entries(r.env??{}).map(([y,te])=>`${y}=${te}`),Labels:N,ExposedPorts:Object.fromEntries(M.map((y)=>[`${y}/tcp`,{}])),HostConfig:{...L,...i,NetworkMode:r.network==="none"?"none":s.networkMode??"bridge",PortBindings:r.network==="none"?{}:O,Init:!0}}));d.createContainerMs=performance.now()-u;let J=T(E.Id);if(b.set(J,d),r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)w.add(J);try{if(u=performance.now(),await a.call("POST",`/containers/${k(J)}/start`),d.createStartMs=performance.now()-u,u=performance.now(),s.user!==void 0){if(await a.exec(J,["chown","--",s.user,"/workspace"],{user:"0",onChunk(){}})!==0)throw c(`Could not give /workspace to user ${s.user}`,"invalid_argument")}if(r.from!==void 0)await C(J,["sh","-c",oe]);if(d.createPrerequisiteMs=performance.now()-u,r.signal?.aborted)throw c("Creation aborted","aborted");if(r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)return await P.connect(J);return{id:J,key:r.key,labels:Z(N),state:"running",createdAt:A}}catch(y){throw await P.destroy(J),y}},async find(r){try{let i=await P.connect(V(r));return i.key===r?i:void 0}catch(i){if(i instanceof e&&i.code==="not_found")return;throw i}},async connect(r){let{info:i,labels:d}=ee(await h(r)),u=(O)=>O?Number(O):1/0,p=u(d[F]),m=u(d[H]);if(Number.isFinite(p)||Number.isFinite(m))w.add(i.id);let M=Date.now()>=p;if(!M&&Number.isFinite(m)&&i.state==="running"){let O="";if(await a.exec(i.id,["node","-e",`const f=require('fs'), p='/tmp/.sandbox-sdk';const busy=(f.existsSync(p+'/runs')&&f.readdirSync(p+'/runs').length)||(f.existsSync(p+'/procs')&&f.readdirSync(p+'/procs').some(n=>!f.existsSync(p+'/procs/'+n+'/exit')));process.stdout.write(String(busy?Date.now():Math.max(${i.createdAt},f.existsSync('${_}')?f.statSync('${_}').mtimeMs:0)))`],{onChunk(N){if(N.stream==="stdout")O+=N.text}})!==0||!Number.isFinite(Number(O)))throw c("Could not check local idle deadline","provider");M=Date.now()-Number(O)>=m}if(M)throw await P.destroy(i.id),c("Local sandbox deadline expired; create another sandbox","not_found");return i},async list(r){let i=k(JSON.stringify({label:Object.entries({...r,"sandbox-sdk":"1"}).map(([p,m])=>`${p}=${m}`)})),d=q(await a.call("GET",`/containers/json?all=1&filters=${i}`)),u=[];for(let p of d)try{u.push(Q(await h(T(g(p).Id))))}catch(m){if(!(m instanceof e)||m.code!=="not_found")throw m}return u},async destroy(r){let i=I.get(r);if(i)return i;let d=(async()=>{try{let u=Q(await h(r));if(u.state==="paused")await a.call("POST",`/containers/${k(r)}/unpause`);if(u.state!=="stopped")await a.call("POST",`/containers/${k(r)}/stop?t=1`);await a.call("DELETE",`/containers/${k(r)}?force=1&v=1`)}catch(u){if(!(u instanceof e)||u.code!=="not_found")throw u}})();I.set(r,d);try{await d}finally{I.delete(r),w.delete(r),b.delete(r)}},async exec(r,i){let d=performance.now();if(i.signal?.aborted)return{exitCode:null,timedOut:!0};let u=`/tmp/.sandbox-sdk-exec-${K()}`,p=!1,m=()=>{},M=new Promise((E)=>{m=()=>{p=!0,E("cancelled")}});i.signal?.addEventListener("abort",m,{once:!0});let O=setTimeout(m,i.timeoutMs),A=["setsid","--wait","sh","-c",`echo $$ > ${n(u)}; ${w.has(r)?`touch ${_}; trap 'touch ${_}' EXIT;`:""} cd ${n(i.cwd)} || exit; sh -c ${n(i.command)}`],N=a.exec(r,A,{env:i.env,stdin:i.stdin,onChunk:i.onChunk});try{if(await Promise.race([N,M]),p)await C(r,["sh","-c",`i=0; while [ ! -s ${n(u)} ]; do i=$((i+1)); [ "$i" -lt 3000 ] || exit 1; sleep .01; done; p=$(cat ${n(u)}); node -e 'try {process.kill(-Number(process.argv[1]), "SIGKILL")} catch(e) {if(e.code!=="ESRCH") throw e}' "$p"`]);let E=await N;return{exitCode:p?null:E,timedOut:p}}finally{clearTimeout(O),i.signal?.removeEventListener("abort",m),await C(r,["rm","-f",u]).catch(()=>{});let E=b.get(r);if(E&&E.firstCommandMs===void 0)E.firstCommandMs=performance.now()-d}},files:{writeCreatesParents:!0,writeSupportsMode:!0,async read(r,i){return new Uint8Array(Buffer.from(await x(r,"process.stdout.write(require('fs').readFileSync(process.argv[1]).toString('base64'))",[i]),"base64"))},async write(r,i,d,u){await x(r,"const f=require('fs'),p=process.argv[1];f.mkdirSync(require('path').dirname(p),{recursive:true});f.writeFileSync(p,Buffer.from(f.readFileSync(0,'utf8'),'base64'));if(process.argv[2])f.chmodSync(p,parseInt(process.argv[2],8))",[i,u?.mode===void 0?"":u.mode.toString(8)],Buffer.from(d).toString("base64"))},async stat(r,i){return D(j(await x(r,S+"process.stdout.write(JSON.stringify(stat(process.argv[1])))",[i])))},async list(r,i){return q(j(await x(r,S+"process.stdout.write(JSON.stringify(fs.readdirSync(process.argv[1]).map(x=>stat(p.join(process.argv[1],x)))))",[i]))).map(D)},async mkdir(r,i){await x(r,"require('fs').mkdirSync(process.argv[1],{recursive:true})",[i])},async remove(r,i,d){await x(r,"require('fs').rmSync(process.argv[1],{recursive:process.argv[2]==='true'})",[i,String(d.recursive)])}},async previewUrl(r,i){let d=g(await h(r)),u=g(d.NetworkSettings),p=g(u.Ports??{}),m=q(p[`${i}/tcp`]??[])[0];if(!m)throw c(`Port ${i} has no localhost mapping; declare it in ports when creating the sandbox`,"unsupported");let M=g(m);if(M.HostIp!=="127.0.0.1")throw c("Preview binding is not loopback","unsupported");return{url:`http://127.0.0.1:${T(M.HostPort)}/`}},native(r){return{id:r,client:a}},async usage(r){let i=g(await h(r)),d=g(i.State);return{...b.get(r),runningMs:d.Running&&!d.Paused?Math.max(0,Date.now()-Date.parse(T(d.StartedAt))):0}},async pause(r){await P.connect(r),await a.call("POST",`/containers/${k(r)}/pause`)},async resume(r){await P.connect(r),await a.call("POST",`/containers/${k(r)}/unpause`)},async snapshot(r,i){if(i?.expiresInMs)throw c("Docker images do not expire; omit expiresInMs and delete the snapshot image when you are done","unsupported");await P.connect(r);let d=g(await a.call("POST",`/commit?container=${k(r)}&pause=true`,{Labels:{"sandbox-sdk":"1",[Y]:"1"}}));return{id:T(d.Id)}}};return P}export{xe as local};
|
|
1
|
+
import{n}from"../../chunk-2ts3evzh.js";import{x}from"../../chunk-drhcb2hx.js";import{c}from"../../chunk-0wp6x4wb.js";import{t,o,e}from"../../chunk-0eeyc0aq.js";import{createHash as oe,randomUUID as V}from"node:crypto";import{Agent as re,request as W}from"node:http";import{StringDecoder as G}from"node:string_decoder";var d=(s,a="provider")=>new e(`${s}. Docker request failed. Check Docker access and the supplied options.`,{code:a,provider:"local"});function g(s){if(!c(s))throw d("Invalid Docker response");return Object.fromEntries(Object.entries(s))}function L(s){if(!t(s))throw d("Expected a Docker string");return s}function q(s){if(!o(s)||!Number.isFinite(s))throw d("Expected a Docker number");return s}function B(s){if(!Array.isArray(s))throw d("Expected a Docker array");return s}var k=encodeURIComponent;function R(s){try{return JSON.parse(s)}catch{throw d("Malformed Docker JSON response")}}class K{emit;pending=Buffer.alloc(0);stdout=new G("utf8");stderr=new G("utf8");constructor(s){this.emit=s}push(s){this.pending=Buffer.concat([this.pending,s]);while(this.pending.length>=8){let a=this.pending.readUInt32BE(4);if(a>67108864||![1,2].includes(this.pending[0]??0))throw d("Invalid Docker exec frame");if(this.pending.length<a+8)return;let l=this.pending[0]===1?"stdout":"stderr",E=this[l].write(this.pending.subarray(8,a+8));if(E)this.emit({stream:l,text:E});this.pending=this.pending.subarray(a+8)}}end(){if(this.pending.length)throw d("Truncated Docker exec frame");for(let s of["stdout","stderr"]){let a=this[s].end();if(a)this.emit({stream:s,text:a})}}}class U{socketPath;connectionPool;pool(){return this.connectionPool??=new re({keepAlive:!0,timeout:5000})}constructor(s=process.env.DOCKER_HOST??"unix:///var/run/docker.sock"){if(!s.startsWith("unix://")||!s.slice(7).startsWith("/"))throw d("DOCKER_HOST must be an absolute unix:// socket URL; remote Docker hosts cannot provide localhost previews","unsupported");this.socketPath=s.slice(7)}async call(s,a,l){let E=l===void 0?void 0:JSON.stringify(l),C=await new Promise((T,w)=>{let b=W({agent:this.pool(),socketPath:this.socketPath,path:`/v1.44${a}`,method:s,headers:{"Content-Type":"application/json","User-Agent":x}},(h)=>{let M=[];h.on("data",(S)=>M.push(S)),h.on("error",(S)=>w(d(S.message,"unavailable"))),h.on("end",()=>{let S=Buffer.concat(M);if((h.statusCode??500)>=400){w(d(S.toString(),h.statusCode===404?"not_found":h.statusCode===401||h.statusCode===403?"auth":"provider"));return}T(S)})});b.setTimeout(600000,()=>b.destroy(d("Docker API timed out","timeout"))),b.on("error",(h)=>w(h instanceof e?h:d(h.message,"unavailable"))),b.end(E)});if(!C.length)return;if(a.startsWith("/images/create")){for(let T of C.toString().trim().split(`
|
|
2
|
+
`)){let w=g(R(T));if(w.error)throw d(`Image pull: ${L(w.error)}`)}return}return R(C.toString())}async exec(s,a,l){let E=g(await this.call("POST",`/containers/${k(s)}/exec`,{Cmd:a,WorkingDir:l.cwd??"/",User:l.user,Env:Object.entries(l.env??{}).map(([w,b])=>`${w}=${b}`),AttachStdout:!0,AttachStderr:!0,AttachStdin:l.stdin!==void 0,Tty:!1})),C=L(E.Id);await new Promise((w,b)=>{let h=new K(l.onChunk),M=W({agent:this.pool(),socketPath:this.socketPath,path:`/v1.44/exec/${k(C)}/start`,method:"POST",headers:{"Content-Type":"application/json","User-Agent":x,Connection:"Upgrade",Upgrade:"tcp"}}),S=(v)=>{v.on("data",(P)=>{try{h.push(P)}catch(I){v.destroy(),b(I)}}),v.on("error",(P)=>b(d(P.message,"unavailable"))),v.on("end",()=>{try{h.end(),w()}catch(P){b(P)}})};M.on("upgrade",(v,P,I)=>{if(P.setTimeout(0),S(P),I.length)try{h.push(I)}catch(r){P.destroy(),b(r);return}P.end(l.stdin??"")}),M.on("response",(v)=>{if((v.statusCode??500)>=400){v.resume(),b(d(`Exec attach HTTP ${v.statusCode}`));return}S(v)}),M.on("error",(v)=>b(d(v.message,"unavailable"))),M.setTimeout(30000,()=>M.destroy(d("Exec attach timed out","timeout"))),M.end(JSON.stringify({Detach:!1,Tty:!1}))});let T=g(await this.call("GET",`/exec/${k(C)}/json`));if(T.Running)throw d("Exec attachment ended before the process exited","outcome_unknown");return q(T.ExitCode)}}var F="sandbox-sdk.local.deadline",H="sandbox-sdk.local.idle-ms",_="/tmp/.sandbox-sdk-activity",z="sandbox-sdk.local.key",Z="sandbox-sdk.local.snapshot",se=["for d in /tmp/.sandbox-sdk/procs/*/",'do [ -d "$d" ] || continue','rm -rf "$d"lock','[ ! -f "$d"spec.json ] || [ -f "$d"exit ] || printf 137 > "$d"exit || exit 1',"done","rm -rf /tmp/.sandbox-sdk/runs/*"].join("; "),ie=new Set([F,H,z,Z]),ee=(s)=>Object.fromEntries(Object.entries(s).filter(([a])=>!ie.has(a))),X=(s)=>`sandbox-sdk-${oe("sha256").update(s).digest("hex")}`,ae={small:{cpu:1,memoryMb:1024},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}};function ce(s){if(!s)return{};if(!t(s)&&s.diskGb!==void 0)throw d("Docker cannot enforce diskGb portably; pass only cpu and memoryMb, or use small, medium, or large","unsupported");let a=t(s)?ae[s]:s;if(!a)throw d("Unknown size preset","unsupported");if(!(a.cpu>0)||!Number.isFinite(a.cpu)||!Number.isSafeInteger(a.memoryMb)||a.memoryMb<6)throw d("Custom sizes need cpu above 0 and memoryMb of at least 6","invalid_argument");return{NanoCpus:Math.round(a.cpu*1e9),Memory:a.memoryMb*1024*1024,MemorySwap:a.memoryMb*1024*1024}}function de(s,a){let l=g(s);return a.startsWith(`${String(l.Os)}/${String(l.Architecture)}`)}var Q=(s,a)=>{if(s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw d(`${a} must be a positive integer`,"invalid_argument")};function ue(s){Q(s.pidsLimit,"pidsLimit"),Q(s.shmSizeMb,"shmSizeMb");let a=s.networkMode;if(a!==void 0&&(!a||a==="host"||a==="none"||a.startsWith("container:")))throw d("networkMode must name a bridge-style network; host and container modes break localhost previews and network: none","unsupported");for(let l of s.mounts??[]){if(!["bind","volume","tmpfs"].includes(l.type)||!l.target.startsWith("/"))throw d("Mounts need type bind, volume or tmpfs and an absolute target","invalid_argument");if(l.type==="bind"?!l.source?.startsWith("/"):l.type==="tmpfs"&&l.source!==void 0)throw d("Bind mounts need an absolute host source; tmpfs mounts take none","invalid_argument")}return{Runtime:s.runtime,Mounts:s.mounts?.length?s.mounts.map((l)=>({Type:l.type,Target:l.target,Source:l.source,ReadOnly:l.readOnly??!1})):void 0,PidsLimit:s.pidsLimit,ShmSize:s.shmSizeMb===void 0?void 0:s.shmSizeMb*1024*1024,CapAdd:s.capAdd?.length?s.capAdd:void 0,CapDrop:s.capDrop?.length?s.capDrop:void 0,SecurityOpt:s.securityOpt?.length?s.securityOpt:void 0}}function te(s){let a=g(s),l=g(a.Config),E=g(a.State),C=Object.fromEntries(Object.entries(g(l.Labels??{})).map(([T,w])=>[T,L(w)]));if(C["sandbox-sdk"]!=="1")throw d("Container was not created by Sandbox SDK","not_found");return{info:{id:L(a.Id),key:C[z]||void 0,labels:ee(C),state:E.Paused?"paused":E.Running?"running":"stopped",createdAt:Date.parse(L(a.Created))},labels:C}}var Y=(s)=>te(s).info;function ve(s={}){let a=new U(s.dockerHost),l=s.image??"node:22-bookworm",E=ue(s),C=s.platform?`&platform=${k(s.platform)}`:"",T=new Map,w=new Set,b=new Map,h=(r)=>a.call("GET",`/containers/${k(r)}/json`);async function M(r,i,u){let f="",p="",m=w.has(r)?["sh","-c",`touch ${_}; "$@"; code=$?; touch ${_}; exit "$code"`,"sh",...i]:i,O=await a.exec(r,m,{stdin:u,onChunk(D){if(D.stream==="stdout")f+=D.text;else p+=D.text}});if(O!==0)throw d(`Container operation exited ${O}: ${p}`,p.includes("ENOENT")||p.includes("No such file")?"file_not_found":"provider");return f}let S=(r,i,u=[],f)=>M(r,["node","-e",i,...u],f),v="const fs=require('fs'); const p=require('path'); const stat=x=>{const s=fs.lstatSync(x);return {path:x,type:s.isSymbolicLink()?'symlink':s.isDirectory()?'directory':'file',size:s.size,modifiedAt:s.mtimeMs}};";function P(r){let i=g(r),u=i.type;if(u!=="file"&&u!=="directory"&&u!=="symlink")throw d("Invalid file type");return{path:L(i.path),type:u,size:q(i.size),modifiedAt:q(i.modifiedAt)}}let I={name:"local",keyMode:"exact",capabilities:new Set(["pause","snapshot","size","network-policy"]),async create(r){if(r.network!==void 0&&r.network!=="all"&&r.network!=="none")throw d("Network allow-lists cannot be enforced by this Docker adapter","unsupported");for(let y of[r.idleTimeoutMs,r.timeoutMs])if(y!==void 0&&(!Number.isFinite(y)||y<=0))throw d("Timeouts must be positive milliseconds","invalid_argument");let i=ce(r.size);if(r.signal?.aborted)throw d("Creation aborted","aborted");let u={},f=performance.now(),p=r.from??l,m;try{let y=await a.call("GET",`/images/${k(p)}/json`);m=!s.platform||r.from!==void 0||de(y,s.platform)}catch(y){if(!(y instanceof e)||y.code!=="not_found")throw y;if(r.from)throw d("Snapshot image not found","not_found");m=!1}if(!m)await a.call("POST",`/images/create?fromImage=${k(p)}${C}`);if(u.createInspectMs=performance.now()-f,r.signal?.aborted)throw d("Creation aborted after image pull","aborted");let O=[...new Set(r.ports??[3000])],D=Object.fromEntries(O.map((y)=>[`${y}/tcp`,[{HostIp:"127.0.0.1",HostPort:""}]]));f=performance.now();let j=Date.now(),J={...r.labels,"sandbox-sdk":"1",[z]:r.key??"",[F]:r.timeoutMs===void 0?"":String(j+r.timeoutMs),[H]:r.idleTimeoutMs===void 0?"":String(r.idleTimeoutMs)},N=g(await a.call("POST",`/containers/create?name=${k(r.key?X(r.key):`sandbox-sdk-${V()}`)}${r.from===void 0?C:""}`,{Image:p,WorkingDir:"/workspace",Cmd:["sh","-c","exec sleep infinity"],User:s.user,Env:Object.entries(r.env??{}).map(([y,ne])=>`${y}=${ne}`),Labels:J,ExposedPorts:Object.fromEntries(O.map((y)=>[`${y}/tcp`,{}])),HostConfig:{...E,...i,NetworkMode:r.network==="none"?"none":s.networkMode??"bridge",PortBindings:r.network==="none"?{}:D,Init:!0}}));u.createContainerMs=performance.now()-f;let A=L(N.Id);if(b.set(A,u),r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)w.add(A);try{if(f=performance.now(),await a.call("POST",`/containers/${k(A)}/start`),u.createStartMs=performance.now()-f,f=performance.now(),s.user!==void 0){if(await a.exec(A,["chown","--",s.user,"/workspace"],{user:"0",onChunk(){}})!==0)throw d(`Could not give /workspace to user ${s.user}`,"invalid_argument")}if(r.from!==void 0)await M(A,["sh","-c",se]);if(u.createPrerequisiteMs=performance.now()-f,r.signal?.aborted)throw d("Creation aborted","aborted");if(r.timeoutMs!==void 0||r.idleTimeoutMs!==void 0)return await I.connect(A);return{id:A,key:r.key,labels:ee(J),state:"running",createdAt:j}}catch(y){throw await I.destroy(A),y}},async find(r){try{let i=await I.connect(X(r));return i.key===r?i:void 0}catch(i){if(i instanceof e&&i.code==="not_found")return;throw i}},async connect(r){let{info:i,labels:u}=te(await h(r)),f=(D)=>D?Number(D):1/0,p=f(u[F]),m=f(u[H]);if(Number.isFinite(p)||Number.isFinite(m))w.add(i.id);let O=Date.now()>=p;if(!O&&Number.isFinite(m)&&i.state==="running"){let D="";if(await a.exec(i.id,["node","-e",`const f=require('fs'), p='/tmp/.sandbox-sdk';const busy=(f.existsSync(p+'/runs')&&f.readdirSync(p+'/runs').length)||(f.existsSync(p+'/procs')&&f.readdirSync(p+'/procs').some(n=>!f.existsSync(p+'/procs/'+n+'/exit')));process.stdout.write(String(busy?Date.now():Math.max(${i.createdAt},f.existsSync('${_}')?f.statSync('${_}').mtimeMs:0)))`],{onChunk(J){if(J.stream==="stdout")D+=J.text}})!==0||!Number.isFinite(Number(D)))throw d("Could not check local idle deadline","provider");O=Date.now()-Number(D)>=m}if(O)throw await I.destroy(i.id),d("Local sandbox deadline expired; create another sandbox","not_found");return i},async list(r){let i=k(JSON.stringify({label:Object.entries({...r,"sandbox-sdk":"1"}).map(([p,m])=>`${p}=${m}`)})),u=B(await a.call("GET",`/containers/json?all=1&filters=${i}`)),f=[];for(let p of u)try{f.push(Y(await h(L(g(p).Id))))}catch(m){if(!(m instanceof e)||m.code!=="not_found")throw m}return f},async destroy(r){let i=T.get(r);if(i)return i;let u=(async()=>{try{let f=Y(await h(r));if(f.state==="paused")await a.call("POST",`/containers/${k(r)}/unpause`);if(f.state!=="stopped")await a.call("POST",`/containers/${k(r)}/stop?t=1`);await a.call("DELETE",`/containers/${k(r)}?force=1&v=1`)}catch(f){if(!(f instanceof e)||f.code!=="not_found")throw f}})();T.set(r,u);try{await u}finally{T.delete(r),w.delete(r),b.delete(r)}},async exec(r,i){let u=performance.now();if(i.signal?.aborted)return{exitCode:null,timedOut:!0};let f=`/tmp/.sandbox-sdk-exec-${V()}`,p=!1,m=()=>{},O=new Promise((N)=>{m=()=>{p=!0,N("cancelled")}});i.signal?.addEventListener("abort",m,{once:!0});let D=setTimeout(m,i.timeoutMs),j=["setsid","--wait","sh","-c",`echo $$ > ${n(f)}; ${w.has(r)?`touch ${_}; trap 'touch ${_}' EXIT;`:""} cd ${n(i.cwd)} || exit; sh -c ${n(i.command)}`],J=a.exec(r,j,{env:i.env,stdin:i.stdin,onChunk:i.onChunk});try{if(await Promise.race([J,O]),p)await M(r,["sh","-c",`i=0; while [ ! -s ${n(f)} ]; do i=$((i+1)); [ "$i" -lt 3000 ] || exit 1; sleep .01; done; p=$(cat ${n(f)}); node -e 'try {process.kill(-Number(process.argv[1]), "SIGKILL")} catch(e) {if(e.code!=="ESRCH") throw e}' "$p"`]);let N=await J;return{exitCode:p?null:N,timedOut:p}}finally{clearTimeout(D),i.signal?.removeEventListener("abort",m),await M(r,["rm","-f",f]).catch(()=>{});let N=b.get(r);if(N&&N.firstCommandMs===void 0)N.firstCommandMs=performance.now()-u}},files:{writeCreatesParents:!0,writeSupportsMode:!0,listOrder:"name",async read(r,i){return new Uint8Array(Buffer.from(await S(r,"process.stdout.write(require('fs').readFileSync(process.argv[1]).toString('base64'))",[i]),"base64"))},async write(r,i,u,f){await S(r,"const f=require('fs'),p=process.argv[1];f.mkdirSync(require('path').dirname(p),{recursive:true});f.writeFileSync(p,Buffer.from(f.readFileSync(0,'utf8'),'base64'));if(process.argv[2])f.chmodSync(p,parseInt(process.argv[2],8))",[i,f?.mode===void 0?"":f.mode.toString(8)],Buffer.from(u).toString("base64"))},async stat(r,i){return P(R(await S(r,v+"process.stdout.write(JSON.stringify(stat(process.argv[1])))",[i])))},async list(r,i){return B(R(await S(r,v+"process.stdout.write(JSON.stringify(fs.readdirSync(process.argv[1]).map(x=>stat(p.join(process.argv[1],x)))))",[i]))).map(P)},async mkdir(r,i){await S(r,"require('fs').mkdirSync(process.argv[1],{recursive:true})",[i])},async remove(r,i,u){await S(r,"require('fs').rmSync(process.argv[1],{recursive:process.argv[2]==='true'})",[i,String(u.recursive)])}},async previewUrl(r,i){let u=g(await h(r)),f=g(u.NetworkSettings),p=g(f.Ports??{}),m=B(p[`${i}/tcp`]??[])[0];if(!m)throw d(`Port ${i} has no localhost mapping; declare it in ports when creating the sandbox`,"unsupported");let O=g(m);if(O.HostIp!=="127.0.0.1")throw d("Preview binding is not loopback","unsupported");return{url:`http://127.0.0.1:${L(O.HostPort)}/`}},native(r){return{id:r,client:a}},async usage(r){let i=g(await h(r)),u=g(i.State);return{...b.get(r),runningMs:u.Running&&!u.Paused?Math.max(0,Date.now()-Date.parse(L(u.StartedAt))):0}},async pause(r){await I.connect(r),await a.call("POST",`/containers/${k(r)}/pause`)},async resume(r){await I.connect(r),await a.call("POST",`/containers/${k(r)}/unpause`)},async snapshot(r,i){if(i?.expiresInMs)throw d("Docker images do not expire; omit expiresInMs and delete the snapshot image when you are done","unsupported");await I.connect(r);let u=g(await a.call("POST",`/commit?container=${k(r)}&pause=true`,{Labels:{"sandbox-sdk":"1",[Z]:"1"}}));return{id:L(u.Id)}}};return I}export{ve as local};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ModalClientParams, Sandbox } from "modal";
|
|
2
|
+
import { type ModalAdapter, type ModalOptions as NativeModalOptions } from "./provider.js";
|
|
3
|
+
export type { ModalCapability, ModalDestroyEvent, ModalPendingSandbox, ModalPreparedApp, ModalResources, PrepareAppOptions, } from "./provider.js";
|
|
4
|
+
export type ModalOptions = NativeModalOptions & {
|
|
5
|
+
/** Defaults to MODAL_TOKEN_ID, then the active profile in ~/.modal.toml. */
|
|
6
|
+
tokenId?: string;
|
|
7
|
+
/** Defaults to MODAL_TOKEN_SECRET, then the active profile in ~/.modal.toml. */
|
|
8
|
+
tokenSecret?: string;
|
|
9
|
+
/** Other `ModalClient` settings, such as `timeoutMs`, `maxRetries` or `logLevel`. */
|
|
10
|
+
client?: Omit<ModalClientParams, "tokenId" | "tokenSecret" | "environment">;
|
|
11
|
+
};
|
|
12
|
+
export type ModalProvider = ModalAdapter<Sandbox>;
|
|
13
|
+
/** Modal Sandboxes through the official `modal` SDK, an optional peer loaded on first use. */
|
|
14
|
+
export declare function modal(options?: ModalOptions): ModalProvider;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{u}from"../../chunk-pdgnaxp9.js";import{h}from"../../chunk-qfhee1t8.js";import{o,e,i,d,a}from"../../chunk-0eeyc0aq.js";import{createHash as Re}from"node:crypto";var Ce=new Map([["NotFoundError","not_found"],["SandboxFilesystemNotFoundError","file_not_found"],["SandboxFilesystemNotADirectoryError","invalid_argument"],["SandboxFilesystemIsADirectoryError","invalid_argument"],["SandboxFilesystemDirectoryNotEmptyError","invalid_argument"],["SandboxFilesystemPathAlreadyExistsError","invalid_argument"],["SandboxFilesystemFileTooLargeError","invalid_argument"],["SandboxFilesystemPermissionError","invalid_argument"],["AlreadyExistsError","invalid_argument"],["ConflictError","invalid_argument"],["InvalidError","invalid_argument"],["ResourceExhaustedError","quota"],["InternalFailure","unavailable"],["TimeoutError","timeout"],["SandboxTimeoutError","timeout"],["AbortError","aborted"]]),De=new Map([[1,"aborted"],[3,"invalid_argument"],[4,"timeout"],[5,"not_found"],[7,"auth"],[8,"quota"],[14,"unavailable"],[16,"auth"]]);function Ae(s){if(/is not a valid sandbox ID/.test(s.message))return"not_found";let c=Ce.get(s.name);if(c)return c;let f=o(s.code)?De.get(s.code):void 0;if(f)return f;if(/token|credential|unauthenticated/i.test(s.message))return"auth";return"provider"}function P(s,c){if(s instanceof e)return s;let f=u(s),p=Ae(f),g=i(s,{code:p,status:o(f.code)?`gRPC ${f.code}`:void 0,redact:d([process.env.MODAL_TOKEN_ID,process.env.MODAL_TOKEN_SECRET])});return new e(`Modal request failed: ${a(p,g.detail)}. Check credentials, resource limits, and the sandbox state before retrying.`,{code:p,provider:"modal",sandboxId:c,retryable:p==="quota"||p==="unavailable",cause:g.cause})}function R(s){throw new e(`${s}. Modal cannot enforce this request. Use the supported Modal settings or another provider.`,{code:"unsupported",provider:"modal"})}function W(s){throw new e(s,{code:"invalid_argument",provider:"modal"})}var B="sandbox-sdk",V="sandbox-sdk-key",Y="sandbox-sdk-created",q="sandbox-sdk-destroying",Oe="destroyed",Le=60000,me="node:22-bookworm",$e=3600000,Fe=24*$e,Be=10,qe=1024,fe=/^[\w.-]{1,63}$/,pe=(s)=>`sdk-${Re("sha256").update(s).digest("hex").slice(0,56)}`,je={small:{cpu:1,memoryMb:2048},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}},We='for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; true',ee="__sandbox_sdk_pgid__=",he="__sandbox_sdk_cwd_error__",Ke=`cd -- "$1" 2>/dev/null || { echo ${he} >&2; exit 125; }; echo "${ee}$$" >&2; exec timeout --signal=KILL "$2" sh -c "$3"`;function te(s){return Math.ceil(s/1000)*1000}function Ge(s){let c=new TextEncoder;return Object.entries(s).reduce((f,[p,g])=>f+c.encode(p).length+c.encode(g).length,0)}function Ue(s,c){if(s===void 0)return c??{};if(c!==void 0)W("Pass size to createSandbox or resources to modal(), not both.");if(s==="small"||s==="medium"||s==="large")return we(je[s]);if(s.diskGb!==void 0)R("Modal sets no disk size for a sandbox; leave diskGb unset");if(!Number.isFinite(s.cpu)||s.cpu<0.125)R("Modal needs a cpu of at least 0.125");if(!Number.isSafeInteger(s.memoryMb)||s.memoryMb<128)R("Modal needs memoryMb as a whole number of at least 128");return we(s)}function we({cpu:s,memoryMb:c}){return{cpu:s,cpuLimit:s,memoryMiB:c,memoryLimitMiB:c}}var ze=/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/;function He(s){if(s===void 0||s==="all")return{};if(s==="none")return{outboundCidrAllowlist:[],outboundDomainAllowlist:[]};let c=s.allow.filter((p)=>ze.test(p)||p.includes(":")),f=s.allow.filter((p)=>!c.includes(p));return{outboundCidrAllowlist:c.map((p)=>p.includes("/")?p:`${p}/${p.includes(":")?128:32}`),outboundDomainAllowlist:f}}function Je(s){let c=s??process.env.MODAL_SANDBOX_REGION;if(c===void 0)return;let f=[c].flat().flatMap((p)=>p.split(",")).map((p)=>p.trim()).filter(Boolean);return f.length?f:void 0}function be(s){if(s===void 0)return;if(s>Fe)R("Modal caps a sandbox's lifetime at 24 hours");return te(s)}async function K(s,c){let f=s.getReader();try{for(;;){let{done:p,value:g}=await f.read();if(p)return;if(g)c(g)}}finally{f.releaseLock()}}var Xe=9;function Qe(s){return s.code===Xe&&/Exec has already completed/.test(s.message)}var Ve=new Set([3,7,8,12,16]);function Ye(s,c){let f=P(s,c);if(f.sandboxId===c)return f;return new e(f.message,{code:f.code,retryable:f.retryable,hint:f.hint,provider:"modal",sandboxId:c,cause:s})}function Ze(s){return o(s.code)&&Ve.has(s.code)||s.name==="InvalidError"}var Z=(s)=>new Promise((c)=>setTimeout(c,s));async function G(s,c){let f;s.catch(()=>{});try{return await Promise.race([s.then((p)=>({settled:!0,value:p})),new Promise((p)=>{f=setTimeout(()=>p({settled:!1}),Math.max(0,c))})])}finally{clearTimeout(f)}}function ye(s){return s[q]!==void 0||s[B]===Oe}function ge(s){return{path:s.path,type:s.type,size:s.size,modifiedAt:s.modifiedTime*1000}}function xe(s,c={}){let f=new Map,p=new Map,g=new Map,C=new Set,k=c.app??"sandbox-sdk",ve=be(c.timeoutMs),ne=c.destroyWaitMs??Le,re,O=new Map,Me,N=()=>re??=(async()=>{try{return await s()}catch(t){throw re=void 0,t}})(),U=(t=k)=>{if(!fe.test(t))W("Modal App names use letters, digits, dashes, periods and underscores, under 64 characters.");let n=O.get(t);if(n)return n;let r=(async()=>{try{return await(await N()).apps.fromName(t,{createIfMissing:!0,environment:c.environment})}catch(l){throw O.delete(t),l}})();return O.set(t,r),r},ae=async(t)=>{let n=O.get(t);if(n)return n;try{let r=await(await N()).apps.fromName(t,{createIfMissing:!1,environment:c.environment});return O.set(t,Promise.resolve(r)),r}catch(r){if(P(r).code==="not_found")return null;throw r}};async function oe(t){let n=await N();await ae(k);let r=(await Promise.allSettled(O.values())).flatMap((m)=>m.status==="fulfilled"?[m.value]:[]),l=new Map;for(let m of r)for await(let w of n.sandboxes.list({appId:m.appId,tags:t,environment:c.environment}))l.set(w.sandboxId,w);return[...l.values()]}let y=async(t,n)=>{try{return await n()}catch(r){throw P(r,t)}},Pe=(t)=>new e("Sandbox has finished. Modal sandboxes cannot run again once they stop. Create a new sandbox.",{code:"not_found",provider:"modal",sandboxId:t}),Ie=(t)=>{let n=f.get(t);if(!n)throw new e("Sandbox is not attached. No local native object exists. Connect the sandbox first.",{code:"not_found",provider:"modal",sandboxId:t});return n},T=async(t)=>{let n=f.get(t);if(n)return n;let r=await(await N()).sandboxes.fromId(t);return f.set(t,r),r};function z(t,n){let{[V]:r,[Y]:l,[q]:m,...w}=n,v=ye(n)||C.has(t)?"stopped":"running";return{id:t,key:r,labels:w,state:v,createdAt:Number(l)||0}}async function H(t){let[n,r]=await Promise.all([t.poll(),t.getTags()]);if(n!==null)throw Pe(t.sandboxId);let l=r,m=Date.now()+60000;while(l[B]==="pending"){if(Date.now()>=m)throw new e("Sandbox initialization is incomplete. The creator has not finished setup. Retry connection later.",{code:"unavailable",provider:"modal",sandboxId:t.sandboxId,retryable:!0});await Z(250),l=await t.getTags()}return f.set(t.sandboxId,t),g.set(t.sandboxId,l),z(t.sandboxId,l)}async function ke(t){let n=await N(),r;try{r=await n.sandboxes.fromName(k,t,{environment:c.environment})}catch(l){if(P(l).code==="not_found")return!0;throw l}if(!C.has(r.sandboxId)&&!ye(await r.getTags()))return!1;return J(r,Date.now()+60000)}async function se(t,n){let r=await t.exec(["sh","-c",n]);await r.stdin.close();let[l]=await Promise.all([r.wait(),K(r.stdout,()=>{}),K(r.stderr,()=>{})]);return l}async function ie(t,n,r=1,l=()=>!0){for(let m=0;m<r&&l();m++){if(m)await Z(250*m);try{let{[q]:w,...v}=g.get(t.sandboxId)??await t.getTags(),b=n?{...v,[q]:String(Date.now())}:v;return await t.setTags(b),g.set(t.sandboxId,b),!0}catch{}}return!1}async function J(t,n){for(;;){try{let l=await G(t.poll(),n-Date.now());if(l.settled&&l.value!==null)return!0}catch(l){if(P(l).code==="not_found")return!0;throw l}let r=n-Date.now();if(r<=0)return!1;await Z(Math.min(250,r))}}function j(t){f.get(t)?.detach(),f.delete(t),p.delete(t),g.delete(t),C.delete(t)}async function Se(t,n){await se(t,`kill -KILL -${n} 2>/dev/null || true`)}async function Ne(t,n){let r=Date.now(),l=await t.exec(["setsid","--wait","sh","-c",Ke,"sh",n.cwd,`${Math.max(1,Math.ceil(n.timeoutMs))/1000}s`,n.command],{env:n.env}),m,w=()=>{},v=new Promise((M)=>w=M),b=!1,x=!1,L,D=()=>L??=(async()=>{if(await Promise.race([v,new Promise((M)=>setTimeout(M,1e4))]),m!==void 0)await Se(t,m)})(),A=()=>{x=!0,D().catch(()=>{})};n.signal?.addEventListener("abort",A,{once:!0});let E=setTimeout(A,Math.max(0,n.timeoutMs-(Date.now()-r)));if(n.signal?.aborted)A();let S="",F=!1,le=(M)=>{let I=S.indexOf(`
|
|
2
|
+
`);if(!M&&I<0&&S.length<256)return;F=!0;let _=I<0?S:S.slice(0,I),ue=I<0?"":S.slice(I+1);if(_.startsWith(ee)){let Q=Number(_.slice(ee.length));if(Number.isSafeInteger(Q)&&Q>0)m=Q}else if(_===he)b=!0;else{w(),n.onChunk({stream:"stderr",text:S});return}if(w(),ue)n.onChunk({stream:"stderr",text:ue})},X=l.wait(),ce=!1;X.then(()=>ce=!0,()=>{});let _e=async(M)=>{let I;try{return await Promise.race([X.then(()=>!0,()=>!1),new Promise((_)=>I=setTimeout(()=>_(!1),M))])}finally{clearTimeout(I)}},Ee=async()=>{try{if(n.stdin!==void 0)await l.stdin.writeText(n.stdin);await l.stdin.close()}catch(M){if(!Qe(u(M))||!(ce||await _e(1000)))throw P(M,t.sandboxId);l.stdin.close().catch(()=>{})}};try{let M=Ee(),[I]=await Promise.all([X,K(l.stdout,(_)=>n.onChunk({stream:"stdout",text:_})),K(l.stderr,(_)=>{if(F)n.onChunk({stream:"stderr",text:_});else S+=_,le(!1)}),M]);if(!F&&S)le(!0);if(I===137&&Date.now()-r>=n.timeoutMs)x=!0;if(await L,!x&&I===125&&b)throw new e("Command could not start. The working directory does not exist or is not a directory. Check cwd.",{code:"invalid_argument",provider:"modal",sandboxId:t.sandboxId});return{exitCode:x?null:I,timedOut:x}}catch(M){throw await D().catch(()=>{}),M}finally{w(),clearTimeout(E),n.signal?.removeEventListener("abort",A)}}async function Te(t,n){let{timeoutMs:r,signal:l}=n;if(r===void 0&&l===void 0)return t;let m,w=()=>{},v=new Promise((b,x)=>{if(r!==void 0)m=setTimeout(()=>x(new e("Template build timed out. Modal may still finish the image. Retry with a longer timeoutMs.",{code:"timeout",provider:"modal"})),r);if(w=()=>x(new e("Template build aborted. Modal may still finish the image.",{code:"aborted",provider:"modal"})),l?.addEventListener("abort",w,{once:!0}),l?.aborted)w()});try{return await Promise.race([t,v])}finally{clearTimeout(m),l?.removeEventListener("abort",w)}}let de={name:"modal",keyMode:"exact",capabilities:new Set(["snapshot","snapshot-delete","templates","network-policy","size"]),native:Ie,create:(t)=>y(void 0,async()=>{let n={...t.labels,[Y]:String(Date.now())};if(t.key!==void 0)n[V]=t.key;if(Object.keys(n).length+1>Be)R("Modal allows ten tags per sandbox, and the SDK uses up to four of them (sandbox-sdk, sandbox-sdk-created, sandbox-sdk-key, sandbox-sdk-destroying)");if(Ge({...n,[q]:String(Date.now())})>qe)R("Modal allows 1024 bytes of tag names and values per sandbox, key included");let r=[...new Set(t.ports)],l={...Ue(t.size,c.resources),...He(t.network),timeoutMs:be(t.timeoutMs)??ve,idleTimeoutMs:t.idleTimeoutMs===void 0?void 0:te(t.idleTimeoutMs),workdir:"/workspace",env:t.env,encryptedPorts:r.length?r:void 0,regions:Je(c.region),runtime:c.runtime,name:t.key===void 0?void 0:pe(t.key),tags:t.from===void 0?n:{...n,[B]:"pending"}},m=await N(),w=t.from===void 0?Me??=m.images.fromRegistry(c.image??me):await m.images.fromId(t.from),v=await U(t.key===void 0?c.createApp?.({labels:t.labels})??k:k),b;try{b=await m.sandboxes.create(v,w,l)}catch(x){if(l.name===void 0||!await ke(l.name))throw x;b=await m.sandboxes.create(v,w,l)}if(f.set(b.sandboxId,b),p.set(b.sandboxId,new Set(r)),g.set(b.sandboxId,n),t.from===void 0)return z(b.sandboxId,n);try{if(await se(b,We)!==0)throw Error("Could not invalidate restored processes");return await b.setTags(n),z(b.sandboxId,n)}catch(x){throw await de.destroy(b.sandboxId).catch(()=>{}),Ye(x,b.sandboxId)}}),find:(t)=>y(void 0,async()=>{let n;try{n=await(await N()).sandboxes.fromName(k,pe(t),{environment:c.environment})}catch(l){if(P(l).code==="not_found")return;throw l}let r;try{r=await H(n)}catch(l){if(P(l).code==="not_found")return;throw l}if(r.labels[B]!=="1"||r.key!==t||r.state==="stopped")return;return r}),connect:(t)=>y(t,async()=>H(f.get(t)??await(await N()).sandboxes.fromId(t))),list:(t)=>y(void 0,async()=>{let n={...t,[B]:"1"};return(await Promise.all((await oe(n)).map(async(l)=>{try{return await H(l)}catch(m){if(P(m,l.sandboxId).code==="not_found")return;throw m}}))).filter((l)=>l!==void 0&&Object.entries(n).every(([m,w])=>l.labels[m]===w))}),destroy:(t)=>y(t,async()=>{let n=await T(t),r=Date.now(),l=r+ne,m=!1,w=(E)=>new e(`Sandbox termination was requested, but ${E} within ${ne} ms. It stays listed with state "stopped". Call destroy again to keep waiting.`,{code:"timeout",provider:"modal",sandboxId:t,retryable:!0}),v=C.has(t);C.add(t);let b=ie(n,!0,3,()=>!m),x;try{x=await G(n.terminate(),l-Date.now())}catch(E){if(P(E).code==="not_found"){m=!0;try{c.onDestroy?.({sandboxId:t,requestMs:null,stoppedMs:Date.now()-r})}catch{}return j(t)}if(Ze(u(E))){if(m=!0,v)throw E;C.delete(t);let F=await G(b,l-Date.now());if(F.settled&&F.value)await G(ie(n,!1),l-Date.now());throw E}let S=!1;try{S=await J(n,l)}catch{}finally{m=!0}if(!S)throw E;try{c.onDestroy?.({sandboxId:t,requestMs:null,stoppedMs:Date.now()-r})}catch{}return j(t)}if(!x.settled)throw m=!0,w("Modal did not accept the request");let L=Date.now()-r,D;try{D=await J(n,l)}finally{m=!0}let A=D?Date.now()-r:null;try{c.onDestroy?.({sandboxId:t,requestMs:L,stoppedMs:A})}catch{}if(!D)throw w("Modal still reports it running");j(t)}),exec:(t,n)=>y(t,async()=>{if(n.signal?.aborted)return{exitCode:null,timedOut:!0};return Ne(await T(t),n)}),files:{writeCreatesParents:!0,read:(t,n)=>y(t,async()=>new Uint8Array(await(await T(t)).filesystem.readBytes(n))),write:(t,n,r)=>y(t,async()=>{await(await T(t)).filesystem.writeBytes(r,n)}),list:(t,n)=>y(t,async()=>(await(await T(t)).filesystem.listFiles(n)).map(ge)),stat:(t,n)=>y(t,async()=>ge(await(await T(t)).filesystem.stat(n))),remove:(t,n,r)=>y(t,async()=>{await(await T(t)).filesystem.remove(n,{recursive:r.recursive})}),mkdir:(t,n)=>y(t,async()=>{await(await T(t)).filesystem.makeDirectory(n,{createParents:!0})})},previewUrl:(t,n)=>y(t,async()=>{let r=p.get(t),l=()=>new e(`Port ${n} was not declared at creation. Modal tunnels only ports given in CreateInput. Recreate with ports: [${n}].`,{code:"invalid_argument",provider:"modal",sandboxId:t});if(r&&!r.has(n))throw l();let m=(await(await T(t)).tunnels())[n];if(!m)throw l();return{url:m.url}}),close:async(t)=>j(t),snapshot:(t,n={})=>y(t,async()=>{let{expiresInMs:r}=n,l=r===void 0?void 0:r===0?null:te(r);return{id:(await(await T(t)).snapshotFilesystem({ttlMs:l})).imageId}}),deleteSnapshot:(t)=>y(void 0,async()=>{let n=await N();try{await n.images.fromId(t)}catch(r){if(P(r).code==="not_found")return!1;throw r}return await n.images.delete(t),!0}),buildTemplate:(t,n)=>y(void 0,async()=>{if(t.size!==void 0)R("Modal images carry no CPU or memory size. Pass size to createSandbox instead");if(t.workdir!==void 0&&(!t.workdir.startsWith("/")||/[\r\n]/.test(t.workdir)))W("Template workdir must be an absolute path on one line.");let r=[...t.workdir===void 0?[]:[`WORKDIR ${t.workdir}`],...(t.run??[]).map((b)=>`RUN ${JSON.stringify(["sh","-c",b])}`)],m=(await N()).images.fromRegistry(t.image??c.image??me),w=r.length?m.dockerfileCommands(r,{env:t.env}):m;return{id:(await Te(U().then((b)=>w.build(b)),n)).imageId,name:t.name}})};return Object.assign(de,{prepareApp:(t,n={})=>y(void 0,async()=>{if(n.createIfMissing??!0)return{name:t,appId:(await U(t)).appId};if(!fe.test(t))return null;let r=await ae(t);return r&&{name:t,appId:r.appId}}),listPending:(t)=>y(void 0,async()=>{let n={...t,[B]:"pending"};return(await Promise.all((await oe(n)).map(async(l)=>{try{let[m,w]=await Promise.all([l.poll(),l.getTags()]);if(m!==null||!Object.entries(n).every(([D,A])=>w[D]===A))return;let{[V]:v,[Y]:b,[q]:x,...L}=w;return{id:l.sandboxId,labels:L,createdAt:Number(b)||0}}catch(m){if(P(m,l.sandboxId).code==="not_found")return;throw m}}))).filter((l)=>l!==void 0)})})}function pt(s={}){let{tokenId:c,tokenSecret:f,client:p,...g}=s;return xe(async()=>{let{ModalClient:C}=await h("modal","modal",()=>import("modal")),k={...p};if(c!==void 0)k.tokenId=c;if(f!==void 0)k.tokenSecret=f;if(g.environment!==void 0)k.environment=g.environment;return new C(k)},g)}export{pt as modal};
|