@opencoredev/sandbox-sdk 1.0.2 → 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 (59) hide show
  1. package/CHANGELOG.md +6 -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-bfzdkjjw.js → chunk-g0vk7g1k.js} +2 -2
  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 +12 -12
  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-6a3wkj84.js +0 -2
  52. package/dist/chunk-8wq767xb.js +0 -17
  53. package/dist/chunk-9w9rddra.js +0 -2
  54. package/dist/chunk-ckym4cht.js +0 -23
  55. package/dist/chunk-hgrwyjrb.js +0 -2
  56. package/dist/chunk-kk1hw8wa.js +0 -1
  57. package/dist/chunk-vz47a139.js +0 -5
  58. package/dist/chunk-x681p5d2.js +0 -68
  59. package/dist/chunk-xgxfy2n8.js +0 -4
@@ -1,4 +1,4 @@
1
- import{l}from"../../chunk-23tjmd39.js";import{b}from"../../chunk-x681p5d2.js";import{N}from"../../chunk-q5vqajhg.js";import{m}from"../../chunk-bd481sb7.js";import{g}from"../../chunk-k60b4r27.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,e,S,w,i,a}from"../../chunk-xgxfy2n8.js";import{posix as ae}from"node:path";var ue=`import os,select,_signal as signal,sys,time,fcntl
1
+ import{u}from"../../chunk-6nf686jb.js";import{b}from"../../chunk-6bemkxcx.js";import{D}from"../../chunk-19gteae8.js";import{m}from"../../chunk-drgkmewv.js";import{g}from"../../chunk-3zd78ha4.js";import{n}from"../../chunk-2ts3evzh.js";import{F}from"../../chunk-305dymgq.js";import{t,o,r,e,S,h,i,a}from"../../chunk-n7x9ha44.js";import{posix as be}from"node:path";var _e=`import os,select,_signal as signal,sys,time,fcntl
2
2
  ${b}
3
3
  command,directory,cwd,limit=sys.argv[1:]
4
4
  os.makedirs(directory,mode=0o700,exist_ok=True)
@@ -50,7 +50,7 @@ finally:
50
50
  try: os.unlink(directory+'/'+name)
51
51
  except FileNotFoundError: pass
52
52
  os.rmdir(directory)
53
- `,fe=`import os,signal,sys,fcntl,time
53
+ `,Pe=`import os,signal,sys,fcntl,time
54
54
  p=sys.argv[1]
55
55
  pid=None
56
56
  for attempt in range(3):
@@ -73,13 +73,13 @@ if pid:
73
73
  except ProcessLookupError: break
74
74
  if time.monotonic()>=end: sys.exit(1)
75
75
  time.sleep(.01)
76
- `;async function te(d,f,x){if(f.signal?.aborted)return{exitCode:null,timedOut:!0};let C=`/tmp/.sandbox-sdk/exec/sdk-${crypto.randomUUID()}`,v=Object.entries(l).filter(([A])=>(A in f.env)).map(([A,s])=>n(`${A}=${s}`)).join(" "),p=`${x?`${x} && `:""}env ${v} python3 -S -u -c ${n(ue)} ${n(f.command)} ${n(C)} ${n(f.cwd)} ${n(String(f.timeoutMs/1000))}`;if(Buffer.byteLength(p)>=98304)return;let B=Date.now()+f.timeoutMs,P=!1,O=!1,I=!1,D=()=>{},j=new Promise((A)=>{D=()=>A(void 0)}),F,_,E=()=>new e("Command output is incomplete. Upstash did not confirm exact output and exit. Inspect the box before retrying.",{code:"outcome_unknown",provider:"upstash",sandboxId:d.id}),L=()=>{if(P=!0,D(),O)return;F??=d.exec.command(`python3 -c ${n(fe)} ${n(C)}`).then((A)=>{if(A.exitCode!==0)throw E()}).catch((A)=>{_=A})},T={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},z=(A)=>{let s=/^(O|E):([0-9a-f]*)$/.exec(A);if(!s||A.length>8194||Buffer.from(s[2]??"","hex").toString("hex")!==s[2])throw E();let c=s[1]==="O"?"stdout":"stderr",u=T[c].decode(Buffer.from(s[2]??"","hex"),{stream:!0});if(u)f.onChunk({stream:c,text:u})};f.signal?.addEventListener("abort",L,{once:!0});let H=setTimeout(L,Math.max(0,B-Date.now()));try{let A=await d.exec.command(p);if(A.exitCode===127&&A.stderr.includes("python3")&&!P)return;let s=A.stdout.trimEnd().split(`
77
- `),c=/^R:(\d+):([01]):([01])$/.exec(s.pop()??"");if(A.exitCode!==0||!c)throw E();O=!0,I=c[3]==="1";for(let y of s)if(y)z(y);if(I&&!P){let y=0,h="";while(!P){let k=await Promise.race([d.files.read(`${C}/output`,{offset:y,length:65536,encoding:"base64"}),j]);if(k===void 0)break;let U=Buffer.from(k,"base64");if(P)break;y+=U.length,h+=U.toString("ascii");let M;while((M=h.indexOf(`
78
- `))>=0)z(h.slice(0,M)),h=h.slice(M+1);if(h.length>8194)throw E();if(U.length<65536){if(h)throw E();break}}}for(let y of["stdout","stderr"]){let h=T[y].decode();if(h)f.onChunk({stream:y,text:h})}if(await F,_!==void 0)throw E();let u=c[2]==="1"||P;return{exitCode:u?null:Number(c[1]),timedOut:u}}catch(A){if(!O){if(L(),await F,_!==void 0)throw E()}throw A}finally{if(clearTimeout(H),f.signal?.removeEventListener("abort",L),await F,O&&(F||I))await d.files.remove(C,{recursive:!0}).catch(()=>{})}}var me=(d,f)=>w(d,f)??"Native request failed";function K(d,f,x=!1,C=x?"files":"request",v=(p)=>{let B=new S;return B.add([process.env.UPSTASH_BOX_API_KEY??""]),B.text(p)}){if(d instanceof e)return d;let p=m(d).statusCode,B="provider";if(p===401||p===403)B="auth";else if(p===404)B=x?"file_not_found":"not_found";else if(p===410)B="not_found";else if(p===429||p===402)B="quota";else if(p===408||p===504)B="timeout";else if(p!==void 0&&p>=500)B="unavailable";else if(p===400||p===422)B="invalid_argument";let P=`${C}${p===void 0?"":` HTTP ${p}`}: ${me(d,v)}`;return new e(`Upstash Box ${C} failed${p===void 0?"":` (HTTP ${p})`}: ${a(B,i(d,{code:B,status:p===void 0?void 0:String(p),redact:v}).detail)}. Check credentials, limits, and sandbox state.`,{code:B,provider:"upstash",sandboxId:f,retryable:["quota","timeout","unavailable"].includes(B),cause:P})}function q(d){throw new e(`${d}. Upstash Box cannot enforce this request. Choose supported settings.`,{code:"unsupported",provider:"upstash"})}import{StringDecoder as se}from"node:string_decoder";async function re(d,f,x,C){if(f.signal?.aborted)return{exitCode:null,timedOut:!0};let v,p=!1,B=()=>{p=!0,v?.kill("KILL")},P=setTimeout(B,f.timeoutMs);f.signal?.addEventListener("abort",B,{once:!0});let O=`sdk-prepared-${crypto.randomUUID()}
79
- `,I="",D=x!==void 0,j=new se("utf8"),F=new se("utf8");try{if(v=await d.exec.session({argv:x?["sh","-c",`${x} && printf '%s
80
- ' '${O.trimEnd()}' && cd "$1" && exec sh -c "$2"`,"sh",f.cwd,f.command]:["sh","-c",f.command],cwd:x?"/":f.cwd,env:Object.entries(f.env).map(([T,z])=>`${T}=${z}`),onStdout:(T)=>{let z=j.write(Buffer.from(T));if(D){I+=z;let H=I.indexOf(O);if(H>=0)z=I.slice(0,H)+I.slice(H+O.length),I="",D=!1,C?.();else{let A=Math.max(0,I.length-O.length+1);z=I.slice(0,A),I=I.slice(A)}}if(z)f.onChunk({stream:"stdout",text:z})},onStderr:(T)=>{let z=F.write(Buffer.from(T));if(z)f.onChunk({stream:"stderr",text:z})}}),p||f.signal?.aborted)B();else{if(f.stdin!==void 0)v.write(f.stdin);v.endStdin()}let _=await v.wait();if(_<0&&!p)throw new e("Command session disconnected. Upstash could not confirm an exit code. Inspect the box before retrying.",{code:"unavailable",provider:"upstash",sandboxId:d.id});let E=I+j.end();if(E)f.onChunk({stream:"stdout",text:E});let L=F.end();if(L)f.onChunk({stream:"stderr",text:L});return{exitCode:p?null:_,timedOut:p}}catch(_){throw v?.close(),_}finally{clearTimeout(P),f.signal?.removeEventListener("abort",B),v?.close()}}async function oe(d,f,x,C){let v=`/tmp/.sandbox-sdk/upstash-runs/${crypto.randomUUID()}`,p=`${v}/env`,B=`${C?`${C} && `:""}chmod 600 ${n(p)} && . ${n(p)} && /bin/rm -f -- ${n(p)} || exit 1; echo $$ > ${n(`${v}/pid`)}; cd ${n(f.cwd)} || exit 1; sh -c ${n(f.command)}; code=$?; printf '%s' "$code" > ${n(`${v}/exit`)}; exit "$code"`,P;try{if((await d.exec.command(`umask 077; mkdir -p /tmp/.sandbox-sdk/upstash-runs && mkdir ${n(v)} && : > ${n(p)}`)).exitCode!==0)throw Error("Durable process environment setup failed");if(await d.files.write({path:p,content:Object.entries(f.env).map(([L,T])=>`export ${n(`${L}=${T}`)}`).join(`
76
+ `;async function fe(d,f,y){if(f.signal?.aborted)return{exitCode:null,timedOut:!0};let E=`/tmp/.sandbox-sdk/exec/sdk-${crypto.randomUUID()}`,x=Object.entries(u).filter(([M])=>(M in f.env)).map(([M,q])=>n(`${M}=${q}`)).join(" "),l=`${y?`${y} && `:""}env ${x} python3 -S -u -c ${n(_e)} ${n(f.command)} ${n(E)} ${n(f.cwd)} ${n(String(f.timeoutMs/1000))}`;if(Buffer.byteLength(l)>=98304)return;let B=Date.now()+f.timeoutMs,C=!1,O=!1,I=!1,R=()=>{},H=new Promise((M)=>{R=()=>M(void 0)}),X,P,L=()=>new e("Command output is incomplete. Upstash did not confirm exact output and exit. Inspect the box before retrying.",{code:"outcome_unknown",provider:"upstash",sandboxId:d.id}),T=()=>{if(C=!0,R(),O)return;X??=d.exec.command(`python3 -c ${n(Pe)} ${n(E)}`).then((M)=>{if(M.exitCode!==0)throw L()}).catch((M)=>{P=M})},U={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},N=(M)=>{let q=/^(O|E):([0-9a-f]*)$/.exec(M);if(!q||M.length>8194||Buffer.from(q[2]??"","hex").toString("hex")!==q[2])throw L();let s=q[1]==="O"?"stdout":"stderr",c=U[s].decode(Buffer.from(q[2]??"","hex"),{stream:!0});if(c)f.onChunk({stream:s,text:c})};f.signal?.addEventListener("abort",T,{once:!0});let W=setTimeout(T,Math.max(0,B-Date.now()));try{let M=await d.exec.command(l);if(M.exitCode===127&&M.stderr.includes("python3")&&!C)return;let q=M.stdout.trimEnd().split(`
77
+ `),s=/^R:(\d+):([01]):([01])$/.exec(q.pop()??"");if(M.exitCode!==0||!s)throw L();O=!0,I=s[3]==="1";for(let p of q)if(p)N(p);if(I&&!C){let p=0,w="";while(!C){let v=await Promise.race([d.files.read(`${E}/output`,{offset:p,length:65536,encoding:"base64"}),H]);if(v===void 0)break;let k=Buffer.from(v,"base64");if(C)break;p+=k.length,w+=k.toString("ascii");let _;while((_=w.indexOf(`
78
+ `))>=0)N(w.slice(0,_)),w=w.slice(_+1);if(w.length>8194)throw L();if(k.length<65536){if(w)throw L();break}}}for(let p of["stdout","stderr"]){let w=U[p].decode();if(w)f.onChunk({stream:p,text:w})}if(await X,P!==void 0)throw L();let c=s[2]==="1"||C;return{exitCode:c?null:Number(s[1]),timedOut:c}}catch(M){if(!O){if(T(),await X,P!==void 0)throw L()}throw M}finally{if(clearTimeout(W),f.signal?.removeEventListener("abort",T),await X,O&&(X||I))await d.files.remove(E,{recursive:!0}).catch(()=>{})}}var Ue=(d,f)=>h(d,f)??"Native request failed";function K(d,f,y=!1,E=y?"files":"request",x=(l)=>{let B=new S;return B.add([process.env.UPSTASH_BOX_API_KEY??""]),B.text(l)}){if(d instanceof e)return d;let l=m(d).statusCode,B="provider";if(l===401||l===403)B="auth";else if(l===404)B=y?"file_not_found":"not_found";else if(l===410)B="not_found";else if(l===429||l===402)B="quota";else if(l===408||l===504)B="timeout";else if(l!==void 0&&l>=500)B="unavailable";else if(l===400||l===422)B="invalid_argument";let C=`${E}${l===void 0?"":` HTTP ${l}`}: ${Ue(d,x)}`;return new e(`Upstash Box ${E} failed${l===void 0?"":` (HTTP ${l})`}: ${a(B,i(d,{code:B,status:l===void 0?void 0:String(l),redact:x}).detail)}. Check credentials, limits, and sandbox state.`,{code:B,provider:"upstash",sandboxId:f,retryable:["quota","timeout","unavailable"].includes(B),cause:C})}function Q(d){throw new e(`${d}. Upstash Box cannot enforce this request. Choose supported settings.`,{code:"unsupported",provider:"upstash"})}import{StringDecoder as me}from"node:string_decoder";async function he(d,f,y,E){if(f.signal?.aborted)return{exitCode:null,timedOut:!0};let x,l=!1,B=()=>{l=!0,x?.kill("KILL")},C=setTimeout(B,f.timeoutMs);f.signal?.addEventListener("abort",B,{once:!0});let O=`sdk-prepared-${crypto.randomUUID()}
79
+ `,I="",R=y!==void 0,H=new me("utf8"),X=new me("utf8");try{if(x=await d.exec.session({argv:y?["sh","-c",`${y} && printf '%s
80
+ ' '${O.trimEnd()}' && cd "$1" && exec sh -c "$2"`,"sh",f.cwd,f.command]:["sh","-c",f.command],cwd:y?"/":f.cwd,env:Object.entries(f.env).map(([U,N])=>`${U}=${N}`),onStdout:(U)=>{let N=H.write(Buffer.from(U));if(R){I+=N;let W=I.indexOf(O);if(W>=0)N=I.slice(0,W)+I.slice(W+O.length),I="",R=!1,E?.();else{let M=Math.max(0,I.length-O.length+1);N=I.slice(0,M),I=I.slice(M)}}if(N)f.onChunk({stream:"stdout",text:N})},onStderr:(U)=>{let N=X.write(Buffer.from(U));if(N)f.onChunk({stream:"stderr",text:N})}}),l||f.signal?.aborted)B();else{if(f.stdin!==void 0)x.write(f.stdin);x.endStdin()}let P=await x.wait();if(P<0&&!l)throw new e("Command session disconnected. Upstash could not confirm an exit code. Inspect the box before retrying.",{code:"unavailable",provider:"upstash",sandboxId:d.id});let L=I+H.end();if(L)f.onChunk({stream:"stdout",text:L});let T=X.end();if(T)f.onChunk({stream:"stderr",text:T});return{exitCode:l?null:P,timedOut:l}}catch(P){throw x?.close(),P}finally{clearTimeout(C),f.signal?.removeEventListener("abort",B),x?.close()}}async function we(d,f,y,E){let x=`/tmp/.sandbox-sdk/upstash-runs/${crypto.randomUUID()}`,l=`${x}/env`,B=`${E?`${E} && `:""}chmod 600 ${n(l)} && . ${n(l)} && /bin/rm -f -- ${n(l)} || exit 1; echo $$ > ${n(`${x}/pid`)}; cd ${n(f.cwd)} || exit 1; sh -c ${n(f.command)}; code=$?; printf '%s' "$code" > ${n(`${x}/exit`)}; exit "$code"`,C;try{if((await d.exec.command(`umask 077; mkdir -p /tmp/.sandbox-sdk/upstash-runs && mkdir ${n(x)} && : > ${n(l)}`)).exitCode!==0)throw Error("Durable process environment setup failed");if(await d.files.write({path:l,content:Object.entries(f.env).map(([T,U])=>`export ${n(`${T}=${U}`)}`).join(`
81
81
  `)+`
82
- `}),(await d.exec.command(`nohup setsid sh -c ${n(B)} > /dev/null 2>&1 < /dev/null &`)).exitCode!==0)throw Error("Durable process launch failed");for(let L=0;L<200;L++){try{let T=Number(await d.files.read(`${v}/pid`));if(Number.isSafeInteger(T)&&T>1){P=T;break}}catch(T){if(K(T,d.id,!0).code!=="file_not_found")throw T}await new Promise((T)=>setTimeout(T,25))}if(P===void 0)throw Error("Durable process PID missing")}catch(_){throw await d.files.remove(p).catch(()=>{}),await x(v),_}let O=P,I=!1,D=(async()=>{while(!0){if(I)await new Promise(()=>{});try{let _=Number(await d.files.read(`${v}/exit`));if(!Number.isInteger(_)||_<0||_>255)throw Error("Invalid durable exit code");return{exitCode:_,signal:null}}catch(_){let E=K(_,d.id,!0).code;if(E!=="file_not_found"&&E!=="unavailable"&&E!=="quota"&&E!=="timeout")throw _}await new Promise((_)=>setTimeout(_,50))}})();D.catch(()=>{});let j=async(_)=>{if((await d.exec.command(`kill -${_} -${O} 2>/dev/null || ! kill -0 -${O} 2>/dev/null`)).exitCode!==0)throw new e("Process termination is unconfirmed. The remote process group could not be signalled. Destroy the box before retrying.",{code:"outcome_unknown",provider:"upstash",sandboxId:d.id})},F=!1;return{pid:O,wait:()=>D,detach(){I=!0},async stop({graceMs:_}){if(F)return;await j("TERM"),await new Promise((E)=>setTimeout(E,_)),await j("KILL");try{await d.files.read(`${v}/exit`)}catch(E){if(K(E,d.id,!0).code!=="file_not_found")throw E;await d.files.write({path:`${v}/exit`,content:"137"})}await D,F=!0}}}import{posix as he}from"node:path";var Z=4194304,we="import os,sys; p=sys.argv[1]; os.makedirs(os.path.dirname(p),exist_ok=True); f=open(p,'wb'); f.write(sys.stdin.buffer.read()); f.close()",ye=`import os,sys,shutil,tempfile,stat
82
+ `}),(await d.exec.command(`nohup setsid sh -c ${n(B)} > /dev/null 2>&1 < /dev/null &`)).exitCode!==0)throw Error("Durable process launch failed");for(let T=0;T<200;T++){try{let U=Number(await d.files.read(`${x}/pid`));if(Number.isSafeInteger(U)&&U>1){C=U;break}}catch(U){if(K(U,d.id,!0).code!=="file_not_found")throw U}await new Promise((U)=>setTimeout(U,25))}if(C===void 0)throw Error("Durable process PID missing")}catch(P){throw await d.files.remove(l).catch(()=>{}),await y(x),P}let O=C,I=!1,R=(async()=>{while(!0){if(I)await new Promise(()=>{});try{let P=Number(await d.files.read(`${x}/exit`));if(!Number.isInteger(P)||P<0||P>255)throw Error("Invalid durable exit code");return{exitCode:P,signal:null}}catch(P){let L=K(P,d.id,!0).code;if(L!=="file_not_found"&&L!=="unavailable"&&L!=="quota"&&L!=="timeout")throw P}await new Promise((P)=>setTimeout(P,50))}})();R.catch(()=>{});let H=async(P)=>{if((await d.exec.command(`kill -${P} -${O} 2>/dev/null || ! kill -0 -${O} 2>/dev/null`)).exitCode!==0)throw new e("Process termination is unconfirmed. The remote process group could not be signalled. Destroy the box before retrying.",{code:"outcome_unknown",provider:"upstash",sandboxId:d.id})},X=!1;return{pid:O,wait:()=>R,detach(){I=!0},async stop({graceMs:P}){if(X)return;await H("TERM"),await new Promise((L)=>setTimeout(L,P)),await H("KILL");try{await d.files.read(`${x}/exit`)}catch(L){if(K(L,d.id,!0).code!=="file_not_found")throw L;await d.files.write({path:`${x}/exit`,content:"137"})}await R,X=!0}}}import{posix as Se}from"node:path";var se=4194304,Ce="import os,sys; p=sys.argv[1]; os.makedirs(os.path.dirname(p),exist_ok=True); f=open(p,'wb'); f.write(sys.stdin.buffer.read()); f.close()",Ie=`import os,sys,shutil,tempfile,stat
83
83
  p,d,n=sys.argv[1:]; p=os.path.realpath(p); tmp=None
84
84
  try:
85
85
  os.makedirs(os.path.dirname(p),exist_ok=True)
@@ -92,7 +92,7 @@ try:
92
92
  os.replace(tmp,p); tmp=None
93
93
  finally:
94
94
  if tmp is not None: os.unlink(tmp)
95
- shutil.rmtree(d,ignore_errors=True)`;async function V(d,f,x){if(!x)try{return new Uint8Array(Buffer.from(await d.files.read(f,{encoding:"base64"}),"base64"))}catch(B){if(["auth","file_not_found","not_found","quota"].includes(K(B,d.id,!0).code))throw B}let C=[],v=x?.offset??0,p=x?.length??1/0;while(p>0){let B=Math.min(Z,p),P=Buffer.from(await d.files.read(f,{offset:v,length:B,encoding:"base64"}),"base64");if(C.push(P),v+=P.length,p-=P.length,P.length<B)break}return new Uint8Array(Buffer.concat(C))}async function ne(d,f,x,C){if(C){let O=await d.exec.session({argv:["sh","-c",`${C} && exec python3 -c "$1" "$2"`,"sh",we,f],cwd:"/"});try{if(O.write(x),O.endStdin(),await O.wait()!==0)throw new e("File write failed. Check workspace permissions and Python availability.",{code:"provider",provider:"upstash",sandboxId:d.id});return}finally{O.close()}}let v=async(O,I)=>{let D={path:O,content:Buffer.from(I).toString("base64"),encoding:"base64"};try{await d.files.write(D)}catch(j){if(K(j,d.id,!0).code!=="file_not_found")throw j;await d.files.mkdir(he.dirname(O),{parents:!0}),await d.files.write(D)}};if(x.length<=Z)return v(f,x);let p=`/tmp/.sandbox-sdk/upload-${crypto.randomUUID()}`;if((await d.exec.command(`umask 077; mkdir -p /tmp/.sandbox-sdk && mkdir ${n(p)}`)).exitCode!==0)throw new e("Private upload staging could not be created. Check guest permissions.",{code:"provider",provider:"upstash",sandboxId:d.id});let P=!1;try{let O=0;for(let D=0;D<x.length;D+=Z)await v(`${p}/${O++}`,x.subarray(D,D+Z));P=!0;let I;try{I=await d.exec.command(`python3 -c ${n(ye)} ${n(f)} ${n(p)} ${O}`)}catch{throw new e(`Large upload outcome is unknown. Inspect ${p} and the destination before retrying; destroy the sandbox to remove any retained staging.`,{code:"outcome_unknown",provider:"upstash",sandboxId:d.id})}if(I.exitCode!==0)throw await d.files.remove(p,{recursive:!0}).catch(()=>{}),new e("Large file assembly failed. Check guest Python and destination permissions.",{code:"provider",provider:"upstash",sandboxId:d.id})}finally{if(!P)await d.files.remove(p,{recursive:!0})}}var xe=`import os,sys,json,stat
95
+ shutil.rmtree(d,ignore_errors=True)`;async function le(d,f,y){if(!y)try{return new Uint8Array(Buffer.from(await d.files.read(f,{encoding:"base64"}),"base64"))}catch(B){if(["auth","file_not_found","not_found","quota"].includes(K(B,d.id,!0).code))throw B}let E=[],x=y?.offset??0,l=y?.length??1/0;while(l>0){let B=Math.min(se,l),C=Buffer.from(await d.files.read(f,{offset:x,length:B,encoding:"base64"}),"base64");if(E.push(C),x+=C.length,l-=C.length,C.length<B)break}return new Uint8Array(Buffer.concat(E))}async function ye(d,f,y,E){if(E){let O=await d.exec.session({argv:["sh","-c",`${E} && exec python3 -c "$1" "$2"`,"sh",Ce,f],cwd:"/"});try{if(O.write(y),O.endStdin(),await O.wait()!==0)throw new e("File write failed. Check workspace permissions and Python availability.",{code:"provider",provider:"upstash",sandboxId:d.id});return}finally{O.close()}}let x=async(O,I)=>{let R={path:O,content:Buffer.from(I).toString("base64"),encoding:"base64"};try{await d.files.write(R)}catch(H){if(K(H,d.id,!0).code!=="file_not_found")throw H;await d.files.mkdir(Se.dirname(O),{parents:!0}),await d.files.write(R)}};if(y.length<=se)return x(f,y);let l=`/tmp/.sandbox-sdk/upload-${crypto.randomUUID()}`;if((await d.exec.command(`umask 077; mkdir -p /tmp/.sandbox-sdk && mkdir ${n(l)}`)).exitCode!==0)throw new e("Private upload staging could not be created. Check guest permissions.",{code:"provider",provider:"upstash",sandboxId:d.id});let C=!1;try{let O=0;for(let R=0;R<y.length;R+=se)await x(`${l}/${O++}`,y.subarray(R,R+se));C=!0;let I;try{I=await d.exec.command(`python3 -c ${n(Ie)} ${n(f)} ${n(l)} ${O}`)}catch{throw new e(`Large upload outcome is unknown. Inspect ${l} and the destination before retrying; destroy the sandbox to remove any retained staging.`,{code:"outcome_unknown",provider:"upstash",sandboxId:d.id})}if(I.exitCode!==0)throw await d.files.remove(l,{recursive:!0}).catch(()=>{}),new e("Large file assembly failed. Check guest Python and destination permissions.",{code:"provider",provider:"upstash",sandboxId:d.id})}finally{if(!C)await d.files.remove(l,{recursive:!0})}}var Oe=`import os,sys,json,stat
96
96
  p=sys.argv[1]
97
97
  try: names=os.listdir(p)
98
98
  except (FileNotFoundError,NotADirectoryError): names=[]
@@ -102,4 +102,4 @@ for n in names:
102
102
  except FileNotFoundError: print('SDK_FILE_NOT_FOUND'); sys.exit(0)
103
103
  m=s.st_mode
104
104
  out.append([n.encode('utf-8','surrogateescape').decode('utf-8','replace'),'symlink' if stat.S_ISLNK(m) else 'directory' if stat.S_ISDIR(m) else 'file' if stat.S_ISREG(m) else 'other',s.st_size,s.st_mtime_ns//1000000])
105
- print(json.dumps(out))`;function ge(d){return Array.isArray(d)&&d.length===4&&t(d[0])&&(d[1]==="file"||d[1]==="directory"||d[1]==="symlink"||d[1]==="other")&&o(d[2])&&o(d[3])}async function ie(d,f,x){if(!f.startsWith("/"))return;let C=await d.exec.command(`${x?`${x} && `:""}python3 -c ${n(xe)} ${n(f)}`);if(C.exitCode!==0)return;let v=C.stdout.trim();if(v==="SDK_FILE_NOT_FOUND")throw Object.assign(Error("Directory entry vanished during listing"),{statusCode:404});try{let p=JSON.parse(v);if(!Array.isArray(p)||!p.every(ge))return;return p.map(([B,P,O,I])=>({name:B,type:P,size:O,modifiedAt:I}))}catch{return}}var de=259200,Y="sandbox-sdk",G="SANDBOX_SDK_UPSTASH_METADATA",X='if ! mkdir -p /workspace 2>/dev/null || [ ! -w /workspace ]; then sudo -n install -d -o "$(id -u)" -g "$(id -g)" -m 755 /workspace; fi && test -w /workspace',be="/tmp/.sandbox-sdk/upstash.json",ee='for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/upstash-runs; true';function ve(d){return r(d)&&"snapshots"in d&&(d.snapshots===null||Array.isArray(d.snapshots))}function ke(d){let f=(p)=>{throw new e(`Invalid SDK ${p}`,{code:"not_found",provider:"upstash"})},{key:x,labels:C,version:v}=N(d,f);if(v!==1||x===null)f("metadata");return x===void 0?{version:1,labels:C}:{version:1,labels:C,key:x}}function ce(d,f){return{id:d.id,key:f.key,labels:f.labels,createdAt:d.created_at*1000,state:d.status==="paused"?"paused":d.status==="running"||d.status==="idle"?"running":"stopped"}}var J=(d)=>("ephemeral"in d)&&d.ephemeral===!0;function le(d,f){if(f.type==="other")q("Special filesystem entries are not supported");return{path:d,type:f.type,size:f.size,modifiedAt:Date.parse(f.mod_time)}}function Be(d){if(!r(d))return{mode:d==="none"?"deny-all":"allow-all"};if(!d.allow.length)return{mode:"deny-all"};if(d.allow.some((f)=>f.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(f)))q("Network allow entries must be DNS hostnames");return{mode:"custom",allowedDomains:d.allow}}function pe(d,f){let x=d.ephemeral?d.ttlSeconds??3600:void 0;if(x!==void 0&&(!Number.isSafeInteger(x)||x<1||x>de))throw new e(`Ephemeral ttlSeconds must be a whole number from 1 to ${de}.`,{code:"invalid_argument",provider:"upstash"});let C=new S,v=new Map,p=new Set,B=new Map,P=new Map,O,I=new Map,D=new Map,j=(s)=>{for(let c of I.get(s)??[])c();I.delete(s)},F=()=>{let s=d.apiKey??process.env.UPSTASH_BOX_API_KEY;if(!s)throw new e("Upstash Box API key is missing. Authentication is required. Set UPSTASH_BOX_API_KEY or pass apiKey.",{code:"auth",provider:"upstash"});return C.add([s]),{apiKey:s,baseUrl:d.baseUrl,enableTelemetry:d.enableTelemetry}},_=async()=>{let s=F(),{Box:c,EphemeralBox:u}=await(O??=g("@upstash/box","upstash",f));return{Box:c,EphemeralBox:u,config:s}};async function E(s,c,u=!1,y="request"){try{return await s()}catch(h){throw K(h,c,u,y,(k)=>C.text(k))}}async function L(s){let c=B.get(s);if(c){let U=c();return v.set(s,U),B.delete(s),U}let u=v.get(s);if(u)return u;let{Box:y,config:h}=await _(),k=await y.get(s,{...h,timeout:d.requestTimeoutMs});return v.set(s,k),p.add(s),k}let T=(s,c,u)=>E(async()=>u(await L(s)),s,!0,`files.${c}`),z=async(s)=>{let c=await s.exec.command(`if [ -n "$${G}" ]; then printf %s "$${G}"; else cat ${n(be)}; fi`);if(c.exitCode!==0)throw new e("SDK metadata was not found",{code:"not_found",provider:"upstash",sandboxId:s.id});return ke(c.stdout)};async function H(s){let c=F(),u=(c.baseUrl??process.env.UPSTASH_BOX_BASE_URL??"https://us-east-1.box.upstash.com").replace(/\/$/,""),y=await fetch(`${u}/v2/box/snapshots`,{headers:{Authorization:`Bearer ${c.apiKey}`},signal:AbortSignal.timeout(d.requestTimeoutMs??30000)});if(!y.ok)throw Object.assign(Error("Snapshot metadata lookup failed"),{statusCode:y.status});let h=await y.json();if(!ve(h))throw new e("Invalid snapshot metadata response. Upstash did not return a snapshot list. Retry when the service is available.",{code:"provider",provider:"upstash"});for(let k of h.snapshots??[]){let U=k;if(!r(U)||!("id"in U)||U.id!==s)continue;if("name"in U&&t(U.name)){let M=/^sdk-v1-(small|medium|large)-/.exec(U.name)?.[1];if(M==="small"||M==="medium"||M==="large")return M}if("box_id"in U&&t(U.box_id))try{return(await L(U.box_id)).size}catch(M){if(K(M).code!=="not_found")throw M}q("Snapshot size is unknown because its source box is unavailable; pass an explicit size")}throw new e("Snapshot was not found. It may have been deleted. Check the snapshot ID and account.",{code:"not_found",provider:"upstash"})}let A={name:"upstash",keyMode:"best-effort",capabilities:new Set(x===void 0?["pause","snapshot","size","network-policy"]:["snapshot","size","network-policy"]),create:(s)=>E(async()=>{if(s.idleTimeoutMs!==void 0||s.timeoutMs!==void 0)q("Custom idle deadlines and hard lifetimes are not available on durable boxes");if(s.size!==void 0&&!t(s.size))q("Use small, medium, or large; exact CPU, memory, and disk sizes are unavailable");if(s.env&&G in s.env)throw new e(`${G} is reserved for SDK discovery metadata. Choose another environment variable name.`,{code:"invalid_argument",provider:"upstash"});C.add(Object.values(s.env??{})),C.add(Object.values(d.attachHeaders??{}).flatMap((Q)=>Object.values(Q)));let c=Be(s.network),{Box:u,EphemeralBox:y,config:h}=await _(),k={version:1,key:s.key,labels:{...s.labels,"sandbox-sdk":"1"}},U={...h,runtime:d.runtime,size:s.size??(s.from===void 0?void 0:await H(s.from)),env:{...s.env,[G]:JSON.stringify(k)},labels:[Y],networkPolicy:c,timeout:d.requestTimeoutMs};if(d.attachHeaders!==void 0)U.attachHeaders=d.attachHeaders;let M={};if(!d.ephemeral&&d.keepAlive!==void 0)M.keepAlive=d.keepAlive;if(!d.ephemeral&&d.browser!==void 0)M.browser=d.browser;let W=Date.now(),R=x===void 0?s.from===void 0?await u.create({...U,...M,initCommand:ee}):await u.fromSnapshot(s.from,{...U,...M,initCommand:ee}):s.from===void 0?await y.create({...U,ttl:x}):await y.fromSnapshot(s.from,{...U,ttl:x});try{if(s.signal?.aborted)throw new e("Creation aborted. The caller cancelled. Retry when ready.",{code:"aborted",provider:"upstash"});if(R instanceof u)v.set(R.id,R);else B.set(R.id,()=>new u({id:R.id,status:"running",created_at:W/1000,updated_at:W/1000,size:U.size??"small",labels:[Y],network_policy:"allowedDomains"in c?{mode:c.mode,allowed_domains:c.allowedDomains}:{mode:c.mode}},{baseUrl:(h.baseUrl??process.env.UPSTASH_BOX_BASE_URL??"https://us-east-1.box.upstash.com").replace(/\/$/,""),headers:{"X-Box-Api-Key":h.apiKey},timeout:d.requestTimeoutMs??600000,debug:!1}));if(x!==void 0&&s.from!==void 0&&(await R.exec.command(ee)).exitCode!==0)throw new e("Restored process records could not be invalidated",{code:"provider",provider:"upstash",sandboxId:R.id});return P.set(R.id,{...s.env,...l}),p.add(R.id),{id:R.id,key:k.key,labels:k.labels,createdAt:W,state:"running"}}catch(Q){throw await R.delete(),v.delete(R.id),B.delete(R.id),p.delete(R.id),P.delete(R.id),Q}},void 0,!1,"create"),list:(s)=>E(async()=>{let{Box:c,config:u}=await _(),y=[];for(let h of await c.list({...u,label:Y})){if(!h.labels?.includes(Y)||h.status==="deleted"||J(h)!==(x!==void 0))continue;try{let k=await z(await L(h.id));if(Object.entries(s).every(([U,M])=>k.labels[U]===M))y.push(ce(h,k))}catch(k){if(K(k).code!=="not_found")throw k}}return y},void 0,!1,"list"),async find(s){return(await A.list({})).find((c)=>c.key===s)},connect:(s)=>E(async()=>{let{Box:c,config:u}=await _(),y=(await c.list(u)).find((k)=>k.id===s);if(!y)throw Object.assign(Error("Missing box"),{statusCode:404});if(J(y)!==(x!==void 0))throw new e(`Box ${s} is ${J(y)?"an Ephemeral Box":"a durable Box"}. Connect with upstash({ ephemeral: ${J(y)} }).`,{code:"unsupported",provider:"upstash",sandboxId:s});let h=await L(s);return p.add(s),ce(y,await z(h))},s,!1,"connect"),destroy:(s)=>E(async()=>{try{await(await L(s)).delete()}catch(c){if(K(c).code!=="not_found")throw c}finally{j(s),D.delete(s),v.delete(s),P.delete(s),B.delete(s),p.delete(s)}},s,!1,"destroy"),exec:(s,c)=>E(async()=>{let u=await L(s),y=P.get(s)??l;if(c.streaming!==!0&&c.stdin===void 0&&c.timeoutMs+15000<=(d.requestTimeoutMs??600000)&&Object.entries(c.env).every(([k,U])=>y[k]===U)){let k=await te(u,c,p.has(s)?X:void 0);if(k){if(!k.timedOut)p.delete(s);return k}}return await re(u,c,p.has(s)?X:void 0,()=>p.delete(s))},s,!1,"exec"),startProcess:(s,c)=>E(async()=>{let u=await L(s),h=await oe(u,c,x===void 0?async()=>{await u.pause()}:async(U)=>{await u.exec.command(`for p in $(pgrep -f ${n(`[${U[1]}]${U.slice(2)}/`)}); do kill -KILL -$p 2>/dev/null; done; true`)},p.has(s)?X:void 0);p.delete(s);let k=I.get(s);if(!k)k=new Set,I.set(s,k);return k.add(h.detach),h.wait().finally(()=>k.delete(h.detach)).catch(()=>{}),{pid:h.pid,wait:()=>E(h.wait,s,!1,"process.wait"),stop:(U)=>E(()=>h.stop(U),s,!1,"process.stop")}},s,!1,"process.start"),async close(s){j(s),v.delete(s),P.delete(s),B.delete(s),p.delete(s)},files:{writeCreatesParents:!0,internal:[".step-git"],read:(s,c)=>T(s,"read",(u)=>V(u,c)),readRange:(s,c,u)=>T(s,"readRange",(y)=>V(y,c,u)),write:(s,c,u)=>T(s,"write",(y)=>ne(y,c,u,p.has(s)?X:void 0).then(()=>{p.delete(s)})),list:(s,c)=>T(s,"list",async(u)=>{let y=await ie(u,c,p.has(s)?X:void 0);if(y)return p.delete(s),y.map((h)=>{if(h.type==="other")q("Special filesystem entries are not supported");return{path:ae.join(c,h.name),type:h.type,size:h.size,modifiedAt:h.modifiedAt}});return Promise.all((await u.files.list(c)).map(async(h)=>{let k=ae.join(c,h.name);return le(k,await u.files.stat(k))}))}),stat:(s,c)=>T(s,"stat",async(u)=>{try{return le(c,await u.files.stat(c))}catch(y){if(c!=="/workspace"||!p.has(s)||K(y,s,!0).code!=="file_not_found")throw y;return{path:c,type:"directory",size:0,modifiedAt:Date.now()}}}),remove:(s,c,u)=>T(s,"remove",async(y)=>{try{await y.files.remove(c,u)}catch(h){if(c!=="/workspace"||!p.has(s)||K(h,s,!0).code!=="file_not_found")throw h}if(c==="/workspace")p.delete(s)}),mkdir:(s,c)=>T(s,"mkdir",async(u)=>{if(!p.has(s))return u.files.mkdir(c,{parents:!0});if((await u.exec.command(`${X} && mkdir -p ${n(c)}`)).exitCode!==0)throw new e("Directory creation failed. Check guest permissions.",{code:"provider",provider:"upstash",sandboxId:s});p.delete(s)})},previewUrl:(s,c)=>{let u=D.get(s);if(!u)u=new Map,D.set(s,u);let y=u.get(c);if(y)return y;let h=E(async()=>{let k=await(await L(s)).getPublicURL(c,d.public?void 0:{bearerToken:!0});if(!d.public&&!k.token)throw Error("Protected preview returned no bearer token");return k.token?{url:k.url,headers:{Authorization:`Bearer ${k.token}`}}:{url:k.url}},s,!1,"preview");return u.set(c,h),h.catch(()=>u.delete(c)),h},snapshot:(s,c)=>E(async()=>{if(c?.expiresInMs)q("Snapshot expiry is unavailable; Upstash keeps snapshots until you delete them. Omit expiresInMs, or pass 0");let u=await L(s);return{id:(await u.snapshot({name:`sdk-v1-${u.size}-${crypto.randomUUID()}`})).id}},s,!1,"snapshot"),native(s){let c=B.get(s);if(c){let y=c();return v.set(s,y),B.delete(s),y}let u=v.get(s);if(!u)throw new e("Sandbox is not connected. No native object is cached. Connect first.",{code:"not_found",provider:"upstash",sandboxId:s});return u}};if(x===void 0)A.pause=(s)=>E(async()=>{j(s),await(await L(s)).pause()},s,!1,"pause"),A.resume=(s)=>E(async()=>{await(await L(s)).resume()},s,!1,"resume");return A}function st(d={}){return pe(d,()=>import("@upstash/box"))}export{st as upstash};
105
+ print(json.dumps(out))`;function Te(d){return Array.isArray(d)&&d.length===4&&t(d[0])&&(d[1]==="file"||d[1]==="directory"||d[1]==="symlink"||d[1]==="other")&&o(d[2])&&o(d[3])}async function xe(d,f,y){if(!f.startsWith("/"))return;let E=await d.exec.command(`${y?`${y} && `:""}python3 -c ${n(Oe)} ${n(f)}`);if(E.exitCode!==0)return;let x=E.stdout.trim();if(x==="SDK_FILE_NOT_FOUND")throw Object.assign(Error("Directory entry vanished during listing"),{statusCode:404});try{let l=JSON.parse(x);if(!Array.isArray(l)||!l.every(Te))return;return l.map(([B,C,O,I])=>({name:B,type:C,size:O,modifiedAt:I}))}catch{return}}var ge=259200,ne="sandbox-sdk",oe="SANDBOX_SDK_UPSTASH_METADATA",ee='if ! mkdir -p /workspace 2>/dev/null || [ ! -w /workspace ]; then sudo -n install -d -o "$(id -u)" -g "$(id -g)" -m 755 /workspace; fi && test -w /workspace',De="/tmp/.sandbox-sdk/upstash.json",ve='for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/upstash-runs; true';function Ae(d){return r(d)&&"snapshots"in d&&(d.snapshots===null||Array.isArray(d.snapshots))}function Le(d){let f=(l)=>{throw new e(`Invalid SDK ${l}`,{code:"not_found",provider:"upstash"})},{key:y,labels:E,version:x}=D(d,f);if(x!==1||y===null)f("metadata");return y===void 0?{version:1,labels:E}:{version:1,labels:E,key:y}}function ke(d,f){return{id:d.id,key:f.key,labels:f.labels,createdAt:d.created_at*1000,state:d.status==="paused"?"paused":d.status==="running"||d.status==="idle"?"running":"stopped"}}var ie=(d)=>("ephemeral"in d)&&d.ephemeral===!0;function Be(d,f){if(f.type==="other")Q("Special filesystem entries are not supported");return{path:d,type:f.type,size:f.size,modifiedAt:Date.parse(f.mod_time)}}function Me(d){if(!r(d))return{mode:d==="none"?"deny-all":"allow-all"};if(!d.allow.length)return{mode:"deny-all"};if(d.allow.some((f)=>f.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(f)))Q("Network allow entries must be DNS hostnames");return{mode:"custom",allowedDomains:d.allow}}function ze(d){return d.mode==="custom"?{mode:d.mode,allowed_domains:d.allowedDomains,allowed_cidrs:d.allowedCidrs,denied_cidrs:d.deniedCidrs}:{mode:d.mode}}async function Re(d){let f=`Request failed with status ${d.status}`;try{let y=await d.json();if(r(y)&&"error"in y&&t(y.error))f=y.error}catch{}return Object.assign(Error(f),{statusCode:d.status})}function Ne(d){return r(d)&&"id"in d&&t(d.id)&&d.id!==""&&"status"in d&&t(d.status)}var ue=(d)=>(d.baseUrl??process.env.UPSTASH_BOX_BASE_URL??"https://us-east-1.box.upstash.com").replace(/\/$/,"");async function je(d,f,y){for(let E=0;E<4;E++){if(E)await new Promise((x)=>setTimeout(x,250*E));try{let x=await fetch(`${d}/v2/box/${encodeURIComponent(y)}`,{method:"DELETE",headers:f,signal:AbortSignal.timeout(1e4)});if(x.ok||x.status===404)return!0;if(x.status!==429&&x.status<500)return!1}catch{}}return!1}function $e(d,f){let y=d.ephemeral?d.ttlSeconds??3600:void 0;if(y!==void 0&&(!Number.isSafeInteger(y)||y<1||y>ge))throw new e(`Ephemeral ttlSeconds must be a whole number from 1 to ${ge}.`,{code:"invalid_argument",provider:"upstash"});let E=new S,x=new Map,l=new Set,B=new Map,C=new Map,O,I=new Map,R=new Map,H=(s)=>{for(let c of I.get(s)??[])c();I.delete(s)},X=()=>{let s=d.apiKey??process.env.UPSTASH_BOX_API_KEY;if(!s)throw new e("Upstash Box API key is missing. Authentication is required. Set UPSTASH_BOX_API_KEY or pass apiKey.",{code:"auth",provider:"upstash"});return E.add([s]),{apiKey:s,baseUrl:d.baseUrl,enableTelemetry:d.enableTelemetry}},P=async()=>{let s=X(),{Box:c,EphemeralBox:p}=await(O??=g("@upstash/box","upstash",f));return{Box:c,EphemeralBox:p,config:s}};async function L(s,c,p){let{Box:w,config:{apiKey:v}}=await P(),k=ue(c),_={"X-Box-Api-Key":v},A={};if(s!==void 0)A.snapshot_id=s;if(c.labels?.length)A.labels=c.labels;if(c.size)A.size=c.size;if(c.keepAlive)A.keep_alive=!0;if(c.initCommand!==void 0)A.init_command=c.initCommand;if(c.runtime)A.runtime=c.runtime;if(s===void 0&&c.browser)A.browser=!0;if(c.env)A.env_vars=c.env;if(c.attachHeaders)A.attach_headers=c.attachHeaders;if(c.networkPolicy)A.network_policy=ze(c.networkPolicy);let J=Date.now()+300000,j,V=(z,Y)=>new e(`Upstash ${z}, so a box may exist without its ID. List sandboxes and destroy any you do not expect before retrying.`,{code:"outcome_unknown",provider:"upstash",cause:Y}),ae=()=>new e("Creation aborted. The caller cancelled. Retry when ready.",{code:"aborted",provider:"upstash"});try{j=await fetch(`${k}/v2/box${s===void 0?"":"/from-snapshot"}`,{method:"POST",headers:{..._,"Content-Type":"application/json"},body:JSON.stringify(A),signal:AbortSignal.timeout(Math.min(c.timeout??600000,J-Date.now()))})}catch(z){if(F(z))throw z;throw V(z instanceof Error&&z.name==="TimeoutError"?"did not answer the create request in time":"lost the connection after the create request was sent",z)}if(!j.ok)throw await Re(j);let Z;try{Z=await j.json()}catch(z){throw V("accepted the create request but its answer could not be read",z)}if(!Ne(Z))throw new e("Upstash returned a created box without an ID or status. Inspect the account before retrying.",{code:"outcome_unknown",provider:"upstash"});let de=(z)=>new e(`Upstash box ${Z.id} could not be read before the create deadline. Retry when ready.`,{code:"timeout",provider:"upstash",sandboxId:Z.id,cause:z}),Ee=(z)=>{let Y=Math.min(c.timeout??600000,z),G=p?AbortSignal.any([AbortSignal.timeout(Y),p]):AbortSignal.timeout(Y),te=w.get(Z.id,{apiKey:v,baseUrl:c.baseUrl,enableTelemetry:c.enableTelemetry,timeout:Y});return te.catch(()=>{}),new Promise((re,pe)=>{let ce=()=>pe(p?.aborted?ae():de());if(G.aborted)ce();G.addEventListener("abort",ce,{once:!0}),te.then(re,pe).finally(()=>G.removeEventListener("abort",ce))})};try{let z;while(!z){if(p?.aborted)throw ae();if(Date.now()>=J)throw de();try{z=await Ee(J-Date.now())}catch(G){if(G instanceof e)throw G;let te=K(G,Z.id,!1,"request",(re)=>E.text(re));if(["auth","not_found"].includes(te.code))throw G;if(Date.now()+200>=J)throw de(te);await new Promise((re)=>setTimeout(re,200))}}let Y=Z.status;while(Y==="creating"){if(p?.aborted)throw ae();if(Date.now()>=J)throw Error(s===void 0?"Box creation timed out":"Box creation from snapshot timed out");await new Promise((G)=>setTimeout(G,200));try{Y=(await z.getStatus()).status}catch(G){if(["auth","not_found"].includes(K(G,Z.id).code))throw G}}if(Y==="error")throw Error(s===void 0?"Box creation failed":"Box creation from snapshot failed");return z}catch(z){if(!await je(k,_,Z.id))throw new e(`Upstash box ${Z.id} did not finish creating (${z instanceof Error?z.message:"unknown error"}) and could not be deleted, so it may still be running. Destroy it before retrying.`,{code:"outcome_unknown",provider:"upstash",sandboxId:Z.id,cause:z});throw z}}async function T(s,c,p=!1,w="request"){try{return await s()}catch(v){throw K(v,c,p,w,(k)=>E.text(k))}}async function U(s){let c=B.get(s);if(c){let _=c();return x.set(s,_),B.delete(s),_}let p=x.get(s);if(p)return p;let{Box:w,config:v}=await P(),k=await w.get(s,{...v,timeout:d.requestTimeoutMs});return x.set(s,k),l.add(s),k}let N=(s,c,p)=>T(async()=>p(await U(s)),s,!0,`files.${c}`),W=async(s)=>{let c=await s.exec.command(`if [ -n "$${oe}" ]; then printf %s "$${oe}"; else cat ${n(De)}; fi`);if(c.exitCode!==0)throw new e("SDK metadata was not found",{code:"not_found",provider:"upstash",sandboxId:s.id});return Le(c.stdout)};async function M(s){let c=X(),p=ue(c),w=await fetch(`${p}/v2/box/snapshots`,{headers:{Authorization:`Bearer ${c.apiKey}`},signal:AbortSignal.timeout(d.requestTimeoutMs??30000)});if(!w.ok)throw Object.assign(Error("Snapshot metadata lookup failed"),{statusCode:w.status});let v=await w.json();if(!Ae(v))throw new e("Invalid snapshot metadata response. Upstash did not return a snapshot list. Retry when the service is available.",{code:"provider",provider:"upstash"});for(let k of v.snapshots??[]){let _=k;if(!r(_)||!("id"in _)||_.id!==s)continue;if("name"in _&&t(_.name)){let A=/^sdk-v1-(small|medium|large)-/.exec(_.name)?.[1];if(A==="small"||A==="medium"||A==="large")return A}if("box_id"in _&&t(_.box_id))try{return(await U(_.box_id)).size}catch(A){if(K(A).code!=="not_found")throw A}Q("Snapshot size is unknown because its source box is unavailable; pass an explicit size")}throw new e("Snapshot was not found. It may have been deleted. Check the snapshot ID and account.",{code:"not_found",provider:"upstash"})}let q={name:"upstash",keyMode:"best-effort",procActivity:!0,capabilities:new Set(y===void 0?["pause","snapshot","size","network-policy"]:["snapshot","size","network-policy"]),create:(s)=>T(async()=>{if(s.idleTimeoutMs!==void 0||s.timeoutMs!==void 0)Q("Custom idle deadlines and hard lifetimes are not available on durable boxes");if(s.size!==void 0&&!t(s.size))Q("Use small, medium, or large; exact CPU, memory, and disk sizes are unavailable");if(s.env&&oe in s.env)throw new e(`${oe} is reserved for SDK discovery metadata. Choose another environment variable name.`,{code:"invalid_argument",provider:"upstash"});E.add(Object.values(s.env??{})),E.add(Object.values(d.attachHeaders??{}).flatMap((V)=>Object.values(V)));let c=Me(s.network),{Box:p,EphemeralBox:w,config:v}=await P(),k={version:1,key:s.key,labels:{...s.labels,"sandbox-sdk":"1"}},_={...v,runtime:d.runtime,size:s.size??(s.from===void 0?void 0:await M(s.from)),env:{...s.env,[oe]:JSON.stringify(k)},labels:[ne],networkPolicy:c,timeout:d.requestTimeoutMs};if(d.attachHeaders!==void 0)_.attachHeaders=d.attachHeaders;let A={};if(!d.ephemeral&&d.keepAlive!==void 0)A.keepAlive=d.keepAlive;if(!d.ephemeral&&d.browser!==void 0)A.browser=d.browser;let J=Date.now(),j=y===void 0?await L(s.from,{..._,...A,initCommand:ve},s.signal):s.from===void 0?await w.create({..._,ttl:y}):await w.fromSnapshot(s.from,{..._,ttl:y});try{if(s.signal?.aborted)throw new e("Creation aborted. The caller cancelled. Retry when ready.",{code:"aborted",provider:"upstash"});if(j instanceof p)x.set(j.id,j);else B.set(j.id,()=>new p({id:j.id,status:"running",created_at:J/1000,updated_at:J/1000,size:_.size??"small",labels:[ne],network_policy:"allowedDomains"in c?{mode:c.mode,allowed_domains:c.allowedDomains}:{mode:c.mode}},{baseUrl:ue(v),headers:{"X-Box-Api-Key":v.apiKey},timeout:d.requestTimeoutMs??600000,debug:!1}));if(y!==void 0&&s.from!==void 0&&(await j.exec.command(ve)).exitCode!==0)throw new e("Restored process records could not be invalidated",{code:"provider",provider:"upstash",sandboxId:j.id});return C.set(j.id,{...s.env,...u}),l.add(j.id),{id:j.id,key:k.key,labels:k.labels,createdAt:J,state:"running"}}catch(V){throw await j.delete(),x.delete(j.id),B.delete(j.id),l.delete(j.id),C.delete(j.id),V}},void 0,!1,"create"),list:(s)=>T(async()=>{let{Box:c,config:p}=await P(),w=[];for(let v of await c.list({...p,label:ne})){if(!v.labels?.includes(ne)||v.status==="deleted"||ie(v)!==(y!==void 0))continue;try{let k=await W(await U(v.id));if(Object.entries(s).every(([_,A])=>k.labels[_]===A))w.push(ke(v,k))}catch(k){if(K(k).code!=="not_found")throw k}}return w},void 0,!1,"list"),async find(s){return(await q.list({})).find((c)=>c.key===s)},connect:(s)=>T(async()=>{let{Box:c,config:p}=await P(),w=(await c.list(p)).find((k)=>k.id===s);if(!w)throw Object.assign(Error("Missing box"),{statusCode:404});if(ie(w)!==(y!==void 0))throw new e(`Box ${s} is ${ie(w)?"an Ephemeral Box":"a durable Box"}. Connect with upstash({ ephemeral: ${ie(w)} }).`,{code:"unsupported",provider:"upstash",sandboxId:s});let v=await U(s);return l.add(s),ke(w,await W(v))},s,!1,"connect"),destroy:(s)=>T(async()=>{try{await(await U(s)).delete()}catch(c){if(K(c).code!=="not_found")throw c}finally{H(s),R.delete(s),x.delete(s),C.delete(s),B.delete(s),l.delete(s)}},s,!1,"destroy"),exec:(s,c)=>T(async()=>{let p=await U(s),w=C.get(s)??u;if(c.streaming!==!0&&c.stdin===void 0&&c.timeoutMs+15000<=(d.requestTimeoutMs??600000)&&Object.entries(c.env).every(([k,_])=>w[k]===_)){let k=await fe(p,c,l.has(s)?ee:void 0);if(k){if(!k.timedOut)l.delete(s);return k}}return await he(p,c,l.has(s)?ee:void 0,()=>l.delete(s))},s,!1,"exec"),startProcess:(s,c)=>T(async()=>{let p=await U(s),v=await we(p,c,y===void 0?async()=>{await p.pause()}:async(_)=>{await p.exec.command(`for p in $(pgrep -f ${n(`[${_[1]}]${_.slice(2)}/`)}); do kill -KILL -$p 2>/dev/null; done; true`)},l.has(s)?ee:void 0);l.delete(s);let k=I.get(s);if(!k)k=new Set,I.set(s,k);return k.add(v.detach),v.wait().finally(()=>k.delete(v.detach)).catch(()=>{}),{pid:v.pid,wait:()=>T(v.wait,s,!1,"process.wait"),stop:(_)=>T(()=>v.stop(_),s,!1,"process.stop")}},s,!1,"process.start"),async close(s){H(s),x.delete(s),C.delete(s),B.delete(s),l.delete(s)},files:{writeCreatesParents:!0,editInGuest:"replace",listOrder:"directory",internal:[".step-git"],read:(s,c)=>N(s,"read",(p)=>le(p,c)),readRange:(s,c,p)=>N(s,"readRange",(w)=>le(w,c,p)),write:(s,c,p)=>N(s,"write",(w)=>ye(w,c,p,l.has(s)?ee:void 0).then(()=>{l.delete(s)})),list:(s,c)=>N(s,"list",async(p)=>{let w=await xe(p,c,l.has(s)?ee:void 0);if(w)return l.delete(s),w.map((v)=>{if(v.type==="other")Q("Special filesystem entries are not supported");return{path:be.join(c,v.name),type:v.type,size:v.size,modifiedAt:v.modifiedAt}});return Promise.all((await p.files.list(c)).map(async(v)=>{let k=be.join(c,v.name);return Be(k,await p.files.stat(k))}))}),stat:(s,c)=>N(s,"stat",async(p)=>{try{return Be(c,await p.files.stat(c))}catch(w){if(c!=="/workspace"||!l.has(s)||K(w,s,!0).code!=="file_not_found")throw w;return{path:c,type:"directory",size:0,modifiedAt:Date.now()}}}),remove:(s,c,p)=>N(s,"remove",async(w)=>{try{await w.files.remove(c,p)}catch(v){if(c!=="/workspace"||!l.has(s)||K(v,s,!0).code!=="file_not_found")throw v}if(c==="/workspace")l.delete(s)}),mkdir:(s,c)=>N(s,"mkdir",async(p)=>{if(!l.has(s))return p.files.mkdir(c,{parents:!0});if((await p.exec.command(`${ee} && mkdir -p ${n(c)}`)).exitCode!==0)throw new e("Directory creation failed. Check guest permissions.",{code:"provider",provider:"upstash",sandboxId:s});l.delete(s)})},previewUrl:(s,c)=>{let p=R.get(s);if(!p)p=new Map,R.set(s,p);let w=p.get(c);if(w)return w;let v=T(async()=>{let k=await(await U(s)).getPublicURL(c,d.public?void 0:{bearerToken:!0});if(!d.public&&!k.token)throw Error("Protected preview returned no bearer token");return k.token?{url:k.url,headers:{Authorization:`Bearer ${k.token}`}}:{url:k.url}},s,!1,"preview");return p.set(c,v),v.catch(()=>p.delete(c)),v},snapshot:(s,c)=>T(async()=>{if(c?.expiresInMs)Q("Snapshot expiry is unavailable; Upstash keeps snapshots until you delete them. Omit expiresInMs, or pass 0");let p=await U(s);return{id:(await p.snapshot({name:`sdk-v1-${p.size}-${crypto.randomUUID()}`})).id}},s,!1,"snapshot"),native(s){let c=B.get(s);if(c){let w=c();return x.set(s,w),B.delete(s),w}let p=x.get(s);if(!p)throw new e("Sandbox is not connected. No native object is cached. Connect first.",{code:"not_found",provider:"upstash",sandboxId:s});return p}};if(y===void 0)q.pause=(s)=>T(async()=>{H(s),await(await U(s)).pause()},s,!1,"pause"),q.resume=(s)=>T(async()=>{await(await U(s)).resume()},s,!1,"resume");return q}function vt(d={}){return $e(d,()=>import("@upstash/box"))}export{vt as upstash};
@@ -40,7 +40,7 @@ export type UpstashEphemeralProvider = Provider<Box, UpstashEphemeralCapability>
40
40
  /** What a finished command reports, as far as the adapter reads it. */
41
41
  export type UpstashRun = Pick<Run<string>, "exitCode" | "stdout" | "stderr">;
42
42
  /** The parts of an Upstash Box handle the adapter uses. */
43
- export type UpstashBox = Pick<Box, "id" | "size" | "getPublicURL" | "pause" | "resume" | "delete"> & {
43
+ export type UpstashBox = Pick<Box, "id" | "size" | "getPublicURL" | "pause" | "resume" | "delete" | "getStatus"> & {
44
44
  files: Pick<Box["files"], "read" | "write" | "mkdir" | "stat" | "list" | "remove">;
45
45
  exec: {
46
46
  command(command: string): Promise<UpstashRun>;
@@ -1 +1 @@
1
- import{m}from"../../chunk-bd481sb7.js";import{g}from"../../chunk-k60b4r27.js";import{n}from"../../chunk-2ts3evzh.js";import{e,i,c,a}from"../../chunk-xgxfy2n8.js";import{createHash as ae}from"node:crypto";import{posix as G}from"node:path";import{Readable as H}from"node:stream";function B(u){return m(u).bodyCode}function oe(u){let{responseStatus:s,code:w,name:h}=u;if(s===401||s===403)return"auth";if(s===404)return"not_found";if(s===429)return"quota";if(s!==void 0&&s>=500)return"unavailable";if(w==="ENOENT")return"file_not_found";if(w==="ENOTEMPTY"||w==="ENOTDIR"||s===400)return"invalid_argument";if(h==="AbortError")return"aborted";if(h==="TimeoutError")return"timeout";if(/credentials|OIDC|token/i.test(u.message))return"auth";return"provider"}function E(u,s){if(u instanceof e)return u;let w=m(u),h=w.responseStatus;if(w.bodyCode==="snapshot_not_found")return new e("Vercel snapshot not found. It was deleted, expired, or never existed. Check the snapshot ID, or create a new sandbox.",{code:"not_found",provider:"vercel",sandboxId:s,cause:"snapshot_not_found"});let C=oe(w),x=i(u,{code:C,status:h===void 0?void 0:`HTTP ${h}`,redact:c([process.env.VERCEL_TOKEN,process.env.VERCEL_OIDC_TOKEN])});return new e(`Vercel request failed: ${a(C,x.detail)}. Check credentials, resource limits, and the sandbox state before retrying.`,{code:C,provider:"vercel",sandboxId:s,retryable:C==="quota"||C==="unavailable",cause:x.cause})}function R(u){throw new e(`${u}. Vercel cannot enforce this request. Use the supported Vercel settings or another provider.`,{code:"unsupported",provider:"vercel"})}var J=86400000;function F(u){throw new e(u,{code:"invalid_argument",provider:"vercel"})}function A(u,s){if(u!==void 0&&(!Number.isSafeInteger(u)||u!==0&&u<J))F(`${s} must be 0 (never expires) or at least ${J} ms (one day). Vercel rejects shorter snapshot lifetimes.`);return u}var U="sandbox-sdk-key",W=(u)=>`sdk-${ae("sha256").update(u).digest("hex")}`,Y="flock -x /tmp/.sandbox-sdk-workspace-ready.lock sh -c 'if [ ! -f /tmp/.sandbox-sdk/prepared-workspace ]; then sudo mkdir -p /workspace && sudo chmod 777 /workspace && mkdir -p /tmp/.sandbox-sdk && touch /tmp/.sandbox-sdk/prepared-workspace || exit 1; fi' || exit 1",Q="stat --printf '%n\\0%f %s %y\\0' --";function X(u){let s=u.split("\x00");if(s.pop()!==""||s.length%2)throw Error("Invalid Vercel file metadata");let w=[];for(let h=0;h<s.length;h+=2){let C=s[h],_=s[h+1]?.match(/^([0-9a-f]+) ([0-9]+) (.+)$/);if(C===void 0||!_)throw Error("Invalid Vercel stat response");let T=Number.parseInt(_[1]??"",16),L=Number(_[2]),p=Date.parse(_[3]??"");if(![T,L,p].every(Number.isFinite))throw Error("Invalid Vercel stat fields");w.push({path:C,type:(T&61440)===40960?"symlink":(T&61440)===16384?"directory":"file",size:L,modifiedAt:p})}return w}var se='for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; true';function Z(u,s={}){let w=new Map,h=new Set,C=s.persistent??!0,x=s.keepLastSnapshots;if(x!==void 0&&(!Number.isSafeInteger(x.count)||x.count<1||x.count>10))F("keepLastSnapshots.count must be a whole number from 1 to 10.");let _={snapshotExpiration:A(s.snapshotExpiresInMs,"snapshotExpiresInMs"),keepLastSnapshots:x&&{count:x.count,expiration:A(x.expiresInMs,"keepLastSnapshots.expiresInMs"),deleteEvicted:x.deleteEvicted}},T,L=()=>T??=u(),p=async(t,r)=>{try{return await r()}catch(o){if(t!==void 0&&B(o)==="snapshot_not_found")throw new e("Sandbox session has ended. Vercel has no saved file system to resume from, because the sandbox is not persistent or its snapshot expired. Destroy it and create a new sandbox.",{code:"not_found",provider:"vercel",sandboxId:t});throw E(o,t)}},D=()=>s.fetch===void 0?K():{...K(),fetch:s.fetch};function K(){let t=s.token??process.env.VERCEL_TOKEN,r=s.teamId??process.env.VERCEL_TEAM_ID,o=s.projectId??process.env.VERCEL_PROJECT_ID;if(t){if(!r||!o)throw new e("Vercel credentials are incomplete. Token authentication requires teamId and projectId. Set VERCEL_TEAM_ID and VERCEL_PROJECT_ID.",{code:"auth",provider:"vercel"});return{token:t,teamId:r,projectId:o}}return{}}let j=async(t,r=!1)=>{if((await(await t.runCommand({cmd:"sh",args:["-c",se+(r?"; mkdir -p /tmp/.sandbox-sdk && touch /tmp/.sandbox-sdk/prepared-workspace":"")],detached:!0})).wait()).exitCode!==0)throw Error("Could not invalidate restored processes")},ee=(t)=>{let r=w.get(t);if(!r)throw new e("Sandbox is not attached. No local native object exists. Connect the sandbox first.",{code:"not_found",provider:"vercel",sandboxId:t});return r};function M(t){let r={...t.tags},o=r[U];return delete r[U],{id:t.name,key:o,labels:r,createdAt:t.createdAt.getTime(),state:t.status==="running"||t.status==="pending"?"running":t.status==="stopped"&&t.persistent?"paused":"stopped"}}let te=(t)=>!t.persistent&&(t.status==="stopped"||t.status==="failed"||t.status==="aborted"),O=async(t,r=!1)=>{let o=await L(),d=await o.get({...D(),name:t,resume:r,onResume:j}),l=Date.now()+60000;while(d.tags?.["sandbox-sdk"]==="pending"){if(Date.now()>=l)throw new e("Sandbox initialization is incomplete. The creator has not finished setup. Retry connection later.",{code:"unavailable",provider:"vercel",sandboxId:t,retryable:!0});await new Promise((f)=>setTimeout(f,25)),d=await o.get({...D(),name:t,resume:!1,onResume:j})}return w.set(t,d),d},k=async(t)=>w.get(t)??O(t);function re(t){if(t===void 0)return;if(t==="small"||t==="medium"||t==="large")return{vcpus:{small:1,medium:2,large:4}[t]};if(Number.isSafeInteger(t.cpu)&&t.cpu>0&&t.memoryMb===t.cpu*2048&&t.diskGb===void 0)return{vcpus:t.cpu};R("Custom sizes need a whole number of vCPUs, memoryMb equal to 2048 per vCPU, and no diskGb; Vercel derives memory from vCPUs and has no disk setting")}let q=async(t,r)=>{let o=await(await k(t)).fs.lstat(r);return{path:r,type:o.isSymbolicLink()?"symlink":o.isDirectory()?"directory":"file",size:o.size,modifiedAt:o.mtimeMs}};async function P(t,r,o,d){if(h.has(t)||!(o[0]==="/workspace"||o[0]?.startsWith("/workspace/")))return;let f=await(await k(t)).runCommand({cmd:"sh",args:["-c",`${Y}; ${r}`,"sh",...o],cwd:"/",env:{LC_ALL:"C"},stdin:d===void 0?!1:H.from([d]),detached:!0}),y="",I="",b=(async()=>{for await(let V of f.logs())if(V.stream==="stdout")y+=V.data;else I+=V.data})(),[S]=await Promise.all([f.wait(),b]);if(S.exitCode!==0){if(/No such file or directory/.test(I))throw E({code:"ENOENT"},t);if(/Not a directory|Directory not empty/.test(I))throw E({code:"ENOTDIR"},t);throw Error("Vercel workspace or file operation failed")}return h.add(t),y}async function ne(t,r,o){let d=`/tmp/sandbox-sdk-${crypto.randomUUID()}.pid`,l=`${d}.error`,f=`${h.has(t.name)?"":`(${Y}) || { echo setup-error > ${n(l)}; exit 125; }; `}cd ${n(r.cwd)} || { echo cwd-error > ${n(l)}; exit 125; }; exec sh -c ${n(r.command)}`,y=`echo $$ > ${n(d)}; exec timeout --signal=KILL ${o/1000}s sh -c ${n(f)}`,I=await t.runCommand({cmd:"setsid",args:["--wait","sh","-c",y],cwd:"/",env:r.env,stdin:r.stdin===void 0?!1:H.from([r.stdin]),detached:!0}),b;try{for(let v=0;v<200;v++){try{if(b=Number((await t.fs.readFile(d)).toString()),Number.isInteger(b)&&b>0)break}catch(N){if(E(N,t.name).code!=="file_not_found")throw N}await new Promise((N)=>setTimeout(N,5))}if(!b||!Number.isInteger(b))throw await I.kill("SIGKILL"),new e("Command launch could not be confirmed. Remote process ID was unavailable. Reconnect and inspect the sandbox.",{code:"outcome_unknown",provider:"vercel"});await t.fs.rm(d,{force:!0})}catch(v){let N=b&&Number.isInteger(b)&&b>0?String(b):`$(cat ${n(d)})`;if((await(await t.runCommand({cmd:"sh",args:["-c",`pid=${N}; case "$pid" in ''|*[!0-9]*) exit 1;; esac; kill -KILL -"$pid" 2>/dev/null || true`],detached:!0})).wait()).exitCode!==0)throw new e("Command launch cleanup could not be confirmed. The remote PID is unavailable. Inspect or destroy the sandbox.",{code:"outcome_unknown",provider:"vercel",sandboxId:t.name});throw await I.wait(),v}let S=b;return{command:I,pid:b,kill:async(v)=>{await(await t.runCommand({cmd:"sh",args:["-c",`kill -${v} -${S} 2>/dev/null || true`],detached:!0})).wait()},errorPath:l}}let z={name:"vercel",keyMode:"exact",capabilities:new Set(C?["pause","snapshot","network-policy","size"]:["snapshot","network-policy","size"]),native:ee,create:(t)=>p(void 0,async()=>{if(t.idleTimeoutMs!==void 0)R("idleTimeoutMs is not exposed by the Vercel SDK");let r={...t.labels,"sandbox-sdk":"1"};if(t.key!==void 0)r[U]=t.key;if(Object.keys(r).length>5)R("Vercel supports at most five tags, including sandbox-sdk and sandbox-sdk-key");if(new Set(t.ports).size>15)R("Vercel supports at most fifteen declared ports");if(t.network!==void 0&&s.networkPolicy!==void 0)F("Pass network to createSandbox or networkPolicy to vercel(), not both.");let o=s.networkPolicy??"allow-all";if(t.network==="none")o="deny-all";else if(t.network==="all")o="allow-all";else if(t.network!==void 0)o={allow:t.network.allow};let d={...D(),name:t.key===void 0?`sdk-${crypto.randomUUID()}`:W(t.key),persistent:C,timeout:t.timeoutMs===void 0?void 0:Math.ceil(t.timeoutMs),env:t.env,tags:r,ports:t.ports,resources:re(t.size),networkPolicy:o,networkId:s.networkId,region:s.region,failoverRegions:s.failoverRegions,mounts:s.mounts,..._,signal:t.signal,onResume:j},l;if(t.from)l={...{...d,tags:{...r,"sandbox-sdk":"pending"}},source:{type:"snapshot",snapshotId:t.from}};else{if(l={...d},s.image!==void 0)l.image=s.image;else if(s.runtime!==void 0)l.runtime=s.runtime;if(s.source!==void 0)l.source=s.source}let f=await(await L()).create(l);w.set(f.name,f);try{if(!t.from)return M(f);if((await(await f.runCommand({cmd:"sh",args:["-c","mkdir -p /workspace && chmod 777 /workspace"],sudo:!0,detached:!0})).wait()).exitCode!==0)throw Error("Could not initialize /workspace");return await j(f,!0),await f.update({tags:r}),h.add(f.name),M(f)}catch(y){throw await f.delete(),w.delete(f.name),y}}),find:(t)=>p(void 0,async()=>{let r;try{r=await O(W(t))}catch(o){if(E(o).code==="not_found")return;throw o}if(r.tags?.["sandbox-sdk"]!=="1"||r.tags[U]!==t)return;if(te(r)){await z.destroy(r.name);return}return M(r)}),connect:(t)=>p(t,async()=>M(await O(t))),list:(t)=>p(void 0,async()=>{let r=[];for await(let o of await(await L()).list({...D(),tags:{"sandbox-sdk":"1"}}))try{let d=M(await O(o.name));if(d.labels["sandbox-sdk"]==="1"&&Object.entries(t).every(([l,f])=>d.labels[l]===f))r.push(d)}catch(d){if(E(d,o.name).code!=="not_found")throw d}return r}),destroy:(t)=>p(t,async()=>{try{await(await k(t)).delete(s.deleteOrphanSnapshots?{deleteOrphanSnapshots:!0}:void 0)}catch(r){if(E(r).code!=="not_found")throw r}w.delete(t),h.delete(t)}),exec:(t,r)=>p(t,async()=>{if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let o=Date.now(),d=await k(t),l=await ne(d,r,r.timeoutMs),f=!1,y,I=()=>{f=!0,y??=l.kill("KILL"),y.catch(()=>{})};r.signal?.addEventListener("abort",I,{once:!0});let b=setTimeout(I,Math.max(0,r.timeoutMs-(Date.now()-o)));if(r.signal?.aborted)I();try{let S=(async()=>{for await(let v of l.command.logs())r.onChunk({stream:v.stream,text:v.data})})(),[V]=await Promise.all([l.command.wait(),S]);if(V.exitCode===137&&Date.now()-o>=r.timeoutMs)f=!0;if(await y,!f&&V.exitCode===125){let v;try{v=(await d.fs.readFile(l.errorPath)).toString().trim()}catch(N){if(E(N,t).code!=="file_not_found")throw N}if(v!==void 0)throw await d.fs.rm(l.errorPath,{force:!0}),new e("Command could not start. Workspace initialization or the requested working directory failed. Check the directory and sandbox permissions.",{code:v==="cwd-error"?"invalid_argument":"provider",provider:"vercel",sandboxId:t})}if(!f&&V.exitCode===0)h.add(t);return{exitCode:f?null:V.exitCode,timedOut:f}}catch(S){throw await l.kill("KILL"),await l.command.wait(),S}finally{clearTimeout(b),r.signal?.removeEventListener("abort",I)}}),files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(t,r)=>p(t,async()=>{let o=await P(t,'base64 -- "$1"',[r]);return o===void 0?new Uint8Array(await(await k(t)).fs.readFile(r)):new Uint8Array(Buffer.from(o,"base64"))}),write:(t,r,o,d={})=>p(t,async()=>{let{mode:l}=d;if((l===void 0?await P(t,'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"',[r],o):await P(t,'mkdir -p -- "$(dirname -- "$1")" && (umask 077 && cat > "$1") && chmod -- "$2" "$1"',[r,l.toString(8)],o))!==void 0)return;let y=await k(t);if(await y.fs.mkdir(G.dirname(r),{recursive:!0}),l===void 0){await y.fs.writeFile(r,o);return}if(await y.writeFiles([{path:r,content:o,mode:l&511}]),l&3584)await y.fs.chmod(r,l)}),stat:(t,r)=>p(t,async()=>{let o=await P(t,`${Q} "$1"`,[r]);if(o===void 0)return q(t,r);let d=X(o)[0];if(!d)throw Error("Missing Vercel stat response");return d}),list:(t,r)=>p(t,async()=>{let o=await P(t,`if [ ! -d "$1" ]; then if [ -e "$1" ] || [ -L "$1" ]; then echo 'Not a directory' >&2; else echo 'No such file or directory' >&2; fi; exit 1; fi; find -H "$1" -mindepth 1 -maxdepth 1 -exec ${Q} {} +`,[r]);if(o===void 0)return Promise.all((await(await k(t)).fs.readdir(r)).map((d)=>q(t,G.join(r,d))));return X(o)}),mkdir:(t,r)=>p(t,async()=>{if(await P(t,'mkdir -p -- "$1"',[r])!==void 0)return;await(await k(t)).fs.mkdir(r,{recursive:!0})}),remove:(t,r,o)=>p(t,async()=>{if(await P(t,'if [ "$2" = true ]; then rm -r -- "$1"; else rm -- "$1"; fi',[r,String(o.recursive)])!==void 0)return;await(await k(t)).fs.rm(r,{recursive:o.recursive})})},previewUrl:(t,r)=>p(t,async()=>{let o=await k(t);if(!o.routes.some((d)=>d.port===r))throw new e(`Port ${r} was not declared at creation. Vercel needs ports in CreateInput. Recreate with ports: [${r}].`,{code:"invalid_argument",provider:"vercel",sandboxId:t});return{url:o.domain(r)}}),close:async(t)=>{w.delete(t),h.delete(t)},pause:(t)=>p(t,async()=>{await(await k(t)).stop()}),resume:(t)=>p(t,async()=>{await O(t,!0)}),snapshot:(t,r={})=>p(t,async()=>{let o=A(r.expiresInMs,"expiresInMs");return{id:(await(await k(t)).snapshot(o===void 0?void 0:{expiration:o})).snapshotId}})};return z}function xe(u={}){return Z(async()=>{let{Sandbox:s}=await g("@vercel/sandbox","vercel",()=>import("@vercel/sandbox"));return s},u)}export{xe as vercel};
1
+ import{m}from"../../chunk-drgkmewv.js";import{g}from"../../chunk-3zd78ha4.js";import{n}from"../../chunk-2ts3evzh.js";import{e,i,l,a}from"../../chunk-n7x9ha44.js";import{createHash as ae}from"node:crypto";import{posix as G}from"node:path";import{Readable as H}from"node:stream";function B(u){return m(u).bodyCode}function oe(u){let{responseStatus:s,code:w,name:h}=u;if(s===401||s===403)return"auth";if(s===404)return"not_found";if(s===429)return"quota";if(s!==void 0&&s>=500)return"unavailable";if(w==="ENOENT")return"file_not_found";if(w==="ENOTEMPTY"||w==="ENOTDIR"||s===400)return"invalid_argument";if(h==="AbortError")return"aborted";if(h==="TimeoutError")return"timeout";if(/credentials|OIDC|token/i.test(u.message))return"auth";return"provider"}function E(u,s){if(u instanceof e)return u;let w=m(u),h=w.responseStatus;if(w.bodyCode==="snapshot_not_found")return new e("Vercel snapshot not found. It was deleted, expired, or never existed. Check the snapshot ID, or create a new sandbox.",{code:"not_found",provider:"vercel",sandboxId:s,cause:"snapshot_not_found"});let C=oe(w),x=i(u,{code:C,status:h===void 0?void 0:`HTTP ${h}`,redact:l([process.env.VERCEL_TOKEN,process.env.VERCEL_OIDC_TOKEN])});return new e(`Vercel request failed: ${a(C,x.detail)}. Check credentials, resource limits, and the sandbox state before retrying.`,{code:C,provider:"vercel",sandboxId:s,retryable:C==="quota"||C==="unavailable",cause:x.cause})}function R(u){throw new e(`${u}. Vercel cannot enforce this request. Use the supported Vercel settings or another provider.`,{code:"unsupported",provider:"vercel"})}var J=86400000;function F(u){throw new e(u,{code:"invalid_argument",provider:"vercel"})}function A(u,s){if(u!==void 0&&(!Number.isSafeInteger(u)||u!==0&&u<J))F(`${s} must be 0 (never expires) or at least ${J} ms (one day). Vercel rejects shorter snapshot lifetimes.`);return u}var U="sandbox-sdk-key",W=(u)=>`sdk-${ae("sha256").update(u).digest("hex")}`,Y="flock -x /tmp/.sandbox-sdk-workspace-ready.lock sh -c 'if [ ! -f /tmp/.sandbox-sdk/prepared-workspace ]; then sudo mkdir -p /workspace && sudo chmod 777 /workspace && mkdir -p /tmp/.sandbox-sdk && touch /tmp/.sandbox-sdk/prepared-workspace || exit 1; fi' || exit 1",Q="stat --printf '%n\\0%f %s %y\\0' --";function X(u){let s=u.split("\x00");if(s.pop()!==""||s.length%2)throw Error("Invalid Vercel file metadata");let w=[];for(let h=0;h<s.length;h+=2){let C=s[h],_=s[h+1]?.match(/^([0-9a-f]+) ([0-9]+) (.+)$/);if(C===void 0||!_)throw Error("Invalid Vercel stat response");let T=Number.parseInt(_[1]??"",16),L=Number(_[2]),p=Date.parse(_[3]??"");if(![T,L,p].every(Number.isFinite))throw Error("Invalid Vercel stat fields");w.push({path:C,type:(T&61440)===40960?"symlink":(T&61440)===16384?"directory":"file",size:L,modifiedAt:p})}return w}var se='for d in /tmp/.sandbox-sdk/procs/*; do [ -f "$d/spec.json" ] && [ ! -f "$d/exit" ] && printf 137 > "$d/exit"; done; rm -rf /tmp/.sandbox-sdk/runs; true';function Z(u,s={}){let w=new Map,h=new Set,C=s.persistent??!0,x=s.keepLastSnapshots;if(x!==void 0&&(!Number.isSafeInteger(x.count)||x.count<1||x.count>10))F("keepLastSnapshots.count must be a whole number from 1 to 10.");let _={snapshotExpiration:A(s.snapshotExpiresInMs,"snapshotExpiresInMs"),keepLastSnapshots:x&&{count:x.count,expiration:A(x.expiresInMs,"keepLastSnapshots.expiresInMs"),deleteEvicted:x.deleteEvicted}},T,L=()=>T??=u(),p=async(t,r)=>{try{return await r()}catch(o){if(t!==void 0&&B(o)==="snapshot_not_found")throw new e("Sandbox session has ended. Vercel has no saved file system to resume from, because the sandbox is not persistent or its snapshot expired. Destroy it and create a new sandbox.",{code:"not_found",provider:"vercel",sandboxId:t});throw E(o,t)}},D=()=>s.fetch===void 0?K():{...K(),fetch:s.fetch};function K(){let t=s.token??process.env.VERCEL_TOKEN,r=s.teamId??process.env.VERCEL_TEAM_ID,o=s.projectId??process.env.VERCEL_PROJECT_ID;if(t){if(!r||!o)throw new e("Vercel credentials are incomplete. Token authentication requires teamId and projectId. Set VERCEL_TEAM_ID and VERCEL_PROJECT_ID.",{code:"auth",provider:"vercel"});return{token:t,teamId:r,projectId:o}}return{}}let j=async(t,r=!1)=>{if((await(await t.runCommand({cmd:"sh",args:["-c",se+(r?"; mkdir -p /tmp/.sandbox-sdk && touch /tmp/.sandbox-sdk/prepared-workspace":"")],detached:!0})).wait()).exitCode!==0)throw Error("Could not invalidate restored processes")},ee=(t)=>{let r=w.get(t);if(!r)throw new e("Sandbox is not attached. No local native object exists. Connect the sandbox first.",{code:"not_found",provider:"vercel",sandboxId:t});return r};function M(t){let r={...t.tags},o=r[U];return delete r[U],{id:t.name,key:o,labels:r,createdAt:t.createdAt.getTime(),state:t.status==="running"||t.status==="pending"?"running":t.status==="stopped"&&t.persistent?"paused":"stopped"}}let te=(t)=>!t.persistent&&(t.status==="stopped"||t.status==="failed"||t.status==="aborted"),O=async(t,r=!1)=>{let o=await L(),d=await o.get({...D(),name:t,resume:r,onResume:j}),c=Date.now()+60000;while(d.tags?.["sandbox-sdk"]==="pending"){if(Date.now()>=c)throw new e("Sandbox initialization is incomplete. The creator has not finished setup. Retry connection later.",{code:"unavailable",provider:"vercel",sandboxId:t,retryable:!0});await new Promise((f)=>setTimeout(f,25)),d=await o.get({...D(),name:t,resume:!1,onResume:j})}return w.set(t,d),d},k=async(t)=>w.get(t)??O(t);function re(t){if(t===void 0)return;if(t==="small"||t==="medium"||t==="large")return{vcpus:{small:1,medium:2,large:4}[t]};if(Number.isSafeInteger(t.cpu)&&t.cpu>0&&t.memoryMb===t.cpu*2048&&t.diskGb===void 0)return{vcpus:t.cpu};R("Custom sizes need a whole number of vCPUs, memoryMb equal to 2048 per vCPU, and no diskGb; Vercel derives memory from vCPUs and has no disk setting")}let q=async(t,r)=>{let o=await(await k(t)).fs.lstat(r);return{path:r,type:o.isSymbolicLink()?"symlink":o.isDirectory()?"directory":"file",size:o.size,modifiedAt:o.mtimeMs}};async function P(t,r,o,d){if(h.has(t)||!(o[0]==="/workspace"||o[0]?.startsWith("/workspace/")))return;let f=await(await k(t)).runCommand({cmd:"sh",args:["-c",`${Y}; ${r}`,"sh",...o],cwd:"/",env:{LC_ALL:"C"},stdin:d===void 0?!1:H.from([d]),detached:!0}),y="",I="",b=(async()=>{for await(let V of f.logs())if(V.stream==="stdout")y+=V.data;else I+=V.data})(),[S]=await Promise.all([f.wait(),b]);if(S.exitCode!==0){if(/No such file or directory/.test(I))throw E({code:"ENOENT"},t);if(/Not a directory|Directory not empty/.test(I))throw E({code:"ENOTDIR"},t);throw Error("Vercel workspace or file operation failed")}return h.add(t),y}async function ne(t,r,o){let d=`/tmp/sandbox-sdk-${crypto.randomUUID()}.pid`,c=`${d}.error`,f=`${h.has(t.name)?"":`(${Y}) || { echo setup-error > ${n(c)}; exit 125; }; `}cd ${n(r.cwd)} || { echo cwd-error > ${n(c)}; exit 125; }; exec sh -c ${n(r.command)}`,y=`echo $$ > ${n(d)}; exec timeout --signal=KILL ${o/1000}s sh -c ${n(f)}`,I=await t.runCommand({cmd:"setsid",args:["--wait","sh","-c",y],cwd:"/",env:r.env,stdin:r.stdin===void 0?!1:H.from([r.stdin]),detached:!0}),b;try{for(let v=0;v<200;v++){try{if(b=Number((await t.fs.readFile(d)).toString()),Number.isInteger(b)&&b>0)break}catch(N){if(E(N,t.name).code!=="file_not_found")throw N}await new Promise((N)=>setTimeout(N,5))}if(!b||!Number.isInteger(b))throw await I.kill("SIGKILL"),new e("Command launch could not be confirmed. Remote process ID was unavailable. Reconnect and inspect the sandbox.",{code:"outcome_unknown",provider:"vercel"});await t.fs.rm(d,{force:!0})}catch(v){let N=b&&Number.isInteger(b)&&b>0?String(b):`$(cat ${n(d)})`;if((await(await t.runCommand({cmd:"sh",args:["-c",`pid=${N}; case "$pid" in ''|*[!0-9]*) exit 1;; esac; kill -KILL -"$pid" 2>/dev/null || true`],detached:!0})).wait()).exitCode!==0)throw new e("Command launch cleanup could not be confirmed. The remote PID is unavailable. Inspect or destroy the sandbox.",{code:"outcome_unknown",provider:"vercel",sandboxId:t.name});throw await I.wait(),v}let S=b;return{command:I,pid:b,kill:async(v)=>{await(await t.runCommand({cmd:"sh",args:["-c",`kill -${v} -${S} 2>/dev/null || true`],detached:!0})).wait()},errorPath:c}}let z={name:"vercel",keyMode:"exact",capabilities:new Set(C?["pause","snapshot","network-policy","size"]:["snapshot","network-policy","size"]),native:ee,create:(t)=>p(void 0,async()=>{if(t.idleTimeoutMs!==void 0)R("idleTimeoutMs is not exposed by the Vercel SDK");let r={...t.labels,"sandbox-sdk":"1"};if(t.key!==void 0)r[U]=t.key;if(Object.keys(r).length>5)R("Vercel supports at most five tags, including sandbox-sdk and sandbox-sdk-key");if(new Set(t.ports).size>15)R("Vercel supports at most fifteen declared ports");if(t.network!==void 0&&s.networkPolicy!==void 0)F("Pass network to createSandbox or networkPolicy to vercel(), not both.");let o=s.networkPolicy??"allow-all";if(t.network==="none")o="deny-all";else if(t.network==="all")o="allow-all";else if(t.network!==void 0)o={allow:t.network.allow};let d={...D(),name:t.key===void 0?`sdk-${crypto.randomUUID()}`:W(t.key),persistent:C,timeout:t.timeoutMs===void 0?void 0:Math.ceil(t.timeoutMs),env:t.env,tags:r,ports:t.ports,resources:re(t.size),networkPolicy:o,networkId:s.networkId,region:s.region,failoverRegions:s.failoverRegions,mounts:s.mounts,..._,signal:t.signal,onResume:j},c;if(t.from)c={...{...d,tags:{...r,"sandbox-sdk":"pending"}},source:{type:"snapshot",snapshotId:t.from}};else{if(c={...d},s.image!==void 0)c.image=s.image;else if(s.runtime!==void 0)c.runtime=s.runtime;if(s.source!==void 0)c.source=s.source}let f=await(await L()).create(c);w.set(f.name,f);try{if(!t.from)return M(f);if((await(await f.runCommand({cmd:"sh",args:["-c","mkdir -p /workspace && chmod 777 /workspace"],sudo:!0,detached:!0})).wait()).exitCode!==0)throw Error("Could not initialize /workspace");return await j(f,!0),await f.update({tags:r}),h.add(f.name),M(f)}catch(y){throw await f.delete(),w.delete(f.name),y}}),find:(t)=>p(void 0,async()=>{let r;try{r=await O(W(t))}catch(o){if(E(o).code==="not_found")return;throw o}if(r.tags?.["sandbox-sdk"]!=="1"||r.tags[U]!==t)return;if(te(r)){await z.destroy(r.name);return}return M(r)}),connect:(t)=>p(t,async()=>M(await O(t))),list:(t)=>p(void 0,async()=>{let r=[];for await(let o of await(await L()).list({...D(),tags:{"sandbox-sdk":"1"}}))try{let d=M(await O(o.name));if(d.labels["sandbox-sdk"]==="1"&&Object.entries(t).every(([c,f])=>d.labels[c]===f))r.push(d)}catch(d){if(E(d,o.name).code!=="not_found")throw d}return r}),destroy:(t)=>p(t,async()=>{try{await(await k(t)).delete(s.deleteOrphanSnapshots?{deleteOrphanSnapshots:!0}:void 0)}catch(r){if(E(r).code!=="not_found")throw r}w.delete(t),h.delete(t)}),exec:(t,r)=>p(t,async()=>{if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let o=Date.now(),d=await k(t),c=await ne(d,r,r.timeoutMs),f=!1,y,I=()=>{f=!0,y??=c.kill("KILL"),y.catch(()=>{})};r.signal?.addEventListener("abort",I,{once:!0});let b=setTimeout(I,Math.max(0,r.timeoutMs-(Date.now()-o)));if(r.signal?.aborted)I();try{let S=(async()=>{for await(let v of c.command.logs())r.onChunk({stream:v.stream,text:v.data})})(),[V]=await Promise.all([c.command.wait(),S]);if(V.exitCode===137&&Date.now()-o>=r.timeoutMs)f=!0;if(await y,!f&&V.exitCode===125){let v;try{v=(await d.fs.readFile(c.errorPath)).toString().trim()}catch(N){if(E(N,t).code!=="file_not_found")throw N}if(v!==void 0)throw await d.fs.rm(c.errorPath,{force:!0}),new e("Command could not start. Workspace initialization or the requested working directory failed. Check the directory and sandbox permissions.",{code:v==="cwd-error"?"invalid_argument":"provider",provider:"vercel",sandboxId:t})}if(!f&&V.exitCode===0)h.add(t);return{exitCode:f?null:V.exitCode,timedOut:f}}catch(S){throw await c.kill("KILL"),await c.command.wait(),S}finally{clearTimeout(b),r.signal?.removeEventListener("abort",I)}}),files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(t,r)=>p(t,async()=>{let o=await P(t,'base64 -- "$1"',[r]);return o===void 0?new Uint8Array(await(await k(t)).fs.readFile(r)):new Uint8Array(Buffer.from(o,"base64"))}),write:(t,r,o,d={})=>p(t,async()=>{let{mode:c}=d;if((c===void 0?await P(t,'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"',[r],o):await P(t,'mkdir -p -- "$(dirname -- "$1")" && (umask 077 && cat > "$1") && chmod -- "$2" "$1"',[r,c.toString(8)],o))!==void 0)return;let y=await k(t);if(await y.fs.mkdir(G.dirname(r),{recursive:!0}),c===void 0){await y.fs.writeFile(r,o);return}if(await y.writeFiles([{path:r,content:o,mode:c&511}]),c&3584)await y.fs.chmod(r,c)}),stat:(t,r)=>p(t,async()=>{let o=await P(t,`${Q} "$1"`,[r]);if(o===void 0)return q(t,r);let d=X(o)[0];if(!d)throw Error("Missing Vercel stat response");return d}),list:(t,r)=>p(t,async()=>{let o=await P(t,`if [ ! -d "$1" ]; then if [ -e "$1" ] || [ -L "$1" ]; then echo 'Not a directory' >&2; else echo 'No such file or directory' >&2; fi; exit 1; fi; find -H "$1" -mindepth 1 -maxdepth 1 -exec ${Q} {} +`,[r]);if(o===void 0)return Promise.all((await(await k(t)).fs.readdir(r)).map((d)=>q(t,G.join(r,d))));return X(o)}),mkdir:(t,r)=>p(t,async()=>{if(await P(t,'mkdir -p -- "$1"',[r])!==void 0)return;await(await k(t)).fs.mkdir(r,{recursive:!0})}),remove:(t,r,o)=>p(t,async()=>{if(await P(t,'if [ "$2" = true ]; then rm -r -- "$1"; else rm -- "$1"; fi',[r,String(o.recursive)])!==void 0)return;await(await k(t)).fs.rm(r,{recursive:o.recursive})})},previewUrl:(t,r)=>p(t,async()=>{let o=await k(t);if(!o.routes.some((d)=>d.port===r))throw new e(`Port ${r} was not declared at creation. Vercel needs ports in CreateInput. Recreate with ports: [${r}].`,{code:"invalid_argument",provider:"vercel",sandboxId:t});return{url:o.domain(r)}}),close:async(t)=>{w.delete(t),h.delete(t)},pause:(t)=>p(t,async()=>{await(await k(t)).stop()}),resume:(t)=>p(t,async()=>{await O(t,!0)}),snapshot:(t,r={})=>p(t,async()=>{let o=A(r.expiresInMs,"expiresInMs");return{id:(await(await k(t)).snapshot(o===void 0?void 0:{expiration:o})).snapshotId}})};return z}function xe(u={}){return Z(async()=>{let{Sandbox:s}=await g("@vercel/sandbox","vercel",()=>import("@vercel/sandbox"));return s},u)}export{xe as vercel};
package/dist/run.d.ts CHANGED
@@ -3,6 +3,8 @@ import { Redactor, type SandboxError } from "./errors.js";
3
3
  import type { RunHandle, RunOptions } from "./types.js";
4
4
  import { quote } from "./shared/shell.js";
5
5
  export { quote };
6
+ /** Every SDK command carries this variable, and so does every descendant that keeps its environment. */
7
+ export declare const activityTag = "SANDBOX_SDK_RUN";
6
8
  export declare const defaults: {
7
9
  CI: string;
8
10
  PAGER: string;
@@ -10,9 +12,16 @@ export declare const defaults: {
10
12
  DEBIAN_FRONTEND: string;
11
13
  TERM: string;
12
14
  NO_COLOR: string;
15
+ SANDBOX_SDK_RUN: string;
13
16
  };
14
17
  export declare const pathOf: (path?: string) => string;
15
18
  export declare const secretRecoveryCommand = "if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi";
19
+ /**
20
+ * Idle scan for procActivity adapters. Exit 0 only when every live process is readable and none carries
21
+ * the tag; any other outcome means busy. Processes the exec user cannot read are re-read through
22
+ * passwordless sudo (root reads root-owned processes); a process nobody can read keeps the sandbox busy.
23
+ */
24
+ export declare const activityScanCommand = "t=SANDBOX_SDK_RUN=1\nset -- /proc/[0-9]*/environ\n[ -e \"$1\" ] || exit 2\ngrep -s -q -a -F -e \"$t\" -- \"$@\"; c=$?\n[ \"$c\" = 0 ] && exit 10\n[ \"$c\" = 1 ] && exit 0\n[ \"$c\" = 2 ] || exit 2\nu=\nfor f in \"$@\"; do\n grep -s -q -a -F -e \"$t\" -- \"$f\"; c=$?\n [ \"$c\" = 0 ] && exit 10\n [ \"$c\" = 2 ] && [ -d \"${f%/environ}\" ] && u=\"$u $f\"\ndone\n[ -z \"$u\" ] && exit 0\n[ \"$(id -u)\" = 0 ] && exit 11\nsudo -n sh -c 'for f; do grep -s -q -a -F -e \"$0\" -- \"$f\"; c=$?; [ \"$c\" = 0 ] && exit 10; [ \"$c\" = 2 ] && [ -d \"${f%/environ}\" ] && exit 11; done; exit 0' \"$t\" $u </dev/null 2>/dev/null";
16
25
  export declare const isRunActive: (provider: string, id: string) => boolean;
17
26
  export declare class BufferCap {
18
27
  readonly limit: number;
@@ -1,6 +1,33 @@
1
1
  import type { FileInfo, ProviderFiles } from "../provider.js";
2
2
  export declare const python: (code: string, ...args: string[]) => string;
3
- export declare const guestProcess = "def 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";
3
+ /**
4
+ * Wraps a per-command supervisor so the guest compiles it once, not on every
5
+ * command: compiling ~5 KB of source costs 2-5 ms on a small VM. The source still
6
+ * travels with each command, so a missing, foreign or stale cache only means a
7
+ * compile. A cache entry is used only when this user owns it, nobody else can
8
+ * write it, and it was compiled from this exact source by this interpreter.
9
+ * `store` is the Python condition under which a compile writes the cache.
10
+ */
11
+ export declare function cachedPython(source: string, run?: string, store?: string): string;
12
+ /**
13
+ * Commands for a supervisor that can run from a zygote. A client's first
14
+ * command in a sandbox runs the plain supervisor: a zygote only pays off from
15
+ * later commands, and its client and server add ~10 KB to the command, which
16
+ * Superserve charges for per request (~2 ms per KB on a fresh sandbox). That
17
+ * command is the bare supervisor source, as before zygotes existed; it marks the
18
+ * sandbox as reused, so the next command's one-shot starts the zygote.
19
+ */
20
+ export declare function zygoteSupervisor(source: string): {
21
+ /**
22
+ * Without `spec` the supervisor reads its hex spec from the command's stdin.
23
+ * With it, the spec travels in the command: as an argument to the plain
24
+ * supervisor, or as a heredoc that a zygote child can read as the client's stdin.
25
+ */
26
+ command(sandbox: string, root: string, spec?: string): string;
27
+ zygote: (root: string) => string;
28
+ };
29
+ export declare const guestProcess = "def 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";
30
+ export declare const guestPump = "def 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";
4
31
  export interface Guest {
5
32
  name: string;
6
33
  raw(command: string): Promise<string>;
package/dist/testing.js CHANGED
@@ -1,9 +1,9 @@
1
- import{X,O,j,W,Q}from"./chunk-hgrwyjrb.js";import{e}from"./chunk-xgxfy2n8.js";import{describe as D,test as c,expect as a,afterEach as P}from"vitest";import{mkdtemp as S,mkdir as T,writeFile as _,readFile as A,rm as R}from"node:fs/promises";import{tmpdir as I}from"node:os";import{join as w}from"node:path";function z(m,n){let f=n.timeoutMs??(n.live?120000:void 0);D("Sandbox SDK conformance",{timeout:f},()=>{let u=[],h=[];async function g(){let t=await m();if(!n.live&&!["memory","local"].includes(t.name))throw new e("Live provider refused. live is false. Enable live explicitly with provider credentials.",{code:"invalid_argument"});return t}async function d(t={},s){let o=s??await g(),i=await O(o,{ports:n.ports,...t});return u.push(i),{provider:o,box:i}}P(async()=>{await Promise.all(u.splice(0).map((t)=>t.destroy())),await Promise.all(h.splice(0).map((t)=>R(t,{recursive:!0,force:!0})))}),c("create, key lookup, connect and labels",async()=>{let t=await g(),s=`conformance-${crypto.randomUUID()}`,o=await O(t,{key:s,labels:{suite:s}});u.push(o);let i=await O(t,{key:s});u.push(i),a(o.created).toBe(!0),a(i.created).toBe(!1),a(i.id).toBe(o.id);let r=await j(t,o.id);u.push(r),a(r.native).toBeDefined(),await a.poll(async()=>(await W(t,{labels:{suite:s}})).map((p)=>p.id),{timeout:15000,interval:500}).toEqual([o.id])}),c("exit results, stdin, resolved cwd and default environment",async()=>{let{box:t}=await d();a(await t.run("false")).toMatchObject({ok:!1,exitCode:1,timedOut:!1}),a(await t.run("exit 7")).toMatchObject({exitCode:7}),a((await t.run("cat",{stdin:`input
1
+ import{ne,O,U,Q,re}from"./chunk-ea8y7y2p.js";import{e}from"./chunk-n7x9ha44.js";import{describe as C,test as c,expect as a,afterEach as D}from"vitest";import{mkdtemp as P,mkdir as S,writeFile as j,readFile as T,rm as A}from"node:fs/promises";import{tmpdir as R}from"node:os";import{join as w}from"node:path";function z(m,n){let f=n.timeoutMs??(n.live?120000:void 0);C("Sandbox SDK conformance",{timeout:f},()=>{let u=[],h=[];async function g(){let t=await m();if(!n.live&&!["memory","local"].includes(t.name))throw new e("Live provider refused. live is false. Enable live explicitly with provider credentials.",{code:"invalid_argument"});return t}async function d(t={},s){let o=s??await g(),i=await O(o,{ports:n.ports,...t});return u.push(i),{provider:o,box:i}}D(async()=>{await Promise.all(u.splice(0).map((t)=>t.destroy())),await Promise.all(h.splice(0).map((t)=>A(t,{recursive:!0,force:!0})))}),c("create, key lookup, connect and labels",async()=>{let t=await g(),s=`conformance-${crypto.randomUUID()}`,o=await O(t,{key:s,labels:{suite:s}});u.push(o);let i=await O(t,{key:s});u.push(i),a(o.created).toBe(!0),a(i.created).toBe(!1),a(i.id).toBe(o.id);let r=await U(t,o.id);u.push(r),a(r.native).toBeDefined(),await a.poll(async()=>(await Q(t,{labels:{suite:s}})).map((p)=>p.id),{timeout:15000,interval:500}).toEqual([o.id])}),c("exit results, stdin, resolved cwd and default environment",async()=>{let{box:t}=await d();a(await t.run("false")).toMatchObject({ok:!1,exitCode:1,timedOut:!1}),a(await t.run("exit 7")).toMatchObject({exitCode:7}),a((await t.run("cat",{stdin:`input
2
2
  `})).stdout).toBe(`input
3
3
  `),a((await t.run("pwd")).stdout).toBe(`/workspace
4
- `),a((await t.run(`printf '%s' "$CI:$PAGER:$GIT_TERMINAL_PROMPT:$DEBIAN_FRONTEND:$TERM:$NO_COLOR"`)).stdout).toBe("1:cat:0:noninteractive:dumb:1")});let E=Math.max(f??0,30000);c("timeout and abort kill a launched command before its delayed side effect",{timeout:E},async()=>{let{box:t}=await d(),s=Date.now();await t.run("true");let o=Date.now()-s,i=500+2*o,r=Math.ceil((i+o+500)/1000)*1000,p=500+o;async function l(b,y){let x=Promise.resolve(t.run(`echo launched > ${b}-launched; sleep ${r/1000}; echo survived > ${b}-survived`,y));return await a.poll(()=>t.files.exists(`${b}-launched`),{timeout:r,interval:20}).toBe(!0),{run:x,launchedAt:Date.now()}}async function v(b,y){let x=y+r+p-Date.now();await new Promise((C)=>setTimeout(C,Math.max(0,x))),a(await t.files.exists(`${b}-survived`)).toBe(!1)}let M=await l("timeout",{timeoutMs:i});a(await M.run).toMatchObject({timedOut:!0,exitCode:null,ok:!1}),await v("timeout",M.launchedAt);let k=new AbortController,B=await l("abort",{signal:k.signal});k.abort(),a(await B.run).toMatchObject({timedOut:!0,exitCode:null,ok:!1}),await v("abort",B.launchedAt)}),c("bounded head and tail output, interleaving and streaming",async()=>{let{box:t}=await d(),s=await t.run(`printf '${"a".repeat(1024)}END'`,{maxOutputBytes:64});a(s.truncated).toBe(!0),a(s.stdout.startsWith("a")).toBe(!0),a(s.stdout.endsWith("END")).toBe(!0),a(s.stdout).toContain("bytes cut");let o=t.run("printf A; printf B >&2; printf C"),i=[];for await(let l of o)i.push(l.text);let r=await o;a(r).toMatchObject({stdout:"AC",stderr:"B",output:i.join("")});let p=[];for await(let l of t.run("echo streamed"))p.push(l.text);a(p.join("")).toBe(`streamed
4
+ `),a((await t.run(`printf '%s' "$CI:$PAGER:$GIT_TERMINAL_PROMPT:$DEBIAN_FRONTEND:$TERM:$NO_COLOR"`)).stdout).toBe("1:cat:0:noninteractive:dumb:1")});let _=Math.max(f??0,30000);c("timeout and abort kill a launched command before its delayed side effect",{timeout:_},async()=>{let{box:t}=await d(),s=Date.now();await t.run("true");let o=Date.now()-s,i=500+2*o,r=Math.ceil((i+o+500)/1000)*1000,p=500+o;async function l(b,y){let x=Promise.resolve(t.run(`echo launched > ${b}-launched; sleep ${r/1000}; echo survived > ${b}-survived`,y));return await a.poll(()=>t.files.exists(`${b}-launched`),{timeout:r,interval:20}).toBe(!0),{run:x,launchedAt:Date.now()}}async function v(b,y){let x=y+r+p-Date.now();await new Promise((E)=>setTimeout(E,Math.max(0,x))),a(await t.files.exists(`${b}-survived`)).toBe(!1)}let M=await l("timeout",{timeoutMs:i});a(await M.run).toMatchObject({timedOut:!0,exitCode:null,ok:!1}),await v("timeout",M.launchedAt);let k=new AbortController,B=await l("abort",{signal:k.signal});k.abort(),a(await B.run).toMatchObject({timedOut:!0,exitCode:null,ok:!1}),await v("abort",B.launchedAt)}),c("bounded head and tail output, interleaving and streaming",async()=>{let{box:t}=await d(),s=await t.run(`printf '${"a".repeat(1024)}END'`,{maxOutputBytes:64});a(s.truncated).toBe(!0),a(s.stdout.startsWith("a")).toBe(!0),a(s.stdout.endsWith("END")).toBe(!0),a(s.stdout).toContain("bytes cut");let o=t.run("printf A; printf B >&2; printf C"),i=[];for await(let l of o)i.push(l.text);let r=await o;a(r).toMatchObject({stdout:"AC",stderr:"B",output:i.join("")});let p=[];for await(let l of t.run("echo streamed"))p.push(l.text);a(p.join("")).toBe(`streamed
5
5
  `)}),c("tag escaping and chain options prevent interpolation execution",async()=>{let{box:t}=await d(),s="x'; echo injected; printf '";a((await t.$`printf '%s' ${"x'; echo injected; printf '"}`.cwd(".").env({X:"ok"}).timeout(n.live?1e4:1000)).stdout).toBe("x'; echo injected; printf '"),a((await t.run(`printf '%s' "$X"`)).stdout).toBe("")}),c("all file primitives, exact edits, glob search, checkpoints",async()=>{let{box:t}=await d({trackChanges:!0});await t.files.write({"app/a.ts":`TODO one
6
6
  second`,"app/b.ts":"two two","app/raw":new Uint8Array([0,255])}),a(await t.files.read("app/raw",{as:"bytes"})).toEqual(new Uint8Array([0,255])),a((await t.files.stat("app/a.ts")).type).toBe("file"),a((await t.files.list("app",{recursive:!0,glob:"**/*.ts"})).length).toBe(2),a(await t.files.search("TODO",{path:"app",glob:"*.ts"})).toMatchObject([{line:1,text:"TODO one"}]),await a(t.files.edit("app/a.ts",{find:"missing",replace:"x"})).rejects.toMatchObject({code:"edit_not_found"}),await a(t.files.edit("app/b.ts",{find:"two",replace:"x"})).rejects.toMatchObject({code:"edit_not_unique"});let s=await t.files.mark();await t.files.edit("app/a.ts",{find:"TODO",replace:"DONE"}),await t.files.remove("app/b.ts"),await t.files.write("app/new","new"),a(await t.files.changes({since:s})).toMatchObject({added:["/workspace/app/new"],modified:["/workspace/app/a.ts"],removed:["/workspace/app/b.ts"]}),a((await t.files.changes()).added).toContain("/workspace/app/a.ts"),await t.files.remove("app",{recursive:!0}),a(await t.files.exists("app")).toBe(!1)}),c("write mode sets permission bits and rejects invalid modes",async(t)=>{if(n.unsupported?.fileModes){t.skip(n.unsupported.fileModes);return}let{box:s}=await d();await s.files.write("modes/secret","x",{mode:384}),await s.files.write({"modes/a":"a","modes/b":"b"},{mode:416}),a((await s.run("stat -c %a modes/secret modes/a modes/b")).stdout).toBe(`600
7
7
  640
8
8
  640
9
- `);for(let o of[-1,4096,1.5,Number.NaN])await a(s.files.write("modes/bad","x",{mode:o})).rejects.toMatchObject({code:"invalid_argument"});a(await s.files.exists("modes/bad")).toBe(!1)}),c("snapshot expiresInMs is validated, forwarded to the provider, and accepted or refused as declared",async(t)=>{let s=await g(),o=N(s),{box:i}=await d({},s);if(!X(i,"snapshot")){t.skip();return}if(await a(i.snapshot({expiresInMs:-1})).rejects.toMatchObject({code:"invalid_argument"}),a(o).toEqual([]),n.snapshotExpiry==="honored")a((await i.snapshot({expiresInMs:86400000})).id).not.toBe(""),a(o).toEqual([{expiresInMs:86400000}]);else if(n.snapshotExpiry==="refused")await a(i.snapshot({expiresInMs:86400000})).rejects.toMatchObject({name:"SandboxError",code:a.stringMatching(/^(unsupported|invalid_argument)$/)}),a(o).toEqual([{expiresInMs:86400000}])}),c("changes without since needs trackChanges or an explicit mark",async()=>{let{box:t}=await d();await a(t.files.changes()).rejects.toMatchObject({code:"invalid_argument",message:a.stringContaining("trackChanges: true")}),await t.files.write("late","x");let s=await t.files.mark("start");await t.files.write("late","y"),a((await t.files.changes()).modified).toEqual(["/workspace/late"]),a((await t.files.changes({since:s})).modified).toEqual(["/workspace/late"])}),c("upload/download round trip with ignores",async()=>{let{box:t}=await d(),s=await S(w(I(),"sdk-conformance-"));h.push(s),await T(w(s,"source")),await _(w(s,"source","keep"),"hello"),await _(w(s,"source","ignore"),"no"),await t.files.upload(w(s,"source"),"upload",{ignore:["ignore"]}),a(await t.files.exists("upload/ignore")).toBe(!1),await t.files.download("upload",w(s,"download")),a(await A(w(s,"download","keep"),"utf8")).toBe("hello")}),c("file watch observes changes",{timeout:Math.max(f??0,60000)},async()=>{let{box:t}=await d(),s=Date.now();await t.files.write("watch/file","a");let o=Date.now()-s,i=[],r=t.files.watch("watch",(l)=>i.push(l.type),{recursive:!0,intervalMs:10}),p=0;try{await a.poll(async()=>(await t.files.write("watch/file",`different-${p++}`),i),{timeout:Math.max(1e4,20*o),interval:50}).toContain("modified")}finally{r()}}),c("process logs, cursors, fresh client reattach, stop and exit-before-ready",async(t)=>{if(n.unsupported?.processes){t.skip(n.unsupported.processes);return}let{box:s}=await d(),o=await s.start("echo READY; sleep 5",{name:"dev",ready:{log:/READY/},readyTimeoutMs:2000});a(o.ready).toBe(!0);let i=await o.logs();a(i.text).toContain("READY"),a((await o.logs({after:i.nextCursor})).text).toBe("");let r=await j(await g(),s.id);u.push(r),a((await r.processes()).map((p)=>p.name)).toContain("dev"),a((await r.process("dev").logs()).text).toContain("READY"),await r.process("dev").stop({graceMs:10}),a((await o.wait()).exitCode).not.toBe(null),await a(s.start("exit 3",{name:"early",ready:{log:/never/},readyTimeoutMs:1000})).rejects.toMatchObject({code:"process_exited"})}),c("readiness timeout preserves the process",async(t)=>{if(n.unsupported?.processes){t.skip(n.unsupported.processes);return}let{box:s}=await d();await a(s.start("sleep 5",{name:"unready",ready:{log:/never/},readyTimeoutMs:30})).rejects.toMatchObject({code:"timeout"}),a(s.process("unready").ready).toBe(!1),a((await s.processes())[0]?.status).toBe("running"),await s.process("unready").stop({graceMs:10})}),c("preview and capability gating",async()=>{let{provider:t,box:s}=await d();if(n.unsupported?.previews)await a(s.preview(3000)).rejects.toMatchObject({code:"unsupported"});else a(["http:","https:"]).toContain(new URL((await s.preview(3000)).url).protocol);for(let[o,i]of[["pause","pause"],["snapshot","snapshot"],["terminal","terminal"]])a(i in s).toBe(t.capabilities.has(o));if(!t.capabilities.has("network-policy"))await a(O(t,{network:"none"})).rejects.toMatchObject({code:"unsupported"});if(!t.capabilities.has("size"))await a(O(t,{size:"small"})).rejects.toMatchObject({code:"unsupported"})}),c("close, disposal, destroy and label-scoped reaping",async()=>{let{provider:t,box:s}=await d(),o=s.id;await s.close(),a((await j(t,o)).id).toBe(o),await s.destroy(),await a(j(t,o)).rejects.toMatchObject({code:"not_found"});let i=crypto.randomUUID(),r=await O(t,{key:i,labels:{reap:i}});u.push(r),await r[Symbol.asyncDispose](),a((await t.connect(r.id)).id).toBe(r.id),a(await Q(t,{labels:{reap:i},olderThanMs:0})).toBe(1);let p=await O(t);await p[Symbol.asyncDispose](),await a(t.connect(p.id)).rejects.toMatchObject({code:"not_found"})}),c("usage counters",async()=>{let{box:t}=await d();await t.run("echo abc"),a(await t.usage()).toMatchObject({commands:1,bytesOut:4})}),c("local bare git clone, commit and push (live providers only)",async(t)=>{if(n.unsupported?.gitPush){t.skip(n.unsupported.gitPush);return}let{box:s}=await d();a((await s.run("git init --bare /tmp/sdk-bare")).ok).toBe(!0),a((await s.git.clone("/tmp/sdk-bare",{dir:"repo"})).ok).toBe(!0),await s.run("git config user.name Conformance; git config user.email test@example.com",{cwd:"repo"}),await s.files.write("repo/test","test"),a((await s.git.commit("repo",{message:"conformance",all:!0})).ok).toBe(!0),a((await s.git.status("repo")).stdout).toBe(""),a((await s.git.push("repo",{branch:"HEAD"})).ok).toBe(!0)}),c("real HTTP preview probe (live Linux providers only)",async(t)=>{let s=n.unsupported?.previews??n.unsupported?.httpProbe;if(s){t.skip(s);return}let{box:o}=await d(),i=await o.start(`node -e 'require("http").createServer((_,r)=>r.end("ok")).listen(3000,"0.0.0.0")'`,{name:"http",ready:{http:{port:3000}}});a(i.ready).toBe(!0),a((await o.preview(3000,{waitMs:2000})).url).toBeTruthy(),await i.stop()})})}function N(m){let n=[],f=m.snapshot;if(f)m.snapshot=(u,h)=>(n.push(h),f.call(m,u,h));return n}export{z as runConformance};
9
+ `);for(let o of[-1,4096,1.5,Number.NaN])await a(s.files.write("modes/bad","x",{mode:o})).rejects.toMatchObject({code:"invalid_argument"});a(await s.files.exists("modes/bad")).toBe(!1)}),c("snapshot expiresInMs is validated, forwarded to the provider, and accepted or refused as declared",async(t)=>{let s=await g(),o=I(s),{box:i}=await d({},s);if(!ne(i,"snapshot")){t.skip();return}if(await a(i.snapshot({expiresInMs:-1})).rejects.toMatchObject({code:"invalid_argument"}),a(o).toEqual([]),n.snapshotExpiry==="honored")a((await i.snapshot({expiresInMs:86400000})).id).not.toBe(""),a(o).toEqual([{expiresInMs:86400000}]);else if(n.snapshotExpiry==="refused")await a(i.snapshot({expiresInMs:86400000})).rejects.toMatchObject({name:"SandboxError",code:a.stringMatching(/^(unsupported|invalid_argument)$/)}),a(o).toEqual([{expiresInMs:86400000}])}),c("changes without since needs trackChanges or an explicit mark",async()=>{let{box:t}=await d();await a(t.files.changes()).rejects.toMatchObject({code:"invalid_argument",message:a.stringContaining("trackChanges: true")}),await t.files.write("late","x");let s=await t.files.mark("start");await t.files.write("late","y"),a((await t.files.changes()).modified).toEqual(["/workspace/late"]),a((await t.files.changes({since:s})).modified).toEqual(["/workspace/late"])}),c("upload/download round trip with ignores",async()=>{let{box:t}=await d(),s=await P(w(R(),"sdk-conformance-"));h.push(s),await S(w(s,"source")),await j(w(s,"source","keep"),"hello"),await j(w(s,"source","ignore"),"no"),await t.files.upload(w(s,"source"),"upload",{ignore:["ignore"]}),a(await t.files.exists("upload/ignore")).toBe(!1),await t.files.download("upload",w(s,"download")),a(await T(w(s,"download","keep"),"utf8")).toBe("hello")}),c("file watch observes changes",{timeout:Math.max(f??0,60000)},async()=>{let{box:t}=await d(),s=Date.now();await t.files.write("watch/file","a");let o=Date.now()-s,i=[],r=t.files.watch("watch",(l)=>i.push(l.type),{recursive:!0,intervalMs:10}),p=0;try{await a.poll(async()=>(await t.files.write("watch/file",`different-${p++}`),i),{timeout:Math.max(1e4,20*o),interval:50}).toContain("modified")}finally{r()}}),c("process logs, cursors, fresh client reattach, stop and exit-before-ready",async(t)=>{if(n.unsupported?.processes){t.skip(n.unsupported.processes);return}let{box:s}=await d(),o=await s.start("echo READY; sleep 5",{name:"dev",ready:{log:/READY/},readyTimeoutMs:2000});a(o.ready).toBe(!0);let i=await o.logs();a(i.text).toContain("READY"),a((await o.logs({after:i.nextCursor})).text).toBe("");let r=await U(await g(),s.id);u.push(r),a((await r.processes()).map((p)=>p.name)).toContain("dev"),a((await r.process("dev").logs()).text).toContain("READY"),await r.process("dev").stop({graceMs:10}),a((await o.wait()).exitCode).not.toBe(null),await a(s.start("exit 3",{name:"early",ready:{log:/never/},readyTimeoutMs:1000})).rejects.toMatchObject({code:"process_exited"})}),c("readiness timeout preserves the process",async(t)=>{if(n.unsupported?.processes){t.skip(n.unsupported.processes);return}let{box:s}=await d();await a(s.start("sleep 5",{name:"unready",ready:{log:/never/},readyTimeoutMs:30})).rejects.toMatchObject({code:"timeout"}),a(s.process("unready").ready).toBe(!1),a((await s.processes())[0]?.status).toBe("running"),await s.process("unready").stop({graceMs:10})}),c("preview and capability gating",async()=>{let{provider:t,box:s}=await d();if(n.unsupported?.previews)await a(s.preview(3000)).rejects.toMatchObject({code:"unsupported"});else a(["http:","https:"]).toContain(new URL((await s.preview(3000)).url).protocol);for(let[o,i]of[["pause","pause"],["snapshot","snapshot"],["terminal","terminal"]])a(i in s).toBe(t.capabilities.has(o));if(!t.capabilities.has("network-policy"))await a(O(t,{network:"none"})).rejects.toMatchObject({code:"unsupported"});if(!t.capabilities.has("size"))await a(O(t,{size:"small"})).rejects.toMatchObject({code:"unsupported"})}),c("close, disposal, destroy and label-scoped reaping",async()=>{let{provider:t,box:s}=await d(),o=s.id;await s.close(),a((await U(t,o)).id).toBe(o),await s.destroy(),await a(U(t,o)).rejects.toMatchObject({code:"not_found"});let i=crypto.randomUUID(),r=await O(t,{key:i,labels:{reap:i}});u.push(r),await r[Symbol.asyncDispose](),a((await t.connect(r.id)).id).toBe(r.id),a(await re(t,{labels:{reap:i},olderThanMs:0})).toBe(1);let p=await O(t);await p[Symbol.asyncDispose](),await a(t.connect(p.id)).rejects.toMatchObject({code:"not_found"})}),c("usage counters",async()=>{let{box:t}=await d();await t.run("echo abc"),a(await t.usage()).toMatchObject({commands:1,bytesOut:4})}),c("local bare git clone, commit and push (live providers only)",async(t)=>{if(n.unsupported?.gitPush){t.skip(n.unsupported.gitPush);return}let{box:s}=await d();a((await s.run("git init --bare /tmp/sdk-bare")).ok).toBe(!0),a((await s.git.clone("/tmp/sdk-bare",{dir:"repo"})).ok).toBe(!0),await s.run("git config user.name Conformance; git config user.email test@example.com",{cwd:"repo"}),await s.files.write("repo/test","test"),a((await s.git.commit("repo",{message:"conformance",all:!0})).ok).toBe(!0),a((await s.git.status("repo")).stdout).toBe(""),a((await s.git.push("repo",{branch:"HEAD"})).ok).toBe(!0)}),c("real HTTP preview probe (live Linux providers only)",async(t)=>{let s=n.unsupported?.previews??n.unsupported?.httpProbe;if(s){t.skip(s);return}let{box:o}=await d(),i=await o.start(`node -e 'require("http").createServer((_,r)=>r.end("ok")).listen(3000,"0.0.0.0")'`,{name:"http",ready:{http:{port:3000}}});a(i.ready).toBe(!0),a((await o.preview(3000,{waitMs:2000})).url).toBeTruthy(),await i.stop()})})}function I(m){let n=[],f=m.snapshot;if(f)m.snapshot=(u,h)=>(n.push(h),f.call(m,u,h));return n}export{z as runConformance};
package/dist/tools.js CHANGED
@@ -1 +1 @@
1
- import{P,M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import"./chunk-23tjmd39.js";export{M as createSandboxTools,P as toolSchemas};
1
+ import{P,R}from"./chunk-c1wemt0y.js";import"./chunk-5gnqph3c.js";import"./chunk-6nf686jb.js";export{R as createSandboxTools,P as toolSchemas};
package/dist/types.d.ts CHANGED
@@ -45,7 +45,11 @@ export interface ListOptions {
45
45
  export interface ReapOptions extends ListOptions {
46
46
  /** Only destroy sandboxes at least this old, in milliseconds. Default: 0. */
47
47
  olderThanMs?: number;
48
- /** Skip sandboxes with an active SDK command or a running background process. */
48
+ /**
49
+ * Skip sandboxes with an active SDK command or a running background process. On adapters that scan `/proc`
50
+ * (E2B, Upstash), a process an SDK command left running also counts until it exits, and so does a process
51
+ * whose environment cannot be read.
52
+ */
49
53
  idleOnly?: boolean;
50
54
  }
51
55
  /** Per-command options for `box.run`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencoredev/sandbox-sdk",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "One TypeScript API for cloud and local sandboxes: E2B, Daytona, Vercel, Upstash, Docker, and more. Run commands, edit files, start servers, and give AI agents a sandbox.",
5
5
  "keywords": [
6
6
  "agent-tools",
@@ -1,8 +0,0 @@
1
- import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-xgxfy2n8.js";import{posix as q}from"node:path";var l={CI:"1",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",DEBIAN_FRONTEND:"noninteractive",TERM:"dumb",NO_COLOR:"1"},u=(t=".")=>q.resolve("/workspace",t),re="if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi",G=`trap 'rm -rf -- "$2"' EXIT
2
- (umask 077; mkdir -p "$2") || exit 1
3
- { { "$3" -c "$1" 3>&- 4>&-; printf '%s\\n' "$?" > "$2/status"; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat
4
- read -r code < "$2/status"
5
- exit "$code"`,z=(t,e,o="sh")=>`sh -c ${n(G)} sh ${n(t)} ${n(e)} ${n(o)}`,B=new Map,me=(t,e)=>(B.get(t)?.get(e)??0)>0;function F(t,e){let o=B.get(t);if(!o)o=new Map,B.set(t,o);let a=o;return a.set(e,(a.get(e)??0)+1),()=>{let h=(a.get(e)??1)-1;if(h)a.set(e,h);else a.delete(e);if(!a.size)B.delete(t)}}class A{limit;head=Buffer.alloc(0);tail=Buffer.alloc(0);total=0;constructor(t){this.limit=t}add(t){let e=Buffer.from(t);this.total+=e.length;let o=Math.ceil(this.limit/2),a=Math.min(e.length,o-this.head.length);if(a>0)this.head=Buffer.concat([this.head,e.subarray(0,a)]);if(this.tail=Buffer.concat([this.tail,e.subarray(Math.max(0,a))]),this.tail.length>this.limit-o)this.tail=this.tail.subarray(this.tail.length-(this.limit-o))}get truncated(){return this.total>this.limit}text(){if(!this.truncated)return Buffer.concat([this.head,this.tail]).toString();let t=new TextDecoder().decode(this.head,{stream:!0}),e=0;while(e<this.tail.length&&((this.tail[e]??0)&192)===128)e++;let o=this.tail.subarray(e).toString();return t+`
6
- [${this.total-Buffer.byteLength(t)-Buffer.byteLength(o)} bytes cut]
7
- `+o}}class J{listeners=new Set;ended=!1;failure;emit(t){for(let e of this.listeners)e(t)}fail(t){this.failure=t,this.end()}end(){this.ended=!0;for(let t of this.listeners)t()}async*stream(){let t=[],e=0,o=()=>{},a=(h)=>{if(h){let d=Buffer.byteLength(h.text)>1048576?Buffer.from(h.text).subarray(-1048576).toString():h.text;t.push({...h,text:d}),e+=Buffer.byteLength(d);while(e>1048576&&t.length>1)e-=Buffer.byteLength(t.shift()?.text??"")}o()};this.listeners.add(a);try{while(!this.ended||t.length){let h=t.shift();if(h)e-=Buffer.byteLength(h.text),yield h;else await new Promise((d)=>{o=d})}if(this.failure)throw this.failure}finally{this.listeners.delete(a)}}}function E(t,e,o=!1){let a=[];function h(d=!1){let b=t.secrets,w=new Set(b.map((i)=>i[0]));while(a.length){let i=a[0];if(!i)break;if(!w.has(i.text[0])){let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;if(e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r),!i.text)a.shift();continue}let v=a.flatMap((r)=>o||r.stream===i.stream?[r.text]:[]).join(""),y=b.find((r)=>v.startsWith(r));if(y){e({stream:i.stream,text:"[REDACTED]"});let r=y.length;for(let x of a)if((o||x.stream===i.stream)&&r){let g=Math.min(r,x.text.length);x.text=x.text.slice(g),r-=g}}else{if(!d&&b.some((x)=>x.startsWith(v))){if(a.reduce((x,g)=>x+Buffer.byteLength(g.text),0)<=1048576)break;e({stream:i.stream,text:"[REDACTED]"}),a.shift();continue}let r=1;while(r<i.text.length&&!w.has(i.text[r]))r++;e({stream:i.stream,text:i.text.slice(0,r)}),i.text=i.text.slice(r)}for(let r=a.length-1;r>=0;r--)if(!a[r]?.text)a.splice(r,1)}}return{push(d){if(!t.secrets.length){e(d);return}a.push({...d}),h()},flush(){h(!0)}}}function oe(t,e,o,a,h,d=()=>{}){return(b,w={})=>{let i={...w},v,y=new J,r=(c=!1)=>v??=x(c).catch((p)=>{let m=o.error(p,t.name,e);throw y.fail(m),m});async function x(c){await d();let p=i.timeoutMs??120000,m=i.maxOutputBytes??1048576;if(!Number.isFinite(p)||p<=0||!Number.isSafeInteger(m)||m<1)s("timeoutMs and maxOutputBytes must be positive");let D=u(i.cwd),N=Date.now(),O=new A(m),C=new A(m),S=new A(m*2),k=new AbortController,R=i.signal?.aborted??!1,_=()=>{R=!0,k.abort()};i.signal?.addEventListener("abort",_,{once:!0});let j=setTimeout(_,p),P=`/tmp/.sandbox-sdk/runs/${crypto.randomUUID()}`,I=!1,H=F(t.name,e),T=E(o,(f)=>{S.add(f.text),y.emit(f)},!0),L=E(o,(f)=>{(f.stream==="stdout"?O:C).add(f.text),T.push(f)});try{if(R)k.abort();let f=R?{exitCode:null,timedOut:!0}:await t.exec(e,{command:t.inlineActivity?b:z(b,P,t.commandShell),cwd:D,env:{...a,...i.env,...l},stdin:i.stdin,timeoutMs:p,signal:k.signal,streaming:c,envMode:i.env===void 0?"sandbox":void 0,activityPath:t.inlineActivity?P:void 0,onChunk:(M)=>L.push(M)});return I=f.exitCode!==null&&f.exitCode>=0&&f.exitCode<128&&!f.timedOut&&!k.signal.aborted,R||=f.timedOut,L.flush(),T.flush(),h(O.total+C.total),{ok:!R&&f.exitCode===0,exitCode:R?null:f.exitCode,stdout:O.text(),stderr:C.text(),output:S.text(),durationMs:Date.now()-N,truncated:O.truncated||C.truncated||S.truncated,timedOut:R,cwd:D,command:o.text(b)}}catch(f){L.flush(),T.flush();let M=o.error(f,t.name,e);throw y.fail(M),M}finally{if(clearTimeout(j),i.signal?.removeEventListener("abort",_),!I&&!t.inlineActivity)await Promise.resolve().then(()=>t.files.remove(e,P,{recursive:!0})).catch(()=>{});H(),y.end()}}let g={[Symbol.toStringTag]:"RunHandle",then(c,p){return r().then(c,p)},catch(c){return r().catch(c)},finally(c){return r().finally(c)},[Symbol.asyncIterator](){let c=y.stream(),p=c.next();r(!0).catch(()=>{});let m=!0;return{next:()=>{if(m)return m=!1,p;return c.next()},return:()=>c.return(void 0)}},cwd(c){if(v)s("Run already started");return i.cwd=c,g},env(c){if(v)s("Run already started");return i.env={...i.env,...c},g},timeout(c){if(v)s("Run already started");return i.timeoutMs=c,g}};return g}}
8
- export{l,u,re,me,A,J,E,oe};
@@ -1,2 +0,0 @@
1
- import{f}from"./chunk-9w9rddra.js";import{Y}from"./chunk-k60b4r27.js";import{t,r,e,D,w,c,fe,s}from"./chunk-xgxfy2n8.js";function Ze(o){return["localhost","127.0.0.1","[::1]"].includes(o)||/\.(test|invalid|example|localhost)$/.test(o)}function d(o,a){let u=Date.now()+o,p=AbortSignal.timeout(Math.max(0,o));return{signal:a?AbortSignal.any([a,p]):p,timeout:p,parent:a,remaining:()=>Math.max(0,u-Date.now())}}function y(o,a,u){return new Promise((p,g)=>{let E=()=>{clearTimeout(W),a.signal.removeEventListener("abort",C)},C=()=>{E(),g(We(a,u))},W=setTimeout(()=>{E(),p()},o);if(a.signal.aborted)C();else a.signal.addEventListener("abort",C,{once:!0})})}function Re(o,a){if(a.aborted)return Promise.reject(a.reason);return new Promise((u,p)=>{let g=()=>p(a.reason);a.addEventListener("abort",g,{once:!0}),o.then(u,p).finally(()=>a.removeEventListener("abort",g))})}function We(o,a,u){return o.parent?.aborted&&!o.timeout.aborted?new e("Request aborted. The signal was cancelled.",{code:"aborted",provider:a,sandboxId:u}):new e("Request timed out. The operation took too long.",{code:"timeout",provider:a,sandboxId:u,retryable:!0})}var _e=new WeakMap;function H(o){return o instanceof e?_e.get(o):void 0}var Xe=65536,Ye=33554432,Qe=20000,Ue=1e4,Ce=5,Le=new Set([429,502,503,504]),qe=new Set([301,302,303,307,308]),Se=new Set(["GET","HEAD","PUT","DELETE"]),et=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","UND_ERR_CONNECT_TIMEOUT","ConnectionRefused","FailedToOpenSocket","ERR_INVALID_URL","ERR_TLS_CERT_ALTNAME_INVALID","UNABLE_TO_VERIFY_LEAF_SIGNATURE","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED"]),tt=/^(?:authorization|proxy-authorization|cookie|x-api-key|api-key|apikey)$|[-_](?:token|key|secret|password)$/,nt=/^(?:x-)?idempotency-key$/,rt=/^\s*(?:bearer|basic|token|bot|digest)\s+(\S.*?)\s*$/i,ot=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,je=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/,at=/^[A-Za-z0-9_.:-]{1,128}$/;function De(o,a=0){if(!r(o)||a>3)return[];return[..."code"in o&&t(o.code)?[o.code]:[],...De("cause"in o?o.cause:void 0,a+1)]}function st(o){return typeof o==="string"||o instanceof Uint8Array||o instanceof ArrayBuffer||ArrayBuffer.isView(o)||o instanceof Blob||o instanceof FormData||o instanceof URLSearchParams||o instanceof ReadableStream}function it(o){let a=o.get("retry-after");if(a===null)return;if(/^\d+$/.test(a.trim()))return Number(a.trim())*1000;let u=Date.parse(a);return Number.isNaN(u)?void 0:Math.max(0,u-Date.now())}function he(o,a){if(!f(o))return;for(let u of a){let p=Object.hasOwn(o,u)?o[u]:void 0;if(t(p)&&p)return p}return}function ve(o){let a;try{a=o?JSON.parse(o):void 0}catch{a=void 0}let u=f(a)?a.error:void 0,p=he(a,["code","error_code","errorCode","type"])??he(u,["code","type"])??(t(u)&&je.test(u)?u:void 0),g=he(a,["message","detail","error_description","title"])??he(u,["message"])??(t(u)?u:void 0)??(a===void 0&&o.trim()?o.trim():void 0),E={text:o,json:a};if(p!==void 0)E.code=p;if(g!==void 0)E.message=g;return E}async function Ne(o,a,u){if(!o)return new Uint8Array;let p=o.getReader(),g=[],E=0;try{for(;;){let{done:ee,value:N}=await p.read();if(ee)break;if(E+N.byteLength>a){let O=u();if(g.push(N.subarray(0,a-E)),E=a,await p.cancel().catch(()=>{}),O)throw O;break}g.push(N),E+=N.byteLength}}finally{p.releaseLock()}let C=new Uint8Array(E),W=0;for(let ee of g)C.set(ee,W),W+=ee.byteLength;return C}var Pe=new TextDecoder;function dt(o,a,u,p){return{status:o,headers:a,body:u,text:()=>Pe.decode(u),json(){let g=Pe.decode(u);if(!g.trim())return;try{return JSON.parse(g)}catch{throw p("returned a body that is not JSON. Use fetch for text, bytes or streams")}}}}function x(o){let{provider:a,label:u}=o,p=o.timeoutMs??60000,g=o.retries??2,E=o.backoffMs??250,C=new Set,W=(n)=>{C.delete(n),C.add(n);for(let i of C){if(C.size<=256)break;C.delete(i)}},ee=(n)=>{if(!n)return;W(n);let i=rt.exec(n)?.[1];if(i)W(i)},N=(n)=>D(c([...C,...o.secrets?.()??[]])(n)),O=new Map,L=(n,i)=>{let l=i.toLowerCase();return O.get(n)?.has(l)===!0||tt.test(l)&&!nt.test(l)},S=new Map,X=o.planes;function oe(n){let i=n??o.defaultPlane,l=Object.hasOwn(X,i)?X[i]:void 0;if(!l)throw j(`Unknown plane "${String(i).slice(0,32)}". Use one of: ${Object.keys(X).join(", ")}`);return{name:i,plane:l}}function j(n,i){return new e(`${N(n)}. The request is invalid. Check the supplied options.`,{code:"invalid_argument",provider:a,sandboxId:i})}function me(n){let i=/^[a-z][a-z0-9+.-]*:/i.test(n.path)?"[absolute URL]":(n.path.split("?")[0]??"").slice(0,200);return`${n.method} ${D(i)}`}function Be(n){let i=n.params??{},l=new Set,m=n.path.replace(ot,(P,T)=>{if(!Object.hasOwn(i,T))throw j(`The path has a {${T}} placeholder but params.${T} is missing`,n.sandboxId);let A=String(i[T]);if(A===""||A==="."||A==="..")throw j(`params.${T} must not be empty, "." or ".."`,n.sandboxId);return l.add(T),encodeURIComponent(A)}),b=Object.keys(i).filter((P)=>!l.has(P));if(b.length)throw j(`params.${b[0]} has no {${b[0]}} placeholder in the path`,n.sandboxId);return m}function Fe(n,i){let l=Be(i),m;if(/^[a-z][a-z0-9+.-]*:/i.test(l)){try{m=new URL(l)}catch{throw j("The path is not a valid URL",i.sandboxId)}if(m.protocol!=="https:"&&m.protocol!=="http:")throw j("Only http and https URLs are supported",i.sandboxId)}else{if(!l.startsWith("/"))throw j('The path must start with "/" or be an absolute URL',i.sandboxId);if(l.split("?")[0]?.split("/").some((b)=>b==="."||b===".."))throw j('The path must not contain "." or ".." segments',i.sandboxId);m=new URL(n.replace(/\/+$/,"")+l)}for(let[b,P]of Object.entries(i.query??{}))if(P!==void 0)m.searchParams.append(b,String(P));return m}function I(n,i,l,m,b=n==="unavailable"||n==="quota"){let P=n==="auth"?o.authHint:void 0;return new e(N(`${u} ${me(i)} failed${l}`),{code:n,provider:a,sandboxId:i.sandboxId,retryable:b,hint:P,cause:m===void 0?void 0:N(m)})}function B(n,i,l,m=!1){let b=Ve(n,i,l,m),P=o.cause?.(n,{method:i.method,plane:l,operation:me(i),sandboxId:i.sandboxId});if(P===void 0)return b;return new e(b.message,{code:b.code,provider:a,sandboxId:b.sandboxId,retryable:b.retryable,hint:b.hint,cause:P})}function Ve(n,i,l,m){let b=!Se.has(i.method)&&!i.readOnly,P=o.mapError?.(n,{method:i.method,plane:l,operation:me(i),sandboxId:i.sandboxId});switch(n.kind){case"status":{let T=P??fe(n.status);if(b&&(T==="timeout"||m))T="outcome_unknown";let A=n.body.code!==void 0&&je.test(n.body.code)?` ${n.body.code}`:"",ae=["x-request-id","request-id","x-amzn-requestid","cf-ray"].map((Q)=>n.headers.get(Q)).find((Q)=>Q!==null&&at.test(Q)),F=`HTTP ${n.status}${A}`,J=i.detail==="message"&&n.body.message?`: ${D(N(n.body.message)).slice(0,300)}`:"",te=`${F}${ae?` (request ${ae})`:""}${J}`,Z=I(T,i,` (${F})${J}.${T==="outcome_unknown"?" The request may or may not have taken effect; check before repeating it.":""}`,te,T==="unavailable"||T==="quota"||T==="timeout");return _e.set(Z,A?{status:n.status,code:A.trim()}:{status:n.status}),Z}case"network":{let T=w(n.error,N);if(b&&n.sent)return I(P??"outcome_unknown",i,": the connection failed after the request was sent, so it may or may not have taken effect. Check before repeating it.",T,!1);return I(P??"unavailable",i,`: ${n.sent?"the connection failed":"the service is unreachable"}.`,T,!0)}case"timeout":if(b&&n.sent)return I(P??"outcome_unknown",i,": no response before the deadline, so it may or may not have taken effect. Check before repeating it.",void 0,!1);return I(P??"timeout",i,": no response before the deadline.",void 0,!0);case"aborted":return I(P??"aborted",i,": the signal was cancelled.",void 0,!1);default:return n}}function ze(n){if(n.body===void 0)return{body:void 0,replayable:!0};if(n.method==="GET"||n.method==="HEAD")throw j(`A ${n.method} request cannot have a body`,n.sandboxId);if(st(n.body))return{body:n.body,replayable:!(n.body instanceof ReadableStream)};return{body:JSON.stringify(n.body),contentType:"application/json",replayable:!0}}async function Ee(n,i){let{name:l,plane:m}=oe(n.plane),{body:b,contentType:P,replayable:T}=ze(n),A=!Se.has(n.method),ae=T&&(!A||n.idempotencyKey!==void 0),{signal:F}=i,J={signal:F};if(n.sandboxId!==void 0)J.sandboxId=n.sandboxId;let te=o.fetch??((z,G)=>globalThis.fetch(z,G)),Z=`${l}\x00${n.sandboxId??""}`,Q=!1,V=()=>i.parent?.aborted&&!i.timeout.aborted?{kind:"aborted"}:F.aborted?{kind:"timeout",sent:!1}:void 0,se=async(z)=>{try{return Pe.decode(await Ne(z.body,Xe,()=>{return}))}catch{let G=V();if(G)throw B(G,n,l);return""}};for(let z=0;;z++){let G=V();if(G)throw B(G,n,l);let ge,de,{baseUrl:ye,auth:He}=m;try{ge=t(ye)?ye:await Re(Promise.resolve().then(()=>ye(J)),F),de=n.auth===!1||!He?{}:await Re(Promise.resolve().then(()=>He(J)),F)}catch(U){if(U instanceof e)throw U;let M=V();if(M)throw B(M,n,l);throw I("auth",n,`: resolving ${u} credentials failed.`,w(U,N),!1)}let $e=V();if($e)throw B($e,n,l);let we=O.get(l);if(!we)O.set(l,we=new Set);for(let[U,M]of Object.entries(de))we.add(U.toLowerCase()),ee(M);let Ge=S.get(Z)?.generation??0,ue,le;try{le=new URL(ge)}catch{throw I("provider",n,`: the ${u} base URL is invalid.`,void 0,!1)}if(ue=le.origin,Object.keys(de).length>0&&le.protocol==="http:"&&!Ze(le.hostname))throw I("invalid_argument",n,`: the ${u} base URL uses plain HTTP, which would send credentials unencrypted. Use an https URL.`,void 0,!1);let ne=Fe(ge,n),ke=n.method,pe=b,R,q;for(let U=0;;U++){let M=new Headers(P&&pe!==void 0?{...m.headers,"content-type":P}:m.headers);if(n.idempotencyKey!==void 0&&o.idempotencyHeader)M.set(o.idempotencyHeader,n.idempotencyKey);if(ne.origin===ue)for(let[K,re]of Object.entries(de))M.set(K,re);for(let[K,re]of Object.entries(n.headers??{}))M.set(K,re);if(ne.origin!==ue){for(let K of Array.from(M.keys()))if(L(l,K))M.delete(K)}for(let[K,re]of M)if(L(l,K))ee(re);let ce={method:ke,headers:M,body:pe,signal:F,redirect:"manual"};if(pe instanceof ReadableStream)ce.duplex="half";try{R=await te(ne.href,ce)}catch(K){R=void 0;let re=V();q=re?.kind==="timeout"?{kind:"timeout",sent:!0}:re??{kind:"network",sent:!De(K).some((Ke)=>et.has(Ke)),error:K};break}let Ie=R.headers.get("location");if(!qe.has(R.status)||Ie===null)break;if(await R.body?.cancel().catch(()=>{}),U>=Ce)throw I("provider",n,`: more than ${Ce} redirects.`,void 0,!1);try{ne=new URL(Ie,ne)}catch{throw I("provider",n,": the redirect location is invalid.",void 0,!1)}if(ne.protocol!=="https:"&&ne.protocol!=="http:")throw I("provider",n,": the redirect left http and https.",void 0,!1);if(R.status===303||(R.status===301||R.status===302)&&ke==="POST")ke="GET",pe=void 0;else if(!T)throw I("provider",n,": the server redirected a streamed upload, which cannot be sent twice.",void 0,!1)}let Ae=R!==void 0&&m.refresh!==void 0&&!Q&&T&&n.auth!==!1&&ne.origin===ue,ie;if(Ae&&m.stale&&R&&R.status>=400&&R.status!==401)ie=ve(await se(R));let Me=!Ae||!R?void 0:R.status===401?"refused":ie!==void 0?m.stale?.({status:R.status,body:ie,credentials:de},J):void 0;if(Me!==void 0&&m.refresh&&R){if(ie===void 0)await R.body?.cancel().catch(()=>{});Q=!0;let U=S.get(Z)??{generation:0};if(S.set(Z,U),U.generation===Ge){U.pending??=m.refresh(J).then(()=>{U.generation++}).finally(()=>{U.pending=void 0});try{await Re(U.pending,F)}catch(M){let ce=V();if(ce)throw B(ce,n,l);if(M instanceof e)throw M;throw I("auth",n,`: refreshing ${u} credentials failed.`,w(M,N),!1)}}if(Me==="refused"||ae){z--;continue}throw B({kind:"status",status:R.status,headers:R.headers,body:ie??ve("")},n,l,!0)}let Oe;if(R&&R.status>=200&&R.status<300)return R;if(R){let U=ie??ve(await se(R));if(q={kind:"status",status:R.status,headers:R.headers,body:U},Le.has(R.status)){let M=it(R.headers);Oe=M===void 0?void 0:M<=Qe?M:1/0}if(!Le.has(R.status))throw B(q,n,l)}if(!q)throw new e(`${u} request produced no response`,{code:"provider",provider:a});if(q.kind==="aborted"||q.kind==="timeout")throw B(q,n,l);let xe=Oe??E*2**z*(0.5+Math.random()/2);if(!ae||z>=g||xe===1/0||xe>=i.remaining())throw B(q,n,l);try{await y(xe,i,a)}catch{throw B(V()??q,n,l)}}}async function be(n){let i=n.deadline??d(n.timeoutMs??p,n.signal),l=await Ee(n,i),m=n.maxBytes??Ye,b;try{b=await Ne(l.body,m,()=>I("unsupported",n,`: the response is larger than ${m} bytes.`,void 0,!1))}catch(P){if(P instanceof e)throw P;let{name:T}=oe(n.plane);if(i.parent?.aborted&&!i.timeout.aborted)throw B({kind:"aborted"},n,T);throw B(i.signal.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:P},n,T)}return dt(l.status,l.headers,b,(P)=>I("provider",{...n,detail:"status"},` (HTTP ${l.status}): the response ${P}.`,void 0,!1))}async function Je(n){let i=n.deadline??(n.timeoutMs===void 0?d(2147483647,n.signal):d(n.timeoutMs,n.signal)),l=d(n.startupTimeoutMs??p),m=new AbortController,b=()=>m.abort(),P=AbortSignal.any([i.signal,l.signal]);if(P.addEventListener("abort",b,{once:!0}),P.aborted)b();let T={signal:m.signal,timeout:i.timeout,parent:i.parent,remaining:()=>Math.min(i.remaining(),l.remaining())},A;try{A=await Ee(n,T)}finally{P.removeEventListener("abort",b)}if(!A.body||A.status===204||A.status===205)return A;i.signal.addEventListener("abort",b,{once:!0});let{name:ae}=oe(n.plane),F=A.body.getReader(),J,te=!1,Z=()=>{clearTimeout(J),i.signal.removeEventListener("abort",b)},Q=new ReadableStream({async pull(V){if(n.idleTimeoutMs!==void 0)J=setTimeout(()=>{te=!0,F.cancel().catch(()=>{}),m.abort()},n.idleTimeoutMs);try{let{done:se,value:z}=await F.read();if(clearTimeout(J),te)throw Error("idle");if(se){Z(),V.close();return}V.enqueue(z)}catch(se){Z();let z=i.parent?.aborted&&!i.timeout.aborted?{kind:"aborted"}:te||i.timeout.aborted?{kind:"timeout",sent:!0}:{kind:"network",sent:!0,error:se},G=!Se.has(n.method)&&!n.readOnly;V.error(te&&z.kind==="timeout"?I(G?"outcome_unknown":"timeout",n,`: no data for ${n.idleTimeoutMs} ms${G?", so its result is unconfirmed. Check before repeating it.":"."}`,void 0,!G):B(z,n,ae))}},async cancel(V){Z(),await F.cancel(V).catch(()=>{}),m.abort()}},{highWaterMark:0});return new Response(Q,{status:A.status,statusText:A.statusText,headers:A.headers})}return{provider:a,label:u,redact:N,request:be,async json(n){return(await be(n)).json()},stream:Je,cleanup(n){let{signal:i,deadline:l,...m}=n;return be({...m,timeoutMs:Math.min(n.timeoutMs??Ue,Ue)})}}}function Te(o){return o instanceof Function||r(o)&&!Array.isArray(o)}function _(o,a,u){if(!Te(o))s(`${a} from ${u} is not an object. Install a supported version of ${u}`);return o}var ct=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE"]);function h(o){let{http:a,placeholder:u,sandboxId:p,sdk:g}=o,E=t(u)?[u]:u;function C(O,L,S={}){if(!t(O)||!ct.has(O))s(`Unsupported HTTP method ${String(O).slice(0,16)}`);if(!t(L))s("The path must be a string");let X=E.filter((j)=>L.includes(`{${j}}`)&&S.params?.[j]===void 0),oe=p===void 0||X.length===0?S.params:{...S.params,...Object.fromEntries(X.map((j)=>[j,p]))};return{method:O,path:L,plane:S.plane,sandboxId:p,params:oe,query:S.query,body:S.body,headers:S.headers,signal:S.signal,timeoutMs:S.timeoutMs,detail:"message"}}async function W(O){if(!g)throw new e(`${a.label} has no official SDK binding. Use native.request or native.fetch.`,{code:"unsupported",provider:a.provider,sandboxId:p});if(!(O instanceof Function))s(`Pass a function that imports the SDK: native.sdk(() => import("${g.package}"))`);let L;try{L=Y(await O())}catch(S){if(S instanceof Error&&(("code"in S)&&(S.code==="ERR_MODULE_NOT_FOUND"||S.code==="MODULE_NOT_FOUND")||/Cannot find (?:package|module)/.test(S.message)))throw new e(`${g.package} could not be imported. Install it next to @opencoredev/sandbox-sdk to use native.sdk().`,{code:"unavailable",provider:a.provider,sandboxId:p,hint:`npm i ${g.package}`,cause:w(S,a.redact)});throw new e(`Loading ${g.package} failed: ${w(S,a.redact)??"a non-Error value was thrown"}. Check the import passed to native.sdk().`,{code:"provider",provider:a.provider,sandboxId:p})}if(!Te(L)||Array.isArray(L))s(`native.sdk() needs the module object. Pass () => import("${g.package}")`);try{return await g.connect(L,p)}catch(S){if(S instanceof e)throw S;throw new e(`${g.package} failed in native.sdk(): ${w(S,a.redact)??"a non-Error value was thrown"}. Check the SDK version and the sandbox.`,{code:"provider",provider:a.provider,sandboxId:p,cause:w(S,a.redact)})}}return{sandboxId:p,async request(O,L,S){return await a.json(C(O,L,S))},fetch(O,L,S){let{timeoutMs:X,...oe}=C(O,L,S);return a.stream({...oe,startupTimeoutMs:X})},sdk:W}}function v(o,a,u,p){let g=o[a];if(!(g instanceof Function))s(`The module passed to native.sdk() has no ${a} export. Pass () => import("${p}")`);try{return _(Reflect.construct(g,u),a,p)}catch(E){if(E instanceof TypeError&&/constructor/i.test(E.message))s(`${a} from the module passed to native.sdk() is not a class. Pass () => import("${p}")`);throw E}}async function k(o,a,u,p){let g=Te(o)?o[a]:void 0;if(!(g instanceof Function))s(`The ${p} object has no ${a} method. Install a supported version of ${p}`);return await g.apply(o,u)}
2
- export{d,y,H,x,_,h,v,k};