@opencoredev/sandbox-sdk 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/ai.js +1 -1
  3. package/dist/chunk-11mbpwem.js +17 -0
  4. package/dist/{chunk-q5vqajhg.js → chunk-19gteae8.js} +2 -2
  5. package/dist/chunk-1k6yz176.js +1 -0
  6. package/dist/chunk-2z6fxyg5.js +2 -0
  7. package/dist/chunk-305dymgq.js +2 -0
  8. package/dist/chunk-348pdz09.js +5 -0
  9. package/dist/{chunk-k60b4r27.js → chunk-3zd78ha4.js} +2 -2
  10. package/dist/chunk-5gnqph3c.js +78 -0
  11. package/dist/chunk-6bemkxcx.js +290 -0
  12. package/dist/chunk-6nf686jb.js +26 -0
  13. package/dist/{chunk-nw845a93.js → chunk-c1wemt0y.js} +8 -8
  14. package/dist/{chunk-bd481sb7.js → chunk-drgkmewv.js} +1 -1
  15. package/dist/chunk-ea8y7y2p.js +2 -0
  16. package/dist/chunk-g0vk7g1k.js +2 -0
  17. package/dist/chunk-n7x9ha44.js +4 -0
  18. package/dist/{chunk-8786zrns.js → chunk-r8xnq6v3.js} +2 -2
  19. package/dist/{chunk-hzbssbep.js → chunk-rnksrxfc.js} +4 -4
  20. package/dist/chunk-tvw3kb8b.js +2 -0
  21. package/dist/http.d.ts +3 -0
  22. package/dist/index.js +1 -1
  23. package/dist/mastra.js +1 -1
  24. package/dist/memory.js +1 -1
  25. package/dist/openai.js +1 -1
  26. package/dist/provider.d.ts +25 -0
  27. package/dist/provider.js +1 -1
  28. package/dist/providers/agentos/index.js +2 -2
  29. package/dist/providers/boat/index.js +1 -1
  30. package/dist/providers/boxd/index.js +11 -13
  31. package/dist/providers/daytona/index.js +15 -15
  32. package/dist/providers/e2b/index.js +1 -1
  33. package/dist/providers/freestyle/execute.d.ts +3 -1
  34. package/dist/providers/freestyle/index.js +6 -15
  35. package/dist/providers/local/index.js +2 -2
  36. package/dist/providers/railway/index.js +1 -1
  37. package/dist/providers/sandboxer/index.js +1 -1
  38. package/dist/providers/superserve/execute.d.ts +3 -1
  39. package/dist/providers/superserve/index.js +21 -23
  40. package/dist/providers/tenki/index.js +14 -24
  41. package/dist/providers/upstash/index.js +10 -10
  42. package/dist/providers/upstash/provider.d.ts +1 -1
  43. package/dist/providers/vercel/index.js +1 -1
  44. package/dist/run.d.ts +9 -0
  45. package/dist/shared/guest.d.ts +28 -1
  46. package/dist/testing.js +3 -3
  47. package/dist/tools.js +1 -1
  48. package/dist/types.d.ts +5 -1
  49. package/package.json +1 -1
  50. package/dist/chunk-23tjmd39.js +0 -8
  51. package/dist/chunk-83avbjns.js +0 -2
  52. package/dist/chunk-8wq767xb.js +0 -17
  53. package/dist/chunk-9w9rddra.js +0 -2
  54. package/dist/chunk-ch71kvcp.js +0 -2
  55. package/dist/chunk-ckym4cht.js +0 -23
  56. package/dist/chunk-hgrwyjrb.js +0 -2
  57. package/dist/chunk-kk1hw8wa.js +0 -1
  58. package/dist/chunk-x2skgx3m.js +0 -5
  59. package/dist/chunk-x681p5d2.js +0 -68
  60. package/dist/chunk-xgxfy2n8.js +0 -4
@@ -1,7 +1,9 @@
1
1
  import type { ExecInput, ExecResult } from "../../provider.js";
2
2
  import { type PagedGuest } from "../../shared/paged-exec.js";
3
- 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.argv[2])) if len(sys.argv)>2 else marshal.loads(bytes.fromhex(sys.stdin.read()))\nif 'envKeys' in v: v['env']={k:os.environ[k] for k in v['envKeys']}\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.\nfor 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 if os.environ.get('SANDBOX_SDK_BOOTSTRAP') not in (None,'{}'):\n bootstrap=os.environ.pop('SANDBOX_SDK_BOOTSTRAP')\n if bootstrap=='{\"env\":{}}': initial={}\n else:\n import json\n initial=json.loads(bootstrap).get('env')\n if initial is not None: saved=initial\n if initial is not None and (initial or os.path.exists('/var/lib/sandbox-sdk-env.json')):\n import json\n os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)\n tmp='/var/lib/sandbox-sdk-env.json.'+str(os.getpid())\n fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)\n with os.fdopen(fd,'w') as f: json.dump(saved,f)\n os.replace(tmp,'/var/lib/sandbox-sdk-env.json')\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 stdout=p.stdout.fileno(); streams={stdout:'stdout',p.stderr.fileno():'stderr'}\n end=time.monotonic()+v['timeoutMs']/1000\n while streams or p.poll() is None:\n if not timed and time.monotonic()>=end:\n timed=True\n try: os.killpg(p.pid,signal.SIGKILL)\n except ProcessLookupError: pass\n for fd in select.select(list(streams),[],[],.01)[0]:\n data=os.read(fd,8192)\n if data: out.write(('[\"'+streams[fd]+'\",\"'+data.hex()+'\"]\\n').encode())\n else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()\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";
3
+ 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.argv[2])) if len(sys.argv)>2 else marshal.loads(bytes.fromhex(sys.stdin.read()))\nif 'envKeys' in v: v['env']={k:os.environ[k] for k in v['envKeys']}\nos.makedirs(root,mode=0o700,exist_ok=True)\n# Keep small completed responses until their request deadline has passed.\n# Sweep expired responses inline, at most every 30 seconds, so no ack RPC or\n# background daemon is needed and a busy sandbox does not rescan every run.\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 if os.environ.get('SANDBOX_SDK_BOOTSTRAP') not in (None,'{}'):\n bootstrap=os.environ.pop('SANDBOX_SDK_BOOTSTRAP')\n if bootstrap=='{\"env\":{}}': initial={}\n else:\n import json\n initial=json.loads(bootstrap).get('env')\n if initial is not None: saved=initial\n if initial is not None and (initial or os.path.exists('/var/lib/sandbox-sdk-env.json')):\n import json\n os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)\n tmp='/var/lib/sandbox-sdk-env.json.'+str(os.getpid())\n fd=os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)\n with os.fdopen(fd,'w') as f: json.dump(saved,f)\n os.replace(tmp,'/var/lib/sandbox-sdk-env.json')\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";
4
4
  export interface ExecutionGuest extends PagedGuest {
5
+ /** The sandbox ID. */
6
+ readonly id: string;
5
7
  exec(command: string, stdin: string, timeoutMs: number, signal?: AbortSignal): Promise<string>;
6
8
  run?(command: string, env: Record<string, string>, timeoutMs: number, signal?: AbortSignal): Promise<string>;
7
9
  }
@@ -1,19 +1,27 @@
1
- import{U}from"../../chunk-hzbssbep.js";import{T}from"../../chunk-8786zrns.js";import{p,b,R}from"../../chunk-x681p5d2.js";import{m}from"../../chunk-bd481sb7.js";import{d,y,H,x,_,h,k}from"../../chunk-ch71kvcp.js";import{f}from"../../chunk-9w9rddra.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,e,i,c,a,s}from"../../chunk-xgxfy2n8.js";function A(l,v="provider",S,P){return new e(v==="auth"?l:`${l}. Check superserve configuration and retry.`,{code:v,provider:"superserve",sandboxId:S,cause:P})}var Fe=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[408,"timeout"],[409,"unavailable"],[422,"invalid_argument"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),Je=new Map([["AuthenticationError","auth"],["NotFoundError","not_found"],["ValidationError","invalid_argument"],["TimeoutError","timeout"],["AbortError","aborted"],["ConflictError","unavailable"]]);function se(l,v){if(l instanceof e)return l;let S=m(l),P=S.statusCode,L=P===void 0?Je.get(S.name)??"provider":Fe.get(P)??"provider",B=i(l,{code:L,status:P===void 0?void 0:`HTTP ${P}`,redact:c([process.env.SUPERSERVE_API_KEY])});return A(`Superserve request failed: ${a(L,B.detail)}`,L,v,B.cause)}var ke=`import os,sys,marshal,_signal as signal,select,time,fcntl
1
+ import{q}from"../../chunk-rnksrxfc.js";import{C}from"../../chunk-r8xnq6v3.js";import{p,z,b,M,N}from"../../chunk-6bemkxcx.js";import{m}from"../../chunk-drgkmewv.js";import{T,w,k}from"../../chunk-2z6fxyg5.js";import{d,y,X,x}from"../../chunk-305dymgq.js";import{f}from"../../chunk-tvw3kb8b.js";import{t,o,r,e,i,l,a,s}from"../../chunk-n7x9ha44.js";function _(u,c="provider",g,S){return new e(c==="auth"?u:`${u}. Check superserve configuration and retry.`,{code:c,provider:"superserve",sandboxId:g,cause:S})}var Je=new Map([[400,"invalid_argument"],[401,"auth"],[403,"auth"],[404,"not_found"],[408,"timeout"],[409,"unavailable"],[422,"invalid_argument"],[429,"quota"],[500,"unavailable"],[502,"unavailable"],[503,"unavailable"],[504,"timeout"]]),ze=new Map([["AuthenticationError","auth"],["NotFoundError","not_found"],["ValidationError","invalid_argument"],["TimeoutError","timeout"],["AbortError","aborted"],["ConflictError","unavailable"]]);function oe(u,c){if(u instanceof e)return u;let g=m(u),S=g.statusCode,D=S===void 0?ze.get(g.name)??"provider":Je.get(S)??"provider",B=i(u,{code:D,status:S===void 0?void 0:`HTTP ${S}`,redact:l([process.env.SUPERSERVE_API_KEY])});return _(`Superserve request failed: ${a(D,B.detail)}`,D,c,B.cause)}var Ve=`import os,sys,marshal,_signal as signal,select,time,fcntl
2
2
  ${b}
3
+ ${M}
3
4
  root=sys.argv[1]
4
5
  v=marshal.loads(bytes.fromhex(sys.argv[2])) if len(sys.argv)>2 else marshal.loads(bytes.fromhex(sys.stdin.read()))
5
6
  if 'envKeys' in v: v['env']={k:os.environ[k] for k in v['envKeys']}
6
7
  os.makedirs(root,mode=0o700,exist_ok=True)
7
8
  # Keep small completed responses until their request deadline has passed.
8
- # Sweep expired responses inline, so no ack RPC or background daemon is needed.
9
- for entry in os.scandir(os.path.dirname(root)):
10
- if not entry.name.startswith('run-') or entry.path==root: continue
11
- try:
12
- with open(entry.path+'/expires') as f: expired=time.time()>float(f.read())
13
- if expired:
14
- import shutil
15
- shutil.rmtree(entry.path,ignore_errors=True)
16
- except (FileNotFoundError,NotADirectoryError): pass
9
+ # Sweep expired responses inline, at most every 30 seconds, so no ack RPC or
10
+ # background daemon is needed and a busy sandbox does not rescan every run.
11
+ with open(os.path.dirname(root)+'/.sweep','a') as sweep:
12
+ try: fcntl.flock(sweep,fcntl.LOCK_EX|fcntl.LOCK_NB)
13
+ except BlockingIOError: pass
14
+ else:
15
+ if time.time()-os.fstat(sweep.fileno()).st_mtime>30:
16
+ os.utime(sweep.fileno(),None)
17
+ for entry in os.scandir(os.path.dirname(root)):
18
+ if not entry.name.startswith('run-') or entry.path==root: continue
19
+ try:
20
+ with open(entry.path+'/expires') as f: expired=time.time()>float(f.read())
21
+ if expired:
22
+ import shutil
23
+ shutil.rmtree(entry.path,ignore_errors=True)
24
+ except (FileNotFoundError,NotADirectoryError): pass
17
25
  a=v.get('activityPath')
18
26
  timed=False
19
27
  code=127
@@ -53,17 +61,7 @@ try:
53
61
  if p:
54
62
  with open(root+'/pid','w') as m: m.write(str(p.pid))
55
63
  if p:
56
- stdout=p.stdout.fileno(); streams={stdout:'stdout',p.stderr.fileno():'stderr'}
57
- end=time.monotonic()+v['timeoutMs']/1000
58
- while streams or p.poll() is None:
59
- if not timed and time.monotonic()>=end:
60
- timed=True
61
- try: os.killpg(p.pid,signal.SIGKILL)
62
- except ProcessLookupError: pass
63
- for fd in select.select(list(streams),[],[],.01)[0]:
64
- data=os.read(fd,8192)
65
- if data: out.write(('["'+streams[fd]+'","'+data.hex()+'"]\\n').encode())
66
- else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()
64
+ timed=pump(p,lambda name,data: out.write(('["'+name+'","'+data.hex()+'"]\\n').encode()),time.monotonic()+v['timeoutMs']/1000)
67
65
  code=p.wait()
68
66
  timed=timed or os.path.exists(root+'/cancelled')
69
67
  result='{"exitCode":%s,"timedOut":%s}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower())
@@ -82,7 +80,7 @@ finally:
82
80
  if a:
83
81
  try: os.unlink(a)
84
82
  except FileNotFoundError: pass
85
- `;async function Pe(l,v){return U({guest:l,input:v,fail:(S,P)=>A(S,P),launch:(S,P)=>{let L={command:v.command,cwd:v.cwd,timeoutMs:v.timeoutMs,activityPath:v.activityPath},B=T({...L,envKeys:Object.keys(v.env)}).toString("hex"),D=`python3 -S -c ${n(ke)} ${n(S)} ${n(B)}`;if(l.run&&v.stdin===void 0&&Buffer.byteLength(D)<98304)return l.run(D,v.env,v.timeoutMs+5000,P);return l.exec(`python3 -S -c ${n(ke)} ${n(S)}`,T({...L,env:v.env,stdin:v.stdin??""}).toString("hex"),v.timeoutMs+5000,P)}})}var Ve=p(`import os,json,shutil,sys,tempfile
83
+ `,Pe=z(Ve);async function _e(u,c){return q({guest:u,input:c,fail:(g,S)=>_(g,S),launch:(g,S)=>{let D={command:c.command,cwd:c.cwd,timeoutMs:c.timeoutMs,activityPath:c.activityPath},B=C({...D,envKeys:Object.keys(c.env)}).toString("hex"),U=Pe.command(u.id,g,B);if(u.run&&c.stdin===void 0&&Buffer.byteLength(U)<98304)return u.run(U,c.env,c.timeoutMs+5000,S);return u.exec(Pe.command(u.id,g),C({...D,env:c.env,stdin:c.stdin??""}).toString("hex"),c.timeoutMs+5000,S)}})}var We=p(`import os,json,shutil,sys,tempfile
86
84
  v=json.loads(os.environ.pop('SANDBOX_SDK_BOOTSTRAP'))
87
85
  if any(shutil.which(tool) is None for tool in ('git','tar','nohup')): sys.exit(79)
88
86
  os.makedirs('/workspace',exist_ok=True)
@@ -91,4 +89,4 @@ os.makedirs(os.path.dirname('/var/lib/sandbox-sdk-env.json'),exist_ok=True)
91
89
  if v.get('env') is not None:
92
90
  with tempfile.NamedTemporaryFile(mode='w',dir=os.path.dirname('/var/lib/sandbox-sdk-env.json'),delete=False) as f:
93
91
  json.dump(v['env'],f)
94
- os.replace(f.name,'/var/lib/sandbox-sdk-env.json')`);function Ee(l){let v=l.installPython===!0?"export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get install -y -qq python3 python3-venv python3-pip >/dev/null || exit 1":"exit 78";if(l.execution)return{command:`if ! command -v python3 >/dev/null 2>&1; then ${v}; fi; command -v git tar nohup >/dev/null || exit 79; mkdir -p /workspace /tmp/.sandbox-sdk`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:l.env})}};return{command:`if ! command -v python3 >/dev/null 2>&1; then ${v}; fi; ${Ve}`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:l.env})}}}function le(l,v){if(l===78)throw A("Template lacks python3; use a template with Python 3 or explicitly set installPython: true to allow apt installation","unsupported",v);if(l===79)throw A("Template must include git, tar and nohup","unsupported",v)}var ze="https://api.superserve.ai",Re="sandbox.superserve.ai",Oe=new Map([["use",{baseUrl:"https://api.superserve.ai",sandboxHost:"sandbox.superserve.ai"}],["usw",{baseUrl:"https://api-usw.superserve.ai",sandboxHost:"usw-sandbox.superserve.ai"}]]),Ge=/^ss_live_([a-z0-9]{1,17})_[A-Za-z0-9_-]{32}$/,We=new Set(["sandbox.superserve.ai","staging-sandbox.superserve.ai","usw-sandbox.superserve.ai"]);function Xe(l){try{let v=new URL(l).hostname;if(v==="api-staging.superserve.ai")return"staging-sandbox.superserve.ai";for(let S of Oe.values())if(new URL(S.baseUrl).hostname===v)return S.sandboxHost}catch{}return Re}function Ae(l){let v=l.apiKey??process.env.SUPERSERVE_API_KEY;if(!v?.trim())throw A("Superserve API key is missing. Authentication is required. Set SUPERSERVE_API_KEY or pass apiKey.","auth");let S=(l.baseUrl??process.env.SUPERSERVE_BASE_URL)?.trim()||void 0;if(S!==void 0)return{apiKey:v,baseUrl:S,sandboxHost:Xe(S)};let P=Oe.get(Ge.exec(v)?.[1]??"");return{apiKey:v,baseUrl:P?.baseUrl??ze,sandboxHost:P?.sandboxHost??Re}}var Ze="X-Superserve-Sandbox-Id",pe="X-Superserve-Routing-Hint",Ie="X-Access-Token";function fe(l,v){let S=v.toLowerCase();return We.has(S)?{url:`https://${S}`,headers:{[Ze]:l}}:{url:`https://boxd-${l}.${S}`,headers:{}}}function Me(l,v){return`wss://boxd-${l}.${v.toLowerCase()}/exec/connect`}function Te(l,v,S){if(!Number.isInteger(S)||S<1024||S>65535||S===49983)throw A(S===49983?"Preview port 49983 is reserved for sandbox control traffic":"Preview ports must be integers from 1024 to 65535","invalid_argument");return`https://${S}-${l}.${v}`}function Ye(l){try{let v=JSON.parse(atob((l.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"))),S=r(v)?"e"in v?v.e:void 0:void 0;return o(S)&&Number.isFinite(S)?S*1000:void 0}catch{return}}function _e(l,v,S){let P=r(l)?"access_token"in l?l.access_token:void 0:void 0,L=r(l)?"routing_hint"in l?l.routing_hint:void 0:void 0;if(!t(P)||!P)throw A(`Superserve ${S} returned no access token`,"provider",v);let B={token:P};if(t(L)&&L)B.hint=L;return B}function Qe(l,v){if(!v)return l;return new Promise((S,P)=>{let L=()=>P(Error("Superserve route activation abandoned by its caller"));if(v.aborted)return L();v.addEventListener("abort",L,{once:!0}),l.then(S,P).finally(()=>v.removeEventListener("abort",L))})}function Ne(l){let v=l.refreshBeforeMs??30000,S=new Map,P=(O)=>{let N=S.get(O);if(!N)S.set(O,N={issued:0});return N};function L(O,N,C){if(!O.current||N>O.current.revision)O.current={...C,revision:N};return O.current}async function B(O,N,C){let F=++N.issued;return L(N,F,_e(await l.rotate(O,C),O,`POST /sandboxes/{id}/${C}`))}function D(O,N){let C=P(O);if(!C.activating){let F=B(O,C,"activate"),q=()=>{if(C.activating===F)C.activating=void 0};F.then(q,q),C.activating=F}return Qe(C.activating,N)}let J=(O)=>{let N=O.hint===void 0?void 0:Ye(O.hint);return N!==void 0&&N-Date.now()<=v};return{async current(O,N){let C=S.get(O)?.current;return C&&!J(C)?C:D(O,N)},async refresh(O,N,C){let F=S.get(O)?.current;if(F&&N!==void 0&&F.revision>N&&!J(F))return F;return D(O,C)},activate:D,resume:(O)=>{let N=P(O);return B(O,N,"resume")},seed(O,N){let C=P(O);return L(C,++C.issued,_e(N,O,"POST /sandboxes"))},forget:(O)=>{S.delete(O)},secrets:()=>[...S.values()].flatMap((O)=>O.current?[O.current.token,...O.current.hint?[O.current.hint]:[]]:[])}}var et="superserve.exec.v1",Ce=32768,$e=10485760,tt=new TextEncoder,ne=(l)=>A("Command startup aborted","aborted",l);async function Ue(l){if(typeof WebSocket>"u")throw A("Superserve commands with stdin need a global WebSocket (Node 22 or later, or Bun)","unsupported",l.sandboxId);let v=l.startupSignal;if(v?.aborted)throw ne(l.sandboxId);let S=await l.route(v),P;try{P=await je(l,S)}catch{if(v?.aborted)throw ne(l.sandboxId);S=await l.refresh(S,v),P=await je(l,S)}if(v?.aborted)throw P.close(),ne(l.sandboxId);return P.send(JSON.stringify({command:l.command,...l.env===void 0?void 0:{env:l.env},...l.timeoutMs===void 0?void 0:{timeout_s:Math.ceil(l.timeoutMs/1000)}})),nt(P,l)}function je(l,v){let{sandboxId:S,startupSignal:P}=l;return new Promise((L,B)=>{if(P?.aborted)return B(ne(S));let D=new WebSocket(l.url,[et,`token.${v.token}`,...v.hint?[`route.${v.hint}`]:[]]);D.binaryType="arraybuffer";let J=()=>{D.removeEventListener("open",O),D.removeEventListener("error",N),D.removeEventListener("close",C),P?.removeEventListener("abort",F)},O=()=>{J(),L(D)},N=()=>{J(),B(A("Superserve exec/connect could not open the connection","unavailable",S))},C=(q)=>{J(),B(A(`Superserve exec/connect closed before it opened (code ${q.code})`,"unavailable",S))},F=()=>{J(),D.addEventListener("error",()=>{}),D.close(),B(ne(S))};D.addEventListener("open",O),D.addEventListener("error",N),D.addEventListener("close",C),P?.addEventListener("abort",F,{once:!0})})}function nt(l,v){let S={stdout:new TextDecoder,stderr:new TextDecoder},P={stdout:"",stderr:""},L=0,B,D=new Promise((q,G)=>{B={resolve:q,reject:G}});D.catch(()=>{});let J=()=>{P.stdout+=S.stdout.decode(),P.stderr+=S.stderr.decode()},O=(q)=>{let G=B;B=void 0,J(),G?.resolve({exitCode:q,...P})},N=(q)=>{let G=B;if(B=void 0,J(),G?.reject(q),l.readyState<=WebSocket.OPEN)l.close()},C=()=>l.readyState===WebSocket.OPEN;l.addEventListener("message",(q)=>{if(t(q.data)){let K;try{K=JSON.parse(q.data)}catch{return}if(!r(K)||K===null)return;let X="error"in K?K.error:void 0;if(t(X))P.stderr+=X;if(("finished"in K?K.finished:void 0)===!0){let Z="exit_code"in K?K.exit_code:void 0;O(o(Z)?Z:0)}return}if(!(q.data instanceof ArrayBuffer))return;let G=new Uint8Array(q.data);if(!G.length)return;if(L+=G.length,L>$e)return N(A(`Superserve exec/connect sent more than ${$e} bytes of output`,"unsupported",v.sandboxId));let W=G[0]===1?"stdout":G[0]===2?"stderr":void 0;if(W)P[W]+=S[W].decode(G.subarray(1),{stream:!0})}),l.addEventListener("close",(q)=>{let G=q.code===1009?"a frame exceeded the server's size limit":q.reason?v.redact(q.reason).slice(0,200):`close code ${q.code}`;N(A(`Superserve exec/connect closed before the command finished (${G})`,"provider",v.sandboxId))}),l.addEventListener("error",()=>N(A("Superserve exec/connect failed before the command finished","provider",v.sandboxId)));let F=()=>{if(C())l.send(JSON.stringify({type:"signal",name:"SIGTERM"}))};return{stdin:{write(q){if(!C())return;let G=t(q)?tt.encode(q):q;for(let W=0;W<G.length;W+=Ce){let K=G.subarray(W,W+Ce),X=new Uint8Array(K.length+1);X.set(K,1),l.send(X)}},close(){if(C())l.send(JSON.stringify({type:"stdin_close"}))}},wait:()=>D,async close(){F(),N(A("Superserve exec/connect session closed by the client","aborted",v.sandboxId)),await D.then(()=>{},()=>{})}}}var rt=["1.1.1.1/32","8.8.8.8/32"],me=(l)=>/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/.test(l);function st(l){if(l===void 0||l==="all")return;if(l==="none")return{allowOut:[],denyOut:["0.0.0.0/0"]};for(let P of l.allow)if(!me(P)&&!/^(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(P))throw A("Network allow entries must be hostnames, *.wildcards, IPv4 addresses or IPv4 CIDRs","unsupported");let v=l.allow.map((P)=>me(P)&&!P.includes("/")?`${P}/32`:P),S=v.some((P)=>!me(P));return{allowOut:[...new Set([...v,...S?rt:[]])],denyOut:["0.0.0.0/0"]}}function ot(l,v){let S=(P=[],L=[])=>P.length===L.length&&P.every((B)=>L.includes(B));return S(l.allowOut,v?.allowOut)&&S(l.denyOut,v?.denyOut)}var Be=(l,v,S)=>{if(l===void 0)return;if(!Number.isSafeInteger(l)||l<0||!S&&l===0)throw A(`${v} must be a ${S?"non-negative":"positive"} integer of milliseconds`,"invalid_argument");return Math.ceil(l/1000)},z=(l,v)=>f(l)?l[v]:void 0,De=(l)=>Array.isArray(l)&&l.every((v)=>t(v))?l:void 0;function oe(l,v){let S=z(l,"id"),P=z(l,"status"),L=z(l,"created_at");if(!t(S)||!S||!t(P)||!P||!t(L))throw A("Superserve returned a sandbox without id, status or created_at","provider",v);let B={},D=z(l,"metadata");if(r(D)){for(let[N,C]of Object.entries(D))if(t(C))B[N]=C}let J=z(l,"timeout_seconds"),O=z(l,"network");return{id:S,status:P,metadata:B,createdAt:Date.parse(L),...o(J)?{timeoutSeconds:J}:void 0,...r(O)?{network:{allowOut:De(z(O,"allow_out")),denyOut:De(z(O,"deny_out"))}}:void 0}}var at=10485760,it=2147483648,dt=30000,Le=1000,ut=50,Ke=2000,ct=1000,lt=2000,pt=11,ae="@superserve/sdk",ft=(l)=>new Promise((v)=>setTimeout(v,l));function Ft(l={}){let v=new Map,S=new Set,P=new Set,L=new Map,B=new Map,D=()=>Ae(l),J=l.requestTimeoutMs??90000,O=Be(l.autoPauseMs,"autoPauseMs",!1),N=Be(l.autoDeleteMs,"autoDeleteMs",!0),C=l.previewAccess??"private";if(C!=="private"&&C!=="public")throw A("previewAccess must be private or public","invalid_argument");async function F(u,w){try{return await w()}catch(g){throw se(g,u)}}let q=(u)=>{if(u.sandboxId===void 0)s("The Superserve data plane needs a sandbox. Use box.native instead of provider.api");return u.sandboxId},G=new WeakMap,W=Ne({async rotate(u,w){let g={method:"POST",path:`/sandboxes/{sandboxId}/${w}`,params:{sandboxId:u},sandboxId:u,readOnly:!0},E=Date.now()+dt;for(;;)try{return await K.json(g)}catch(I){let M=H(I);if(w!=="activate"||M?.status!==409||M.code!=="sandbox_pausing"||E-Date.now()<=Le)throw I;await ft(Le)}}}),K=x({provider:"superserve",label:"Superserve",defaultPlane:"api",timeoutMs:J,secrets:()=>[l.apiKey,process.env.SUPERSERVE_API_KEY,...W.secrets()],authHint:"Set SUPERSERVE_API_KEY to a valid Superserve API key.",mapError:(u)=>u.kind==="status"&&u.status===409?"unavailable":void 0,planes:{api:{baseUrl:()=>D().baseUrl,auth:()=>({"X-API-Key":D().apiKey})},data:{baseUrl:(u)=>fe(q(u),D().sandboxHost).url,async auth(u){let w=q(u),g=await W.current(w,u.signal);return G.set(u,g.revision),{...fe(w,D().sandboxHost).headers,[Ie]:g.token,...g.hint?{[pe]:g.hint}:void 0}},async refresh(u){await W.refresh(q(u),G.get(u))},stale:({status:u,body:w,credentials:g})=>{if(u===404&&w.code==="sandbox_route_stale")return"refused";if(u!==503)return;if(w.code==="sandbox_unavailable"||/^sandbox is (paused|stopped)$/.test(w.text.trim()))return"refused";return g[pe]?void 0:"unsure"}}}});function X(u){let w=B.get(u);if(!w){let g=W.activate(u).then(()=>{return});w=g,B.set(u,g),g.catch(()=>{if(B.get(u)===g)B.delete(u)})}return w}let Z=(u)=>({params:{sandboxId:u},sandboxId:u}),ie=async(u)=>oe(await K.json({method:"GET",path:"/sandboxes/{sandboxId}",...Z(u)}),u);function ve(u){B.delete(u),W.forget(u),v.delete(u),P.delete(u),S.delete(u)}function be(u){if(u.metadata["sandbox-sdk"]!=="1")throw A("Not an SDK sandbox","not_found",u.id);let w={};for(let[g,E]of Object.entries(u.metadata))if(g.startsWith("label:"))w[g.slice(6)]=E;return{id:u.id,key:u.metadata["sdk-key"],labels:w,createdAt:u.createdAt,state:u.status==="active"?"running":["paused","pausing"].includes(u.status)?"paused":"stopped"}}function he(u,w,g){if(g?P.has(u):S.has(u))return{command:w,env:{}};let E=Ee({env:v.get(u),installPython:l.installPython,execution:g});return{command:`${E.command} && ${w}`,env:E.env}}async function He(u,w,g){let E=await K.json({method:"POST",path:"/exec",plane:"data",sandboxId:u,body:{command:w,...g.env===void 0?void 0:{env:g.env},timeout_s:Math.ceil(g.timeoutMs/1000)},timeoutMs:g.timeoutMs+5000,maxBytes:at}),I=z(E,"stdout"),M=z(E,"stderr"),j=z(E,"exit_code"),V=z(E,"truncated");return{stdout:t(I)?I:"",stderr:t(M)?M:"",exitCode:o(j)?j:0,truncated:V===!0}}async function de(u,w,g,E=!1){let I=he(u,w,E),M=await He(u,I.command,{...g,env:{...g.env,...I.env}});if(le(M.exitCode,u),M.exitCode===0){if(S.add(u),E)P.add(u)}return M}let ge=(u)=>{if(!u.startsWith("/")||u.split("/").includes(".."))throw A("Superserve file paths must be absolute without .. segments","invalid_argument");return u};async function xe(u){return await X(u),{name:"superserve",raw:async(w)=>{let g=await de(u,w,{timeoutMs:J});if(g.exitCode!==0)throw A("Guest operation failed","provider",u);return g.stdout},upload:async(w,g)=>{await K.request({method:"POST",path:"/files",plane:"data",sandboxId:u,query:{path:ge(w)},body:g,headers:{"content-type":"application/octet-stream"}})},read:async(w,g)=>{try{if(g){let E=await de(u,p("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",w,String(g.offset),String(g.length)),{timeoutMs:J});if(E.exitCode!==0)throw A("File range read failed","file_not_found",u);return new Uint8Array(Buffer.from(E.stdout.trim(),"base64"))}return(await K.request({method:"GET",path:"/files",plane:"data",sandboxId:u,query:{path:ge(w)},maxBytes:it})).body}catch(E){if(se(E).code==="not_found")throw A("File does not exist","file_not_found",u);throw E}}}}async function we(u,w,g){let E=Date.now();for(let I=!0;;I=!1){if(!I)try{await y(Date.now()-E<Ke?ut:ct,w,"superserve")}catch{throw g()}let M;try{M=oe(await K.json({method:"GET",path:"/sandboxes/{sandboxId}",...Z(u),deadline:w}),u).status}catch(j){if(H(j)?.status===404)return;if(w.timeout.aborted)throw g();throw j}if(M==="paused"||M==="deleted")return;if(M==="active"&&Date.now()-E<Ke)continue;if(M!=="pausing")throw A(`Sandbox did not pause: its status is ${M.slice(0,32)}`,"provider",u)}}let ye=(u)=>({deadline:d(J),stillPausing:()=>A(`Sandbox is still pausing after ${J} ms; it finishes in the background`,"timeout",u)}),Se={package:ae,async connect(u,w){let g=u.Sandbox;if(!(g instanceof Function))s(`The module passed to native.sdk() has no Sandbox export. Pass () => import("${ae}")`);if(w===void 0)return g;return _(await k(g,"connect",[w,{apiKey:D().apiKey,baseUrl:l.baseUrl}],ae),"Sandbox.connect",ae)}},re={name:"superserve",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","snapshot","network-policy"]),api:h({http:K,placeholder:"sandboxId",sdk:Se}),create:(u)=>F(void 0,async()=>{if(u.size!==void 0||u.idleTimeoutMs!==void 0||u.timeoutMs!==void 0)throw A("Template resources cannot be overridden, and Superserve has no idle or hard lifetime; use autoPauseMs and autoDeleteMs","unsupported");let w=st(u.network);if(!Number.isSafeInteger(J)||J<=0)throw A("requestTimeoutMs must be a positive integer","invalid_argument");if(u.signal?.aborted)throw A("Creation aborted","aborted");D();let g=new Map([["sandbox-sdk","1"]]);if(u.key!==void 0)g.set("sdk-key",u.key);for(let[j,V]of Object.entries(u.labels))g.set(`label:${j}`,V);let E=Date.now(),I;try{I=await K.json({method:"POST",path:"/sandboxes",body:{name:`sbxsdk-${crypto.randomUUID()}`,metadata:Object.fromEntries(g),...u.env===void 0?void 0:{env_vars:u.env},preview_access:C,...w?{network:{allow_out:w.allowOut,deny_out:w.denyOut}}:void 0,...O===void 0?void 0:{timeout_seconds:O},...N===void 0?void 0:{auto_delete_seconds:N},...l.secretBindings&&Object.keys(l.secretBindings).length?{secrets:l.secretBindings}:void 0,...u.from?{from_snapshot:u.from}:{from_template:l.template??"superserve/node-22"}}})}catch(j){let V=se(j);if(["timeout","unavailable","aborted","outcome_unknown"].includes(V.code))throw A("Creation outcome unknown; inspect SDK-labelled sandboxes before retrying","outcome_unknown");throw V}let M=oe(I);W.seed(M.id,I),B.set(M.id,Promise.resolve());try{if(u.signal?.aborted)throw A("Creation aborted","aborted");if(v.set(M.id,{...u.env}),u.from||w){let j=await ie(M.id);if(u.from&&j.timeoutSeconds!==O)await K.request({method:"PATCH",path:"/sandboxes/{sandboxId}",...Z(M.id),body:{timeout_seconds:O??null}});if(w&&!ot(w,j.network))throw A("Superserve did not confirm the requested egress rules","unsupported",M.id)}return{id:M.id,key:u.key,labels:{...u.labels,"sandbox-sdk":"1"},createdAt:E,state:"running"}}catch(j){throw await re.destroy(M.id),j}}),list:(u)=>F(void 0,async()=>{let w=await K.json({method:"GET",path:"/sandboxes",query:{"metadata.sandbox-sdk":"1"}});if(!Array.isArray(w))throw A("Superserve returned a sandbox list that is not an array");return w.map((g)=>oe(g)).filter((g)=>g.status!=="deleted").map(be).filter((g)=>Object.entries(u).every(([E,I])=>g.labels[E]===I))}),async find(u){let w=(await re.list({})).find((g)=>g.key===u);return w?re.connect(w.id):void 0},connect:(u)=>F(u,async()=>(await X(u),be(await ie(u)))),destroy(u){let w=L.get(u);if(!w)w=F(u,async()=>{let g=d(J);for(let E=1;;E++)try{await K.request({method:"DELETE",path:"/sandboxes/{sandboxId}",...Z(u),deadline:g});break}catch(I){let M=H(I)?.status;if(M===404)break;let j=Math.min(100*2**(E-1)*(0.8+Math.random()*0.4),30000);if(M!==409||E>=pt||j>=g.remaining())throw I;await y(j,g,"superserve")}ve(u)}),L.set(u,w),w.finally(()=>L.delete(u)).catch(()=>{});return w},async close(u){ve(u)},exec:(u,w)=>F(u,async()=>{let g=await xe(u);return Pe({raw:g.raw,read:async(E,I)=>{let M=await g.raw(p("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",E,String(I.offset),String(I.length)));return new Uint8Array(Buffer.from(M.trim(),"base64"))},run:async(E,I,M,j)=>{if(j?.aborted)throw A("Command interrupted","aborted",u);let V=()=>{},Y=new Promise((Q,ee)=>{V=()=>ee(A("Command interrupted","aborted",u))});j?.addEventListener("abort",V,{once:!0});try{let Q=de(u,E,{env:I,timeoutMs:M},!0),ee=await Promise.race([Q,Y]);if(ee.exitCode!==0||ee.truncated)throw A("Supervisor failed","provider",u);return ee.stdout}finally{j?.removeEventListener("abort",V)}},exec:async(E,I,M,j)=>{let V=he(u,E,!0),Y=await Ue({sandboxId:u,url:Me(u,D().sandboxHost),command:V.command,env:V.env,timeoutMs:M,startupSignal:j,route:(te)=>W.current(u,te),refresh:(te,ue)=>W.refresh(u,te.revision,ue),redact:K.redact}),Q=()=>{},ee=!1;try{Y.stdin.write(I),Y.stdin.close();let te=new Promise((mt,qe)=>{Q=()=>{qe(A("Command interrupted","aborted",u))}});if(j?.addEventListener("abort",Q,{once:!0}),j?.aborted)Q();let ue=Y.wait().finally(()=>Y.close());ee=!0;let ce=await Promise.race([ue,te]);if(le(ce.exitCode,u),ce.exitCode!==0)throw A("Supervisor failed","provider",u);return P.add(u),S.add(u),ce.stdout}finally{if(j?.removeEventListener("abort",Q),!ee)await Y.close()}}},w)}),files:R(xe,F),previewUrl:(u,w)=>F(u,async()=>{await X(u);let g=Te(u,D().sandboxHost,w),E=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/preview-ports",...Z(u),body:{port:w,access:C}}),I=z(E,"access");if(!o(z(E,"port"))||I!=="public"&&I!=="private")throw A("Superserve returned an invalid preview port","provider",u);if(C==="public")return{url:g};let M=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/preview-ports/{port}/token",params:{sandboxId:u,port:w},sandboxId:u,body:{}}),j=z(M,"token"),V=z(M,"header"),Y=z(M,"expires_at");if(!t(j)||!j||!t(V)||!V)throw A("Superserve returned an invalid preview token","provider",u);let Q=t(Y)?Date.parse(Y):NaN;return{url:g,headers:{[V]:j},...Number.isNaN(Q)?void 0:{expiresAt:Q}}}),pause:(u)=>F(u,async()=>{await X(u);let{deadline:w,stillPausing:g}=ye(u),E;try{E=z(await K.json({method:"POST",path:"/sandboxes/{sandboxId}/pause",...Z(u),timeoutMs:Math.min(30000,J),signal:w.signal}),"status")==="pausing"}catch(I){if(w.timeout.aborted)throw g();if(!(I instanceof e)||I.code!=="timeout"&&I.code!=="outcome_unknown")throw I;E=!0}if(E)await we(u,w,g)}),resume:(u)=>F(u,async()=>{await X(u);try{await W.resume(u)}catch(w){if(H(w)?.status!==409)throw w;let{status:g}=await ie(u);if(g!=="pausing"&&g!=="paused")throw w;if(g==="pausing"){let{deadline:E,stillPausing:I}=ye(u);await we(u,E,I)}await W.resume(u)}}),snapshot:(u,w)=>F(u,async()=>{if(w?.expiresInMs)throw A("Superserve keeps snapshots until they are deleted; omit expiresInMs","unsupported",u);await X(u);let g=`sbxsdk-${crypto.randomUUID()}`,E;try{let I=d(J),M=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/snapshot",...Z(u),body:{kind:"mem+fs",idempotency_key:g,name:g},idempotencyKey:g,deadline:I});for(;;){let j=z(M,"id"),V=z(M,"status");if(!t(j)||!j)throw A("Superserve returned a snapshot without an id","provider",u);if(V==="ready")return{id:j};if(V==="failed"||V==="deleting")throw E=A(`Snapshot ${V}`,"provider",u),E;await y(Math.min(lt,I.remaining()),I,"superserve"),M=await K.json({method:"GET",path:"/snapshots/{snapshotId}",params:{snapshotId:j},sandboxId:u,deadline:I})}}catch{if(E)throw E;throw A(`Snapshot outcome unknown; recover snapshot named ${g} from source ${u}`,"outcome_unknown",u)}}),native:(u)=>h({http:K,placeholder:"sandboxId",sandboxId:u,sdk:Se})};return re}export{Ft as superserve};
92
+ os.replace(f.name,'/var/lib/sandbox-sdk-env.json')`);function Ee(u){let c=u.installPython===!0?"export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get install -y -qq python3 python3-venv python3-pip >/dev/null || exit 1":"exit 78";if(u.execution)return{command:`if ! command -v python3 >/dev/null 2>&1; then ${c}; fi; command -v git tar nohup >/dev/null || exit 79; mkdir -p /workspace /tmp/.sandbox-sdk`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:u.env})}};return{command:`if ! command -v python3 >/dev/null 2>&1; then ${c}; fi; ${We}`,env:{SANDBOX_SDK_BOOTSTRAP:JSON.stringify({env:u.env})}}}function pe(u,c){if(u===78)throw _("Template lacks python3; use a template with Python 3 or explicitly set installPython: true to allow apt installation","unsupported",c);if(u===79)throw _("Template must include git, tar and nohup","unsupported",c)}var Ge="https://api.superserve.ai",Re="sandbox.superserve.ai",Ae=new Map([["use",{baseUrl:"https://api.superserve.ai",sandboxHost:"sandbox.superserve.ai"}],["usw",{baseUrl:"https://api-usw.superserve.ai",sandboxHost:"usw-sandbox.superserve.ai"}]]),Xe=/^ss_live_([a-z0-9]{1,17})_[A-Za-z0-9_-]{32}$/,Ze=new Set(["sandbox.superserve.ai","staging-sandbox.superserve.ai","usw-sandbox.superserve.ai"]);function Ye(u){try{let c=new URL(u).hostname;if(c==="api-staging.superserve.ai")return"staging-sandbox.superserve.ai";for(let g of Ae.values())if(new URL(g.baseUrl).hostname===c)return g.sandboxHost}catch{}return Re}function Ie(u){let c=u.apiKey??process.env.SUPERSERVE_API_KEY;if(!c?.trim())throw _("Superserve API key is missing. Authentication is required. Set SUPERSERVE_API_KEY or pass apiKey.","auth");let g=(u.baseUrl??process.env.SUPERSERVE_BASE_URL)?.trim()||void 0;if(g!==void 0)return{apiKey:c,baseUrl:g,sandboxHost:Ye(g)};let S=Ae.get(Xe.exec(c)?.[1]??"");return{apiKey:c,baseUrl:S?.baseUrl??Ge,sandboxHost:S?.sandboxHost??Re}}var Qe="X-Superserve-Sandbox-Id",fe="X-Superserve-Routing-Hint",Me="X-Access-Token";function me(u,c){let g=c.toLowerCase();return Ze.has(g)?{url:`https://${g}`,headers:{[Qe]:u}}:{url:`https://boxd-${u}.${g}`,headers:{}}}function Te(u,c){return`wss://boxd-${u}.${c.toLowerCase()}/exec/connect`}function Ne(u,c,g){if(!Number.isInteger(g)||g<1024||g>65535||g===49983)throw _(g===49983?"Preview port 49983 is reserved for sandbox control traffic":"Preview ports must be integers from 1024 to 65535","invalid_argument");return`https://${g}-${u}.${c}`}function et(u){try{let c=JSON.parse(atob((u.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"))),g=r(c)?"e"in c?c.e:void 0:void 0;return o(g)&&Number.isFinite(g)?g*1000:void 0}catch{return}}function Oe(u,c,g){let S=r(u)?"access_token"in u?u.access_token:void 0:void 0,D=r(u)?"routing_hint"in u?u.routing_hint:void 0:void 0;if(!t(S)||!S)throw _(`Superserve ${g} returned no access token`,"provider",c);let B={token:S};if(t(D)&&D)B.hint=D;return B}function tt(u,c){if(!c)return u;return new Promise((g,S)=>{let D=()=>S(Error("Superserve route activation abandoned by its caller"));if(c.aborted)return D();c.addEventListener("abort",D,{once:!0}),u.then(g,S).finally(()=>c.removeEventListener("abort",D))})}function Ce(u){let c=u.refreshBeforeMs??30000,g=new Map,S=(E)=>{let I=g.get(E);if(!I)g.set(E,I={issued:0});return I};function D(E,I,A){if(!E.current||I>E.current.revision)E.current={...A,revision:I};return E.current}async function B(E,I,A){let H=++I.issued;return D(I,H,Oe(await u.rotate(E,A),E,`POST /sandboxes/{id}/${A}`))}function U(E,I){let A=S(E);if(!A.activating){let H=B(E,A,"activate"),L=()=>{if(A.activating===H)A.activating=void 0};H.then(L,L),A.activating=H}return tt(A.activating,I)}let F=(E)=>{let I=E.hint===void 0?void 0:et(E.hint);return I!==void 0&&I-Date.now()<=c};return{async current(E,I){let A=g.get(E)?.current;return A&&!F(A)?A:U(E,I)},async refresh(E,I,A){let H=g.get(E)?.current;if(H&&I!==void 0&&H.revision>I&&!F(H))return H;return U(E,A)},activate:U,resume:(E)=>{let I=S(E);return B(E,I,"resume")},seed(E,I){let A=S(E);return D(A,++A.issued,Oe(I,E,"POST /sandboxes"))},forget:(E)=>{g.delete(E)},secrets:()=>[...g.values()].flatMap((E)=>E.current?[E.current.token,...E.current.hint?[E.current.hint]:[]]:[])}}var nt="superserve.exec.v1",je=32768,$e=10485760,rt=new TextEncoder,re=(u)=>_("Command startup aborted","aborted",u);async function Ue(u){if(typeof WebSocket>"u")throw _("Superserve commands with stdin need a global WebSocket (Node 22 or later, or Bun)","unsupported",u.sandboxId);let c=u.startupSignal;if(c?.aborted)throw re(u.sandboxId);let g=await u.route(c),S;try{S=await Be(u,g)}catch{if(c?.aborted)throw re(u.sandboxId);g=await u.refresh(g,c),S=await Be(u,g)}if(c?.aborted)throw S.close(),re(u.sandboxId);return S.send(JSON.stringify({command:u.command,env:u.env,timeout_s:u.timeoutMs===void 0?void 0:Math.ceil(u.timeoutMs/1000)})),st(S,u)}function Be(u,c){let{sandboxId:g,startupSignal:S}=u;return new Promise((D,B)=>{if(S?.aborted)return B(re(g));let U=new WebSocket(u.url,[nt,`token.${c.token}`,...c.hint?[`route.${c.hint}`]:[]]);U.binaryType="arraybuffer";let F=()=>{U.removeEventListener("open",E),U.removeEventListener("error",I),U.removeEventListener("close",A),S?.removeEventListener("abort",H)},E=()=>{F(),D(U)},I=()=>{F(),B(_("Superserve exec/connect could not open the connection","unavailable",g))},A=(L)=>{F(),B(_(`Superserve exec/connect closed before it opened (code ${L.code})`,"unavailable",g))},H=()=>{F(),U.addEventListener("error",()=>{}),U.close(),B(re(g))};U.addEventListener("open",E),U.addEventListener("error",I),U.addEventListener("close",A),S?.addEventListener("abort",H,{once:!0})})}function st(u,c){let g={stdout:new TextDecoder,stderr:new TextDecoder},S={stdout:"",stderr:""},D=0,B,U=new Promise((L,W)=>{B={resolve:L,reject:W}});U.catch(()=>{});let F=()=>{S.stdout+=g.stdout.decode(),S.stderr+=g.stderr.decode()},E=(L)=>{let W=B;B=void 0,F(),W?.resolve({exitCode:L,...S})},I=(L)=>{let W=B;if(B=void 0,F(),W?.reject(L),u.readyState<=WebSocket.OPEN)u.close()},A=()=>u.readyState===WebSocket.OPEN;u.addEventListener("message",(L)=>{if(t(L.data)){let K;try{K=JSON.parse(L.data)}catch{return}if(!r(K)||K===null)return;let Z="error"in K?K.error:void 0;if(t(Z))S.stderr+=Z;if(("finished"in K?K.finished:void 0)===!0){let Q="exit_code"in K?K.exit_code:void 0;E(o(Q)?Q:0)}return}if(!(L.data instanceof ArrayBuffer))return;let W=new Uint8Array(L.data);if(!W.length)return;if(D+=W.length,D>$e)return I(_(`Superserve exec/connect sent more than ${$e} bytes of output`,"unsupported",c.sandboxId));let G=W[0]===1?"stdout":W[0]===2?"stderr":void 0;if(G)S[G]+=g[G].decode(W.subarray(1),{stream:!0})}),u.addEventListener("close",(L)=>{let W=L.code===1009?"a frame exceeded the server's size limit":L.reason?c.redact(L.reason).slice(0,200):`close code ${L.code}`;I(_(`Superserve exec/connect closed before the command finished (${W})`,"provider",c.sandboxId))}),u.addEventListener("error",()=>I(_("Superserve exec/connect failed before the command finished","provider",c.sandboxId)));let H=()=>{if(A())u.send(JSON.stringify({type:"signal",name:"SIGTERM"}))};return{stdin:{write(L){if(!A())return;let W=t(L)?rt.encode(L):L;for(let G=0;G<W.length;G+=je){let K=W.subarray(G,G+je),Z=new Uint8Array(K.length+1);Z.set(K,1),u.send(Z)}},close(){if(A())u.send(JSON.stringify({type:"stdin_close"}))}},wait:()=>U,async close(){H(),I(_("Superserve exec/connect session closed by the client","aborted",c.sandboxId)),await U.then(()=>{},()=>{})}}}var ot=["1.1.1.1/32","8.8.8.8/32"],ve=(u)=>/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/.test(u);function at(u){if(u===void 0||u==="all")return;if(u==="none")return{allowOut:[],denyOut:["0.0.0.0/0"]};for(let S of u.allow)if(!ve(S)&&!/^(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(S))throw _("Network allow entries must be hostnames, *.wildcards, IPv4 addresses or IPv4 CIDRs","unsupported");let c=u.allow.map((S)=>ve(S)&&!S.includes("/")?`${S}/32`:S),g=c.some((S)=>!ve(S));return{allowOut:[...new Set([...c,...g?ot:[]])],denyOut:["0.0.0.0/0"]}}function it(u,c){let g=(S=[],D=[])=>S.length===D.length&&S.every((B)=>D.includes(B));return g(u.allowOut,c?.allowOut)&&g(u.denyOut,c?.denyOut)}var De=(u,c,g)=>{if(u===void 0)return;if(!Number.isSafeInteger(u)||u<0||!g&&u===0)throw _(`${c} must be a ${g?"non-negative":"positive"} integer of milliseconds`,"invalid_argument");return Math.ceil(u/1000)},V=(u,c)=>f(u)?u[c]:void 0,Ke=(u)=>Array.isArray(u)&&u.every((c)=>t(c))?u:void 0;function ae(u,c){let g=V(u,"id"),S=V(u,"status"),D=V(u,"created_at");if(!t(g)||!g||!t(S)||!S||!t(D))throw _("Superserve returned a sandbox without id, status or created_at","provider",c);let B={},U=V(u,"metadata");if(r(U)){for(let[I,A]of Object.entries(U))if(t(A))B[I]=A}let F=V(u,"timeout_seconds"),E=V(u,"network");return{id:g,status:S,metadata:B,createdAt:Date.parse(D),timeoutSeconds:o(F)?F:void 0,network:r(E)?{allowOut:Ke(V(E,"allow_out")),denyOut:Ke(V(E,"deny_out"))}:void 0}}var dt=10485760,ut=2147483648,ct=30000,Le=1000,lt=50,He=2000,pt=1000,ft=2000,mt=11,ie="@superserve/sdk",vt=(u)=>new Promise((c)=>setTimeout(c,u));function Jt(u={}){let c=new Map,g=new Set,S=new Set,D=new Map,B=new Map,U=()=>Ie(u),F=u.requestTimeoutMs??90000,E=De(u.autoPauseMs,"autoPauseMs",!1),I=De(u.autoDeleteMs,"autoDeleteMs",!0),A=u.previewAccess??"private";if(A!=="private"&&A!=="public")throw _("previewAccess must be private or public","invalid_argument");async function H(n,h){try{return await h()}catch(v){throw oe(v,n)}}let L=(n)=>{if(n.sandboxId===void 0)s("The Superserve data plane needs a sandbox. Use box.native instead of provider.api");return n.sandboxId},W=new WeakMap,G=Ce({async rotate(n,h){let v={method:"POST",path:`/sandboxes/{sandboxId}/${h}`,params:{sandboxId:n},sandboxId:n,readOnly:!0},P=Date.now()+ct;for(;;)try{return await K.json(v)}catch(O){let R=X(O);if(h!=="activate"||R?.status!==409||R.code!=="sandbox_pausing"||P-Date.now()<=Le)throw O;await vt(Le)}}}),K=x({provider:"superserve",label:"Superserve",defaultPlane:"api",timeoutMs:F,secrets:()=>[u.apiKey,process.env.SUPERSERVE_API_KEY,...G.secrets()],authHint:"Set SUPERSERVE_API_KEY to a valid Superserve API key.",mapError:(n)=>n.kind==="status"&&n.status===409?"unavailable":void 0,planes:{api:{baseUrl:()=>U().baseUrl,auth:()=>({"X-API-Key":U().apiKey})},data:{baseUrl:(n)=>me(L(n),U().sandboxHost).url,async auth(n){let h=L(n),v=await G.current(h,n.signal);W.set(n,v.revision);let P={...me(h,U().sandboxHost).headers,[Me]:v.token};return v.hint?{...P,[fe]:v.hint}:P},async refresh(n){await G.refresh(L(n),W.get(n))},stale:({status:n,body:h,credentials:v})=>{if(n===404&&h.code==="sandbox_route_stale")return"refused";if(n!==503)return;if(h.code==="sandbox_unavailable"||/^sandbox is (paused|stopped)$/.test(h.text.trim()))return"refused";return v[fe]?void 0:"unsure"}}}});function Z(n){let h=B.get(n);if(!h){let v=G.activate(n).then(()=>{return});h=v,B.set(n,v),v.catch(()=>{if(B.get(n)===v)B.delete(n)})}return h}let Q=(n)=>({params:{sandboxId:n},sandboxId:n}),de=async(n)=>ae(await K.json({method:"GET",path:"/sandboxes/{sandboxId}",...Q(n)}),n);function be(n){B.delete(n),G.forget(n),c.delete(n),S.delete(n),g.delete(n)}function he(n){if(n.metadata["sandbox-sdk"]!=="1")throw _("Not an SDK sandbox","not_found",n.id);let h={};for(let[v,P]of Object.entries(n.metadata))if(v.startsWith("label:"))h[v.slice(6)]=P;return{id:n.id,key:n.metadata["sdk-key"],labels:h,createdAt:n.createdAt,state:n.status==="active"?"running":["paused","pausing"].includes(n.status)?"paused":"stopped"}}function ge(n,h,v){if(v?S.has(n):g.has(n))return{command:h,env:{}};let P=Ee({env:c.get(n),installPython:u.installPython,execution:v});return{command:`${P.command} && ${h}`,env:P.env}}async function qe(n,h,v){let P=await K.json({method:"POST",path:"/exec",plane:"data",sandboxId:n,body:{command:h,env:v.env,timeout_s:Math.ceil(v.timeoutMs/1000)},timeoutMs:v.timeoutMs+5000,maxBytes:dt}),O=V(P,"stdout"),R=V(P,"stderr"),j=V(P,"exit_code"),J=V(P,"truncated");return{stdout:t(O)?O:"",stderr:t(R)?R:"",exitCode:o(j)?j:0,truncated:J===!0}}async function ue(n,h,v,P=!1){let O=ge(n,h,P),R=await qe(n,O.command,{...v,env:{...v.env,...O.env}});if(pe(R.exitCode,n),R.exitCode===0){if(g.add(n),P)S.add(n)}return R}let we=(n)=>{if(!n.startsWith("/")||n.split("/").includes(".."))throw _("Superserve file paths must be absolute without .. segments","invalid_argument");return n};async function xe(n){return await Z(n),{name:"superserve",raw:async(h)=>{let v=await ue(n,h,{timeoutMs:F});if(v.exitCode!==0)throw _("Guest operation failed","provider",n);return v.stdout},upload:async(h,v)=>{await K.request({method:"POST",path:"/files",plane:"data",sandboxId:n,query:{path:we(h)},body:v,headers:{"content-type":"application/octet-stream"}})},read:async(h,v)=>{try{if(v){let P=await ue(n,p("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",h,String(v.offset),String(v.length)),{timeoutMs:F});if(P.exitCode!==0)throw _("File range read failed","file_not_found",n);return new Uint8Array(Buffer.from(P.stdout.trim(),"base64"))}return(await K.request({method:"GET",path:"/files",plane:"data",sandboxId:n,query:{path:we(h)},maxBytes:ut})).body}catch(P){if(oe(P).code==="not_found")throw _("File does not exist","file_not_found",n);throw P}}}}async function ye(n,h,v){let P=Date.now();for(let O=!0;;O=!1){if(!O)try{await y(Date.now()-P<He?lt:pt,h,"superserve")}catch{throw v()}let R;try{R=ae(await K.json({method:"GET",path:"/sandboxes/{sandboxId}",...Q(n),deadline:h}),n).status}catch(j){if(X(j)?.status===404)return;if(h.timeout.aborted)throw v();throw j}if(R==="paused"||R==="deleted")return;if(R==="active"&&Date.now()-P<He)continue;if(R!=="pausing")throw _(`Sandbox did not pause: its status is ${R.slice(0,32)}`,"provider",n)}}let Se=(n)=>({deadline:d(F),stillPausing:()=>_(`Sandbox is still pausing after ${F} ms; it finishes in the background`,"timeout",n)}),ke={package:ie,async connect(n,h){let v=n.Sandbox;if(!(v instanceof Function))s(`The module passed to native.sdk() has no Sandbox export. Pass () => import("${ie}")`);if(h===void 0)return v;return T(await k(v,"connect",[h,{apiKey:U().apiKey,baseUrl:u.baseUrl}],ie),"Sandbox.connect",ie)}},se={name:"superserve",keyMode:"best-effort",inlineActivity:!0,capabilities:new Set(["pause","snapshot","network-policy"]),api:w({http:K,placeholder:"sandboxId",sdk:ke}),create:(n)=>H(void 0,async()=>{if(n.size!==void 0||n.idleTimeoutMs!==void 0||n.timeoutMs!==void 0)throw _("Template resources cannot be overridden, and Superserve has no idle or hard lifetime; use autoPauseMs and autoDeleteMs","unsupported");let h=at(n.network);if(!Number.isSafeInteger(F)||F<=0)throw _("requestTimeoutMs must be a positive integer","invalid_argument");if(n.signal?.aborted)throw _("Creation aborted","aborted");U();let v=new Map([["sandbox-sdk","1"]]);if(n.key!==void 0)v.set("sdk-key",n.key);for(let[j,J]of Object.entries(n.labels))v.set(`label:${j}`,J);let P=Date.now(),O;try{O=await K.json({method:"POST",path:"/sandboxes",body:{name:`sbxsdk-${crypto.randomUUID()}`,metadata:Object.fromEntries(v),env_vars:n.env,preview_access:A,network:h?{allow_out:h.allowOut,deny_out:h.denyOut}:void 0,timeout_seconds:E,auto_delete_seconds:I,secrets:u.secretBindings&&Object.keys(u.secretBindings).length?u.secretBindings:void 0,...n.from?{from_snapshot:n.from}:{from_template:u.template??"superserve/node-22"}}})}catch(j){let J=oe(j);if(["timeout","unavailable","aborted","outcome_unknown"].includes(J.code))throw _("Creation outcome unknown; inspect SDK-labelled sandboxes before retrying","outcome_unknown");throw J}let R=ae(O);G.seed(R.id,O),B.set(R.id,Promise.resolve());try{if(n.signal?.aborted)throw _("Creation aborted","aborted");if(c.set(R.id,{...n.env}),n.from||h){let j=await de(R.id);if(n.from&&j.timeoutSeconds!==E)await K.request({method:"PATCH",path:"/sandboxes/{sandboxId}",...Q(R.id),body:{timeout_seconds:E??null}});if(h&&!it(h,j.network))throw _("Superserve did not confirm the requested egress rules","unsupported",R.id)}return{id:R.id,key:n.key,labels:{...n.labels,"sandbox-sdk":"1"},createdAt:P,state:"running"}}catch(j){throw await se.destroy(R.id),j}}),list:(n)=>H(void 0,async()=>{let h=await K.json({method:"GET",path:"/sandboxes",query:{"metadata.sandbox-sdk":"1"}});if(!Array.isArray(h))throw _("Superserve returned a sandbox list that is not an array");return h.map((v)=>ae(v)).filter((v)=>v.status!=="deleted").map(he).filter((v)=>Object.entries(n).every(([P,O])=>v.labels[P]===O))}),async find(n){let h=(await se.list({})).find((v)=>v.key===n);return h?se.connect(h.id):void 0},connect:(n)=>H(n,async()=>(await Z(n),he(await de(n)))),destroy(n){let h=D.get(n);if(!h)h=H(n,async()=>{let v=d(F);for(let P=1;;P++)try{await K.request({method:"DELETE",path:"/sandboxes/{sandboxId}",...Q(n),deadline:v});break}catch(O){let R=X(O)?.status;if(R===404)break;let j=Math.min(100*2**(P-1)*(0.8+Math.random()*0.4),30000);if(R!==409||P>=mt||j>=v.remaining())throw O;await y(j,v,"superserve")}be(n)}),D.set(n,h),h.finally(()=>D.delete(n)).catch(()=>{});return h},async close(n){be(n)},exec:(n,h)=>H(n,async()=>{let v=await xe(n);return _e({id:n,raw:v.raw,read:async(P,O)=>{let R=await v.raw(p("import sys,base64; f=open(sys.argv[1],'rb'); f.seek(int(sys.argv[2])); print(base64.b64encode(f.read(int(sys.argv[3]))).decode())",P,String(O.offset),String(O.length)));return new Uint8Array(Buffer.from(R.trim(),"base64"))},run:async(P,O,R,j)=>{if(j?.aborted)throw _("Command interrupted","aborted",n);let J=()=>{},ee=new Promise((te,Y)=>{J=()=>Y(_("Command interrupted","aborted",n))});j?.addEventListener("abort",J,{once:!0});try{let te=ue(n,P,{env:O,timeoutMs:R},!0),Y=await Promise.race([te,ee]);if(Y.exitCode!==0||Y.truncated)throw _("Supervisor failed","provider",n);return Y.stdout}finally{j?.removeEventListener("abort",J)}},exec:async(P,O,R,j)=>{let J=ge(n,P,!0),ee=await Ue({sandboxId:n,url:Te(n,U().sandboxHost),command:J.command,env:J.env,timeoutMs:R,startupSignal:j,route:(ne)=>G.current(n,ne),refresh:(ne,ce)=>G.refresh(n,ne.revision,ce),redact:K.redact}),te=()=>{},Y=!1;try{ee.stdin.write(O),ee.stdin.close();let ne=new Promise((bt,Fe)=>{te=()=>{Fe(_("Command interrupted","aborted",n))}});if(j?.addEventListener("abort",te,{once:!0}),j?.aborted)te();let ce=ee.wait().finally(()=>ee.close());Y=!0;let le=await Promise.race([ce,ne]);if(pe(le.exitCode,n),le.exitCode!==0)throw _("Supervisor failed","provider",n);return S.add(n),g.add(n),le.stdout}finally{if(j?.removeEventListener("abort",te),!Y)await ee.close()}}},h)}),files:N(xe,H),previewUrl:(n,h)=>H(n,async()=>{await Z(n);let v=Ne(n,U().sandboxHost,h),P=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/preview-ports",...Q(n),body:{port:h,access:A}}),O=V(P,"access");if(!o(V(P,"port"))||O!=="public"&&O!=="private")throw _("Superserve returned an invalid preview port","provider",n);if(A==="public")return{url:v};let R=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/preview-ports/{port}/token",params:{sandboxId:n,port:h},sandboxId:n,body:{}}),j=V(R,"token"),J=V(R,"header"),ee=V(R,"expires_at");if(!t(j)||!j||!t(J)||!J)throw _("Superserve returned an invalid preview token","provider",n);let te=t(ee)?Date.parse(ee):NaN,Y={url:v,headers:{[J]:j}};if(!Number.isNaN(te))Y.expiresAt=te;return Y}),pause:(n)=>H(n,async()=>{await Z(n);let{deadline:h,stillPausing:v}=Se(n),P;try{P=V(await K.json({method:"POST",path:"/sandboxes/{sandboxId}/pause",...Q(n),timeoutMs:Math.min(30000,F),signal:h.signal}),"status")==="pausing"}catch(O){if(h.timeout.aborted)throw v();if(!(O instanceof e)||O.code!=="timeout"&&O.code!=="outcome_unknown")throw O;P=!0}if(P)await ye(n,h,v)}),resume:(n)=>H(n,async()=>{await Z(n);try{await G.resume(n)}catch(h){if(X(h)?.status!==409)throw h;let{status:v}=await de(n);if(v!=="pausing"&&v!=="paused")throw h;if(v==="pausing"){let{deadline:P,stillPausing:O}=Se(n);await ye(n,P,O)}await G.resume(n)}}),snapshot:(n,h)=>H(n,async()=>{if(h?.expiresInMs)throw _("Superserve keeps snapshots until they are deleted; omit expiresInMs","unsupported",n);await Z(n);let v=`sbxsdk-${crypto.randomUUID()}`,P;try{let O=d(F),R=await K.json({method:"POST",path:"/sandboxes/{sandboxId}/snapshot",...Q(n),body:{kind:"mem+fs",idempotency_key:v,name:v},idempotencyKey:v,deadline:O});for(;;){let j=V(R,"id"),J=V(R,"status");if(!t(j)||!j)throw _("Superserve returned a snapshot without an id","provider",n);if(J==="ready")return{id:j};if(J==="failed"||J==="deleting")throw P=_(`Snapshot ${J}`,"provider",n),P;await y(Math.min(ft,O.remaining()),O,"superserve"),R=await K.json({method:"GET",path:"/snapshots/{snapshotId}",params:{snapshotId:j},sandboxId:n,deadline:O})}}catch{if(P)throw P;throw _(`Snapshot outcome unknown; recover snapshot named ${v} from source ${n}`,"outcome_unknown",n)}}),native:(n)=>w({http:K,placeholder:"sandboxId",sandboxId:n,sdk:ke})};return se}export{Jt as superserve};
@@ -1,4 +1,4 @@
1
- import{T}from"../../chunk-8786zrns.js";import{b,L,F}from"../../chunk-x681p5d2.js";import{m}from"../../chunk-bd481sb7.js";import{g}from"../../chunk-k60b4r27.js";import{t,o,I,r,e,i,se,c,a}from"../../chunk-xgxfy2n8.js";async function oe(n){let{action:u,timeoutMs:h,signal:y}=n;if(y?.aborted)throw n.aborted();let x=new AbortController,_=()=>x.abort(n.aborted());y?.addEventListener("abort",_,{once:!0});let k=setTimeout(()=>x.abort(n.expired()),h),E=()=>{},f=new Promise((S,v)=>{E=()=>v(x.signal.reason),x.signal.addEventListener("abort",E,{once:!0})});try{return await Promise.race([f,u(x.signal)])}finally{clearTimeout(k),y?.removeEventListener("abort",_),x.signal.removeEventListener("abort",E)}}var ne=new Map([["MissingAuthTokenError","auth"],["InvalidAuthTokenError","auth"],["UnauthorizedError","auth"],["PermissionDeniedError","auth"],["SessionNotFoundError","not_found"],["SessionExpiredError","not_found"],["SessionTerminatedError","not_found"],["SnapshotNotFoundError","not_found"],["FileNotFoundError","file_not_found"],["QuotaExceededError","quota"],["PortLimitExceededError","quota"],["RateLimitedError","quota"],["CapacityUnavailableError","unavailable"],["SSHUnavailableError","unavailable"],["DataPlaneNotReadyError","unavailable"],["CommandTimeoutError","timeout"],["SnapshotWaitTimeoutError","timeout"],["PrimitiveTimeoutError","timeout"],["InvalidResourceConfigError","invalid_argument"],["InvalidStateError","invalid_argument"],["InboundDisabledError","unsupported"],["CapabilityUnavailableError","unsupported"]]),ke=new Set(["ResumeFailedError","PauseFailedError","WaitReadyFailedError","StreamClosedError"]);function ie(n,u){let h={},y=new Set,x=n;for(let _=0;_<4&&r(x)&&!y.has(x);_++){y.add(x);let k=m(x);if(ne.has(k.name)||ke.has(k.name))h.nativeName??=k.name;let E=k.status??k.statusCode;if(E!==void 0&&Number.isInteger(E)&&E>=100&&E<=599)h.status??=E;let f=k.code;if(o(f)&&Number.isInteger(f)&&f>=0&&f<=16||t(f)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(f)&&!u.some((v)=>f.includes(v)))h.providerCode??=f;let S=k.requestId??k.metadata.get("x-request-id")??k.metadata.get("request-id");if(S!==void 0&&/^[A-Za-z0-9_-]{1,128}$/.test(S)&&!u.some((v)=>S.includes(v)))h.requestId??=S;x=k.cause}return h}function ae(n,u,h,y){let x=h.status??h.providerCode,{detail:_}=i(n,{code:u,known:h.nativeName===void 0?void 0:!0,status:x===void 0?void 0:String(x),redact:c(y)});return _===void 0?{}:{native:_}}function G(n,u,h="request",y=[]){if(n instanceof e)return n;let x=n instanceof Error?n.name:"",_=ne.get(x)??"provider",k=[...y,process.env.TENKI_API_KEY??"",process.env.TENKI_AUTH_TOKEN??""].filter(Boolean),E=ie(n,k),f={operation:h,...E,...ae(n,_,E,k)};return new e(`Tenki request failed: ${a(_,f.native)}. Check credentials, quotas, and session state.`,{code:_,provider:"tenki",sandboxId:u,cause:se(f),retryable:["quota","unavailable","timeout"].includes(_)})}function de(n,u,h,y){let x=G(n,u.id,"create",h),_=[...h,process.env.TENKI_API_KEY??"",process.env.TENKI_AUTH_TOKEN??""].filter(Boolean),k={operation:"create",admittedByThisCall:!0,stage:u.stage};if(/^[0-9a-f-]{36}$/i.test(u.id)&&!_.some((f)=>u.id.includes(f)))k.sandboxId=u.id;if(/^[A-Z_]{1,32}$/.test(u.state))k.state=u.state;let E=ie(n,_);if(Object.assign(k,E,ae(n,x.code,E,_)),y!==void 0)k.cleanupCode=y;return new e(x.message,{code:x.code,provider:"tenki",sandboxId:u.id,retryable:x.retryable,hint:x.hint,cause:se(k)})}function p(n,u="provider"){return new e(u==="auth"?n:`${n}. Tenki could not honor the request. Check the provider options.`,{code:u,provider:"tenki"})}function U(n,u,h){return oe({action:n,timeoutMs:u,signal:h,aborted:()=>p("Request aborted","aborted"),expired:()=>p("Request deadline exceeded","timeout")})}import{setTimeout as he}from"node:timers/promises";async function ce(n,u,h){let y=Date.now()+u,x=()=>n.state==="RUNNING";if(h?.aborted)throw p("Creation aborted","aborted");if(x()&&n.dataPlaneRPC!==void 0&&n.dataPlaneRPC())return;try{await U((k)=>n.waitReady(u,k),Math.min(5000,u/2),h);return}catch(k){if(h?.aborted)throw p("Creation aborted","aborted");if(G(k).code!=="timeout")throw k}if(x())return;let _;while(Date.now()<y){if(h?.aborted)throw p("Creation aborted","aborted");try{if(await U(()=>n.refresh(),Math.min(1e4,y-Date.now()),h),h?.aborted)throw p("Creation aborted","aborted");if(x())return;if(["TERMINATED","TERMINATING"].includes(n.state))throw p("Session terminated before readiness","not_found")}catch(E){let f=G(E).code;if(["auth","not_found","invalid_argument","aborted"].includes(f))throw E;_=E}let k=y-Date.now();if(k>0)try{await he(Math.min(1000,k),void 0,{signal:h})}catch{throw p("Creation aborted","aborted")}}throw new e("Tenki session did not become ready within its readiness budget.",{code:"timeout",provider:"tenki",sandboxId:n.id,cause:_})}var V=`workspace=globals().get('v',{}).get('workspace','/workspace')
1
+ import{C}from"../../chunk-r8xnq6v3.js";import{j,b,M,H,V}from"../../chunk-6bemkxcx.js";import{m}from"../../chunk-drgkmewv.js";import{g}from"../../chunk-3zd78ha4.js";import{t,o,_,r,e,i,ce,l,a}from"../../chunk-n7x9ha44.js";async function ie(n){let{action:c,timeoutMs:h,signal:y}=n;if(y?.aborted)throw n.aborted();let x=new AbortController,N=()=>x.abort(n.aborted());y?.addEventListener("abort",N,{once:!0});let k=setTimeout(()=>x.abort(n.expired()),h),T=()=>{},f=new Promise((S,v)=>{T=()=>v(x.signal.reason),x.signal.addEventListener("abort",T,{once:!0})});try{return await Promise.race([f,c(x.signal)])}finally{clearTimeout(k),y?.removeEventListener("abort",N),x.signal.removeEventListener("abort",T)}}var se=new Map([["MissingAuthTokenError","auth"],["InvalidAuthTokenError","auth"],["UnauthorizedError","auth"],["PermissionDeniedError","auth"],["SessionNotFoundError","not_found"],["SessionExpiredError","not_found"],["SessionTerminatedError","not_found"],["SnapshotNotFoundError","not_found"],["FileNotFoundError","file_not_found"],["QuotaExceededError","quota"],["PortLimitExceededError","quota"],["RateLimitedError","quota"],["CapacityUnavailableError","unavailable"],["SSHUnavailableError","unavailable"],["DataPlaneNotReadyError","unavailable"],["CommandTimeoutError","timeout"],["SnapshotWaitTimeoutError","timeout"],["PrimitiveTimeoutError","timeout"],["InvalidResourceConfigError","invalid_argument"],["InvalidStateError","invalid_argument"],["InboundDisabledError","unsupported"],["CapabilityUnavailableError","unsupported"]]),be=new Set(["ResumeFailedError","PauseFailedError","WaitReadyFailedError","StreamClosedError"]);function ae(n,c){let h={},y=new Set,x=n;for(let N=0;N<4&&r(x)&&!y.has(x);N++){y.add(x);let k=m(x);if(se.has(k.name)||be.has(k.name))h.nativeName??=k.name;let T=k.status??k.statusCode;if(T!==void 0&&Number.isInteger(T)&&T>=100&&T<=599)h.status??=T;let f=k.code;if(o(f)&&Number.isInteger(f)&&f>=0&&f<=16||t(f)&&/^[A-Z][A-Z0-9_]{0,63}$/.test(f)&&!c.some((v)=>f.includes(v)))h.providerCode??=f;let S=k.requestId??k.metadata.get("x-request-id")??k.metadata.get("request-id");if(S!==void 0&&/^[A-Za-z0-9_-]{1,128}$/.test(S)&&!c.some((v)=>S.includes(v)))h.requestId??=S;x=k.cause}return h}function de(n,c,h,y){let x=h.status??h.providerCode,{detail:N}=i(n,{code:c,known:h.nativeName===void 0?void 0:!0,status:x===void 0?void 0:String(x),redact:l(y)});return N===void 0?{}:{native:N}}function G(n,c,h="request",y=[]){if(n instanceof e)return n;let x=n instanceof Error?n.name:"",N=se.get(x)??"provider",k=[...y,process.env.TENKI_API_KEY??"",process.env.TENKI_AUTH_TOKEN??""].filter(Boolean),T=ae(n,k),f={operation:h,...T,...de(n,N,T,k)};return new e(`Tenki request failed: ${a(N,f.native)}. Check credentials, quotas, and session state.`,{code:N,provider:"tenki",sandboxId:c,cause:ce(f),retryable:["quota","unavailable","timeout"].includes(N)})}function ue(n,c,h,y){let x=G(n,c.id,"create",h),N=[...h,process.env.TENKI_API_KEY??"",process.env.TENKI_AUTH_TOKEN??""].filter(Boolean),k={operation:"create",admittedByThisCall:!0,stage:c.stage};if(/^[0-9a-f-]{36}$/i.test(c.id)&&!N.some((f)=>c.id.includes(f)))k.sandboxId=c.id;if(/^[A-Z_]{1,32}$/.test(c.state))k.state=c.state;let T=ae(n,N);if(Object.assign(k,T,de(n,x.code,T,N)),y!==void 0)k.cleanupCode=y;return new e(x.message,{code:x.code,provider:"tenki",sandboxId:c.id,retryable:x.retryable,hint:x.hint,cause:ce(k)})}function p(n,c="provider"){return new e(c==="auth"?n:`${n}. Tenki could not honor the request. Check the provider options.`,{code:c,provider:"tenki"})}function U(n,c,h){return ie({action:n,timeoutMs:c,signal:h,aborted:()=>p("Request aborted","aborted"),expired:()=>p("Request deadline exceeded","timeout")})}import{setTimeout as ye}from"node:timers/promises";async function le(n,c,h){let y=Date.now()+c,x=()=>n.state==="RUNNING";if(h?.aborted)throw p("Creation aborted","aborted");if(x()&&n.dataPlaneRPC!==void 0&&n.dataPlaneRPC())return;try{await U((k)=>n.waitReady(c,k),Math.min(5000,c/2),h);return}catch(k){if(h?.aborted)throw p("Creation aborted","aborted");if(G(k).code!=="timeout")throw k}if(x())return;let N;while(Date.now()<y){if(h?.aborted)throw p("Creation aborted","aborted");try{if(await U(()=>n.refresh(),Math.min(1e4,y-Date.now()),h),h?.aborted)throw p("Creation aborted","aborted");if(x())return;if(["TERMINATED","TERMINATING"].includes(n.state))throw p("Session terminated before readiness","not_found")}catch(T){let f=G(T).code;if(["auth","not_found","invalid_argument","aborted"].includes(f))throw T;N=T}let k=y-Date.now();if(k>0)try{await ye(Math.min(1000,k),void 0,{signal:h})}catch{throw p("Creation aborted","aborted")}}throw new e("Tenki session did not become ready within its readiness budget.",{code:"timeout",provider:"tenki",sandboxId:n.id,cause:N})}var Y=`workspace=globals().get('v',{}).get('workspace','/workspace')
2
2
  home=os.path.join(os.path.dirname(workspace),'home','tenki')
3
3
  tmp=os.path.join(os.path.dirname(workspace),'tmp')
4
4
  os.makedirs(home+'/.sandbox-sdk',exist_ok=True)
@@ -17,10 +17,11 @@ with open(home+'/.sandbox-sdk/setup.lock','w') as setup_lock:
17
17
  if not os.path.exists(tmp+'/.sandbox-sdk'):
18
18
  try: os.symlink(home+'/.sandbox-sdk',tmp+'/.sandbox-sdk')
19
19
  except FileExistsError: pass
20
- `;function Q(n){return Array.isArray(n)&&n.length===2&&(n[0]==="stdout"||n[0]==="stderr")&&t(n[1])&&n[1].length<=21848}function X(n){return r(n)&&"exitCode"in n&&(n.exitCode===null||o(n.exitCode)&&Number.isInteger(n.exitCode))&&"timedOut"in n&&I(n.timedOut)&&(!("workspaceStable"in n)||I(n.workspaceStable))&&(!("workspaceRoot"in n)||t(n.workspaceRoot))&&(!("workspaceRootHex"in n)||t(n.workspaceRootHex))}var be=`import os,sys,marshal,_signal as signal,select,time,pwd
20
+ `;function ee(n){return Array.isArray(n)&&n.length===2&&(n[0]==="stdout"||n[0]==="stderr")&&t(n[1])&&n[1].length<=21848}function te(n){return r(n)&&"exitCode"in n&&(n.exitCode===null||o(n.exitCode)&&Number.isInteger(n.exitCode))&&"timedOut"in n&&_(n.timedOut)&&(!("workspaceStable"in n)||_(n.workspaceStable))&&(!("workspaceRoot"in n)||t(n.workspaceRoot))&&(!("workspaceRootHex"in n)||t(n.workspaceRootHex))}var ve=`import os,sys,marshal,_signal as signal,select,time,pwd
21
21
  ${b}
22
+ ${M}
22
23
  v=marshal.loads(bytes.fromhex(sys.stdin.read()))
23
- ${V}
24
+ ${Y}
24
25
  def processes():
25
26
  ids=set()
26
27
  for e in os.scandir('/proc'):
@@ -45,18 +46,7 @@ with stdin_file() as f:
45
46
  if v.get('activityPath'):
46
47
  os.makedirs(os.path.dirname(v['activityPath']),exist_ok=True)
47
48
  with open(v['activityPath'],'w') as a: a.write('1')
48
- stdout=p.stdout.fileno(); streams={stdout:'stdout',p.stderr.fileno():'stderr'}
49
- end=time.monotonic()+v['timeoutMs']/1000
50
- timed=False
51
- while streams or p.poll() is None:
52
- if not timed and time.monotonic()>=end:
53
- timed=True
54
- try: os.killpg(p.pid,signal.SIGKILL)
55
- except ProcessLookupError: pass
56
- for fd in select.select(list(streams),[],[],.01)[0]:
57
- data=os.read(fd,8192)
58
- if data: print('["'+streams[fd]+'","'+data.hex()+'"]',flush=True)
59
- else: del streams[fd]; (p.stdout if fd==stdout else p.stderr).close()
49
+ timed=pump(p,lambda name,data: print('["'+name+'","'+data.hex()+'"]',flush=True),time.monotonic()+v['timeoutMs']/1000)
60
50
  code=p.wait()
61
51
  print('{"exitCode":%s,"timedOut":%s,"workspaceStable":%s,"workspaceRootHex":"%s"}'%('null' if timed else str(code if code>=0 else 128-code),str(timed).lower(),str(stable()).lower(),os.path.realpath(v['workspace']).encode().hex()),flush=True)
62
52
  except BaseException:
@@ -68,7 +58,7 @@ with stdin_file() as f:
68
58
  if path:
69
59
  try: os.unlink(path)
70
60
  except FileNotFoundError: pass
71
- `,ye=`import os,sys,time,signal
61
+ `,ge=j(ve),xe=`import os,sys,time,signal
72
62
  for _ in range(100):
73
63
  try:
74
64
  with open(sys.argv[1]) as f: pid=int(f.read())
@@ -76,11 +66,11 @@ for _ in range(100):
76
66
  break
77
67
  except ProcessLookupError: break
78
68
  except (FileNotFoundError,ValueError): time.sleep(.01)
79
- else: raise RuntimeError('PID unavailable')`;async function ue(n,u,h){if(u.signal?.aborted)return{exitCode:null,timedOut:!0};let y=`/home/tenki/.sandbox-sdk-run-${crypto.randomUUID()}`,x=Buffer.from(T({command:u.command,cwd:u.cwd,env:u.env,stdin:u.stdin??"",timeoutMs:u.timeoutMs,marker:y,activityPath:u.activityPath,workspace:"/workspace"}).toString("hex")),_=new AbortController,k,E=!1,f=!1,S={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},v=new TextDecoder,P="";function C(D){let M=JSON.parse(D);if(Q(M)){let[A,q]=M,K=S[A].decode(Buffer.from(q,"hex"),{stream:!0});if(K)u.onChunk({stream:A,text:K});return}if(!X(M))throw p("Invalid command output record");if(M.workspaceRootHex!==void 0)h?.(Buffer.from(M.workspaceRootHex,"hex").toString(),M.workspaceStable===!0);k={exitCode:M.exitCode,timedOut:M.timedOut}}let R=(async()=>{for(let D=0;D<2;D++){let M=new AbortController,A=AbortSignal.any([_.signal,M.signal]),q,K=!1;async function*d(){A.throwIfAborted(),yield{frame:{payload:{case:"start",value:{sessionId:n.id,cmd:["python3","-S","-c",be],privileged:!0,streamStdin:!0}}}},A.throwIfAborted(),f=!0,yield{frame:{payload:{case:"stdin",value:x}}},yield{frame:{payload:{case:"stdinClose",value:!0}}},await new Promise((s)=>{if(A.aborted)s();else A.addEventListener("abort",()=>s(),{once:!0})})}try{A.throwIfAborted(),q=await n.requireDataPlane(!1),A.throwIfAborted();for await(let s of q.run(d(),{signal:A})){let l=s.frame?.payload;if(!l)continue;if(l.case!=="keepalive")K=!0;if(l.case==="started")n.markDataPlaneServing(q);else if(l.case==="stdout"){P+=v.decode(l.value,{stream:!0});let w;while((w=P.indexOf(`
80
- `))!==-1)C(P.slice(0,w)),P=P.slice(w+1);if(P.length>24000)throw p("Oversized command output record")}else if(l.case==="exit"){if(l.value.exitCode!==0||!k||P)throw p("Command supervisor failed");E=!0;for(let w of["stdout","stderr"]){let N=S[w].decode();if(N)u.onChunk({stream:w,text:N})}return k}}throw p("Command stream closed before exit")}catch(s){if(M.abort(),_.signal.aborted)throw s;let l=r(s)&&"code"in s?s.code:void 0,w=s instanceof Error?s.message:"",N=l===16||G(s).code==="auth",j=l===5&&/\bsession not found\b/i.test(w)&&q!==void 0&&n.dataPlaneProvisioningPending(q),z=N||j||l===12&&/\b404\b/.test(w)||(l===10||l===13||l===14)&&/REFUSED_STREAM/i.test(w);if(!K&&(z||!f)){if(f=!1,N){if(D===0&&await n.reauthOnUnauthenticated(s))continue;throw p("Command authorization rejected before launch","auth")}if(z||l===14){if(D===0){if(j&&q)await n.refreshHintedDataPlane(q);continue}throw p("Command transport rejected before launch","unavailable")}}if(f)throw p("Command stream failed after submission; execution outcome is unknown","outcome_unknown");throw s}finally{M.abort()}}throw p("Command recovery exhausted","unavailable")})();R.catch(()=>{});try{return await U(()=>R,u.timeoutMs+1000,u.signal)}catch(D){if(f&&!E)try{await H(n,["python3","-c",ye,y],void 0,1500)}catch{if(!E)throw p("Process cancellation could not be confirmed; execution outcome is unknown","outcome_unknown")}if(u.signal?.aborted||G(D).code==="timeout")return{exitCode:null,timedOut:!0};throw D}finally{_.abort()}}var ve=`import os,sys,json,base64,signal,selectors,time,pwd
69
+ else: raise RuntimeError('PID unavailable')`;async function me(n,c,h){if(c.signal?.aborted)return{exitCode:null,timedOut:!0};let y=`/home/tenki/.sandbox-sdk-run-${crypto.randomUUID()}`,x=Buffer.from(C({command:c.command,cwd:c.cwd,env:c.env,stdin:c.stdin??"",timeoutMs:c.timeoutMs,marker:y,activityPath:c.activityPath,workspace:"/workspace"}).toString("hex")),N=new AbortController,k,T=!1,f=!1,S={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},v=new TextDecoder,E="";function I(F){let A=JSON.parse(F);if(ee(A)){let[O,q]=A,K=S[O].decode(Buffer.from(q,"hex"),{stream:!0});if(K)c.onChunk({stream:O,text:K});return}if(!te(A))throw p("Invalid command output record");if(A.workspaceRootHex!==void 0)h?.(Buffer.from(A.workspaceRootHex,"hex").toString(),A.workspaceStable===!0);k={exitCode:A.exitCode,timedOut:A.timedOut}}let R=(async()=>{for(let F=0;F<2;F++){let A=new AbortController,O=AbortSignal.any([N.signal,A.signal]),q,K=!1;async function*d(){O.throwIfAborted(),yield{frame:{payload:{case:"start",value:{sessionId:n.id,cmd:["python3","-S","-c",ge],privileged:!0,streamStdin:!0}}}},O.throwIfAborted(),f=!0,yield{frame:{payload:{case:"stdin",value:x}}},yield{frame:{payload:{case:"stdinClose",value:!0}}},await new Promise((s)=>{if(O.aborted)s();else O.addEventListener("abort",()=>s(),{once:!0})})}try{O.throwIfAborted(),q=await n.requireDataPlane(!1),O.throwIfAborted();for await(let s of q.run(d(),{signal:O})){let u=s.frame?.payload;if(!u)continue;if(u.case!=="keepalive")K=!0;if(u.case==="started")n.markDataPlaneServing(q);else if(u.case==="stdout"){E+=v.decode(u.value,{stream:!0});let w;while((w=E.indexOf(`
70
+ `))!==-1)I(E.slice(0,w)),E=E.slice(w+1);if(E.length>24000)throw p("Oversized command output record")}else if(u.case==="exit"){if(u.value.exitCode!==0||!k||E)throw p("Command supervisor failed");T=!0;for(let w of["stdout","stderr"]){let P=S[w].decode();if(P)c.onChunk({stream:w,text:P})}return k}}throw p("Command stream closed before exit")}catch(s){if(A.abort(),N.signal.aborted)throw s;let u=r(s)&&"code"in s?s.code:void 0,w=s instanceof Error?s.message:"",P=u===16||G(s).code==="auth",L=u===5&&/\bsession not found\b/i.test(w)&&q!==void 0&&n.dataPlaneProvisioningPending(q),z=P||L||u===12&&/\b404\b/.test(w)||(u===10||u===13||u===14)&&/REFUSED_STREAM/i.test(w);if(!K&&(z||!f)){if(f=!1,P){if(F===0&&await n.reauthOnUnauthenticated(s))continue;throw p("Command authorization rejected before launch","auth")}if(z||u===14){if(F===0){if(L&&q)await n.refreshHintedDataPlane(q);continue}throw p("Command transport rejected before launch","unavailable")}}if(f)throw p("Command stream failed after submission; execution outcome is unknown","outcome_unknown");throw s}finally{A.abort()}}throw p("Command recovery exhausted","unavailable")})();R.catch(()=>{});try{return await U(()=>R,c.timeoutMs+1000,c.signal)}catch(F){if(f&&!T)try{await Z(n,["python3","-c",xe,y],void 0,1500)}catch{if(!T)throw p("Process cancellation could not be confirmed; execution outcome is unknown","outcome_unknown")}if(c.signal?.aborted||G(F).code==="timeout")return{exitCode:null,timedOut:!0};throw F}finally{N.abort()}}var Se=`import os,sys,json,base64,signal,selectors,time,pwd
81
71
  ${b}
82
72
  v=json.load(sys.stdin)
83
- ${V}
73
+ ${Y}
84
74
  def processes():
85
75
  ids=set()
86
76
  for e in os.scandir('/proc'):
@@ -124,7 +114,7 @@ finally:
124
114
  if v.get('activityPath'):
125
115
  try: os.unlink(v['activityPath'])
126
116
  except FileNotFoundError: pass
127
- `,ge=`import sys,json
117
+ `,Te=`import sys,json
128
118
  pos=int(sys.argv[2]); chunks=[]
129
119
  try:
130
120
  with open(sys.argv[1],'rb') as f:
@@ -135,7 +125,7 @@ try:
135
125
  chunks.append(json.loads(line)); pos=f.tell()
136
126
  except FileNotFoundError: pass
137
127
  print(json.dumps({'offset':pos,'chunks':chunks}))
138
- `,xe=`import os,sys,time,signal
128
+ `,Ee=`import os,sys,time,signal
139
129
  p=sys.argv[1]
140
130
  for _ in range(3000):
141
131
  try:
@@ -144,8 +134,8 @@ for _ in range(3000):
144
134
  except (FileNotFoundError,ValueError): time.sleep(.01)
145
135
  else: raise RuntimeError('PID unavailable')
146
136
  try: os.killpg(pid,signal.SIGKILL)
147
- except ProcessLookupError: pass`;async function H(n,u,h,y=30000,x){let _=new ReadableStream({start(E){if(h)E.enqueue(h);E.close()}}),k=await U((E)=>n.run(u,{privileged:!0,stdin:_,timeoutMs:y,signal:E}),y,x);if(k.exitCode!==0||k.timedOut)throw p("Guest operation failed",k.timedOut?"timeout":"provider");return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(k.stdout)}function Se(n){return n.requireDataPlane!==void 0}async function le(n,u,h){if(Se(n))return ue(n,u,h);if(u.signal?.aborted)return{exitCode:null,timedOut:!0};let y=`/home/tenki/.sandbox-sdk-run-${crypto.randomUUID()}`,x=Buffer.from(JSON.stringify({command:u.command,cwd:u.cwd,env:u.env,stdin:Buffer.from(u.stdin??"").toString("base64"),timeoutMs:u.timeoutMs,marker:y,activityPath:u.activityPath,workspace:"/workspace"})),_=!1,k=()=>{},E=new Promise((s)=>{k=()=>{_=!0,s("cancelled")}});u.signal?.addEventListener("abort",k,{once:!0});let f=setTimeout(k,u.timeoutMs),S=new ReadableStream({start(s){s.enqueue(x),s.close()}}),v=new AbortController,P=n.run(["python3","-S","-c",ve],{privileged:!0,stdin:S,signal:v.signal}),C=[];async function R(s,l){let w=new TextDecoder("utf-8",{ignoreBOM:!0}),N=s.getReader();C.push(N);try{while(!0){let{value:z,done:O}=await N.read();if(O)break;let Z=w.decode(z,{stream:!0});if(Z)u.onChunk({stream:l,text:Z})}}finally{N.releaseLock()}let j=w.decode();if(j)u.onChunk({stream:l,text:j})}let D=!1,M=new AbortController,A=Promise.resolve(P).finally(()=>{D=!0});async function q(){let s=0,l={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})};while(!M.signal.aborted){let w=D,N=JSON.parse(await H(n,["python3","-c",ge,`${y}.out`,String(s)],void 0,30000,M.signal));if(!r(N)||!("offset"in N)||!o(N.offset)||!Number.isSafeInteger(N.offset)||N.offset<s||!("chunks"in N)||!Array.isArray(N.chunks)||N.chunks.length>3)throw p("Invalid output page");let j=s;s=N.offset;for(let z of N.chunks){if(!Q(z))throw p("Invalid output chunk");let[O,Z]=z,B=l[O].decode(Buffer.from(Z,"base64"),{stream:!0});if(B&&!M.signal.aborted)u.onChunk({stream:O,text:B})}if(s===j){if(w)break;await new Promise((z)=>setTimeout(z,10))}}for(let w of["stdout","stderr"]){let N=l[w].decode();if(N&&!M.signal.aborted)u.onChunk({stream:w,text:N})}}let K=Promise.all([A,R(P.stdout,"stdout"),R(P.stderr,"stderr"),q()]).then(async()=>{let s=JSON.parse(await H(n,["cat",`${y}.exit`],void 0,30000,M.signal));if(!X(s))throw p("Invalid command result");if(s.workspaceRoot!==void 0)h?.(s.workspaceRoot,s.workspaceStable===!0);return{exitCode:s.exitCode,timedOut:s.timedOut}});K.catch(()=>{});async function d(){await H(n,["python3","-c",xe,y],void 0,1000)}try{if(u.signal?.aborted)k();let s=_?"cancelled":await Promise.race([K,E]);if(s==="cancelled"){try{await d()}catch{throw await U(()=>n.close(),1000).catch(()=>{}),p("Process cancellation could not be confirmed; VM termination was requested","outcome_unknown")}return await U(()=>K,250).catch(()=>{}),v.abort(),{exitCode:null,timedOut:!0}}return s}catch(s){try{await d()}catch{await U(()=>n.close(),1000).catch(()=>{})}throw s}finally{M.abort(),v.abort();for(let s of C)s.cancel().catch(()=>{});clearTimeout(f),u.signal?.removeEventListener("abort",k),await H(n,["rm","-f",y,`${y}.exit`,`${y}.out`],void 0,250).catch(()=>{})}}import{posix as J}from"node:path";var Te=`import os,sys,json,stat
148
- ${V}
137
+ except ProcessLookupError: pass`;async function Z(n,c,h,y=30000,x){let N=new ReadableStream({start(T){if(h)T.enqueue(h);T.close()}}),k=await U((T)=>n.run(c,{privileged:!0,stdin:N,timeoutMs:y,signal:T}),y,x);if(k.exitCode!==0||k.timedOut)throw p("Guest operation failed",k.timedOut?"timeout":"provider");return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(k.stdout)}function Pe(n){return n.requireDataPlane!==void 0}async function fe(n,c,h){if(Pe(n))return me(n,c,h);if(c.signal?.aborted)return{exitCode:null,timedOut:!0};let y=`/home/tenki/.sandbox-sdk-run-${crypto.randomUUID()}`,x=Buffer.from(JSON.stringify({command:c.command,cwd:c.cwd,env:c.env,stdin:Buffer.from(c.stdin??"").toString("base64"),timeoutMs:c.timeoutMs,marker:y,activityPath:c.activityPath,workspace:"/workspace"})),N=!1,k=()=>{},T=new Promise((s)=>{k=()=>{N=!0,s("cancelled")}});c.signal?.addEventListener("abort",k,{once:!0});let f=setTimeout(k,c.timeoutMs),S=new ReadableStream({start(s){s.enqueue(x),s.close()}}),v=new AbortController,E=n.run(["python3","-S","-c",Se],{privileged:!0,stdin:S,signal:v.signal}),I=[];async function R(s,u){let w=new TextDecoder("utf-8",{ignoreBOM:!0}),P=s.getReader();I.push(P);try{while(!0){let{value:z,done:D}=await P.read();if(D)break;let W=w.decode(z,{stream:!0});if(W)c.onChunk({stream:u,text:W})}}finally{P.releaseLock()}let L=w.decode();if(L)c.onChunk({stream:u,text:L})}let F=!1,A=new AbortController,O=Promise.resolve(E).finally(()=>{F=!0});async function q(){let s=0,u={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})};while(!A.signal.aborted){let w=F,P=JSON.parse(await Z(n,["python3","-c",Te,`${y}.out`,String(s)],void 0,30000,A.signal));if(!r(P)||!("offset"in P)||!o(P.offset)||!Number.isSafeInteger(P.offset)||P.offset<s||!("chunks"in P)||!Array.isArray(P.chunks)||P.chunks.length>3)throw p("Invalid output page");let L=s;s=P.offset;for(let z of P.chunks){if(!ee(z))throw p("Invalid output chunk");let[D,W]=z,B=u[D].decode(Buffer.from(W,"base64"),{stream:!0});if(B&&!A.signal.aborted)c.onChunk({stream:D,text:B})}if(s===L){if(w)break;await new Promise((z)=>setTimeout(z,10))}}for(let w of["stdout","stderr"]){let P=u[w].decode();if(P&&!A.signal.aborted)c.onChunk({stream:w,text:P})}}let K=Promise.all([O,R(E.stdout,"stdout"),R(E.stderr,"stderr"),q()]).then(async()=>{let s=JSON.parse(await Z(n,["cat",`${y}.exit`],void 0,30000,A.signal));if(!te(s))throw p("Invalid command result");if(s.workspaceRoot!==void 0)h?.(s.workspaceRoot,s.workspaceStable===!0);return{exitCode:s.exitCode,timedOut:s.timedOut}});K.catch(()=>{});async function d(){await Z(n,["python3","-c",Ee,y],void 0,1000)}try{if(c.signal?.aborted)k();let s=N?"cancelled":await Promise.race([K,T]);if(s==="cancelled"){try{await d()}catch{throw await U(()=>n.close(),1000).catch(()=>{}),p("Process cancellation could not be confirmed; VM termination was requested","outcome_unknown")}return await U(()=>K,250).catch(()=>{}),v.abort(),{exitCode:null,timedOut:!0}}return s}catch(s){try{await d()}catch{await U(()=>n.close(),1000).catch(()=>{})}throw s}finally{A.abort(),v.abort();for(let s of I)s.cancel().catch(()=>{});clearTimeout(f),c.signal?.removeEventListener("abort",k),await Z(n,["rm","-f",y,`${y}.exit`,`${y}.out`],void 0,250).catch(()=>{})}}import{posix as Q}from"node:path";var Ne=`import os,sys,json,stat
138
+ ${Y}
149
139
  op,p=sys.argv[1:3]
150
140
  def info(p):
151
141
  s=os.stat(p) if os.path.normpath(p)==workspace else os.lstat(p)
@@ -172,4 +162,4 @@ try:
172
162
  else: os.unlink(p)
173
163
  except FileNotFoundError: print('SDK_FILE_NOT_FOUND')
174
164
  except OSError: print('SDK_FILE_ERROR')
175
- `,Ee=134217728;function me(n,u){let h=u.modifiedUnixNs/1000000000n,y=u.modifiedUnixNs-h*1000000000n;return{path:n,type:u.isSymlink||u.mode&Ee?"symlink":u.isDir?"directory":"file",size:Number(u.size),modifiedAt:(Number(h)+Number(y)*0.000000001)*1000}}function fe(n,u,h,y){let x=(f,S,v,P,C="")=>u(f,async()=>{let R=await H(await n(f),["python3","-c",Te,S,v,C],P);if(R.trim()==="SDK_FILE_NOT_FOUND")throw p("File does not exist","file_not_found");if(R.trim()==="SDK_FILE_ERROR")throw p("File operation failed; check permissions and recursive removal","invalid_argument");return R});function _(f,S){let v=J.normalize(S);if(S!==v)return;if(v==="/workspace"||v.startsWith("/workspace/")){let P=h(f);if(!P)return;let C=J.join(P,v.slice(10));return C===P||C.startsWith(`${P}/`)?C:void 0}return v.startsWith("/home/tenki/")?v:void 0}async function k(f,S,v){let P=Promise.resolve().then(S);try{return await U(()=>P,30000)}catch(C){let R=G(C).code;if(f==="write"&&R==="timeout")throw await P.catch(()=>{}),p("File write exceeded its deadline; the native write was drained and may have completed","outcome_unknown");if(R==="auth"||R==="invalid_argument"||R==="unsupported")return v();throw C}}let E=(f,S,v,P)=>u(f,async()=>{let C=await n(f),R=_(C,S);if(!R)return P();try{return await U(()=>v(C,R),30000)}catch(D){if(G(D).code==="file_not_found")throw p("File does not exist","file_not_found");return P()}});return{writeCreatesParents:!0,writeSupportsMode:!0,read:(f,S)=>u(f,async()=>{let v=_(await n(f),S),P=async()=>new Uint8Array(Buffer.from(await x(f,"read",S),"base64"));return v?k("read",async()=>(await n(f)).readFile(v),P):P()}),write:(f,S,v,P)=>u(f,async()=>{let C=_(await n(f),S),R=P?.mode,D=async()=>{await x(f,"write",S,v,R===void 0?"":R.toString(8))},M=async()=>{let A=await n(f);if(R===void 0)return A.writeFile(C??S,v);await A.writeFileStream(C??S,new Blob([new Uint8Array(v)]).stream(),{mode:R,truncate:!0})};if(C)await k("write",M,D);else await D()}),mkdir:async(f,S)=>{if(["/","/workspace"].includes(J.normalize(S)))y(await n(f));try{await x(f,"mkdir",S)}finally{if(["/","/workspace"].includes(J.normalize(S)))y(await n(f))}},remove:async(f,S,v)=>{y(await n(f));try{await x(f,"remove",S,void 0,String(v.recursive))}finally{y(await n(f))}},stat:(f,S)=>E(f,S,async(v,P)=>me(S,await v.fs.stat(P)),async()=>{let v=JSON.parse(await x(f,"stat",S));if(!L(v))throw p("Invalid file metadata");return F(v)}),list:(f,S)=>E(f,S,async(v,P)=>(await v.fs.list(P,{includeHidden:!0})).map((C)=>me(J.join(S,J.basename(C.path)),C)),async()=>{let v=JSON.parse(await x(f,"list",S));if(!Array.isArray(v))throw p("Invalid file listing");return v.map((P)=>{if(!L(P))throw p("Invalid file metadata");return F(P)})})}}var Y="sandbox-sdk-key",te="sandbox-sdk-created-at",Pe=new Set([Y,te,"enable_opencode"]),Ne={small:{cpu:1,memoryMb:1024,diskGb:10},medium:{cpu:2,memoryMb:4096,diskGb:20},large:{cpu:4,memoryMb:8192,diskGb:40}};function _e(n){if(n===void 0)return{};let u=t(n)?Ne[n]:n,h=u?.diskGb??5;if(!u||!Number.isInteger(u.cpu)||u.cpu<1||u.cpu>128||!Number.isInteger(u.memoryMb)||u.memoryMb<128||u.memoryMb>524288||u.memoryMb%2||!Number.isInteger(h)||h<5||h>100)throw p("Size requires 1–128 CPUs, even memoryMb from 128–524288, and 5–100 diskGb","unsupported");return{cpuCores:u.cpu,memoryMb:u.memoryMb,diskSizeGb:h}}function ee(n){let u=Number(n.metadata[te]);if(!Number.isFinite(u)||u<=0||n.metadata["sandbox-sdk"]!=="1")throw p("Session was not created by Sandbox SDK or its metadata is missing","not_found");return{id:n.id,key:n.metadata[Y],labels:Object.fromEntries(Object.entries(n.metadata).filter(([h])=>!Pe.has(h))),createdAt:u,state:n.state==="RUNNING"?"running":["PAUSED","PAUSING","RESUMING"].includes(n.state)?"paused":"stopped"}}var Re=["sh","-c","set -e; mkdir -p /home/tenki/.sandbox-sdk /tmp; exec 9>/home/tenki/.sandbox-sdk/setup.lock; flock -x 9; if [ ! -e /workspace ]; then mkdir -p /home/tenki/workspace; ln -s /home/tenki/workspace /workspace; elif [ ! -L /workspace ] && [ ! -e /home/tenki/workspace ]; then mv /workspace /home/tenki/workspace; ln -s /home/tenki/workspace /workspace; fi; flock -u 9; if [ ! -e /tmp/.sandbox-sdk ]; then ln -s /home/tenki/.sandbox-sdk /tmp/.sandbox-sdk; fi; test -L /tmp/.sandbox-sdk; command -v python3 git tar nohup setsid >/dev/null; readlink -f /workspace"];function pe(n,u){let h,y=new Map,x=new Map,_=new WeakMap,k=new Map;function E(d){let s=k.get(d.id);if(!s)s={active:0,revision:0,overlap:!1,untracked:!1},k.set(d.id,s);return s}function f(d){_.delete(d),E(d).revision++}function S(d,s){let l=E(d);if(!l.active&&!l.untracked&&(s==="/home/tenki"||s.startsWith("/home/tenki/")))_.set(d,s)}async function v(d){f(d);let s=E(d).revision,l=(await H(d,Re)).replace(/\n$/,"");if(s===E(d).revision)S(d,l)}let P=n.requestTimeoutMs??30000,C=n.resumeTimeoutMs??180000,R=(d,s)=>U(d,P,s),D=(d,s,l)=>U(d,s,l);async function M(){return h??=(async()=>{if(!Number.isSafeInteger(P)||P<=0)throw p("requestTimeoutMs must be a positive integer","invalid_argument");if(!Number.isSafeInteger(C)||C<=0||C>900000)throw p("resumeTimeoutMs must be an integer from 1 to 900000","invalid_argument");if(n.waitTimeoutMs!==void 0&&(!Number.isSafeInteger(n.waitTimeoutMs)||n.waitTimeoutMs<=0||n.waitTimeoutMs>900000))throw p("waitTimeoutMs must be an integer from 1 to 900000","invalid_argument");let d=n.apiKey??n.authToken??(process.env.TENKI_AUTH_TOKEN?.trim()||process.env.TENKI_API_KEY?.trim());if(!d)throw p("Tenki API key is missing. Authentication is required. Set TENKI_API_KEY or TENKI_AUTH_TOKEN or pass apiKey.","auth");let{TenkiSandbox:s}=await g("@tenkicloud/sandbox","tenki",u);return new s({authToken:d,baseUrl:n.baseUrl})})()}async function A(d,s,l){try{return await l()}catch(w){throw G(w,s,d,[n.apiKey??n.authToken??""])}}async function q(d){let s=y.get(d);if(s)return s;await K.connect(d);let l=y.get(d);if(!l)throw p("Session is detached","not_found");return l}let K={name:"tenki",keyMode:"best-effort",inlineActivity:!0,processRecordRoot:"/home/tenki/.sandbox-sdk/procs",capabilities:new Set(["pause","snapshot","size","network-policy"]),create:(d)=>A("create",void 0,async()=>{if(d.idleTimeoutMs!==void 0)throw p("Tenki no longer auto-pauses on idle; idleTimeoutMs is unavailable","unsupported");if(d.timeoutMs!==void 0&&(!Number.isSafeInteger(d.timeoutMs)||d.timeoutMs<=0))throw p("timeoutMs must be a positive integer","invalid_argument");if(d.signal?.aborted)throw p("Creation aborted","aborted");let s=_e(d.size),l=r(d.network)?d.network.allow:void 0;if(l?.some((B)=>B.length>253||!/^(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(B)))throw p("Network allow entries must be DNS hostnames or leading wildcard domains","unsupported");let w={...d.labels,"sandbox-sdk":"1",[te]:String(Date.now())};if(delete w[Y],d.key!==void 0)w[Y]=d.key;let N={...s,metadata:w,env:d.env,sticky:!1,maxDurationMs:d.timeoutMs,allowInbound:!0,allowOutbound:d.network!=="none"&&l?.length!==0,allowDomains:l,waitReady:!1};if(d.from)N.snapshotId=d.from;else N.image=n.image;if(n.pauseRetentionMs!==void 0)N.pauseRetentionMs=n.pauseRetentionMs;if(n.volumes!==void 0)N.volumes=n.volumes;if(n.workspaceId!==void 0)N.workspaceId=n.workspaceId;let z=(await M()).create(N),O;try{O=await R(()=>z,d.signal)}catch(B){throw z.then((W)=>R(()=>W.close())).catch(()=>{}),B}y.set(O.id,O);let Z="waitReady";try{let B=n.waitTimeoutMs??180000;if(await ce(O,B,d.signal),Z="validate",d.signal?.aborted)throw p("Creation aborted","aborted");if(s.cpuCores!==void 0&&(O.cpuCores!==s.cpuCores||O.memoryMb!==s.memoryMb||O.diskSizeGb!==s.diskSizeGb))throw p("Tenki returned different resources than requested","unsupported");if(O.outboundEnabled!==N.allowOutbound||l?.length&&(l.some((W)=>!O.egress.allowDomains.includes(W))||O.egress.allowDomains.some((W)=>!l.includes(W))||O.egress.allowCidrs.length))throw p("Tenki did not confirm the requested network policy","unsupported");return ee(O)}catch(B){let W={id:O.id,state:O.state,stage:Z},re;try{await K.destroy(O.id)}catch(we){re=G(we).code}throw de(d.signal?.aborted?p("Creation aborted","aborted"):B,W,[n.apiKey??n.authToken??""],re)}}),list:(d)=>A("list",void 0,async()=>(await R(async()=>(await M()).list(n.workspaceId===void 0?void 0:{workspaceId:n.workspaceId}))).filter((s)=>s.state!=="TERMINATED"&&s.state!=="TERMINATING"&&Object.entries({...d,"sandbox-sdk":"1"}).every(([l,w])=>s.metadata[l]===w)).flatMap((s)=>{try{return[ee(s)]}catch(l){if(G(l).code!=="not_found")throw l;return[]}})),async find(d){let s=(await K.list({[Y]:d}))[0];return s?K.connect(s.id):void 0},connect:(d)=>A("connect",d,async()=>{let s=await R(async()=>(await M()).get(d)),l=ee(s);if(["TERMINATED","TERMINATING"].includes(s.state))throw p("Session has terminated","not_found");if(l.state==="running")await v(s);return y.set(d,s),l}),destroy(d){let s=x.get(d);if(s)return s;let l=A("destroy",d,async()=>{let w=!1;try{await R(async()=>(await q(d)).close()),w=!0}catch(N){if(G(N).code!=="not_found")throw N;w=!0}finally{if(y.delete(d),w)k.delete(d)}}).finally(()=>x.delete(d));return x.set(d,l),l},async close(d){y.delete(d)},exec:(d,s)=>A("exec",d,async()=>{let l=await q(d);f(l);let w=E(l),N=w.revision;if(w.active++,w.active>1)w.overlap=!0;let j;try{return await le(l,s,(z,O)=>{if(!O)w.untracked=!0;j=z})}finally{if(j===void 0)w.untracked=!0;if(w.active--,!w.overlap&&N===w.revision&&j!==void 0)S(l,j);if(!w.active)w.overlap=!1}}),files:fe(q,(d,s)=>A("files",d,s),(d)=>{let s=E(d);return s.active||s.untracked?void 0:_.get(d)},f),previewUrl:(d,s)=>A("preview",d,async()=>{let l=await q(d),w=await R(()=>l.exposePort(s,n.previewTtlMs===void 0?void 0:{ttlMs:n.previewTtlMs}));return{url:w.previewUrl,expiresAt:w.expiresAt?.getTime()}}),pause:(d)=>A("pause",d,async()=>{let s=await q(d),l=n.waitTimeoutMs??180000;await U(()=>s.pause(),l),await D((w)=>s.waitPaused(l,w),l)}),resume:(d)=>A("resume",d,async()=>{let s=await q(d);await U(()=>s.resume(),C);let l=n.waitTimeoutMs??180000;await D((w)=>s.waitResumed(l,w),l),await v(s)}),snapshot:(d,s)=>A("snapshot",d,async()=>{let l=s?.expiresInMs;if(l!==void 0&&(!Number.isSafeInteger(l)||l<0))throw p("expiresInMs must be a non-negative integer","invalid_argument");let w=await M(),N=await R(()=>w.createSnapshot(d,l?{async:!0,expiresAt:new Date(Date.now()+l)}:{async:!0})),j=n.waitTimeoutMs??300000;return{id:(await U((O)=>w.waitSnapshotReady(N.id,j,O),j)).id}}),native(d){let s=y.get(d);if(!s)throw p("Session is detached; connect first","not_found");return f(s),E(s).untracked=!0,s}};return K}function Tt(n={}){return pe(n,()=>import("@tenkicloud/sandbox"))}export{Tt as tenki};
165
+ `,_e=134217728;function pe(n,c){let h=c.modifiedUnixNs/1000000000n,y=c.modifiedUnixNs-h*1000000000n;return{path:n,type:c.isSymlink||c.mode&_e?"symlink":c.isDir?"directory":"file",size:Number(c.size),modifiedAt:(Number(h)+Number(y)*0.000000001)*1000}}function we(n,c,h,y){let x=(f,S,v,E,I="")=>c(f,async()=>{let R=await Z(await n(f),["python3","-c",Ne,S,v,I],E);if(R.trim()==="SDK_FILE_NOT_FOUND")throw p("File does not exist","file_not_found");if(R.trim()==="SDK_FILE_ERROR")throw p("File operation failed; check permissions and recursive removal","invalid_argument");return R});function N(f,S){let v=Q.normalize(S);if(S!==v)return;if(v==="/workspace"||v.startsWith("/workspace/")){let E=h(f);if(!E)return;let I=Q.join(E,v.slice(10));return I===E||I.startsWith(`${E}/`)?I:void 0}return v.startsWith("/home/tenki/")?v:void 0}async function k(f,S,v){let E=Promise.resolve().then(S);try{return await U(()=>E,30000)}catch(I){let R=G(I).code;if(f==="write"&&R==="timeout")throw await E.catch(()=>{}),p("File write exceeded its deadline; the native write was drained and may have completed","outcome_unknown");if(R==="auth"||R==="invalid_argument"||R==="unsupported")return v();throw I}}let T=(f,S,v,E)=>c(f,async()=>{let I=await n(f),R=N(I,S);if(!R)return E();try{return await U(()=>v(I,R),30000)}catch(F){if(G(F).code==="file_not_found")throw p("File does not exist","file_not_found");return E()}});return{writeCreatesParents:!0,writeSupportsMode:!0,listOrder:"directory",read:(f,S)=>c(f,async()=>{let v=N(await n(f),S),E=async()=>new Uint8Array(Buffer.from(await x(f,"read",S),"base64"));return v?k("read",async()=>(await n(f)).readFile(v),E):E()}),write:(f,S,v,E)=>c(f,async()=>{let I=N(await n(f),S),R=E?.mode,F=async()=>{await x(f,"write",S,v,R===void 0?"":R.toString(8))},A=async()=>{let O=await n(f);if(R===void 0)return O.writeFile(I??S,v);await O.writeFileStream(I??S,new Blob([new Uint8Array(v)]).stream(),{mode:R,truncate:!0})};if(I)await k("write",A,F);else await F()}),mkdir:async(f,S)=>{if(["/","/workspace"].includes(Q.normalize(S)))y(await n(f));try{await x(f,"mkdir",S)}finally{if(["/","/workspace"].includes(Q.normalize(S)))y(await n(f))}},remove:async(f,S,v)=>{y(await n(f));try{await x(f,"remove",S,void 0,String(v.recursive))}finally{y(await n(f))}},stat:(f,S)=>T(f,S,async(v,E)=>pe(S,await v.fs.stat(E)),async()=>{let v=JSON.parse(await x(f,"stat",S));if(!H(v))throw p("Invalid file metadata");return V(v)}),list:(f,S)=>T(f,S,async(v,E)=>(await v.fs.list(E,{includeHidden:!0})).map((I)=>pe(Q.join(S,Q.basename(I.path)),I)),async()=>{let v=JSON.parse(await x(f,"list",S));if(!Array.isArray(v))throw p("Invalid file listing");return v.map((E)=>{if(!H(E))throw p("Invalid file metadata");return V(E)})})}}var X="sandbox-sdk-key",oe="sandbox-sdk-created-at",Re=new Set([X,oe,"enable_opencode"]),Ce={small:{cpu:1,memoryMb:1024,diskGb:10},medium:{cpu:2,memoryMb:4096,diskGb:20},large:{cpu:4,memoryMb:8192,diskGb:40}};function Ie(n){if(n===void 0)return{};let c=t(n)?Ce[n]:n,h=c?.diskGb??5;if(!c||!Number.isInteger(c.cpu)||c.cpu<1||c.cpu>128||!Number.isInteger(c.memoryMb)||c.memoryMb<128||c.memoryMb>524288||c.memoryMb%2||!Number.isInteger(h)||h<5||h>100)throw p("Size requires 1–128 CPUs, even memoryMb from 128–524288, and 5–100 diskGb","unsupported");return{cpuCores:c.cpu,memoryMb:c.memoryMb,diskSizeGb:h}}function re(n){let c=Number(n.metadata[oe]);if(!Number.isFinite(c)||c<=0||n.metadata["sandbox-sdk"]!=="1")throw p("Session was not created by Sandbox SDK or its metadata is missing","not_found");return{id:n.id,key:n.metadata[X],labels:Object.fromEntries(Object.entries(n.metadata).filter(([h])=>!Re.has(h))),createdAt:c,state:n.state==="RUNNING"?"running":["PAUSED","PAUSING","RESUMING"].includes(n.state)?"paused":"stopped"}}var Me=["sh","-c","set -e; mkdir -p /home/tenki/.sandbox-sdk /tmp; exec 9>/home/tenki/.sandbox-sdk/setup.lock; flock -x 9; if [ ! -e /workspace ]; then mkdir -p /home/tenki/workspace; ln -s /home/tenki/workspace /workspace; elif [ ! -L /workspace ] && [ ! -e /home/tenki/workspace ]; then mv /workspace /home/tenki/workspace; ln -s /home/tenki/workspace /workspace; fi; flock -u 9; if [ ! -e /tmp/.sandbox-sdk ]; then ln -s /home/tenki/.sandbox-sdk /tmp/.sandbox-sdk; fi; test -L /tmp/.sandbox-sdk; command -v python3 git tar nohup setsid >/dev/null; readlink -f /workspace"];function ke(n,c){let h,y=new Map,x=new Map,N=new WeakMap,k=new Map;function T(d){let s=k.get(d.id);if(!s)s={active:0,revision:0,overlap:!1,untracked:!1},k.set(d.id,s);return s}function f(d){N.delete(d),T(d).revision++}function S(d,s){let u=T(d);if(!u.active&&!u.untracked&&(s==="/home/tenki"||s.startsWith("/home/tenki/")))N.set(d,s)}async function v(d){f(d);let s=T(d).revision,u=(await Z(d,Me)).replace(/\n$/,"");if(s===T(d).revision)S(d,u)}let E=n.requestTimeoutMs??30000,I=n.resumeTimeoutMs??180000,R=(d,s)=>U(d,E,s),F=(d,s,u)=>U(d,s,u);async function A(){return h??=(async()=>{if(!Number.isSafeInteger(E)||E<=0)throw p("requestTimeoutMs must be a positive integer","invalid_argument");if(!Number.isSafeInteger(I)||I<=0||I>900000)throw p("resumeTimeoutMs must be an integer from 1 to 900000","invalid_argument");if(n.waitTimeoutMs!==void 0&&(!Number.isSafeInteger(n.waitTimeoutMs)||n.waitTimeoutMs<=0||n.waitTimeoutMs>900000))throw p("waitTimeoutMs must be an integer from 1 to 900000","invalid_argument");let d=n.apiKey??n.authToken??(process.env.TENKI_AUTH_TOKEN?.trim()||process.env.TENKI_API_KEY?.trim());if(!d)throw p("Tenki API key is missing. Authentication is required. Set TENKI_API_KEY or TENKI_AUTH_TOKEN or pass apiKey.","auth");let{TenkiSandbox:s}=await g("@tenkicloud/sandbox","tenki",c);return new s({authToken:d,baseUrl:n.baseUrl})})()}async function O(d,s,u){try{return await u()}catch(w){throw G(w,s,d,[n.apiKey??n.authToken??""])}}async function q(d){let s=y.get(d);if(s)return s;await K.connect(d);let u=y.get(d);if(!u)throw p("Session is detached","not_found");return u}let K={name:"tenki",keyMode:"best-effort",inlineActivity:!0,processRecordRoot:"/home/tenki/.sandbox-sdk/procs",capabilities:new Set(["pause","snapshot","size","network-policy"]),create:(d)=>O("create",void 0,async()=>{if(d.idleTimeoutMs!==void 0)throw p("Tenki no longer auto-pauses on idle; idleTimeoutMs is unavailable","unsupported");if(d.timeoutMs!==void 0&&(!Number.isSafeInteger(d.timeoutMs)||d.timeoutMs<=0))throw p("timeoutMs must be a positive integer","invalid_argument");if(d.signal?.aborted)throw p("Creation aborted","aborted");let s=Ie(d.size),u=r(d.network)?d.network.allow:void 0;if(u?.some((B)=>B.length>253||!/^(\*\.)?(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(B)))throw p("Network allow entries must be DNS hostnames or leading wildcard domains","unsupported");let w={...d.labels,"sandbox-sdk":"1",[oe]:String(Date.now())};if(delete w[X],d.key!==void 0)w[X]=d.key;let P={...s,metadata:w,env:d.env,sticky:!1,maxDurationMs:d.timeoutMs,allowInbound:!0,allowOutbound:d.network!=="none"&&u?.length!==0,allowDomains:u,waitReady:!1};if(d.from)P.snapshotId=d.from;else P.image=n.image;if(n.pauseRetentionMs!==void 0)P.pauseRetentionMs=n.pauseRetentionMs;if(n.volumes!==void 0)P.volumes=n.volumes;if(n.workspaceId!==void 0)P.workspaceId=n.workspaceId;let z=(await A()).create(P),D;try{D=await R(()=>z,d.signal)}catch(B){throw z.then((J)=>R(()=>J.close())).catch(()=>{}),B}y.set(D.id,D);let W="waitReady";try{let B=n.waitTimeoutMs??180000;if(await le(D,B,d.signal),W="validate",d.signal?.aborted)throw p("Creation aborted","aborted");if(s.cpuCores!==void 0&&(D.cpuCores!==s.cpuCores||D.memoryMb!==s.memoryMb||D.diskSizeGb!==s.diskSizeGb))throw p("Tenki returned different resources than requested","unsupported");if(D.outboundEnabled!==P.allowOutbound||u?.length&&(u.some((J)=>!D.egress.allowDomains.includes(J))||D.egress.allowDomains.some((J)=>!u.includes(J))||D.egress.allowCidrs.length))throw p("Tenki did not confirm the requested network policy","unsupported");return re(D)}catch(B){let J={id:D.id,state:D.state,stage:W},ne;try{await K.destroy(D.id)}catch(he){ne=G(he).code}throw ue(d.signal?.aborted?p("Creation aborted","aborted"):B,J,[n.apiKey??n.authToken??""],ne)}}),list:(d)=>O("list",void 0,async()=>(await R(async()=>(await A()).list(n.workspaceId===void 0?void 0:{workspaceId:n.workspaceId}))).filter((s)=>s.state!=="TERMINATED"&&s.state!=="TERMINATING"&&Object.entries({...d,"sandbox-sdk":"1"}).every(([u,w])=>s.metadata[u]===w)).flatMap((s)=>{try{return[re(s)]}catch(u){if(G(u).code!=="not_found")throw u;return[]}})),async find(d){let s=(await K.list({[X]:d}))[0];return s?K.connect(s.id):void 0},connect:(d)=>O("connect",d,async()=>{let s=await R(async()=>(await A()).get(d)),u=re(s);if(["TERMINATED","TERMINATING"].includes(s.state))throw p("Session has terminated","not_found");if(u.state==="running")await v(s);return y.set(d,s),u}),destroy(d){let s=x.get(d);if(s)return s;let u=O("destroy",d,async()=>{let w=!1;try{await R(async()=>(await q(d)).close()),w=!0}catch(P){if(G(P).code!=="not_found")throw P;w=!0}finally{if(y.delete(d),w)k.delete(d)}}).finally(()=>x.delete(d));return x.set(d,u),u},async close(d){y.delete(d)},exec:(d,s)=>O("exec",d,async()=>{let u=await q(d);f(u);let w=T(u),P=w.revision;if(w.active++,w.active>1)w.overlap=!0;let L;try{return await fe(u,s,(z,D)=>{if(!D)w.untracked=!0;L=z})}finally{if(L===void 0)w.untracked=!0;if(w.active--,!w.overlap&&P===w.revision&&L!==void 0)S(u,L);if(!w.active)w.overlap=!1}}),files:we(q,(d,s)=>O("files",d,s),(d)=>{let s=T(d);return s.active||s.untracked?void 0:N.get(d)},f),previewUrl:(d,s)=>O("preview",d,async()=>{let u=await q(d),w=await R(()=>u.exposePort(s,n.previewTtlMs===void 0?void 0:{ttlMs:n.previewTtlMs}));return{url:w.previewUrl,expiresAt:w.expiresAt?.getTime()}}),pause:(d)=>O("pause",d,async()=>{let s=await q(d),u=n.waitTimeoutMs??180000;await U(()=>s.pause(),u),await F((w)=>s.waitPaused(u,w),u)}),resume:(d)=>O("resume",d,async()=>{let s=await q(d);await U(()=>s.resume(),I);let u=n.waitTimeoutMs??180000;await F((w)=>s.waitResumed(u,w),u),await v(s)}),snapshot:(d,s)=>O("snapshot",d,async()=>{let u=s?.expiresInMs;if(u!==void 0&&(!Number.isSafeInteger(u)||u<0))throw p("expiresInMs must be a non-negative integer","invalid_argument");let w=await A(),P=await R(()=>w.createSnapshot(d,u?{async:!0,expiresAt:new Date(Date.now()+u)}:{async:!0})),L=n.waitTimeoutMs??300000;return{id:(await U((D)=>w.waitSnapshotReady(P.id,L,D),L)).id}}),native(d){let s=y.get(d);if(!s)throw p("Session is detached; connect first","not_found");return f(s),T(s).untracked=!0,s}};return K}function Nt(n={}){return ke(n,()=>import("@tenkicloud/sandbox"))}export{Nt as tenki};