@opencoredev/sandbox-sdk 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +9 -6
- package/dist/ai.js +1 -1
- package/dist/chunk-0eeyc0aq.js +4 -0
- package/dist/chunk-0wp6x4wb.js +2 -0
- package/dist/chunk-2999xbh7.js +2 -0
- package/dist/chunk-3h6c1ack.js +2 -0
- package/dist/{chunk-19gteae8.js → chunk-7rkcx5cx.js} +2 -2
- package/dist/{chunk-rnksrxfc.js → chunk-7s9pxk1v.js} +3 -3
- package/dist/chunk-aek8n3a4.js +78 -0
- package/dist/{chunk-r8xnq6v3.js → chunk-aq6fmgdx.js} +2 -2
- package/dist/chunk-drhcb2hx.js +2 -0
- package/dist/{chunk-2z6fxyg5.js → chunk-ek44atpe.js} +2 -2
- package/dist/chunk-g5n5xcmp.js +0 -0
- package/dist/{chunk-6bemkxcx.js → chunk-kdecey83.js} +12 -12
- package/dist/{chunk-drgkmewv.js → chunk-pdgnaxp9.js} +2 -2
- package/dist/{chunk-3zd78ha4.js → chunk-qfhee1t8.js} +2 -2
- package/dist/chunk-rx9318sh.js +5 -0
- package/dist/chunk-sjnk17y5.js +26 -0
- package/dist/chunk-w8nk1xf2.js +17 -0
- package/dist/{chunk-g0vk7g1k.js → chunk-x05t86n3.js} +2 -2
- package/dist/{chunk-c1wemt0y.js → chunk-x4rrgmxf.js} +11 -11
- package/dist/chunk-xqtzts2q.js +1 -0
- package/dist/errors.d.ts +19 -9
- package/dist/files.d.ts +2 -5
- package/dist/index.d.ts +24 -3
- package/dist/index.js +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.js +1 -1
- package/dist/openai.js +1 -1
- package/dist/provider.d.ts +102 -7
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/baseten/errors.d.ts +6 -0
- package/dist/providers/baseten/execute.d.ts +68 -0
- package/dist/providers/baseten/index.d.ts +3 -0
- package/dist/providers/baseten/index.js +97 -0
- package/dist/providers/baseten/provider.d.ts +39 -0
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/errors.d.ts +25 -3
- package/dist/providers/boxd/index.js +7 -5
- package/dist/providers/boxd/provider.d.ts +16 -2
- package/dist/providers/daytona/api.d.ts +2 -2
- package/dist/providers/daytona/index.js +15 -15
- package/dist/providers/e2b/envd.d.ts +32 -2
- package/dist/providers/e2b/errors.d.ts +1 -2
- package/dist/providers/e2b/index.d.ts +40 -4
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/e2b/narrow.d.ts +7 -0
- package/dist/providers/freestyle/index.js +6 -6
- package/dist/providers/instabox/api.d.ts +56 -0
- package/dist/providers/instabox/errors.d.ts +49 -0
- package/dist/providers/instabox/index.d.ts +4 -0
- package/dist/providers/instabox/index.js +7 -0
- package/dist/providers/instabox/provider.d.ts +28 -0
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/modal/errors.d.ts +4 -0
- package/dist/providers/modal/index.d.ts +14 -0
- package/dist/providers/modal/index.js +2 -0
- package/dist/providers/modal/provider.d.ts +94 -0
- package/dist/providers/modal/transport.d.ts +50 -0
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/index.js +5 -5
- package/dist/providers/tenki/deadline.d.ts +1 -1
- package/dist/providers/tenki/index.js +13 -13
- package/dist/providers/tenki/provider.d.ts +12 -12
- package/dist/providers/tenki/records.d.ts +1 -1
- package/dist/providers/upstash/index.js +11 -11
- package/dist/providers/vercel/index.js +1 -1
- package/dist/providers/vercel/transport.d.ts +1 -1
- package/dist/shared/native-error.d.ts +2 -0
- package/dist/streams.d.ts +2 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +32 -13
- package/dist/version.d.ts +4 -0
- package/package.json +28 -4
- package/dist/chunk-11mbpwem.js +0 -17
- package/dist/chunk-1k6yz176.js +0 -1
- package/dist/chunk-305dymgq.js +0 -2
- package/dist/chunk-348pdz09.js +0 -5
- package/dist/chunk-5gnqph3c.js +0 -78
- package/dist/chunk-6nf686jb.js +0 -26
- package/dist/chunk-ea8y7y2p.js +0 -2
- package/dist/chunk-n7x9ha44.js +0 -4
- package/dist/chunk-tvw3kb8b.js +0 -2
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{p,l,fe,O,me}from"./chunk-sjnk17y5.js";import{X,re,ie,he}from"./chunk-3h6c1ack.js";import{Z,ce,ye}from"./chunk-aek8n3a4.js";import{n}from"./chunk-2ts3evzh.js";import{c}from"./chunk-0wp6x4wb.js";import{t,o,e,M,s}from"./chunk-0eeyc0aq.js";function Oe(r,i,d){async function w(g,y,k){if(!y)return await r(`git ${g}`,{cwd:k});d.add([y]);let E=`/tmp/.sandbox-sdk/credential-${crypto.randomUUID()}`,T=`#!/bin/sh
|
|
2
|
+
if [ "$1" = get ]; then printf 'username=x-access-token\\npassword='; cat ${n(E+".token")}; printf '\\n'; fi
|
|
3
|
+
`;await r(`umask 077; mkdir -p /tmp/.sandbox-sdk; cat > ${n(E+".token")}; printf '%s' ${n(T)} > ${n(E)}`,{stdin:y});let A=()=>Promise.all([Z(i,E),Z(i,E+".token")]),j;try{j=await r(`git -c credential.helper= -c ${n(`credential.helper=!sh ${n(E)}`)} ${g}`,{cwd:k})}catch(D){throw await A().catch(()=>{}),D}return await A(),j}return{clone:(g,y={})=>w(`clone ${y.branch?`--branch ${n(y.branch)} `:""}${y.depth?`--depth ${n(String(y.depth))} `:""}-- ${n(g)} ${n(y.dir??"app")}`,y.token),status:(g)=>Promise.resolve(r("git status --porcelain",{cwd:g})),diff:(g)=>Promise.resolve(r("git diff",{cwd:g})),commit:async(g,y)=>{if(y.all)await r("git add -A",{cwd:g});return await r(`git commit -m ${n(y.message)}${y.author?` --author=${n(y.author)}`:""}`,{cwd:g})},push:(g,y={})=>w(`push -- ${n(y.remote??"origin")}${y.branch?` ${n(y.branch)}`:""}`,y.token,g),checkout:(g,y)=>Promise.resolve(r(`git checkout ${y.create?"-b ":""}${n(y.branch)}`,{cwd:g}))}}import{posix as Je}from"node:path";function Me(r){let i=[],d=r.stream==="stdout"?"O":"E",w=r.text.split(`
|
|
4
|
+
`);for(let g=0;g<w.length;g++){let y=w[g]??"",k=g<w.length-1;for(let E=0;E<y.length;){let T=Math.min(y.length,E+8192),A=y.charCodeAt(T-1);if(T<y.length&&A>=55296&&A<=56319)T--;i.push((k&&T===y.length?d:d.toLowerCase())+y.slice(E,T)+`
|
|
5
|
+
`),E=T}if(!y&&k)i.push(d+`
|
|
6
|
+
`)}return i}function Ie(r,i,d,w){let g=Buffer.from(r.buffer,r.byteOffset,r.byteLength),y=[],k=Math.min(i,g.length),E=0;while(k<g.length&&E<d){let T=k===0?0:g.lastIndexOf(10,k-1)+1,A=g[T];if(k===T)k++;let j=g.indexOf(10,k);if(j<0)break;let D=Math.min(j,k+d-E),G=(ae)=>((g[ae]??0)&192)===128;while(D>k&&D<j&&G(D))D--;if(D===k&&k<j){if(E)break;D++;while(D<j&&G(D))D++}let z=g.subarray(k,D).toString();if(E+=D-k,k=D,k===j&&(A===79||A===69)&&E<d)z+=`
|
|
7
|
+
`,E++,k++;else if(k===j&&A!==79&&A!==69)k++;y.push({stream:A===69||A===101?"stderr":"stdout",text:z,cursor:String(w+k)})}return{events:y,offset:k}}function Pe(r){let i=JSON.parse(r);if(!c(i))s("Invalid process record");let{command:d,startedAt:w,port:g}=i;if(!t(d)||!o(w))s("Invalid process record");return{command:d,startedAt:w,port:o(g)?g:void 0}}function Ee(r,i){let d=JSON.parse(r);if(!c(d))s("Invalid process restart record");let{command:w,cwd:g,env:y,readyTimeoutMs:k,readiness:E}=d,T={name:i};if(t(g))T.cwd=g;if(c(y)){T.env={};for(let[A,j]of Object.entries(y))if(t(j))T.env[A]=j}if(o(k))T.readyTimeoutMs=k;if(c(E)){let{log:A,flags:j,port:D,http:G}=E;if(t(A))T.ready={log:new RegExp(A,t(j)?j:"")};else if(o(D))T.ready={port:D};else if(c(G)&&o(G.port))T.ready={http:{port:G.port,path:t(G.path)?G.path:void 0}}}return{command:t(w)?w:void 0,options:T}}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 d;try{d=JSON.parse(r)}catch{s("Invalid line cursor")}if(!c(d))s("Invalid line cursor");let{v:w,offset:g,stdout:y,stderr:k}=d;if(w!==1||!t(g)||!/^\d+$/.test(g)||!Number.isSafeInteger(Number(g))||!t(y)||!t(k)||Buffer.byteLength(y)>65536||Buffer.byteLength(k)>65536)s("Invalid line cursor");return{offset:g,pending:{stdout:y,stderr:k}}}var ue={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 Ne(r){let i=$e(r.dir);return[`[ -f ${i.spec} ] || exit ${ue.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 ${ue.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 ${ue.badCwd}`].join("; ")}function Ae(r){let i=[];for(let d of r.flatMap((w)=>w.split(`
|
|
9
|
+
`))){if(!d)continue;i.push(`s|${Se(d)}|[REDACTED]|g`);for(let w=0;w<d.length-1;w++)i.push(`s|${Se(d.slice(0,d.length-1-w))}$|[REDACTED]|`),i.push(`s|^${Se(d.slice(w+1))}|[REDACTED]|`)}return i.join(`
|
|
10
|
+
`)+`
|
|
11
|
+
`}function Se(r){return r.replace(/[\\[\].*^$|]/g,"\\$&")}function ze(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 -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 Le(r){let i=$e(r.dir);return[`chmod 600 ${n(r.sedPath)}`,`trap 'code=$?; printf "%s" "$code" > ${i.exit}' EXIT`,"trap 'exit 143' TERM",`${ze(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),d=`nohup setsid sh -c ${n(r.supervisor)} > /dev/null 2>&1 < /dev/null & echo $! > ${i.pid}`;if(!r.waitForExit)return d;return[d,"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 w=0;w<r.length;w++)i=Math.imul(i^r.charCodeAt(w),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 pe=(r)=>new Promise((i)=>setTimeout(i,r));function He(r,i,d,w,g){let y=r.processRecordRoot??"/tmp/.sandbox-sdk/procs",k=new Map,E=new Map,T=new Set,A=r.processMode==="stream",j=async(h)=>{try{return await h()}catch(b){throw w.error(b,r.name,i)}},D=(h)=>{if(!/^[a-zA-Z0-9_-]{1,128}$/.test(h))s("Process name must contain 1–128 letters, numbers, hyphens or underscores");return`${y}/${h}`},G=(h,b={},f,u=()=>{})=>r.exec(i,{command:h,stdin:f,cwd:"/workspace",env:{...g,...b,...p},timeoutMs:1e4,onChunk(B){if(B.stream==="stdout")u(B.text)}});async function z(h,b,f){if(r.files.readRange)return r.files.readRange(i,h,{offset:b,length:f});return(await r.files.read(i,h)).subarray(b,b+f)}async function ae(h,b){if(M(h))return!0;return h.code==="provider"&&!await d.exists(b)}async function we(h){try{return Number(await d.read(`${h}/exit`))}catch(b){if(b instanceof e&&await ae(b,`${h}/exit`))return null;throw b}}async function V(h){let b=D(h),[f,u,B]=await Promise.all([d.read(`${b}/spec.json`),we(b),d.read(`${b}/pid`)]),_=Pe(f);return{name:h,command:w.text(_.command),status:u===null?"running":u===0?"exited":"failed",pid:Number(B),ports:_.port===void 0?[]:[_.port],startedAt:_.startedAt,exitCode:u}}async function le(h,b={}){if(!Number.isInteger(h)||h<1||h>65535)s("Port must be between 1 and 65535");let f={...await r.previewUrl(i,h)};if(b.path){let u=new URL(f.url),B=new URL(b.path,u);if(B.origin!==u.origin)s("Preview path must stay on the preview's origin");f.url=B.toString()}if(b.waitMs!==void 0){let u=Date.now()+b.waitMs;do{try{let B=f.url,_=new URL(B).origin,J=new Headers(f.headers),W=new Map,Q=(R)=>{let S=R.split(";")[0]?.trim()??"",I=S.indexOf("=");if(I>0)W.set(S.slice(0,I),S)};for(let R of(J.get("cookie")??"").split(";"))Q(R);for(let R=0;R<5;R++){let S=await fetch(B,{headers:J,redirect:"manual",signal:AbortSignal.timeout(Math.max(1,Math.min(1000,u-Date.now())))});if(await S.body?.cancel(),S.ok)return f;let I=S.headers.get("location");if(![301,302,303,307,308].includes(S.status)||!I)break;let N=new URL(I,B);if(N.origin!==_)break;for(let K of S.headers.getSetCookie())Q(K);if(W.size)J.set("cookie",[...W.values()].join("; "));if(B=N.toString(),Date.now()>=u)break}}catch{}if(Date.now()>=u)break;await pe(Math.min(50,Math.max(1,u-Date.now())))}while(Date.now()<=u);throw new e(`Preview failed. Port ${h} did not answer. Check the process and its logs.`,{code:"port_not_ready"})}return f}function be(h){let b=D(h),f=E.get(h);if(f)return f;let u="starting",B,_=!1,J;async function W(R={}){let S=ve(R.after).offset,I=S===void 0?void 0:Number(S),N=R.maxBytes??16384;if(I!==void 0&&(!Number.isSafeInteger(I)||I<0)||!Number.isSafeInteger(N)||N<1||N>1048576)s("Invalid log cursor or maxBytes");let K=Math.min(N,65536),F=32770,a,m,C,L;if(A)u=(await V(h)).status,a=Number(await d.read(`${b}/base`)),C=(await d.stat(`${b}/out.log`)).size,m=Math.max(0,(I??a)-a-F),L=await z(`${b}/out.log`,m,K+F*2);else{let P="",H=await r.exec(i,{command:Ne({dir:b,after:I,lookbehind:F,length:K+F*2}),cwd:"/workspace",env:{...g,...p},timeoutMs:1e4,onChunk(te){if(te.stream==="stdout"){P+=te.text;let de=P.indexOf("\x00");if(de>=0&&Buffer.byteLength(P.slice(de+1))>262144)s("Oversized log page")}}});if(H.exitCode===ue.missing)throw new e("Process record not found. This process has not been started. Check the process name.",{code:"file_not_found"});if(H.timedOut||H.exitCode!==0)throw new e("Log range read failed. Retry the log request.",{code:"provider"});let oe=P.indexOf("\x00");if(oe<0)s("Invalid process record");Pe(P.slice(0,oe));let Y=P.indexOf(`
|
|
12
|
+
`,oe+1),ee=P.slice(oe+1,Y).split(" ");a=Number(ee[0]),m=Number(ee[1]),C=Number(ee[2]);let q=ee[3];if(q!=="running"&&(q===void 0||!Number.isInteger(Number(q))))s("Invalid remote process status");if(u=q==="running"?"running":Number(q)===0?"exited":"failed",Y<0||![a,m,C].every((te)=>Number.isSafeInteger(te)&&te>=0))s("Invalid remote log page");L=Buffer.from(P.slice(Y+1),"base64")}let x=Math.max(a,I??a),v=Ie(L,Math.max(0,x-a-m),K,a+m),U=a+m+v.offset;return{events:v.events.map((P)=>({...P,text:w.text(P.text)})),nextCursor:String(U),truncated:(I??a)<a||U<a+C}}let Q={name:h,get status(){return u},get url(){return B},get ready(){return _},logs:(R={})=>j(async()=>{let S=await W(R);return{text:w.text(S.events.map((I)=>I.text).join("")),nextCursor:S.nextCursor,truncated:S.truncated}}),async*lines(R={}){let S=ve(R.after),{offset:I,pending:N}=S,K=(F)=>JSON.stringify({v:1,offset:F,...N});do{let F=await j(()=>W({after:I,maxBytes:1048576}));I=F.nextCursor;for(let a of F.events){if(N[a.stream]+=a.text,Buffer.byteLength(N[a.stream])>65536){let m=Buffer.from(N[a.stream]).subarray(-65510),C=0;while(((m[C]??0)&192)===128)C++;N[a.stream]="[line truncated]"+m.subarray(C).toString()}if(N[a.stream].endsWith(`
|
|
13
|
+
`)){let m=N[a.stream].slice(0,-1);N[a.stream]="",yield{text:m,stream:a.stream,cursor:K(a.cursor)}}}if(!F.truncated&&u!=="running"&&u!=="starting"){for(let a of["stdout","stderr"])if(N[a]){let m=N[a];N[a]="",yield{text:m,stream:a,cursor:K(I)}}break}if(!F.truncated)await pe(25)}while(!0)},stop:(R={})=>j(async()=>{let S=await V(h);if(u=S.status,S.exitCode!==null)return;let I=k.get(h);if(I)await I.stop({graceMs:R.graceMs??1000});else await G(`kill -TERM -${S.pid} 2>/dev/null || true`),await pe(R.graceMs??1000),await G(`kill -KILL -${S.pid} 2>/dev/null || true`);if(!await d.exists(`${b}/exit`))await d.write(`${b}/exit`,"143");u="exited"}),restart:()=>j(async()=>{if(await Q.stop(),!J){let R=await V(h),S=Ee(await d.read(`${b}/restart.json`),h);await ne(S.command??R.command,S.options)}else await J()}),wait:()=>j(async()=>{while(!await d.exists(`${b}/exit`))await pe(25);let R=await V(h);return u=R.status,{exitCode:R.exitCode,signal:R.exitCode===143?"SIGTERM":R.exitCode===137?"SIGKILL":null}})};return E.set(h,Q),xe.set(h,{state(R){u=R},access(R){B=R},ready(R){_=R},launch(R){J=R}}),Q}let xe=new Map;async function ne(h,b={}){let f=b.name??De(h);if(!A||!r.startProcess)return se(h,b);if(T.has(f))return j(()=>s(`Process ${f} is already running`));T.add(f);try{return await se(h,b)}finally{T.delete(f)}}async function se(h,b){return j(async()=>{let f={...b,name:b.name??De(h)};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 u=D(f.name);if(A&&r.startProcess&&await d.exists(`${u}/spec.json`)&&!await d.exists(`${u}/exit`))s(`Process ${f.name} is already running`);let B=be(f.name),_=xe.get(f.name),J=f.ready&&"port"in f.ready?f.ready.port:f.ready&&("http"in f.ready)?f.ready.http.port:void 0,W=async()=>{let Q=JSON.stringify({command:w.text(h),cwd:l(f.cwd),env:Object.fromEntries(Object.entries(f.env??{}).map(([x,v])=>[x,w.text(v)])),startedAt:Date.now(),port:J,readiness:f.ready&&("log"in f.ready?{log:f.ready.log.source,flags:f.ready.log.flags}:f.ready),readyTimeoutMs:f.readyTimeoutMs}),R=JSON.stringify({command:h,cwd:l(f.cwd),env:f.env,readiness:f.ready&&("log"in f.ready?{log:f.ready.log.source,flags:f.ready.log.flags}:f.ready),readyTimeoutMs:f.readyTimeoutMs}),S=`${u}/redact.sed`,I=!0,N,K;if(A&&r.startProcess){_?.state("starting"),_?.ready(!1),await d.write(`${u}/spec.json`,Q),await d.write(`${u}/restart.json`,R);let x=await d.exists(`${u}/base`)?Number(await d.read(`${u}/base`))+(await d.stat(`${u}/out.log`)).size:0;if(await d.write(`${u}/out.log`,""),await d.write(`${u}/base`,String(x)),await d.exists(`${u}/exit`))await d.remove(`${u}/exit`)}else{let x=await G(Te({dir:u,cwd:l(f.cwd)}),{},Buffer.from(Q).toString("base64")+`
|
|
14
|
+
`+Buffer.from(R).toString("base64")+`
|
|
15
|
+
`);if(x.exitCode===ue.running)s(`Process ${f.name} is already running`);if(x.exitCode===ue.badCwd)I=!1,_?.state("failed"),_?.ready(!1);else if(x.timedOut||x.exitCode!==0)throw new e("Process setup failed. Could not prepare durable records. Check that /tmp is writable and retry.",{code:"provider"});else{let v=Ae(w.secrets);await r.files.write(i,S,new TextEncoder().encode(v)),_?.state("starting"),_?.ready(!1)}}if(_?.launch(W),I&&A&&r.startProcess){let x,v=[],U=0,P=0,H=()=>x??=(async()=>{while(v.length||P){let q=v;v=[],U=0;let te=P;P=0;let de=await d.read(`${u}/out.log`,{as:"bytes"}),ke=Number(await d.read(`${u}/base`));if(te)ke+=de.length+te,de=new Uint8Array;let ge=Buffer.concat([de,Buffer.from(q.join(""))]);if(ge.length>10485760){let _e=ge.indexOf(10,ge.length-5242880)+1;ke+=_e,ge=ge.subarray(_e)}await d.write(`${u}/base`,String(ke)),await d.write(`${u}/out.log`,ge)}})().finally(()=>{x=void 0}),oe=O(w,(q)=>{for(let te of Me(q)){v.push(te),U+=Buffer.byteLength(te);while(U>1048576&&v.length>1){let de=v.shift()??"";U-=Buffer.byteLength(de),P+=Buffer.byteLength(de)}}H().catch(()=>_?.state("failed"))}),Y=await r.startProcess(i,{command:h,cwd:l(f.cwd),env:{...g,...f.env,...p},onChunk:(q)=>oe.push(q)});k.set(f.name,Y),await d.write(`${u}/pid`,String(Y.pid));let ee=Y.wait();K=ee.then((q)=>{N=q.exitCode??137},()=>{}),ee.then(async(q)=>{N=q.exitCode??137,oe.flush(),await H(),await d.write(`${u}/exit`,String(q.exitCode??137)),_?.state(q.exitCode===0?"exited":"failed")}).catch(async()=>{await d.write(`${u}/exit`,"1").catch(()=>{}),_?.state("failed")})}else if(I){let x=Le({dir:u,cwd:l(f.cwd),command:h,sedPath:S});if(r.startProcess){let v=await r.startProcess(i,{command:x,cwd:"/workspace",env:{...g,...f.env,...p},onChunk(){}});k.set(f.name,v),await d.write(`${u}/pid`,String(v.pid));let U=v.wait().then((P)=>(N=P.exitCode??137,P));K=U.catch(()=>{}),U.then(async(P)=>{if(!await d.exists(`${u}/exit`))await d.write(`${u}/exit`,String(P.exitCode??137))}).catch(async()=>{await d.write(`${u}/exit`,"1").catch(()=>{})})}else{let v="";if(await G(Be({dir:u,supervisor:x,waitForExit:!f.ready}),f.env,void 0,(U)=>{v+=U}),/^\d+$/.test(v.trim()))N=Number(v.trim())}}if(!f.ready){if(N===void 0&&K)await Promise.race([K,pe(100)]);let x=I?N:1;_?.state(x===void 0?"running":x===0?"exited":"failed"),_?.ready(x===void 0||x===0);return}if(I)_?.state("running");let F=Date.now()+(f.readyTimeoutMs??60000),a,m="",C=!1,L=()=>m.replace(/\n$/,"").split(`
|
|
16
|
+
`).slice(-50).join(`
|
|
17
|
+
`);do{let x=await B.logs({after:a,maxBytes:1048576});if(a=x.nextCursor,m=Buffer.from(m+x.text).subarray(-262144).toString(),C=await d.exists(`${u}/exit`),C&&x.truncated)continue;if(C)throw new e(`Process exited before readiness. Exit ${(await V(f.name)).exitCode}. Check the last logs: ${L()}`,{code:"process_exited"});if("log"in f.ready){if(f.ready.log.lastIndex=0,f.ready.log.test(m)){_?.ready(!0);return}}else if(J)try{let v=await le(J,r.previewMode==="placeholder"?{}:{path:"http"in f.ready?f.ready.http.path:void 0,waitMs:Math.max(1,Math.min(5000,F-Date.now()))});_?.access(v.url),_?.ready(!0);return}catch(v){if(!(v instanceof e)||v.code!=="port_not_ready")throw v}if(Date.now()>=F)break;await pe(25)}while(C||Date.now()<=F);throw new e(`Process is still running but readiness timed out. No readiness signal arrived. Inspect logs: ${L()}`,{code:"timeout"})};return await W(),B})}return{start:ne,process:be,preview:(h,b)=>j(()=>le(h,b)),processes:()=>j(async()=>{let h;try{h=await d.list(y)}catch(u){if(u instanceof e&&await ae(u,y))return[];throw u}let b=[],f=h.filter((u)=>u.type==="directory");for(let u=0;u<f.length;u+=4){let _=f.slice(u,u+4).map((J)=>Je.basename(J.path));b.push(...await Promise.all(_.map((J)=>V(J))))}return b})}}function Fe(r){return Array.isArray(r)&&r.every((i)=>t(i)&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))}function Ue(r){let i=new Set;for(let d=r;d!==null&&d!==Object.prototype;d=Object.getPrototypeOf(d))for(let w of Object.getOwnPropertyNames(d))if(w!=="constructor")i.add(w);return[...i].flatMap((d)=>{let w=r[d];return w?[[d,w]]:[]})}async function $t(r,i,d,w,g,y=!0){let k=!1,E=!1,T,A=!1,j=()=>{if(!A)return!1;return A=!1,he(r,i.id)},D=0,G=0,z=()=>{if(k||E)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={...w.env,...w.secrets},we=d||!y?Promise.resolve():void 0,V=we!==void 0,le=()=>we??=xe().catch((a)=>{throw we=void 0,a});async function be(){if(r.readSecretEnvironment){let x=await r.readSecretEnvironment(i.id);if(!x)return;return{record:x.record,environment:new Map(Object.entries(x.environment))}}let a="",m=await r.exec(i.id,{command:fe,cwd:"/",env:{},timeoutMs:1e4,onChunk(x){if(x.stream==="stdout")a+=x.text}});if(m.timedOut||m.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 C=a.indexOf("\x00");if(C<0)s("Invalid secret recovery record");let L=new Map;for(let x of a.slice(C+1).split("\x00")){let v=x.indexOf("=");if(v>=0)L.set(x.slice(0,v),x.slice(v+1))}return{record:a.slice(0,C),environment:L}}async function xe(){let a=await be();if(!a){V=!0;return}let m;try{m=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(!Fe(m))s("Invalid secret names record");let C={};for(let L of m)C[L]=a.environment.get(L)??"";g.add(Object.values(C)),Object.assign(ae,C,w.env,w.secrets),V=!0}let ne=async()=>{z(),await le().finally(z)},se=ce(r,i.id,g,z,le),h="/tmp/.sandbox-sdk/secret-names.json";if(d){if(w.trackChanges)await se.mark("start");else if(w.from!==void 0)await Z(se,"/tmp/.sandbox-sdk/marks/start.json");let a=Object.keys(w.secrets??{});if(a.length||w.from!==void 0){let m=JSON.stringify(a);if(r.files.writeCreatesParents)await se.write(h,m);else if((await r.exec(i.id,{command:`mkdir -p /tmp/.sandbox-sdk && printf '%s' ${n(m)} > ${n(h)}`,cwd:"/",env:p,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 b=me(r,i.id,g,ae,(a)=>{D++,G+=a},ne),f=He(r,i.id,ce(r,i.id,g),g,ae),u=async(a)=>{z();try{return await a()}catch(m){throw g.error(m,r.name,i.id)}},B=(a)=>u(async()=>(await ne(),a())),_=new WeakMap,J=(a)=>{let m=_.get(a);if(m)return m;let C={get name(){return a.name},get url(){return a.url},get ready(){return a.ready},get status(){return a.status},logs:async(L)=>(await u(ne),a.logs(L)),async*lines(L){await u(ne),yield*a.lines(L)},stop:async(L)=>(await u(ne),a.stop(L)),restart:async()=>(await u(ne),a.restart()),wait:async()=>(await u(ne),a.wait())};return _.set(a,C),C},W={},Q=(a,m)=>new e(`Extension ${a} failed. Its error was withheld because the sandbox's secrets could not be read to redact it. Retry, or connect with recoverSecrets enabled.`,{code:m,provider:r.name,sandboxId:i.id}),R=r.extensions??{};for(let[a,m]of Object.entries(R)){if(!m)continue;let C;Object.defineProperty(W,a,{enumerable:!0,get(){if(z(),C)return C;let L,x;try{L=m(i.id,S),x=Ue(L)}catch(v){throw V?g.error(v,r.name,i.id):Q(a,v instanceof e?v.code:"provider")}return C=Object.fromEntries(x.map(([v,U])=>[v,async(...P)=>{z();try{return await U.call(L,...P)}catch(H){if(!V)await le().catch(()=>{});throw V?g.error(H,r.name,i.id):Q(a,H instanceof e?H.code:"provider")}}])),C}})}let S={id:i.id,key:i.key,provider:r.name,created:d,labels:i.labels,capabilities:new Set(r.capabilities),ext:W,get native(){z();try{return r.native(i.id)}catch(a){throw g.error(a,r.name,i.id)}},run(a,m){return z(),b(a,m)},$(a,...m){return z(),b(a.reduce((C,L,x)=>C+L+(x<m.length?n(String(m[x])):""),""))},files:se,git:Oe((a,m)=>(z(),b(a,m)),se,g),start:(a,m)=>B(async()=>J(await f.start(a,m))),process(a){return z(),J(f.process(a))},processes:()=>B(()=>f.processes()),preview:(a,m)=>B(()=>f.preview(a,m)),usage:()=>u(async()=>({...await r.usage?.(i.id),createdAt:i.createdAt,runningMs:Date.now()-i.createdAt,commands:D,bytesOut:G})),async close(){if(k||E)return;T??=(async()=>{let a=j();try{if(a)await r.close?.(i.id)}catch(m){throw A=!0,ie(r,i.id),m}se[Symbol.dispose](),k=!0})().finally(()=>{T=void 0});try{await T}catch(a){throw g.error(a,r.name,i.id)}},async destroy(){if(E)return;try{X(r,i.id),await r.destroy(i.id),se[Symbol.dispose](),E=!0,j();let{key:a,locator:m}=w;if(a&&m?.delete)await re(r,a,w,async()=>{if(await m.get(a)===i.id)await m.delete?.(a)})}catch(a){throw g.error(a,r.name,i.id)}},async[Symbol.asyncDispose](){if(w.key)await S.close();else await S.destroy()}},{pause:I,resume:N,snapshot:K,terminal:F}=r;if(r.capabilities.has("pause")&&I&&N)Object.assign(S,{pause:()=>u(()=>I.call(r,i.id)),resume:()=>u(()=>N.call(r,i.id))});if(r.capabilities.has("snapshot")&&K)Object.assign(S,{snapshot:(a)=>u(async()=>{let m=a?.expiresInMs;if(m!==void 0&&(!Number.isSafeInteger(m)||m<0))s("expiresInMs must be a non-negative integer of milliseconds");return K.call(r,i.id,a)})});if(r.capabilities.has("terminal")&&F)Object.assign(S,{terminal:(a)=>B(async()=>{for(let P of[a.cols,a.rows])if(!Number.isSafeInteger(P)||P<1)s("Terminal cols and rows must be positive integers");for(let P of Object.keys(a.env??{}))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(P))s("Invalid environment variable name");let m=await F.call(r,i.id,{cols:a.cols,rows:a.rows,cwd:l(a.cwd),env:{...ae,...a.env}});if(k||E)await Promise.resolve(m.close()).catch(()=>{}),z();let C=new Set,L=new Set,x=()=>{for(let P of L)P.flush()},v={write:(P)=>B(async()=>{await m.write(P)}),resize:(P,H)=>B(async()=>{await m.resize(P,H)}),onData(P){z();let H=O(g,(ee)=>P(ee.text)),oe=m.onData((ee)=>H.push({stream:"stdout",text:ee}));L.add(H);let Y=()=>{oe(),H.flush(),L.delete(H),C.delete(Y)};return C.add(Y),Y},close:()=>B(async()=>{for(let P of C)P();await m.close()})},U=m.wait;if(U){let P=U.call(m);P.then(x,x),v.wait=()=>u(async()=>{let H=await P;return x(),H})}return v})});return ye(S,g),ie(r,i.id),A=!0,S}export{$t as makeHandle};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t,r,e,
|
|
2
|
-
export{
|
|
1
|
+
import{t,r,e,y}from"./chunk-0eeyc0aq.js";var A=new WeakMap;function z(i){return i instanceof e?A.get(i):void 0}var _={disconnected:"unavailable",truncated:"unavailable",frame_too_large:"unsupported",malformed:"provider"};function h(i,a,s,n){let o=new e(`${a}. The stream from ${s.provider} cannot be read further.`,{code:_[i],provider:s.provider,sandboxId:s.sandboxId,retryable:i==="disconnected"||i==="truncated",cause:n===void 0?void 0:y(n)??i});return A.set(o,i),o}class k{chunks=[];head=0;length=0;push(i){if(i.byteLength)this.chunks.push(i),this.length+=i.byteLength}find(i,a=0){let s=0;for(let n=0;n<this.chunks.length;n++){let o=this.chunks[n],l=n===0?this.head:0,u=o.byteLength-l;if(a<s+u){for(let d=Math.max(l,l+a-s);d<o.byteLength;d++)if(i(o[d]))return s+d-l}s+=u}return-1}at(i){let a=i;for(let s=0;s<this.chunks.length;s++){let n=this.chunks[s],o=s===0?this.head:0;if(a<n.byteLength-o)return n[o+a];a-=n.byteLength-o}return}take(i){let a=new Uint8Array(i),s=0;while(s<i){let n=this.chunks[0],o=Math.min(i-s,n.byteLength-this.head);if(a.set(n.subarray(this.head,this.head+o),s),s+=o,this.head+=o,this.head===n.byteLength)this.chunks.shift(),this.head=0}return this.length-=i,a}}async function*p(i,a){let s=i.getReader(),{signal:n}=a,o=!1,l=()=>{s.cancel(n?.reason).catch(()=>{})};n?.addEventListener("abort",l,{once:!0});try{if(n?.aborted)throw S(a);for(;;){let u;try{u=await s.read()}catch(d){if(o=!0,n?.aborted)throw S(a);if(d instanceof e){if(d.code==="unavailable"||d.code==="outcome_unknown")A.set(d,"disconnected");throw d}throw h("disconnected","The connection dropped mid-stream",a,d)}if(n?.aborted)throw o=!0,S(a);if(u.done){o=!0;return}yield u.value}}finally{if(n?.removeEventListener("abort",l),!o)await s.cancel().catch(()=>{});s.releaseLock()}}function S(i){return new e("Stream aborted. The signal was cancelled.",{code:"aborted",provider:i.provider,sandboxId:i.sandboxId})}var O=new TextDecoder;var C=16777216;async function*pe(i,a){let s=a.maxFrameBytes??C,n=new k,o=(l,u)=>{let d=O.decode(l).replace(/\r$/,"");try{return JSON.parse(d)}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 p(i,a)){let u=n.length;n.push(l);for(let d=n.find((f)=>f===10,u);d>=0;d=n.find((f)=>f===10)){if(d>s)throw h("frame_too_large",`A JSON line exceeds ${s} bytes`,a);let f=n.take(d+1).subarray(0,d);if(f.some((c)=>c!==13&&c!==32&&c!==9))yield o(f,!1)}if(n.length>s)throw h("frame_too_large",`A JSON line exceeds ${s} bytes`,a)}if(n.length){let l=n.take(n.length);if(l.some((u)=>u!==13&&u!==32&&u!==9))yield o(l,!0)}}async function*te(i,a){let s=a.maxFrameBytes??C,n=new k,o=p(i,a),l=async(f)=>{while(n.length<f){let c=await o.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>s)throw h("frame_too_large",`A Connect frame exceeds ${s} 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 d(g);else yield{kind:"message",message:g}}}finally{await o.return()}function u(f){try{return JSON.parse(O.decode(f))}catch{throw h("malformed","A Connect frame is not valid JSON",a)}}function d(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,w="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);let v={code:g};if(t(w))v.message=w;if(Array.isArray(x))v.details=x;m.error=v}if(r(b)){let g=Object.entries(b).filter((w)=>Array.isArray(w[1])&&w[1].every((x)=>t(x)));m.metadata=Object.fromEntries(g)}return m}}function ne(i,a=!1){let s=new TextEncoder().encode(JSON.stringify(i)),n=new Uint8Array(5+s.byteLength);return n[0]=a?2:0,new DataView(n.buffer).setUint32(1,s.byteLength),n.set(s,5),n}
|
|
2
|
+
export{z,pe,te,ne};
|
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
import{
|
|
2
|
-
UI streaming callback failed. Execution was allowed to finish. Fix onEvent before reconnecting the UI.`:""))),{text:
|
|
1
|
+
import{L}from"./chunk-sjnk17y5.js";import{we,ue,le}from"./chunk-aek8n3a4.js";import{t,e,s}from"./chunk-0eeyc0aq.js";import{createHash as ie}from"node:crypto";import{posix as K}from"node:path";import{z as i}from"zod";var b=i.string(),G=i.number().int().positive(),W=i.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),Y=G.max(65535),E={run:i.object({command:b,cwd:b.optional(),timeoutMs:G.optional()}).strict(),read_file:i.object({path:b,offset:i.number().int().nonnegative().optional(),limit:G.optional()}).strict(),write_file:i.object({path:b,content:b}).strict(),edit_file:i.object({path:b,find:b.min(1),replace:b}).strict(),start_process:i.object({name:W,command:b,cwd:b.optional(),port:Y.optional()}).strict(),process_logs:i.object({name:W,cursor:b.optional()}).strict(),stop_process:i.object({name:W}).strict(),search:i.object({query:b,path:b.optional(),glob:b.optional()}).strict(),list_files:i.object({path:b.optional(),glob:b.optional()}).strict(),changes:i.object({}).strict(),preview:i.object({port:Y,path:b.optional()}).strict()},ce={run:"Run a noninteractive command with a timeout. cwd and exports do not persist. Do not use for servers; use start_process, or file tools for reading and editing.",read_file:"Read numbered lines and a SHA-256; offset is a zero-based line index. Do not use for directory listings or binary contents.",write_file:"Create or replace a UTF-8 file. Do not use for a small change to an existing file; use edit_file.",edit_file:"Replace exactly one literal match. Do not use ambiguous snippets; include surrounding lines when a match is repeated.",start_process:"Start a named background process; with port, wait for readiness and return its URL. Do not use for short commands; use run.",process_logs:"Read a page of a named process's logs; pass the returned cursor for the next page. Do not restart a process to retrieve output.",stop_process:"Stop a named background process. Do not use to destroy the sandbox or stop unrelated processes.",search:"Find literal text in files under a path. Do not use for regular expressions; use run with rg instead.",list_files:"List files recursively under a path. Do not use to read file contents.",changes:"Show added, modified and removed files since these tools were created. Do not use for Git history.",preview:"Get the preview URL for a port. Do not use to start a server; use start_process first. Access headers stay server-side."},fe=["run","read_file","write_file","edit_file","start_process","process_logs","stop_process"],ee=(p)=>ie("sha256").update(p).digest("hex");function B(p,O={}){ue(p,"");let F=K.resolve("/workspace",O.root??"."),V=new Set(O.allow??fe);for(let n of O.deny??[])V.delete(n);function te(n="."){let l=K.resolve(F,n);if(l!==F&&!l.startsWith(F==="/"?"/":`${F}/`))s("Path escapes tool root. Use a path inside the configured root");return l}async function j(n="."){let l=te(n),u="/";for(let r of l.split("/").filter(Boolean)){u=K.join(u,r);try{if((await p.files.stat(u)).type==="symlink")s("Symlink path rejected. It may escape tool root. Use a regular path")}catch(m){if(!(m instanceof e&&m.code==="file_not_found"))throw m}}return l}async function Z(n){let l=await O.beforeRun?.(n);if(l===!1)s("Command denied by beforeRun. Application policy refused execution. Choose an allowed command");return t(l)?l:n}let R=(n)=>ue(p,n),D=new Map;function J(n,l){let u=D.get(n)??{buffer:Buffer.alloc(0),base:0,total:0},r=Buffer.from(R(l)),m=Buffer.concat([u.buffer,r]),y=u.total+r.length,N=m.subarray(-1048576);D.set(n,{buffer:N,base:y-N.length,total:y});while(D.size>8){let T=D.keys().next().value;if(T)D.delete(T)}}let S=new Map,P=new Map;function oe(n,l){let u=S.get(n);if(S.delete(n),u&&l>=u.base)return S.set(n,u),u;let r={after:void 0,more:!0,base:0,buffer:Buffer.alloc(0),pending:[],end:0,filter:le(p,(m)=>{let y=Buffer.from(m.text);r.pending.push(y),r.end+=y.length})};S.set(n,r);while(S.size>8){let m=S.keys().next().value;if(m)S.delete(m)}return r}async function re(n,l,u){let r=oe(n,l),m=p.process(n);while(r.end<l+u){let f=await m.logs({after:r.after,maxBytes:1048576});if(r.filter.push({stream:"stdout",text:f.text}),r.more=f.truncated&&f.nextCursor!==r.after,r.after=f.nextCursor,!r.more)break}if(!r.more&&(m.status==="exited"||m.status==="failed"))r.filter.flush();if(r.pending.length)r.buffer=Buffer.concat([r.buffer,...r.pending]),r.pending=[];if(l>r.end)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let y=r.buffer,N=(f)=>((y[f-r.base]??0)&192)===128,T=l,k=Math.min(r.end,l+u);while(T<r.end&&N(T))T++;while(k>T&&k<r.end&&N(k))k--;let C=y.subarray(T-r.base,k-r.base).toString(),U=Math.max(r.base,T-1048576);if(U>r.base)r.buffer=Buffer.from(y.subarray(U-r.base)),r.base=U;return{text:C,end:k,more:k<r.end||r.more}}async function se(n,l,u){let r=(P.get(n)??Promise.resolve()).catch(()=>{}).then(()=>re(n,l,u));P.set(n,r);try{return await r}finally{if(P.get(n)===r)P.delete(n)}}async function Q(){let n=new Map,l=await j();if(!await p.files.exists(l))return n;for(let u of await p.files.list(l,{recursive:!0}))if(u.type==="file")n.set(u.path,ee(await p.files.read(await j(u.path),{as:"bytes"})));return n}let q=V.has("changes")?Q().then((n)=>({value:n}),(n)=>({error:n})):void 0;function ne(n){let l=E[n],u=O.limits?.[n]??{},r=u.maxOutputBytes??16384,m=u.timeoutMs??30000;if(!Number.isSafeInteger(r)||r<256||!Number.isSafeInteger(m)||m<1)s("Tool limits must have maxOutputBytes >= 256 and timeoutMs > 0");for(let y of[u.maxReadBytes,u.maxMatches])if(y!==void 0&&(!Number.isSafeInteger(y)||y<1))s("maxReadBytes and maxMatches must be positive integers");return{name:n,description:ce[n],inputSchema:l,async execute(y,N,T){let k=Date.now(),C=!1;function U(d){try{O.onEvent?.(d)}catch{C=!0}try{N?.(d)}catch{C=!0}}function f(d,o,a="",c,x=""){let g=R(`${d?"OK":"FAILED"}${a?` ${a}`:""} ${((Date.now()-k)/1000).toFixed(1)}s${c?` cwd=${c}`:""}`),_=new L(Math.floor(r/4));_.add(g);let w=_.text(),h=new L(Math.max(1,r-Buffer.byteLength(w)-Buffer.byteLength(x)-100));return h.add(R(o+(C?`
|
|
2
|
+
UI streaming callback failed. Execution was allowed to finish. Fix onEvent before reconnecting the UI.`:""))),{text:R(`${w}
|
|
3
3
|
output:
|
|
4
|
-
${x}${h.text()}`)}}try{let d=de.parse({tool:n,input:y});if(q){let o=await q;if("error"in o&&d.tool==="changes")throw o.error}if(T?.aborted)s("Tool cancelled. The calling agent aborted execution. Retry only if still needed");switch(d.tool){case"run":{let o=d.input,a=await j(o.cwd),c=p.run(await Z(o.command),{cwd:a,timeoutMs:Math.min(o.timeoutMs??m,m),maxOutputBytes:r,signal:T}),x=new
|
|
4
|
+
${x}${h.text()}`)}}try{let d=de.parse({tool:n,input:y});if(q){let o=await q;if("error"in o&&d.tool==="changes")throw o.error}if(T?.aborted)s("Tool cancelled. The calling agent aborted execution. Retry only if still needed");switch(d.tool){case"run":{let o=d.input,a=await j(o.cwd),c=p.run(await Z(o.command),{cwd:a,timeoutMs:Math.min(o.timeoutMs??m,m),maxOutputBytes:r,signal:T}),x=new L(Math.max(1,r-512)),g=`run_${crypto.randomUUID().replaceAll("-","")}`;J(g,"");let _=le(p,(v)=>{x.add(v.text),J(g,v.text);let M={tool:n,kind:"output",stream:v.stream,text:R(v.text)};U(M)});try{for await(let v of c)_.push(v)}finally{_.flush()}let w=await c,h=x.text().replace(/\[(\d+) bytes cut\]/,"[$1 bytes cut, use process_logs]");return f(w.ok,`${h}${w.timedOut?T?.aborted?`
|
|
5
5
|
Aborted. The calling agent cancelled execution and the command was terminated. Retry only if still needed.`:`
|
|
6
6
|
Timed out. Command exceeded its limit and was terminated. Increase the configured timeout or use start_process for servers.`:""}${!w.ok&&!w.timedOut?`
|
|
7
7
|
Command exited with status ${w.exitCode}. Inspect the output and correct the command before retrying.`:""}`,`exit=${w.exitCode}`,a,x.truncated?`name=${g} cursor=0 use=process_logs
|
|
8
|
-
`:"")}case"read_file":{let o=d.input,a=await j(o.path),c=u.maxReadBytes??1048576,x=(await p.files.stat(a)).size;if(x>c)return f(!1,`File is ${x} bytes, above maxReadBytes=${c}. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let g=await
|
|
9
|
-
`),v=o.offset??0,
|
|
8
|
+
`:"")}case"read_file":{let o=d.input,a=await j(o.path),c=u.maxReadBytes??1048576,x=(await p.files.stat(a)).size;if(x>c)return f(!1,`File is ${x} bytes, above maxReadBytes=${c}. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let g=await we(p.files,a,c);if(g.length>c)return f(!1,`File grew above maxReadBytes=${c} while being read. Raise read_file's maxReadBytes or use run to extract a smaller file.`);let _=ee(g),w;try{if(w=new TextDecoder("utf-8",{fatal:!0}).decode(g),w.includes("\x00"))throw Error("binary")}catch{return f(!0,`binary file; size=${g.length} bytes; sha=${_}. Use download outside the agent tools to retrieve bytes.`)}let h=R(w).split(`
|
|
9
|
+
`),v=o.offset??0,M=[],A=0;for(let[z,ae]of h.slice(v,v+(o.limit??200)).entries()){let H=`${v+z+1}: ${ae}`;if(M.length&&A+Buffer.byteLength(H)>r-600)break;M.push(H),A+=Buffer.byteLength(H)+1}let I=v+M.length,X="";if(A>r-600){let z=`read_${crypto.randomUUID().replaceAll("-","")}`;J(z,M.join(`
|
|
10
10
|
`)),X=`name=${z} cursor=0 use=process_logs
|
|
11
|
-
`}return f(!0,`${
|
|
11
|
+
`}return f(!0,`${M.join(`
|
|
12
12
|
`)}
|
|
13
|
-
${
|
|
13
|
+
${I<h.length?"[more lines; use read_file with nextOffset as offset]":""}`,"",void 0,`sha=${_} lines=${h.length} nextOffset=${I<h.length?I:"end"}
|
|
14
14
|
${X}`)}case"write_file":{let o=d.input;return await p.files.write(await j(o.path),o.content),f(!0,"File written.")}case"edit_file":{let o=d.input;return await p.files.edit(await j(o.path),{find:o.find,replace:o.replace}),f(!0,"One exact match replaced.")}case"start_process":{let o=d.input,a;try{a=await p.start(await Z(o.command),{name:o.name,cwd:await j(o.cwd),ready:o.port?{port:o.port}:void 0,readyTimeoutMs:m})}catch(c){if(!(c instanceof e&&c.code==="timeout"))throw c;return f(!1,`name=${o.name} ready=false cursor=0
|
|
15
15
|
${c.message}
|
|
16
16
|
Use process_logs to inspect startup or stop_process to terminate it.`)}return f(a.status!=="failed",`name=${o.name} ready=${a.ready} status=${a.status} url=${a.url??"none"}
|
|
17
17
|
cursor=0
|
|
18
18
|
Use process_logs to inspect output.${!a.ready?`
|
|
19
|
-
Not ready. The process may still be running. Use stop_process to stop it.`:""}`)}case"process_logs":{let o=d.input,a=
|
|
19
|
+
Not ready. The process may still be running. Use stop_process to stop it.`:""}`)}case"process_logs":{let o=d.input,a=D.get(o.name);if(a){let g=o.cursor===void 0?a.base:Number(o.cursor);if(!Number.isSafeInteger(g)||g<0||g>a.total)s("Invalid foreground log cursor. It is outside the retained output. Use cursor=0 to replay");let _=Math.max(g,a.base),w=(A)=>{let I=a.buffer[A-a.base];return I!==void 0&&(I&192)===128};while(_<a.total&&w(_))_++;let h=Math.min(a.total,_+Math.max(64,r-512));while(h>_&&h<a.total&&w(h))h--;let v=a.buffer.subarray(_-a.base,h-a.base).toString(),M={tool:n,kind:"output",stream:"stdout",text:R(v)};return U(M),f(!0,`cursor=${h} more=${h<a.total}
|
|
20
20
|
${g<a.base?`[${a.base-g} bytes expired from replay window]
|
|
21
21
|
`:""}${v}${h<a.total?`
|
|
22
|
-
[more output; use process_logs with cursor]`:""}`)}let c=o.cursor===void 0?0:Number(o.cursor);if(!Number.isSafeInteger(c)||c<0)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let x=await
|
|
22
|
+
[more output; use process_logs with cursor]`:""}`)}let c=o.cursor===void 0?0:Number(o.cursor);if(!Number.isSafeInteger(c)||c<0)s("Log cursor is invalid or expired after rotation. The retained log view changed. Use cursor=0 to replay");let x=await se(o.name,c,Math.max(32,r-512));return U({tool:n,kind:"output",stream:"stdout",text:x.text}),f(!0,`${x.text}${x.more?`
|
|
23
23
|
[more output; use process_logs with cursor]`:""}`,"",void 0,`cursor=${x.end} more=${x.more}
|
|
24
24
|
`)}case"stop_process":return await p.process(d.input.name).stop(),f(!0,"Process stopped.");case"search":{let o=d.input;return f(!0,JSON.stringify(await p.files.search(o.query,{path:await j(o.path),glob:o.glob,maxMatches:u.maxMatches??100})))}case"list_files":{let o=d.input;return f(!0,JSON.stringify(await p.files.list(await j(o.path),{recursive:!0,glob:o.glob})))}case"changes":{let o=await q;if(!o||!("value"in o))s("Changes baseline unavailable");let a=await Q();return f(!0,JSON.stringify({added:[...a.keys()].filter((c)=>!o.value.has(c)),modified:[...a.keys()].filter((c)=>o.value.has(c)&&o.value.get(c)!==a.get(c)),removed:[...o.value.keys()].filter((c)=>!a.has(c))}))}case"preview":{let o=d.input;if(o.path&&(!o.path.startsWith("/")||o.path.startsWith("//")))s("Preview path must be an absolute URL path. External URLs are not allowed. Use /path");let a=await p.preview(o.port,{path:o.path});return f(!0,`url=${a.url}`)}default:return d}}catch(d){if(d instanceof e)return f(!1,`${d.message}
|
|
25
25
|
code=${d.code} retryable=${d.retryable}
|
|
26
|
-
Next: ${d.hint}`);if(d instanceof i.ZodError)return f(!1,"Invalid tool input. Parameters do not match the tool schema. Check the required fields and types, then retry.");return f(!1,"Tool failed. An unexpected execution or callback error occurred. Check server-side diagnostics and retry.")}}}}return[...V].map((n)=>
|
|
27
|
-
export{
|
|
26
|
+
Next: ${d.hint}`);if(d instanceof i.ZodError)return f(!1,"Invalid tool input. Parameters do not match the tool schema. Check the required fields and types, then retry.");return f(!1,"Tool failed. An unexpected execution or callback error occurred. Check server-side diagnostics and retry.")}}}}return[...V].map((n)=>ne(n))}var de=i.discriminatedUnion("tool",[i.object({tool:i.literal("run"),input:E.run}),i.object({tool:i.literal("read_file"),input:E.read_file}),i.object({tool:i.literal("write_file"),input:E.write_file}),i.object({tool:i.literal("edit_file"),input:E.edit_file}),i.object({tool:i.literal("start_process"),input:E.start_process}),i.object({tool:i.literal("process_logs"),input:E.process_logs}),i.object({tool:i.literal("stop_process"),input:E.stop_process}),i.object({tool:i.literal("search"),input:E.search}),i.object({tool:i.literal("list_files"),input:E.list_files}),i.object({tool:i.literal("changes"),input:E.changes}),i.object({tool:i.literal("preview"),input:E.preview})]);
|
|
27
|
+
export{E,B};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{p,l,fe,xe,ve,L,Q,O,me}from"./chunk-sjnk17y5.js";export{L as BufferCap,Q as OutputBus,xe as activityScanCommand,O as chunkRedactor,p as defaults,ve as isRunActive,me as makeRun,l as pathOf,fe as secretRecoveryCommand};
|
package/dist/errors.d.ts
CHANGED
|
@@ -62,19 +62,19 @@ export declare class Redactor {
|
|
|
62
62
|
error(cause: unknown, provider: string, sandboxId?: string): SandboxError;
|
|
63
63
|
}
|
|
64
64
|
/** @internal Removes credential-shaped text (URLs, auth headers, key=value secrets, control characters) and bounds the length. */
|
|
65
|
-
export declare function scrub(text: string): string;
|
|
65
|
+
export declare function scrub(text: string, max?: number): string;
|
|
66
66
|
/**
|
|
67
|
-
*
|
|
67
|
+
* `Name: message` of a native failure, redacted, scrubbed and bounded, with up to two nested causes.
|
|
68
68
|
* Undefined for thrown values that are not Errors, which carry no message to keep.
|
|
69
69
|
*/
|
|
70
70
|
export declare function nativeDetail(cause: unknown, redact?: (text: string) => string, depth?: number): string | undefined;
|
|
71
|
-
/**
|
|
71
|
+
/** What {@link describeNative} keeps: text for the message, and the error's cause. */
|
|
72
72
|
export interface NativeDescription {
|
|
73
73
|
detail?: string;
|
|
74
74
|
cause?: string;
|
|
75
75
|
}
|
|
76
76
|
/**
|
|
77
|
-
*
|
|
77
|
+
* What an adapter keeps from a native failure. Only a failure the adapter did not recognize
|
|
78
78
|
* (`code` is `provider`, unless `known` says otherwise) and that carries no `status` keeps its text:
|
|
79
79
|
* that is an SDK bug or a network error, and the text is the only clue. A recognized error type or a response may carry server text that
|
|
80
80
|
* echoes the request, so it keeps only its name and status. `detail` is the kept text, for the message;
|
|
@@ -88,8 +88,9 @@ export declare function describeNative(cause: unknown, options: {
|
|
|
88
88
|
}): NativeDescription;
|
|
89
89
|
/**
|
|
90
90
|
* @internal Bounded machine fields an adapter copies from a native failure, each already checked
|
|
91
|
-
* against an allowlist and the secrets it knows. Never a response's
|
|
92
|
-
* `native` is at most the scrubbed text
|
|
91
|
+
* against an allowlist and the secrets it knows. Never a response's body, headers or URL, and a
|
|
92
|
+
* response's message only as `providerMessage`; `native` is at most the scrubbed text
|
|
93
|
+
* {@link describeNative} keeps.
|
|
93
94
|
*/
|
|
94
95
|
export interface NativeEvidence {
|
|
95
96
|
operation?: string;
|
|
@@ -99,7 +100,16 @@ export interface NativeEvidence {
|
|
|
99
100
|
source?: string;
|
|
100
101
|
nativeName?: string;
|
|
101
102
|
native?: string;
|
|
102
|
-
/**
|
|
103
|
+
/** The provider's name for `providerCode`, such as gRPC `FAILED_PRECONDITION`. */
|
|
104
|
+
providerStatus?: string;
|
|
105
|
+
/** A machine-readable reason the provider attached, such as boxd's `x-boxd-error-reason` trailer. */
|
|
106
|
+
providerReason?: string;
|
|
107
|
+
/**
|
|
108
|
+
* The provider's own text for a failed control-plane call (create, pause, resume, snapshot), redacted,
|
|
109
|
+
* scrubbed and bounded. Never kept for guest file or command calls, whose text can echo user paths.
|
|
110
|
+
*/
|
|
111
|
+
providerMessage?: string;
|
|
112
|
+
/** Luxor create: the session this call created, and how far it got. */
|
|
103
113
|
admittedByThisCall?: true;
|
|
104
114
|
stage?: string;
|
|
105
115
|
sandboxId?: string;
|
|
@@ -113,9 +123,9 @@ export interface NativeEvidence {
|
|
|
113
123
|
* own error.
|
|
114
124
|
*/
|
|
115
125
|
export declare function evidenceCause(evidence: NativeEvidence): Error & NativeEvidence;
|
|
116
|
-
/**
|
|
126
|
+
/** A redact function for values an adapter knows, such as its API key. Empty values are skipped. */
|
|
117
127
|
export declare function redacting(values: Iterable<string | undefined>): (text: string) => string;
|
|
118
|
-
/**
|
|
128
|
+
/** Why an adapter request failed, as a clause, never the code itself: the kept detail, or what `code` means. */
|
|
119
129
|
export declare function reason(code: ErrorCode, detail?: string): string;
|
|
120
130
|
/**
|
|
121
131
|
* @internal The shared HTTP status mapper. Provider hooks refine it (a 404 for a missing file, a stale route).
|
package/dist/files.d.ts
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
|
-
import type { Provider, FileInfo, WriteOptions } from "./provider.js";
|
|
1
|
+
import type { Provider, FileEvent, FileInfo, WriteOptions } from "./provider.js";
|
|
2
2
|
import { SandboxError, type Redactor } from "./errors.js";
|
|
3
|
-
export
|
|
4
|
-
type: "added" | "modified" | "removed";
|
|
5
|
-
path: string;
|
|
6
|
-
}
|
|
3
|
+
export type { FileEvent };
|
|
7
4
|
export interface FileDiff {
|
|
8
5
|
added: string[];
|
|
9
6
|
modified: string[];
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { Provider, Capability, SandboxInfo } from "./provider.js";
|
|
1
|
+
import type { Provider, Capability, SandboxInfo, TemplateBuildOptions, TemplateInfo, TemplateSpec } from "./provider.js";
|
|
2
2
|
import type { ConnectOptions, CreateOptions, ListOptions, MethodsFor, ProviderSandbox, ReapOptions, SandboxBase } from "./types.js";
|
|
3
3
|
export { SandboxError } from "./errors.js";
|
|
4
4
|
export type { ErrorCode, ErrorOptions } from "./errors.js";
|
|
5
|
-
export type { Sandbox, SandboxBase, ProviderSandbox, CreateOptions, ConnectOptions, ListOptions, ReapOptions, PreviewOptions, Usage, Locator, RunOptions, RunHandle, RunResult, OutputChunk, Capability, CapabilityMethods, MethodsFor, SandboxInfo, FileInfo, Labels, Preview, Terminal, } from "./types.js";
|
|
6
|
-
export type { WriteOptions, SnapshotOptions } from "./provider.js";
|
|
5
|
+
export type { Sandbox, SandboxBase, ProviderSandbox, CreateOptions, ConnectOptions, ListOptions, ReapOptions, PreviewOptions, Usage, Locator, RunOptions, RunHandle, RunResult, OutputChunk, Capability, CapabilityMethods, MethodsFor, SandboxInfo, FileInfo, Labels, Preview, Terminal, TerminalOptions, } from "./types.js";
|
|
6
|
+
export type { WriteOptions, SnapshotOptions, TemplateSpec, TemplateBuildOptions, TemplateInfo, } from "./provider.js";
|
|
7
7
|
export type { NativeApi, NativeRequestOptions, HttpMethod } from "./native.js";
|
|
8
8
|
export type { Files, FileDiff, FileEvent } from "./files.js";
|
|
9
9
|
export type { ProcessHandle, ProcessInfo, StartOptions, Readiness } from "./processes.js";
|
|
@@ -17,3 +17,24 @@ export declare function createSandbox<P extends Provider>(provider: P, options?:
|
|
|
17
17
|
export declare function connectSandbox<P extends Provider>(provider: P, id: string, options?: ConnectOptions): Promise<ProviderSandbox<P>>;
|
|
18
18
|
export declare function listSandboxes(provider: Provider, options?: ListOptions): Promise<SandboxInfo[]>;
|
|
19
19
|
export declare function reapSandboxes(provider: Provider, options?: ReapOptions): Promise<number>;
|
|
20
|
+
/** The members of a provider type, or of a union of them, that do not declare `K`. */
|
|
21
|
+
type Lacking<P, K extends Capability> = P extends Provider<infer _N, infer C, infer _X> ? ([K] extends [C] ? never : P) : never;
|
|
22
|
+
/** `unknown` when every member of `P` declares `K`, else a property that names the missing capability. */
|
|
23
|
+
type Requires<P, K extends Capability> = [Lacking<P, K>] extends [never] ? unknown : {
|
|
24
|
+
readonly missingCapability: K;
|
|
25
|
+
};
|
|
26
|
+
/** The template spec a provider accepts: its own widened spec, or the portable one. */
|
|
27
|
+
export type TemplateSpecOf<P> = P extends {
|
|
28
|
+
buildTemplate(spec: infer S extends TemplateSpec, options: TemplateBuildOptions): Promise<TemplateInfo>;
|
|
29
|
+
} ? S : TemplateSpec;
|
|
30
|
+
/**
|
|
31
|
+
* Delete a snapshot by the ID `box.snapshot()` returned. Resolves `true` when it was deleted and `false`
|
|
32
|
+
* when it was already gone. Needs a provider with the `"snapshot-delete"` capability.
|
|
33
|
+
*/
|
|
34
|
+
export declare function deleteSnapshot<P extends Provider>(provider: P & Requires<P, "snapshot-delete">, snapshotId: string): Promise<boolean>;
|
|
35
|
+
/**
|
|
36
|
+
* Build a reusable template and wait until it is ready. Sandboxes start from it with
|
|
37
|
+
* `createSandbox(provider, { from: template.id })`. Needs a provider with the `"templates"` capability;
|
|
38
|
+
* the spec type widens to the provider's own fields.
|
|
39
|
+
*/
|
|
40
|
+
export declare function buildTemplate<P extends Provider>(provider: P & Requires<P, "templates">, spec: TemplateSpecOf<P>, options?: TemplateBuildOptions): Promise<TemplateInfo>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ae,D,V,oe,de,be,ge}from"./chunk-3h6c1ack.js";import{e}from"./chunk-0eeyc0aq.js";export{e as SandboxError,ge as buildTemplate,V as connectSandbox,D as createSandbox,be as deleteSnapshot,ae as hasCapability,oe as listSandboxes,de as reapSandboxes};
|
package/dist/mastra.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-sjnk17y5.js";import{B}from"./chunk-x4rrgmxf.js";import"./chunk-aek8n3a4.js";import{createTool as s}from"@mastra/core/tools";import{z as e}from"zod";function c(p,r){return Object.fromEntries(B(p,r).map((o)=>[o.name,s({id:o.name,description:o.description,inputSchema:o.inputSchema,outputSchema:e.object({text:e.string()}),execute:(t,a)=>o.execute(t,void 0,a?.abortSignal),toModelOutput:(t)=>({type:"text",value:t.text})})]))}export{c as sandboxTools};
|
package/dist/memory.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e}from"./chunk-
|
|
1
|
+
import{e}from"./chunk-0eeyc0aq.js";import{posix as u}from"node:path";function V(L={}){let b=new Map,g=new Map,w=(r,t)=>new e(`${r}. Memory resource does not exist or request is invalid. Check the path or ID.`,{code:t,provider:"memory"}),v=(r)=>{let t=b.get(r);if(!t)throw w(`Sandbox ${r} not found`,"not_found");if(t.idleTimeoutMs)clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.active.size)v(r);else S.destroy(r)},t.idleTimeoutMs),t.idleTimer.unref?.();return t},M=(r,t)=>{let n=v(r).nodes.get(u.resolve("/",t));if(!n)throw w(`File ${t} not found`,"file_not_found");return n},I=()=>Date.now();function P(r,t){let n=v(r);for(let o=u.resolve("/",t);;o=u.dirname(o)){let s=n.nodes.get(o);if(s?.data)throw w(`${o} is not a directory`,"invalid_argument");if(!s)n.nodes.set(o,{data:null,modifiedAt:I(),mode:493});if(o==="/")break}}let C={transfer:"files",checkpoints:"files",writeCreatesParents:!0,writeSupportsMode:!0,async readRange(r,t,n){let o=M(r,t);if(o.data===null)throw w(`${t} is a directory`,"invalid_argument");return o.data.slice(n.offset,n.offset+n.length)},async read(r,t){let n=M(r,t);if(n.data===null)throw w(`${t} is a directory`,"invalid_argument");return n.data.slice()},async write(r,t,n,o){let s=v(r);P(r,u.dirname(t));let i=u.resolve("/",t),m=s.nodes.get(i);s.nodes.set(i,{data:n.slice(),modifiedAt:Math.max(I(),(m?.modifiedAt??0)+1),mode:o?.mode??m?.mode??420})},async stat(r,t){let n=M(r,t);return{path:u.resolve("/",t),type:n.data===null?"directory":"file",size:n.data?.length??0,modifiedAt:n.modifiedAt}},async list(r,t){let n=u.resolve("/",t);if(M(r,t).data!==null)throw w(`${t} is not a directory`,"invalid_argument");let o=[];for(let s of v(r).nodes.keys())if(s!==n&&u.dirname(s)===n)o.push(await C.stat(r,s));return o.sort((s,i)=>s.path.localeCompare(i.path))},async remove(r,t,n){let o=v(r),s=u.resolve("/",t);M(r,s);let i=[...o.nodes.keys()].filter((m)=>m.startsWith(s+"/"));if(i.length&&!n.recursive)throw w(`${t} is not empty`,"invalid_argument");for(let m of i)o.nodes.delete(m);o.nodes.delete(s)},async mkdir(r,t){P(r,t)}},Z=({args:r,signal:t})=>new Promise((n)=>{if(t.aborted){n(137);return}let o=setTimeout(()=>{t.removeEventListener("abort",s),n(0)},Math.max(0,Number(r[0]??0)*1000)),s=()=>{clearTimeout(o),n(137)};t.addEventListener("abort",s,{once:!0})});g.set("echo",({args:r,stdout:t})=>{let n=r[0]==="-n";return t((n?r.slice(1):r).join(" ")+(n?"":`
|
|
2
2
|
`)),0}),g.set("printf",({args:r,stdout:t})=>{let n=1;return t((r[0]??"").replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\t/g,"\t").replace(/%[sd%]/g,(o)=>o==="%%"?"%":r[n++]??"")),0}),g.set("pwd",({cwd:r,stdout:t})=>(t(r+`
|
|
4
4
|
`),0)),g.set("true",()=>0),g.set("false",()=>1),g.set("exit",({args:r})=>Number(r[0]??0)),g.set("sleep",Z),g.set("cat",async({args:r,stdin:t,stdout:n,stderr:o,files:s})=>{if(!r.length)n(t);else for(let i of r)try{n(new TextDecoder().decode(await s.read(i)))}catch{return o(`cat: ${i}: No such file or directory
|
package/dist/openai.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-sjnk17y5.js";import{B}from"./chunk-x4rrgmxf.js";import"./chunk-aek8n3a4.js";import{tool as r}from"@openai/agents";function m(t,e){return B(t,e).map((o)=>r({name:o.name,description:o.description,parameters:o.inputSchema,strict:!0,execute:async(s,n,a)=>(await o.execute(s,void 0,a?.signal)).text}))}export{m as sandboxTools};
|
package/dist/provider.d.ts
CHANGED
|
@@ -4,7 +4,14 @@
|
|
|
4
4
|
* on timeout/abort. Optional methods must agree with capabilities. No core policy
|
|
5
5
|
* (redaction, edit, git, process records, readiness) belongs in an adapter.
|
|
6
6
|
*/
|
|
7
|
-
|
|
7
|
+
import type { SandboxBase } from "./types.js";
|
|
8
|
+
/**
|
|
9
|
+
* Portable optional features. Sandbox-level ones add methods to the handle (`pause`, `snapshot`,
|
|
10
|
+
* `terminal`); provider-level ones gate root functions (`snapshot-delete` for `deleteSnapshot`,
|
|
11
|
+
* `templates` for `buildTemplate`); `network-policy` and `size` gate creation options.
|
|
12
|
+
* Provider-specific features belong in {@link Provider.extensions} instead.
|
|
13
|
+
*/
|
|
14
|
+
export type Capability = "pause" | "snapshot" | "snapshot-delete" | "templates" | "terminal" | "network-policy" | "size";
|
|
8
15
|
export type Labels = Record<string, string>;
|
|
9
16
|
export interface SandboxInfo {
|
|
10
17
|
id: string;
|
|
@@ -70,6 +77,11 @@ export interface SnapshotOptions {
|
|
|
70
77
|
/** Delete the snapshot after this many milliseconds. `0` keeps it until you delete it, where the provider allows that. */
|
|
71
78
|
expiresInMs?: number;
|
|
72
79
|
}
|
|
80
|
+
/** One file change. Paths are absolute. */
|
|
81
|
+
export interface FileEvent {
|
|
82
|
+
type: "added" | "modified" | "removed";
|
|
83
|
+
path: string;
|
|
84
|
+
}
|
|
73
85
|
export interface ProviderFiles {
|
|
74
86
|
/** Use primitive file transfers when guest tar is missing or incompatible with GNU archives. */
|
|
75
87
|
readonly transfer?: "files";
|
|
@@ -105,6 +117,16 @@ export interface ProviderFiles {
|
|
|
105
117
|
offset: number;
|
|
106
118
|
length: number;
|
|
107
119
|
}): Promise<Uint8Array>;
|
|
120
|
+
/**
|
|
121
|
+
* Native change events for `files.watch`, instead of the core's polling. Call `onEvent` for each change
|
|
122
|
+
* under `path` (children only unless `recursive`) until `signal` aborts, then resolve. Reject when the
|
|
123
|
+
* watch cannot start or breaks; reject with `unsupported` to make the core poll instead.
|
|
124
|
+
*/
|
|
125
|
+
watch?(id: string, path: string, options: {
|
|
126
|
+
recursive: boolean;
|
|
127
|
+
signal: AbortSignal;
|
|
128
|
+
onEvent(event: FileEvent): void;
|
|
129
|
+
}): Promise<void>;
|
|
108
130
|
read(id: string, path: string): Promise<Uint8Array>;
|
|
109
131
|
write(id: string, path: string, data: Uint8Array, options?: WriteOptions): Promise<void>;
|
|
110
132
|
list(id: string, path: string): Promise<FileInfo[]>;
|
|
@@ -119,12 +141,77 @@ export interface Preview {
|
|
|
119
141
|
headers?: Record<string, string>;
|
|
120
142
|
expiresAt?: number;
|
|
121
143
|
}
|
|
144
|
+
/** Options for `box.terminal()`. The adapter receives `cwd` as an absolute path and `env` merged with the handle's. */
|
|
145
|
+
export interface TerminalOptions {
|
|
146
|
+
cols: number;
|
|
147
|
+
rows: number;
|
|
148
|
+
/** Working directory of the shell. Relative paths resolve against `/workspace`. Default: `/workspace`. */
|
|
149
|
+
cwd?: string;
|
|
150
|
+
/** Extra environment variables for the shell. */
|
|
151
|
+
env?: Record<string, string>;
|
|
152
|
+
}
|
|
153
|
+
/** An interactive PTY. Output arrives as text through `onData`. */
|
|
122
154
|
export interface Terminal {
|
|
123
155
|
write(data: string): void | Promise<void>;
|
|
124
156
|
resize(cols: number, rows: number): void | Promise<void>;
|
|
125
157
|
onData(callback: (data: string) => void): () => void;
|
|
126
158
|
close(): void | Promise<void>;
|
|
159
|
+
/** Resolves when the shell exits. Present only when the provider reports the exit. */
|
|
160
|
+
wait?(): Promise<{
|
|
161
|
+
exitCode: number | null;
|
|
162
|
+
}>;
|
|
127
163
|
}
|
|
164
|
+
/** A portable template definition for {@link Provider.buildTemplate}. Providers may accept more fields. */
|
|
165
|
+
export interface TemplateSpec {
|
|
166
|
+
/** Template name. Pass it to the provider factory's template option, or the returned `id` as `from`. */
|
|
167
|
+
name: string;
|
|
168
|
+
/** Base container image, such as `"node:22-bookworm"`. Default: the provider's base image. */
|
|
169
|
+
image?: string;
|
|
170
|
+
/** Environment variables for the build steps only. Give sandboxes their own with `createSandbox({ env })`. */
|
|
171
|
+
env?: Record<string, string>;
|
|
172
|
+
/** Working directory for the build steps that follow. Commands in sandboxes still default to `/workspace`. */
|
|
173
|
+
workdir?: string;
|
|
174
|
+
/** Shell commands run in order, each as one build step. */
|
|
175
|
+
run?: readonly string[];
|
|
176
|
+
/** CPU and memory for sandboxes made from the template, where the provider sets them per template. */
|
|
177
|
+
size?: {
|
|
178
|
+
cpu: number;
|
|
179
|
+
memoryMb: number;
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** Options for one template build. */
|
|
183
|
+
export interface TemplateBuildOptions {
|
|
184
|
+
/** One deadline for the whole build, polling included. Default: the provider's (30 minutes for E2B). */
|
|
185
|
+
timeoutMs?: number;
|
|
186
|
+
signal?: AbortSignal;
|
|
187
|
+
/** Build log lines as the provider reports them. */
|
|
188
|
+
onLog?(line: string): void;
|
|
189
|
+
}
|
|
190
|
+
/** A finished template. */
|
|
191
|
+
export interface TemplateInfo {
|
|
192
|
+
/** The provider's template ID, usable as `createSandbox(provider, { from: id })`. */
|
|
193
|
+
id: string;
|
|
194
|
+
name: string;
|
|
195
|
+
buildId?: string;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* One provider-specific feature set: async methods only. The core binds it lazily to each handle as
|
|
199
|
+
* `box.ext.<name>`, checks the handle is open before every call, and redacts the errors it throws.
|
|
200
|
+
* Returned values are the provider's own data, as with `box.native`.
|
|
201
|
+
*/
|
|
202
|
+
export type ExtensionMethods = {
|
|
203
|
+
readonly [method: string]: (...args: never[]) => Promise<ExtensionResult>;
|
|
204
|
+
};
|
|
205
|
+
/** What an extension method resolves with: any value, so each method keeps its own declared type. */
|
|
206
|
+
export type ExtensionResult = object | string | number | boolean | bigint | symbol | null | undefined | void;
|
|
207
|
+
/** Extension sets by name, such as `{ e2b: { metrics(): Promise<...> } }`. */
|
|
208
|
+
export type Extensions = {
|
|
209
|
+
readonly [name: string]: ExtensionMethods;
|
|
210
|
+
};
|
|
211
|
+
/** What a provider declares for each extension: a factory given the sandbox ID and its handle. */
|
|
212
|
+
export type ExtensionFactories<Native, X extends Extensions> = {
|
|
213
|
+
readonly [K in keyof X]: (id: string, box: SandboxBase<Native>) => X[K];
|
|
214
|
+
};
|
|
128
215
|
/** Native hooks are optional optimizations. Persistent records remain core-owned. */
|
|
129
216
|
export interface NativeProcess {
|
|
130
217
|
pid: number;
|
|
@@ -136,7 +223,7 @@ export interface NativeProcess {
|
|
|
136
223
|
graceMs: number;
|
|
137
224
|
}): Promise<void>;
|
|
138
225
|
}
|
|
139
|
-
export interface Provider<Native = unknown, C extends Capability = Capability> {
|
|
226
|
+
export interface Provider<Native = unknown, C extends Capability = Capability, X extends Extensions = {}> {
|
|
140
227
|
readonly name: string;
|
|
141
228
|
readonly keyMode: "exact" | "best-effort";
|
|
142
229
|
/** Omission uses native hooks or the portable shell process-record shim. "stream" is for
|
|
@@ -176,10 +263,13 @@ export interface Provider<Native = unknown, C extends Capability = Capability> {
|
|
|
176
263
|
snapshot?(id: string, options?: SnapshotOptions): Promise<{
|
|
177
264
|
id: string;
|
|
178
265
|
}>;
|
|
179
|
-
terminal?(id: string, options:
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
266
|
+
terminal?(id: string, options: TerminalOptions): Promise<Terminal>;
|
|
267
|
+
/** Delete a snapshot by ID. `false` when it was already gone. Requires `"snapshot-delete"`. */
|
|
268
|
+
deleteSnapshot?(snapshotId: string): Promise<boolean>;
|
|
269
|
+
/** Build a template and wait until it is ready. Requires `"templates"`. Widen `spec` for provider fields. */
|
|
270
|
+
buildTemplate?(spec: TemplateSpec, options: TemplateBuildOptions): Promise<TemplateInfo>;
|
|
271
|
+
/** Provider-specific features, exposed as `box.ext.<name>`. They keep the portable API free of one provider's shape. */
|
|
272
|
+
readonly extensions?: ExtensionFactories<Native, X>;
|
|
183
273
|
startProcess?(id: string, input: Omit<ExecInput, "timeoutMs">): Promise<NativeProcess>;
|
|
184
274
|
/** Secret recovery without a shell, for runtimes that cannot run the core's recovery
|
|
185
275
|
* command. Return the text of /tmp/.sandbox-sdk/secret-names.json and the environment a
|
|
@@ -190,7 +280,12 @@ export interface Provider<Native = unknown, C extends Capability = Capability> {
|
|
|
190
280
|
environment: Record<string, string>;
|
|
191
281
|
} | undefined>;
|
|
192
282
|
}
|
|
193
|
-
export {
|
|
283
|
+
export { SandboxError, describeNative, redacting, reason } from "./errors.js";
|
|
284
|
+
export type { ErrorCode, ErrorOptions, NativeDescription } from "./errors.js";
|
|
285
|
+
export { connectEnvelope, connectEnvelopes, streamFault } from "./streams.js";
|
|
286
|
+
export type { ConnectFrame, StreamFault, StreamOptions } from "./streams.js";
|
|
287
|
+
export type { JsonValue, JsonObject } from "./shared/json.js";
|
|
288
|
+
export { createHttpClient, createDeadline, sleep } from "./http.js";
|
|
194
289
|
export type { HttpClient, HttpClientOptions, HttpPlane, HttpRequest, StreamRequest, HttpResponse, HttpFailure, FailedRequest, ErrorBody, PlaneContext, Fetch, Deadline, StaleVerdict, } from "./http.js";
|
|
195
290
|
export { createNativeApi, sdkConstruct, sdkCall } from "./native.js";
|
|
196
291
|
export type { NativeApi, NativeApiOptions, NativeSdkBinding, NativeRequestOptions, NativeSdkLoader, AnyNativeSdk, HttpMethod, } from "./native.js";
|
package/dist/provider.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{w,v
|
|
1
|
+
import"./chunk-g5n5xcmp.js";import{z,te,ne}from"./chunk-x05t86n3.js";import{b,S,P}from"./chunk-ek44atpe.js";import{f,w,v}from"./chunk-2999xbh7.js";import{e,i,d,a}from"./chunk-0eeyc0aq.js";export{e as SandboxError,ne as connectEnvelope,te as connectEnvelopes,f as createDeadline,v as createHttpClient,b as createNativeApi,i as describeNative,a as reason,d as redacting,P as sdkCall,S as sdkConstruct,w as sleep,z as streamFault};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
${r.command}`,{cwd:r.cwd,env:r.env,timeoutMs:r.timeoutMs,signal:r.signal,output:{capture:"none"},onStdout(v){let
|
|
1
|
+
import{u}from"../../chunk-pdgnaxp9.js";import{h}from"../../chunk-qfhee1t8.js";import{n}from"../../chunk-2ts3evzh.js";import{e,y,i,a}from"../../chunk-0eeyc0aq.js";import{randomUUID as I}from"node:crypto";import{posix as V}from"node:path";function m(o,d="provider",p,l){return new e(`${o}. Check the agentOS runtime or use local() with Docker.`,{code:d,provider:"agentos",sandboxId:p,cause:l})}function E(o,d,p=!1){if(o instanceof e)return o;let{message:l}=u(o),w=/ENOENT|not found|no such file/i.test(l)?p?"file_not_found":"not_found":/limit|quota|ENOSPC/i.test(l)?"quota":/sidecar.*(exit|closed|missing)|cannot find package|module not found/i.test(l)?"unavailable":/EACCES|EPERM|invalid|EINVAL/i.test(l)?"invalid_argument":"provider",A=i(o,{code:w});return m(`agentOS operation failed: ${a(w,A.detail)}`,w,d,A.cause)}function D(){return{entries:new Map,keys:new Map,destroying:new Map}}var R="sha256:35ae142556050de3604342574494373c318adff3ac3b50ea6b7420c0a033d2d8",j=`https://releases.rivet.dev/agent-os/0.4.1/software/packages/git/${R.slice(7)}.aospkg`;function S(o){return{...o,labels:{...o.labels}}}function F(o,d){let p="file";if(d.isSymbolicLink)p="symlink";else if(d.isDirectory)p="directory";return{path:o,type:p,size:d.size,modifiedAt:d.mtimeMs}}function _(o){return typeof o==="object"&&o!==null&&!Array.isArray(o)&&typeof o.size==="number"&&typeof o.modifiedAt==="number"}async function z(o,d,p){if(!(p??(d!=="/"&&(await o.filesystem.readdirEntries(V.dirname(d))).find((A)=>A.name===V.basename(d))?.isSymbolicLink)))return F(d,await o.filesystem.stat(d));let w=await o.javascript.evaluate(`(() => { const s = require("node:fs").lstatSync(${JSON.stringify(d)}); return { size: s.size, modifiedAt: s.mtimeMs }; })()`);if(w.outcome!=="succeeded"||!_(w.value))throw m("agentOS could not read symbolic link metadata","provider");return{path:d,type:"symlink",size:w.value.size,modifiedAt:w.value.modifiedAt}}async function q(o,d,p){let l=await o.javascript.evaluate(`(() => { require("node:fs").chmodSync(${JSON.stringify(d)}, ${p}); return true; })()`);if(l.outcome!=="succeeded"||l.value!==!0)throw m("agentOS could not set the file mode","provider")}function T(o,d,p){let{entries:l,keys:w,destroying:A}=p,L,N=()=>L??=h("@rivet-dev/agentos-core","agentos",d).catch((t)=>{throw m("Install @rivet-dev/agentos-core@0.4.1 and its platform sidecar package","unavailable",void 0,y(t))});function P(t){let r=l.get(t);if(!r)throw m("Sandbox does not exist in this application process","not_found",t);return r}async function b(t,r,s=!1){try{return await r(P(t).vm)}catch(c){throw E(c,t,s)}}let M={name:"agentos",inlineActivity:!0,keyMode:"exact",processMode:"unsupported",capabilities:new Set(["network-policy"]),async create(t){if(t.size!==void 0||t.from!==void 0)throw m("agentOS cannot enforce machine sizes or restore SDK snapshots","unsupported");if(t.idleTimeoutMs!==void 0||t.timeoutMs!==void 0)throw m("agentOS adapter does not enforce sandbox lifetime or idle deadlines","unsupported");if(t.signal?.aborted)throw m("Creation aborted","aborted");let r=t.network??"all",s={network:r==="none"?"deny":"allow"};if(r!=="all"&&r!=="none"){for(let f of r.allow)if(!/^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(f))throw m("Network allow-list entries must be literal hostnames","unsupported");s={network:{default:"deny",rules:r.allow.map((f)=>({mode:"allow",operations:["*"],patterns:[`dns://${f}`,`tcp://${f}:*`]}))}}}async function c(){let f;try{let{AgentOs:v}=await N(),g={permissions:s};if(Object.keys(t.env??{}).length)g.environment={PATH:"/opt/agentos/bin:/usr/local/bin:/usr/bin:/bin",HOME:"/home/agentos",...t.env};if(o.software?.length)g.software=o.software;if(o.mounts?.length)g.mounts=o.mounts;if(o.limits)g.limits=o.limits;if(f=await v.create(g),await f.software.install(o.gitPackagePath?{type:"path",path:o.gitPackagePath}:{type:"url",url:j,expectedDigest:R}),await f.filesystem.mkdir("/workspace",{recursive:!0}),t.signal?.aborted)throw m("Creation aborted","aborted");let C={id:`agentos-${I()}`,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"},state:"running",createdAt:Date.now()};return l.set(C.id,{vm:f,info:C}),S(C)}catch(v){if(f)await f.dispose().catch(()=>{});throw E(v)}}if(!t.key)return c();if(await M.find(t.key))throw m("Key already exists in this application process","invalid_argument");let O=w.get(t.key);if(O)throw await O,m("Key was created concurrently in this application process","invalid_argument");let x=c();w.set(t.key,x);try{return await x}finally{w.delete(t.key)}},async find(t){for(let r of l.values())if(r.info.key===t)return S(r.info);return},async connect(t){return S(P(t).info)},async list(t){return[...l.values()].flatMap((r)=>Object.entries(t).every(([s,c])=>r.info.labels[s]===c)?[S(r.info)]:[])},async destroy(t){if(!l.get(t))return;let s=A.get(t);if(s)return s;let c=b(t,(k)=>k.dispose()).then(()=>{l.delete(t)});A.set(t,c);try{await c}finally{A.delete(t)}},async exec(t,r){if(r.signal?.aborted)return{exitCode:null,timedOut:!0};return b(t,async(s)=>{let c=new TextDecoder,k=new TextDecoder,O=`/tmp/.sandbox-sdk/stdin-${I()}`;if(r.stdin!==void 0)await s.filesystem.mkdir("/tmp/.sandbox-sdk",{recursive:!0}),await s.filesystem.writeFile(O,r.stdin);try{if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let x=await s.process.exec(`exec < ${r.stdin===void 0?"/dev/null":n(O)}
|
|
2
|
+
${r.command}`,{cwd:r.cwd,env:r.env,timeoutMs:r.timeoutMs,signal:r.signal,output:{capture:"none"},onStdout(v){let g=c.decode(v,{stream:!0});if(g)r.onChunk({stream:"stdout",text:g})},onStderr(v){let g=k.decode(v,{stream:!0});if(g)r.onChunk({stream:"stderr",text:g})}});for(let[v,g]of[["stdout",c.decode()],["stderr",k.decode()]])if(g)r.onChunk({stream:v,text:g});let f=x.outcome==="timed_out"||x.outcome==="cancelled";if(!f&&x.exitCode===void 0)throw m("agentOS did not report a command exit","outcome_unknown",t);return{exitCode:f?null:x.exitCode??null,timedOut:f}}finally{if(r.stdin!==void 0)await s.filesystem.remove(O).catch(()=>{})}})},files:{writeCreatesParents:!0,writeSupportsMode:!0,transfer:"files",read:(t,r)=>b(t,async(s)=>new Uint8Array(await s.filesystem.readFile(r)),!0),write:(t,r,s,c)=>b(t,async(k)=>{if(await k.filesystem.mkdir(V.dirname(r),{recursive:!0}),await k.filesystem.writeFile(r,s),c?.mode!==void 0)await q(k,r,c.mode)},!0),stat:(t,r)=>b(t,async(s)=>z(s,r),!0),list:(t,r)=>b(t,async(s)=>Promise.all((await s.filesystem.readdirEntries(r)).map((c)=>z(s,V.join(r,c.name),c.isSymbolicLink))),!0),mkdir:(t,r)=>b(t,(s)=>s.filesystem.mkdir(r,{recursive:!0}),!0),remove:(t,r,s)=>b(t,(c)=>c.filesystem.remove(r,s),!0)},async previewUrl(t){throw P(t),m("Embedded agentOS has no preview URLs; forward HTTP with native.network.httpRequest","unsupported",t)},native(t){return P(t).vm}};return M}var U=D();function te(o={}){return T(o,()=>import("@rivet-dev/agentos-core"),U)}export{te as agentos};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { SandboxError, type ErrorCode } from "../../errors.js";
|
|
2
|
+
export declare function failure(message: string, code?: ErrorCode, sandboxId?: string): SandboxError;
|
|
3
|
+
/** The HTTP status of a `SandboxApiError` (or `SandboxGatewayError`) from `@basetenlabs/sandbox`. */
|
|
4
|
+
export declare function nativeStatus(cause: unknown): number | undefined;
|
|
5
|
+
/** A Baseten failure as a SandboxError, keeping only the error's name and HTTP status. */
|
|
6
|
+
export declare function basetenError(cause: unknown, sandboxId?: string): SandboxError;
|