@opencoredev/sandbox-sdk 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/ai.js +1 -1
- package/dist/chunk-11mbpwem.js +17 -0
- package/dist/{chunk-q5vqajhg.js → chunk-19gteae8.js} +2 -2
- package/dist/chunk-1k6yz176.js +1 -0
- package/dist/chunk-2z6fxyg5.js +2 -0
- package/dist/chunk-305dymgq.js +2 -0
- package/dist/chunk-348pdz09.js +5 -0
- package/dist/{chunk-k60b4r27.js → chunk-3zd78ha4.js} +2 -2
- package/dist/chunk-5gnqph3c.js +78 -0
- package/dist/chunk-6bemkxcx.js +290 -0
- package/dist/chunk-6nf686jb.js +26 -0
- package/dist/{chunk-nw845a93.js → chunk-c1wemt0y.js} +8 -8
- package/dist/{chunk-bd481sb7.js → chunk-drgkmewv.js} +1 -1
- package/dist/chunk-ea8y7y2p.js +2 -0
- package/dist/chunk-g0vk7g1k.js +2 -0
- package/dist/chunk-n7x9ha44.js +4 -0
- package/dist/{chunk-8786zrns.js → chunk-r8xnq6v3.js} +2 -2
- package/dist/{chunk-hzbssbep.js → chunk-rnksrxfc.js} +4 -4
- package/dist/chunk-tvw3kb8b.js +2 -0
- package/dist/http.d.ts +3 -0
- package/dist/index.js +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.js +1 -1
- package/dist/openai.js +1 -1
- package/dist/provider.d.ts +25 -0
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/index.js +11 -13
- package/dist/providers/daytona/index.js +15 -15
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/freestyle/execute.d.ts +3 -1
- package/dist/providers/freestyle/index.js +6 -15
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/execute.d.ts +3 -1
- package/dist/providers/superserve/index.js +21 -23
- package/dist/providers/tenki/index.js +14 -24
- package/dist/providers/upstash/index.js +10 -10
- package/dist/providers/upstash/provider.d.ts +1 -1
- package/dist/providers/vercel/index.js +1 -1
- package/dist/run.d.ts +9 -0
- package/dist/shared/guest.d.ts +28 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +5 -1
- package/package.json +1 -1
- package/dist/chunk-23tjmd39.js +0 -8
- package/dist/chunk-83avbjns.js +0 -2
- package/dist/chunk-8wq767xb.js +0 -17
- package/dist/chunk-9w9rddra.js +0 -2
- package/dist/chunk-ch71kvcp.js +0 -2
- package/dist/chunk-ckym4cht.js +0 -23
- package/dist/chunk-hgrwyjrb.js +0 -2
- package/dist/chunk-kk1hw8wa.js +0 -1
- package/dist/chunk-x2skgx3m.js +0 -5
- package/dist/chunk-x681p5d2.js +0 -68
- package/dist/chunk-xgxfy2n8.js +0 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
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
|
-
`,
|
|
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
|
|
77
|
-
`),
|
|
78
|
-
`))>=0)
|
|
79
|
-
`,I="",
|
|
80
|
-
' '${O.trimEnd()}' && cd "$1" && exec sh -c "$2"`,"sh",f.cwd,f.command]:["sh","-c",f.command],cwd:
|
|
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
|
|
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
|
|
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;
|
package/dist/shared/guest.d.ts
CHANGED
|
@@ -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
|
-
|
|
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{
|
|
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
|
|
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=
|
|
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,
|
|
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
|
-
/**
|
|
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.
|
|
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",
|
package/dist/chunk-23tjmd39.js
DELETED
|
@@ -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};
|
package/dist/chunk-83avbjns.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t,r,e,w}from"./chunk-xgxfy2n8.js";var A=new WeakMap;function z(s){return s instanceof e?A.get(s):void 0}var C={disconnected:"unavailable",truncated:"unavailable",frame_too_large:"unsupported",malformed:"provider"};function h(s,a,d,n){let i=new e(`${a}. The stream from ${d.provider} cannot be read further.`,{code:C[s],provider:d.provider,sandboxId:d.sandboxId,retryable:s==="disconnected"||s==="truncated",...n===void 0?void 0:{cause:w(n)??s}});return A.set(i,s),i}class S{chunks=[];head=0;length=0;push(s){if(s.byteLength)this.chunks.push(s),this.length+=s.byteLength}find(s,a=0){let d=0;for(let n=0;n<this.chunks.length;n++){let i=this.chunks[n],l=n===0?this.head:0,u=i.byteLength-l;if(a<d+u){for(let o=Math.max(l,l+a-d);o<i.byteLength;o++)if(s(i[o]))return d+o-l}d+=u}return-1}at(s){let a=s;for(let d=0;d<this.chunks.length;d++){let n=this.chunks[d],i=d===0?this.head:0;if(a<n.byteLength-i)return n[i+a];a-=n.byteLength-i}return}take(s){let a=new Uint8Array(s),d=0;while(d<s){let n=this.chunks[0],i=Math.min(s-d,n.byteLength-this.head);if(a.set(n.subarray(this.head,this.head+i),d),d+=i,this.head+=i,this.head===n.byteLength)this.chunks.shift(),this.head=0}return this.length-=s,a}}async function*k(s,a){let d=s.getReader(),{signal:n}=a,i=!1,l=()=>{d.cancel(n?.reason).catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{if(n?.aborted)throw v(a);for(;;){let u;try{u=await d.read()}catch(o){if(i=!0,n?.aborted)throw v(a);if(o instanceof e){if(o.code==="unavailable"||o.code==="outcome_unknown")A.set(o,"disconnected");throw o}throw h("disconnected","The connection dropped mid-stream",a,o)}if(n?.aborted)throw i=!0,v(a);if(u.done){i=!0;return}yield u.value}}finally{if(n?.removeEventListener("abort",l),!i)await d.cancel().catch(()=>{});d.releaseLock()}}function v(s){return new e("Stream aborted. The signal was cancelled.",{code:"aborted",provider:s.provider,sandboxId:s.sandboxId})}var p=new TextDecoder;var O=16777216;async function*ie(s,a){let d=a.maxFrameBytes??O,n=new S,i=(l,u)=>{let o=p.decode(l).replace(/\r$/,"");try{return JSON.parse(o)}catch{throw u?h("truncated","The stream ended inside a JSON line",a):h("malformed","A line is not valid JSON",a)}};for await(let l of k(s,a)){let u=n.length;n.push(l);for(let o=n.find((f)=>f===10,u);o>=0;o=n.find((f)=>f===10)){if(o>d)throw h("frame_too_large",`A JSON line exceeds ${d} bytes`,a);let f=n.take(o+1).subarray(0,o);if(f.some((c)=>c!==13&&c!==32&&c!==9))yield i(f,!1)}if(n.length>d)throw h("frame_too_large",`A JSON line exceeds ${d} bytes`,a)}if(n.length){let l=n.take(n.length);if(l.some((u)=>u!==13&&u!==32&&u!==9))yield i(l,!0)}}async function*ae(s,a){let d=a.maxFrameBytes??O,n=new S,i=k(s,a),l=async(f)=>{while(n.length<f){let c=await i.next();if(c.done)return!1;n.push(c.value)}return!0};try{for(let f=!1;;){if(!await l(5)){if(n.length)throw h("truncated","The stream ended inside a Connect frame header",a);if(!f)throw h("truncated","The stream ended before the Connect end-of-stream frame",a);return}if(f)throw h("malformed","A Connect frame followed the end-of-stream frame",a);let c=n.take(5),b=c[0],m=new DataView(c.buffer,c.byteOffset,5).getUint32(1);if(b&1)throw h("malformed","A Connect frame is compressed, but no compression was negotiated",a);if(b&-4)throw h("malformed","A Connect frame has unknown flags",a);if(m>d)throw h("frame_too_large",`A Connect frame exceeds ${d} bytes`,a);if(!await l(m))throw h("truncated","The stream ended inside a Connect frame",a);let g=u(n.take(m));if(b&2)f=!0,yield o(g);else yield{kind:"message",message:g}}}finally{await i.return()}function u(f){try{return JSON.parse(p.decode(f))}catch{throw h("malformed","A Connect frame is not valid JSON",a)}}function o(f){if(!r(f)||f===null)throw h("malformed","The Connect end-of-stream frame is not an object",a);let c="error"in f?f.error:void 0,b="metadata"in f?f.metadata:void 0,m={kind:"end"};if(c!==void 0){if(!r(c)||c===null)throw h("malformed","The Connect end-of-stream error is not an object",a);let g="code"in c?c.code:void 0,y="message"in c?c.message:void 0,x="details"in c?c.details:void 0;if(!t(g))throw h("malformed","The Connect end-of-stream error has no code",a);m.error={code:g,...t(y)?{message:y}:void 0,...Array.isArray(x)?{details:x}:void 0}}if(r(b)){let g=Object.entries(b).filter((y)=>Array.isArray(y[1])&&y[1].every((x)=>t(x)));m.metadata=Object.fromEntries(g)}return m}}function de(s,a=!1){let d=new TextEncoder().encode(JSON.stringify(s)),n=new Uint8Array(5+d.byteLength);return n[0]=a?2:0,new DataView(n.buffer).setUint32(1,d.byteLength),n.set(d,5),n}
|
|
2
|
-
export{z,ie,ae,de};
|
package/dist/chunk-8wq767xb.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{l,u,re,E,oe}from"./chunk-23tjmd39.js";import{f}from"./chunk-9w9rddra.js";import{V,G,Z,ce}from"./chunk-hgrwyjrb.js";import{K,ee,le}from"./chunk-ckym4cht.js";import{n}from"./chunk-2ts3evzh.js";import{t,o,e,C,s}from"./chunk-xgxfy2n8.js";function Oe(r,i,m){async function y(p,x,k){if(!x)return await r(`git ${p}`,{cwd:k});m.add([x]);let O=`/tmp/.sandbox-sdk/credential-${crypto.randomUUID()}`,N=`#!/bin/sh
|
|
2
|
-
if [ "$1" = get ]; then printf 'username=x-access-token\\npassword='; cat ${n(O+".token")}; printf '\\n'; fi
|
|
3
|
-
`;await r(`umask 077; mkdir -p /tmp/.sandbox-sdk; cat > ${n(O+".token")}; printf '%s' ${n(N)} > ${n(O)}`,{stdin:x});let j=()=>Promise.all([K(i,O),K(i,O+".token")]),M;try{M=await r(`git -c credential.helper= -c ${n(`credential.helper=!sh ${n(O)}`)} ${p}`,{cwd:k})}catch(A){throw await j().catch(()=>{}),A}return await j(),M}return{clone:(p,x={})=>y(`clone ${x.branch?`--branch ${n(x.branch)} `:""}${x.depth?`--depth ${n(String(x.depth))} `:""}-- ${n(p)} ${n(x.dir??"app")}`,x.token),status:(p)=>Promise.resolve(r("git status --porcelain",{cwd:p})),diff:(p)=>Promise.resolve(r("git diff",{cwd:p})),commit:async(p,x)=>{if(x.all)await r("git add -A",{cwd:p});return await r(`git commit -m ${n(x.message)}${x.author?` --author=${n(x.author)}`:""}`,{cwd:p})},push:(p,x={})=>y(`push -- ${n(x.remote??"origin")}${x.branch?` ${n(x.branch)}`:""}`,x.token,p),checkout:(p,x)=>Promise.resolve(r(`git checkout ${x.create?"-b ":""}${n(x.branch)}`,{cwd:p}))}}import{posix as Fe}from"node:path";function Me(r){let i=[],m=r.stream==="stdout"?"O":"E",y=r.text.split(`
|
|
4
|
-
`);for(let p=0;p<y.length;p++){let x=y[p]??"",k=p<y.length-1;for(let O=0;O<x.length;){let N=Math.min(x.length,O+8192),j=x.charCodeAt(N-1);if(N<x.length&&j>=55296&&j<=56319)N--;i.push((k&&N===x.length?m:m.toLowerCase())+x.slice(O,N)+`
|
|
5
|
-
`),O=N}if(!x&&k)i.push(m+`
|
|
6
|
-
`)}return i}function Ie(r,i,m,y){let p=Buffer.from(r.buffer,r.byteOffset,r.byteLength),x=[],k=Math.min(i,p.length),O=0;while(k<p.length&&O<m){let N=k===0?0:p.lastIndexOf(10,k-1)+1,j=p[N];if(k===N)k++;let M=p.indexOf(10,k);if(M<0)break;let A=Math.min(M,k+m-O),F=(ae)=>((p[ae]??0)&192)===128;while(A>k&&A<M&&F(A))A--;if(A===k&&k<M){if(O)break;A++;while(A<M&&F(A))A++}let U=p.subarray(k,A).toString();if(O+=A-k,k=A,k===M&&(j===79||j===69)&&O<m)U+=`
|
|
7
|
-
`,O++,k++;else if(k===M&&j!==79&&j!==69)k++;x.push({stream:j===69||j===101?"stderr":"stdout",text:U,cursor:String(y+k)})}return{events:x,offset:k}}function Pe(r){let i=JSON.parse(r);if(!f(i))s("Invalid process record");let{command:m,startedAt:y,port:p}=i;if(!t(m)||!o(y))s("Invalid process record");return{command:m,startedAt:y,port:o(p)?p:void 0}}function Ne(r,i){let m=JSON.parse(r);if(!f(m))s("Invalid process restart record");let{command:y,cwd:p,env:x,readyTimeoutMs:k,readiness:O}=m,N={name:i};if(t(p))N.cwd=p;if(f(x)){N.env={};for(let[j,M]of Object.entries(x))if(t(M))N.env[j]=M}if(o(k))N.readyTimeoutMs=k;if(f(O)){let{log:j,flags:M,port:A,http:F}=O;if(t(j))N.ready={log:new RegExp(j,t(M)?M:"")};else if(o(A))N.ready={port:A};else if(f(F)&&o(F.port))N.ready={http:{port:F.port,path:t(F.path)?F.path:void 0}}}return{command:t(y)?y:void 0,options:N}}function ve(r){let i={stdout:"",stderr:""};if(r===void 0||/^\d+$/.test(r))return{offset:r,pending:i};if(Buffer.byteLength(r)>1048576)s("Invalid line cursor");let m;try{m=JSON.parse(r)}catch{s("Invalid line cursor")}if(!f(m))s("Invalid line cursor");let{v:y,offset:p,stdout:x,stderr:k}=m;if(y!==1||!t(p)||!/^\d+$/.test(p)||!Number.isSafeInteger(Number(p))||!t(x)||!t(k)||Buffer.byteLength(x)>65536||Buffer.byteLength(k)>65536)s("Invalid line cursor");return{offset:p,pending:{stdout:x,stderr:k}}}var me={missing:66,running:73,badCwd:74};function $e(r){return{dir:n(r),spec:n(`${r}/spec.json`),restart:n(`${r}/restart.json`),base:n(`${r}/base`),log:n(`${r}/out.log`),rotate:n(`${r}/rotate`),exit:n(`${r}/exit`),pid:n(`${r}/pid`),lock:n(`${r}/lock`),stdout:n(`${r}/stdout`),stderr:n(`${r}/stderr`)}}function Re(r){return["lock_me=$$","read -r lock_me _ 2>/dev/null < /proc/self/stat","lock_idle=0",`until mkdir ${r} 2>/dev/null && : > ${r}/"$lock_me"`,"do lock_owner=",`for lock_entry in ${r}/*`,'do [ -e "$lock_entry" ] && lock_owner=${lock_entry##*/}',"done",'if [ -n "$lock_owner" ]',"then lock_idle=0","if [ -r /proc/self/stat ]","then lock_state=Z",'read -r _ _ lock_state _ 2>/dev/null < /proc/"$lock_owner"/stat','elif kill -0 "$lock_owner" 2>/dev/null',"then lock_state=S","else lock_state=Z","fi",`case "$lock_state" in Z|X) rm ${r}/"$lock_owner" 2>/dev/null && rmdir ${r} 2>/dev/null;; esac`,`elif [ -d ${r} ]`,"then lock_idle=$((lock_idle+1))",`[ "$lock_idle" -lt 100 ] || { rmdir ${r} 2>/dev/null; lock_idle=0; }`,"fi","sleep .01","done"]}function Ce(r){return`rm ${r}/"$lock_me" 2>/dev/null && rmdir ${r}`}function Ee(r){let i=$e(r.dir);return[`[ -f ${i.spec} ] || exit ${me.missing}`,`cat ${i.spec} || exit 1`,"printf '\\000'",...Re(i.lock),`trap ${n(Ce(i.lock))} EXIT`,`b=$(cat ${i.base})`,`n=$(wc -c < ${i.log})`,`a=${r.after??'"$b"'}`,`s=$((a-b-${r.lookbehind}))`,'[ "$s" -ge 0 ] || s=0',"e=running",`if [ -f ${i.exit} ]`,`then e=$(cat ${i.exit})`,"fi",`printf '%s %s %s %s\\n' "$b" "$s" "$n" "$e"`,`dd if=${i.log} bs=1 skip="$s" count=${r.length} 2>/dev/null | base64`].join("; ")}function Te(r){let i=$e(r.dir);return[`mkdir -p ${i.dir} || exit 1`,...Re(i.lock),`trap ${n(Ce(i.lock))} EXIT`,`if [ -f ${i.spec} ] && [ ! -f ${i.exit} ]`,`then exit ${me.running}`,"fi","b=0",`if [ -f ${i.base} ]`,`then b=$(cat ${i.base})`,`n=$(wc -c < ${i.log})`,"b=$((b+n))","fi",`IFS= read -r s && IFS= read -r r && printf '%s' "$s" | base64 -d > ${i.spec} && (umask 077; printf '%s' "$r" | base64 -d > ${i.restart}) && : > ${i.log} && printf '%s' "$b" > ${i.base} && rm -f ${i.exit} || exit 1`,`m=$(cd ${n(r.cwd)} 2>&1) && exit 0`,"c=$?",`printf '%s
|
|
8
|
-
' "$m" | sed 's/^/E/' > ${i.log}`,`printf 0 > ${i.pid}`,`printf '%s' "$c" > ${i.exit}`,`exit ${me.badCwd}`].join("; ")}function Le(r){let i=[];for(let m of r.flatMap((y)=>y.split(`
|
|
9
|
-
`))){if(!m)continue;i.push(`s|${Se(m)}|[REDACTED]|g`);for(let y=0;y<m.length-1;y++)i.push(`s|${Se(m.slice(0,m.length-1-y))}$|[REDACTED]|`),i.push(`s|^${Se(m.slice(y+1))}|[REDACTED]|`)}return i.join(`
|
|
10
|
-
`)+`
|
|
11
|
-
`}function Se(r){return r.replace(/[\\[\].*^$|]/g,"\\$&")}function Je(r){let i=$e(r);return`append() { ${[...Re(i.lock),`printf '%s%s\\n' "$1" "$2" >> ${i.log}`,`n=$(wc -c < ${i.log})`,'if [ "$n" -gt 10485760 ]',`then tail -c 5242880 ${i.log} | tail -n +2 > ${i.rotate}`,`kept=$(wc -c < ${i.rotate})`,`b=$(cat ${i.base})`,`echo $((b+n-kept)) > ${i.base}`,`mv ${i.rotate} ${i.log}`,"fi",Ce(i.lock)].join("; ")}; };`}function je(r){return["(nl=$(printf '\\nX')","nl=${nl%X}","while :","do chunk=$(dd bs=4096 count=1 2>/dev/null; printf .)","chunk=${chunk%.}",'[ -n "$chunk" ] || break',"need=0",`for byte in $(printf '%s' "$chunk" | tail -c 4 | od -An -tu1)`,'do if [ "$byte" -ge 240 ]',"then need=3",'elif [ "$byte" -ge 224 ]',"then need=2",'elif [ "$byte" -ge 192 ]',"then need=1",'elif [ "$byte" -ge 128 ]','then [ "$need" -le 0 ] || need=$((need-1))',"else need=0","fi","done",'if [ "$need" -gt 0 ]','then rest=$(dd bs=1 count="$need" 2>/dev/null; printf .)',"rest=${rest%.}",'chunk="$chunk$rest"',"fi",`chunk=$(printf '%s\\n' "$chunk" | sed -u -f ${n(r.sedPath)}; printf .)`,"chunk=${chunk%.}",'chunk=${chunk%"$nl"}','while [ -n "$chunk" ]','do case "$chunk" in *"$nl"*) line=${chunk%%"$nl"*}',`append ${r.marker} "$line"`,'chunk=${chunk#*"$nl"};',`*) append ${r.marker.toLowerCase()} "$chunk"`,"chunk=;","esac","done",`done < ${n(r.fifo)}) &`].join("; ")}function Ae(r){let i=$e(r.dir);return[`chmod 600 ${n(r.sedPath)}`,`trap 'code=$?; printf "%s" "$code" > ${i.exit}' EXIT`,"trap 'exit 143' TERM",`${Je(r.dir)} rm -f ${i.stdout} ${i.stderr}`,`mkfifo ${i.stdout} ${i.stderr}`,`${je({marker:"O",fifo:`${r.dir}/stdout`,sedPath:r.sedPath})} out=$!`,`${je({marker:"E",fifo:`${r.dir}/stderr`,sedPath:r.sedPath})} err=$!`,`{ cd ${n(r.cwd)} && sh -c ${n(r.command)}; } > ${i.stdout} 2> ${i.stderr}`,"code=$?",'wait "$out" "$err"','exit "$code"'].join("; ")}function Be(r){let i=$e(r.dir),m=`nohup setsid sh -c ${n(r.supervisor)} > /dev/null 2>&1 < /dev/null & echo $! > ${i.pid}`;if(!r.waitForExit)return m;return[m,"i=0",`while [ "$i" -lt 10 ] && [ ! -f ${i.exit} ]`,"do sleep 0.01","i=$((i+1))","done",`cat ${i.exit} 2>/dev/null`,"true"].join("; ")}function De(r){let i=2166136261;for(let y=0;y<r.length;y++)i=Math.imul(i^r.charCodeAt(y),16777619)>>>0;return`${(r.trim().split(/\s+/)[0]??"").split("/").pop()?.replace(/[^a-zA-Z0-9_-]/g,"").slice(0,48)||"process"}-${i.toString(16).padStart(8,"0")}`}var we=(r)=>new Promise((i)=>setTimeout(i,r));function He(r,i,m,y,p){let x=r.processRecordRoot??"/tmp/.sandbox-sdk/procs",k=new Map,O=new Map,N=new Set,j=r.processMode==="stream",M=async(w)=>{try{return await w()}catch(b){throw y.error(b,r.name,i)}},A=(w)=>{if(!/^[a-zA-Z0-9_-]{1,128}$/.test(w))s("Process name must contain 1–128 letters, numbers, hyphens or underscores");return`${x}/${w}`},F=(w,b={},c,d=()=>{})=>r.exec(i,{command:w,stdin:c,cwd:"/workspace",env:{...p,...b,...l},timeoutMs:1e4,onChunk(D){if(D.stream==="stdout")d(D.text)}});async function U(w,b,c){if(r.files.readRange)return r.files.readRange(i,w,{offset:b,length:c});return(await r.files.read(i,w)).subarray(b,b+c)}async function ae(w,b){if(C(w))return!0;return w.code==="provider"&&!await m.exists(b)}async function ye(w){try{return Number(await m.read(`${w}/exit`))}catch(b){if(b instanceof e&&await ae(b,`${w}/exit`))return null;throw b}}async function se(w){let b=A(w),[c,d,D]=await Promise.all([m.read(`${b}/spec.json`),ye(b),m.read(`${b}/pid`)]),S=Pe(c);return{name:w,command:y.text(S.command),status:d===null?"running":d===0?"exited":"failed",pid:Number(D),ports:S.port===void 0?[]:[S.port],startedAt:S.startedAt,exitCode:d}}async function be(w,b={}){if(!Number.isInteger(w)||w<1||w>65535)s("Port must be between 1 and 65535");let c={...await r.previewUrl(i,w)};if(b.path){let d=new URL(c.url),D=new URL(b.path,d);if(D.origin!==d.origin)s("Preview path must stay on the preview's origin");c.url=D.toString()}if(b.waitMs!==void 0){let d=Date.now()+b.waitMs;do{try{let D=c.url,S=new URL(D).origin,B=new Headers(c.headers),q=new Map,X=(P)=>{let v=P.split(";")[0]?.trim()??"",a=v.indexOf("=");if(a>0)q.set(v.slice(0,a),v)};for(let P of(B.get("cookie")??"").split(";"))X(P);for(let P=0;P<5;P++){let v=await fetch(D,{headers:B,redirect:"manual",signal:AbortSignal.timeout(Math.max(1,Math.min(1000,d-Date.now())))});if(await v.body?.cancel(),v.ok)return c;let a=v.headers.get("location");if(![301,302,303,307,308].includes(v.status)||!a)break;let g=new URL(a,D);if(g.origin!==S)break;for(let R of v.headers.getSetCookie())X(R);if(q.size)B.set("cookie",[...q.values()].join("; "));if(D=g.toString(),Date.now()>=d)break}}catch{}if(Date.now()>=d)break;await we(Math.min(50,Math.max(1,d-Date.now())))}while(Date.now()<=d);throw new e(`Preview failed. Port ${w} did not answer. Check the process and its logs.`,{code:"port_not_ready"})}return c}function xe(w){let b=A(w),c=O.get(w);if(c)return c;let d="starting",D,S=!1,B;async function q(P={}){let v=ve(P.after).offset,a=v===void 0?void 0:Number(v),g=P.maxBytes??16384;if(a!==void 0&&(!Number.isSafeInteger(a)||a<0)||!Number.isSafeInteger(g)||g<1||g>1048576)s("Invalid log cursor or maxBytes");let R=Math.min(g,65536),_=32770,h,T,z,ne;if(j)d=(await se(w)).status,h=Number(await m.read(`${b}/base`)),z=(await m.stat(`${b}/out.log`)).size,T=Math.max(0,(a??h)-h-_),ne=await U(`${b}/out.log`,T,R+_*2);else{let H="",ge=await r.exec(i,{command:Ee({dir:b,after:a,lookbehind:_,length:R+_*2}),cwd:"/workspace",env:{...p,...l},timeoutMs:1e4,onChunk(Q){if(Q.stream==="stdout"){H+=Q.text;let ie=H.indexOf("\x00");if(ie>=0&&Buffer.byteLength(H.slice(ie+1))>262144)s("Oversized log page")}}});if(ge.exitCode===me.missing)throw new e("Process record not found. This process has not been started. Check the process name.",{code:"file_not_found"});if(ge.timedOut||ge.exitCode!==0)throw new e("Log range read failed. Retry the log request.",{code:"provider"});let de=H.indexOf("\x00");if(de<0)s("Invalid process record");Pe(H.slice(0,de));let ue=H.indexOf(`
|
|
12
|
-
`,de+1),fe=H.slice(de+1,ue).split(" ");h=Number(fe[0]),T=Number(fe[1]),z=Number(fe[2]);let J=fe[3];if(J!=="running"&&(J===void 0||!Number.isInteger(Number(J))))s("Invalid remote process status");if(d=J==="running"?"running":Number(J)===0?"exited":"failed",ue<0||![h,T,z].every((Q)=>Number.isSafeInteger(Q)&&Q>=0))s("Invalid remote log page");ne=Buffer.from(H.slice(ue+1),"base64")}let I=Math.max(h,a??h),L=Ie(ne,Math.max(0,I-h-T),R,h+T),W=h+T+L.offset;return{events:L.events.map((H)=>({...H,text:y.text(H.text)})),nextCursor:String(W),truncated:(a??h)<h||W<h+z}}let X={name:w,get status(){return d},get url(){return D},get ready(){return S},logs:(P={})=>M(async()=>{let v=await q(P);return{text:y.text(v.events.map((a)=>a.text).join("")),nextCursor:v.nextCursor,truncated:v.truncated}}),async*lines(P={}){let v=ve(P.after),{offset:a,pending:g}=v,R=(_)=>JSON.stringify({v:1,offset:_,...g});do{let _=await M(()=>q({after:a,maxBytes:1048576}));a=_.nextCursor;for(let h of _.events){if(g[h.stream]+=h.text,Buffer.byteLength(g[h.stream])>65536){let T=Buffer.from(g[h.stream]).subarray(-65510),z=0;while(((T[z]??0)&192)===128)z++;g[h.stream]="[line truncated]"+T.subarray(z).toString()}if(g[h.stream].endsWith(`
|
|
13
|
-
`)){let T=g[h.stream].slice(0,-1);g[h.stream]="",yield{text:T,stream:h.stream,cursor:R(h.cursor)}}}if(!_.truncated&&d!=="running"&&d!=="starting"){for(let h of["stdout","stderr"])if(g[h]){let T=g[h];g[h]="",yield{text:T,stream:h,cursor:R(a)}}break}if(!_.truncated)await we(25)}while(!0)},stop:(P={})=>M(async()=>{let v=await se(w);if(d=v.status,v.exitCode!==null)return;let a=k.get(w);if(a)await a.stop({graceMs:P.graceMs??1000});else await F(`kill -TERM -${v.pid} 2>/dev/null || true`),await we(P.graceMs??1000),await F(`kill -KILL -${v.pid} 2>/dev/null || true`);if(!await m.exists(`${b}/exit`))await m.write(`${b}/exit`,"143");d="exited"}),restart:()=>M(async()=>{if(await X.stop(),!B){let P=await se(w),v=Ne(await m.read(`${b}/restart.json`),w);await te(v.command??P.command,v.options)}else await B()}),wait:()=>M(async()=>{while(!await m.exists(`${b}/exit`))await we(25);let P=await se(w);return d=P.status,{exitCode:P.exitCode,signal:P.exitCode===143?"SIGTERM":P.exitCode===137?"SIGKILL":null}})};return O.set(w,X),Y.set(w,{state(P){d=P},access(P){D=P},ready(P){S=P},launch(P){B=P}}),X}let Y=new Map;async function te(w,b={}){let c=b.name??De(w);if(!j||!r.startProcess)return he(w,b);if(N.has(c))return M(()=>s(`Process ${c} is already running`));N.add(c);try{return await he(w,b)}finally{N.delete(c)}}async function he(w,b){return M(async()=>{let c={...b,name:b.name??De(w)};if(r.processMode==="unsupported")throw new e("Background processes are unsupported. This runtime cannot run the SDK process-record shim. Use its native process API or another provider.",{code:"unsupported"});let d=A(c.name);if(j&&r.startProcess&&await m.exists(`${d}/spec.json`)&&!await m.exists(`${d}/exit`))s(`Process ${c.name} is already running`);let D=xe(c.name),S=Y.get(c.name),B=c.ready&&"port"in c.ready?c.ready.port:c.ready&&("http"in c.ready)?c.ready.http.port:void 0,q=async()=>{let X=JSON.stringify({command:y.text(w),cwd:u(c.cwd),env:Object.fromEntries(Object.entries(c.env??{}).map(([I,L])=>[I,y.text(L)])),startedAt:Date.now(),port:B,readiness:c.ready&&("log"in c.ready?{log:c.ready.log.source,flags:c.ready.log.flags}:c.ready),readyTimeoutMs:c.readyTimeoutMs}),P=JSON.stringify({command:w,cwd:u(c.cwd),env:c.env,readiness:c.ready&&("log"in c.ready?{log:c.ready.log.source,flags:c.ready.log.flags}:c.ready),readyTimeoutMs:c.readyTimeoutMs}),v=`${d}/redact.sed`,a=!0,g,R;if(j&&r.startProcess){S?.state("starting"),S?.ready(!1),await m.write(`${d}/spec.json`,X),await m.write(`${d}/restart.json`,P);let I=await m.exists(`${d}/base`)?Number(await m.read(`${d}/base`))+(await m.stat(`${d}/out.log`)).size:0;if(await m.write(`${d}/out.log`,""),await m.write(`${d}/base`,String(I)),await m.exists(`${d}/exit`))await m.remove(`${d}/exit`)}else{let I=await F(Te({dir:d,cwd:u(c.cwd)}),{},Buffer.from(X).toString("base64")+`
|
|
14
|
-
`+Buffer.from(P).toString("base64")+`
|
|
15
|
-
`);if(I.exitCode===me.running)s(`Process ${c.name} is already running`);if(I.exitCode===me.badCwd)a=!1,S?.state("failed"),S?.ready(!1);else if(I.timedOut||I.exitCode!==0)throw new e("Process setup failed. Could not prepare durable records. Check that /tmp is writable and retry.",{code:"provider"});else{let L=Le(y.secrets);await r.files.write(i,v,new TextEncoder().encode(L)),S?.state("starting"),S?.ready(!1)}}if(S?.launch(q),a&&j&&r.startProcess){let I,L=[],W=0,H=0,ge=()=>I??=(async()=>{while(L.length||H){let J=L;L=[],W=0;let Q=H;H=0;let ie=await m.read(`${d}/out.log`,{as:"bytes"}),ke=Number(await m.read(`${d}/base`));if(Q)ke+=ie.length+Q,ie=new Uint8Array;let pe=Buffer.concat([ie,Buffer.from(J.join(""))]);if(pe.length>10485760){let _e=pe.indexOf(10,pe.length-5242880)+1;ke+=_e,pe=pe.subarray(_e)}await m.write(`${d}/base`,String(ke)),await m.write(`${d}/out.log`,pe)}})().finally(()=>{I=void 0}),de=E(y,(J)=>{for(let Q of Me(J)){L.push(Q),W+=Buffer.byteLength(Q);while(W>1048576&&L.length>1){let ie=L.shift()??"";W-=Buffer.byteLength(ie),H+=Buffer.byteLength(ie)}}ge().catch(()=>S?.state("failed"))}),ue=await r.startProcess(i,{command:w,cwd:u(c.cwd),env:{...p,...c.env,...l},onChunk:(J)=>de.push(J)});k.set(c.name,ue),await m.write(`${d}/pid`,String(ue.pid));let fe=ue.wait();R=fe.then((J)=>{g=J.exitCode??137},()=>{}),fe.then(async(J)=>{g=J.exitCode??137,de.flush(),await ge(),await m.write(`${d}/exit`,String(J.exitCode??137)),S?.state(J.exitCode===0?"exited":"failed")}).catch(async()=>{await m.write(`${d}/exit`,"1").catch(()=>{}),S?.state("failed")})}else if(a){let I=Ae({dir:d,cwd:u(c.cwd),command:w,sedPath:v});if(r.startProcess){let L=await r.startProcess(i,{command:I,cwd:"/workspace",env:{...p,...c.env,...l},onChunk(){}});k.set(c.name,L),await m.write(`${d}/pid`,String(L.pid));let W=L.wait().then((H)=>(g=H.exitCode??137,H));R=W.catch(()=>{}),W.then(async(H)=>{if(!await m.exists(`${d}/exit`))await m.write(`${d}/exit`,String(H.exitCode??137))}).catch(async()=>{await m.write(`${d}/exit`,"1").catch(()=>{})})}else{let L="";if(await F(Be({dir:d,supervisor:I,waitForExit:!c.ready}),c.env,void 0,(W)=>{L+=W}),/^\d+$/.test(L.trim()))g=Number(L.trim())}}if(!c.ready){if(g===void 0&&R)await Promise.race([R,we(100)]);let I=a?g:1;S?.state(I===void 0?"running":I===0?"exited":"failed"),S?.ready(I===void 0||I===0);return}if(a)S?.state("running");let _=Date.now()+(c.readyTimeoutMs??60000),h,T="",z=!1,ne=()=>T.replace(/\n$/,"").split(`
|
|
16
|
-
`).slice(-50).join(`
|
|
17
|
-
`);do{let I=await D.logs({after:h,maxBytes:1048576});if(h=I.nextCursor,T=Buffer.from(T+I.text).subarray(-262144).toString(),z=await m.exists(`${d}/exit`),z&&I.truncated)continue;if(z)throw new e(`Process exited before readiness. Exit ${(await se(c.name)).exitCode}. Check the last logs: ${ne()}`,{code:"process_exited"});if("log"in c.ready){if(c.ready.log.lastIndex=0,c.ready.log.test(T)){S?.ready(!0);return}}else if(B)try{let L=await be(B,r.previewMode==="placeholder"?{}:{path:"http"in c.ready?c.ready.http.path:void 0,waitMs:Math.max(1,Math.min(5000,_-Date.now()))});S?.access(L.url),S?.ready(!0);return}catch(L){if(!(L instanceof e)||L.code!=="port_not_ready")throw L}if(Date.now()>=_)break;await we(25)}while(z||Date.now()<=_);throw new e(`Process is still running but readiness timed out. No readiness signal arrived. Inspect logs: ${ne()}`,{code:"timeout"})};return await q(),D})}return{start:te,process:xe,preview:(w,b)=>M(()=>be(w,b)),processes:()=>M(async()=>{let w;try{w=await m.list(x)}catch(d){if(d instanceof e&&await ae(d,x))return[];throw d}let b=[],c=w.filter((d)=>d.type==="directory");for(let d=0;d<c.length;d+=4){let S=c.slice(d,d+4).map((B)=>Fe.basename(B.path));b.push(...await Promise.all(S.map((B)=>se(B))))}return b})}}function Ue(r){return Array.isArray(r)&&r.every((i)=>t(i)&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))}async function ht(r,i,m,y,p,x=!0){let k=!1,O=!1,N,j=!1,M=()=>{if(!j)return!1;return j=!1,ce(r,i.id)},A=0,F=0,U=()=>{if(k||O)throw new e("Sandbox handle is closed. Local resources were detached. Connect a new handle.",{code:"not_found",provider:r.name,sandboxId:i.id})},ae={...y.env,...y.secrets},ye=m||!x?Promise.resolve():void 0,se=()=>ye??=xe().catch((a)=>{throw ye=void 0,a});async function be(){if(r.readSecretEnvironment){let h=await r.readSecretEnvironment(i.id);if(!h)return;return{record:h.record,environment:new Map(Object.entries(h.environment))}}let a="",g=await r.exec(i.id,{command:re,cwd:"/",env:{},timeoutMs:1e4,onChunk(h){if(h.stream==="stdout")a+=h.text}});if(g.timedOut||g.exitCode!==0)throw new e("Secret recovery failed. Could not read the sandbox environment. Retry, or connect with recoverSecrets: false.",{code:"provider",provider:r.name,sandboxId:i.id});if(!a)return;let R=a.indexOf("\x00");if(R<0)s("Invalid secret recovery record");let _=new Map;for(let h of a.slice(R+1).split("\x00")){let T=h.indexOf("=");if(T>=0)_.set(h.slice(0,T),h.slice(T+1))}return{record:a.slice(0,R),environment:_}}async function xe(){let a=await be();if(!a)return;let g;try{g=JSON.parse(a.record)}catch{throw new e("Secret recovery failed. The secret names record is not valid JSON. Repair the record and reconnect.",{code:"provider"})}if(!Ue(g))s("Invalid secret names record");let R={};for(let _ of g)R[_]=a.environment.get(_)??"";p.add(Object.values(R)),Object.assign(ae,R,y.env,y.secrets)}let Y=async()=>{U(),await se().finally(U)},te=ee(r,i.id,p,U,se),he="/tmp/.sandbox-sdk/secret-names.json";if(m){if(y.trackChanges)await te.mark("start");else if(y.from!==void 0)await K(te,"/tmp/.sandbox-sdk/marks/start.json");let a=Object.keys(y.secrets??{});if(a.length||y.from!==void 0){let g=JSON.stringify(a);if(r.files.writeCreatesParents)await te.write(he,g);else if((await r.exec(i.id,{command:`mkdir -p /tmp/.sandbox-sdk && printf '%s' ${n(g)} > ${n(he)}`,cwd:"/",env:l,timeoutMs:1e4,onChunk(){}})).exitCode!==0)throw new e("Secret setup failed. Could not record secret names in /tmp/.sandbox-sdk. Ensure /tmp is writable.",{code:"provider",provider:r.name,sandboxId:i.id})}}let w=oe(r,i.id,p,ae,(a)=>{A++,F+=a},Y),b=He(r,i.id,ee(r,i.id,p),p,ae),c=async(a)=>{U();try{return await a()}catch(g){throw p.error(g,r.name,i.id)}},d=(a)=>c(async()=>(await Y(),a())),D=new WeakMap,S=(a)=>{let g=D.get(a);if(g)return g;let R={get name(){return a.name},get url(){return a.url},get ready(){return a.ready},get status(){return a.status},logs:async(_)=>(await c(Y),a.logs(_)),async*lines(_){await c(Y),yield*a.lines(_)},stop:async(_)=>(await c(Y),a.stop(_)),restart:async()=>(await c(Y),a.restart()),wait:async()=>(await c(Y),a.wait())};return D.set(a,R),R},B={id:i.id,key:i.key,provider:r.name,created:m,labels:i.labels,capabilities:new Set(r.capabilities),get native(){U();try{return r.native(i.id)}catch(a){throw p.error(a,r.name,i.id)}},run(a,g){return U(),w(a,g)},$(a,...g){return U(),w(a.reduce((R,_,h)=>R+_+(h<g.length?n(String(g[h])):""),""))},files:te,git:Oe((a,g)=>(U(),w(a,g)),te,p),start:(a,g)=>d(async()=>S(await b.start(a,g))),process(a){return U(),S(b.process(a))},processes:()=>d(()=>b.processes()),preview:(a,g)=>d(()=>b.preview(a,g)),usage:()=>c(async()=>({...await r.usage?.(i.id),createdAt:i.createdAt,runningMs:Date.now()-i.createdAt,commands:A,bytesOut:F})),async close(){if(k||O)return;N??=(async()=>{let a=M();try{if(a)await r.close?.(i.id)}catch(g){throw j=!0,Z(r,i.id),g}te[Symbol.dispose](),k=!0})().finally(()=>{N=void 0});try{await N}catch(a){throw p.error(a,r.name,i.id)}},async destroy(){if(O)return;try{V(r,i.id),await r.destroy(i.id),te[Symbol.dispose](),O=!0,M();let{key:a,locator:g}=y;if(a&&g?.delete)await G(r,a,y,async()=>{if(await g.get(a)===i.id)await g.delete?.(a)})}catch(a){throw p.error(a,r.name,i.id)}},async[Symbol.asyncDispose](){if(y.key)await B.close();else await B.destroy()}},{pause:q,resume:X,snapshot:P,terminal:v}=r;if(r.capabilities.has("pause")&&q&&X)Object.assign(B,{pause:()=>c(()=>q.call(r,i.id)),resume:()=>c(()=>X.call(r,i.id))});if(r.capabilities.has("snapshot")&&P)Object.assign(B,{snapshot:(a)=>c(async()=>{let g=a?.expiresInMs;if(g!==void 0&&(!Number.isSafeInteger(g)||g<0))s("expiresInMs must be a non-negative integer of milliseconds");return P.call(r,i.id,a)})});if(r.capabilities.has("terminal")&&v)Object.assign(B,{terminal:(a)=>d(async()=>{let g=await v.call(r,i.id,a),R=new Set;return{write:(h)=>d(async()=>{await g.write(h)}),resize:(h,T)=>d(async()=>{await g.resize(h,T)}),onData(h){U();let T=E(p,(I)=>h(I.text)),z=g.onData((I)=>T.push({stream:"stdout",text:I})),ne=()=>{z(),T.flush(),R.delete(ne)};return R.add(ne),ne},close:()=>d(async()=>{for(let h of R)h();await g.close()})}})});return le(B,p),Z(r,i.id),j=!0,B}export{ht as makeHandle};
|
package/dist/chunk-9w9rddra.js
DELETED