@opencoredev/sandbox-sdk 1.2.0 → 1.3.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 +6 -0
- package/dist/ai.js +1 -1
- package/dist/{chunk-0v8z9zyf.js → chunk-08jjwqh4.js} +1 -1
- package/dist/{chunk-pat4tmbd.js → chunk-16kht6jp.js} +11 -11
- package/dist/{chunk-z0ssyhva.js → chunk-4m1br1sq.js} +1 -1
- package/dist/{chunk-2sdxaqqn.js → chunk-9a843q9b.js} +14 -14
- package/dist/{chunk-8qvn6q3b.js → chunk-9v2dntaq.js} +3 -3
- package/dist/{chunk-77sw0k43.js → chunk-adrd5ka7.js} +1 -1
- package/dist/{chunk-j0vdktkr.js → chunk-bfvk7mnq.js} +1 -1
- package/dist/chunk-bvwsd99g.js +17 -0
- package/dist/chunk-h6xh0pr0.js +2 -0
- package/dist/{chunk-10w33493.js → chunk-k26rjbb9.js} +2 -2
- package/dist/{chunk-b761qx9j.js → chunk-kq1xms6a.js} +2 -2
- package/dist/chunk-m7hbefp1.js +2 -0
- package/dist/{chunk-74cyqtqk.js → chunk-n0f7xz7g.js} +2 -2
- package/dist/chunk-qdc1zgmf.js +5 -0
- package/dist/{chunk-brqc6v4w.js → chunk-szwxave3.js} +2 -2
- package/dist/{chunk-xyvfzm2q.js → chunk-xw0znbmg.js} +9 -9
- package/dist/{chunk-dat243tf.js → chunk-xx9znywe.js} +3 -3
- package/dist/chunk-y86x0kmz.js +1 -0
- package/dist/chunk-z1pmcdka.js +2 -0
- package/dist/{chunk-1mzegrft.js → chunk-zygv9qfq.js} +3 -3
- package/dist/handle.d.ts +3 -1
- 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 +19 -0
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/archil/errors.d.ts +16 -0
- package/dist/providers/archil/execute.d.ts +89 -0
- package/dist/providers/archil/index.d.ts +3 -0
- package/dist/providers/archil/index.js +25 -0
- package/dist/providers/archil/provider.d.ts +25 -0
- package/dist/providers/baseten/index.js +3 -3
- package/dist/providers/beam/index.js +1 -1
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/index.js +4 -4
- package/dist/providers/daytona/index.js +12 -12
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/freestyle/index.js +4 -4
- package/dist/providers/instabox/index.js +4 -4
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/modal/index.js +2 -2
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/index.js +2 -2
- package/dist/providers/tenki/index.js +9 -9
- package/dist/providers/upstash/index.js +9 -9
- package/dist/providers/vercel/index.js +1 -1
- package/dist/testing.js +2 -2
- package/dist/tools.js +1 -1
- package/dist/version.d.ts +2 -2
- package/package.json +10 -1
- package/dist/chunk-14gk2tnk.js +0 -17
- package/dist/chunk-64f1tk8x.js +0 -2
- package/dist/chunk-77b62b35.js +0 -1
- package/dist/chunk-89mf40z0.js +0 -2
- package/dist/chunk-9059995s.js +0 -5
- package/dist/chunk-nr68156t.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{w,
|
|
1
|
+
import{w,p,N}from"./chunk-zygv9qfq.js";import{n}from"./chunk-2ts3evzh.js";import{W}from"./chunk-kq1xms6a.js";import{t,r,e,D,s}from"./chunk-xx9znywe.js";import{posix as T,resolve as I,relative as ue}from"node:path";import{tmpdir as Q}from"node:os";import{execFile as me}from"node:child_process";import{promisify as ge}from"node:util";import{promises as P}from"node:fs";function ye(d,a,x){let b=(k)=>k?k.replace(/\n$/,"").split(`
|
|
2
2
|
`):[],C=b(a),c=b(x),A=(k,R)=>R&&!k?.endsWith(`
|
|
3
3
|
`)?`\
|
|
4
4
|
`:"";return[`--- ${a===void 0?"/dev/null":`a/${d}`}
|
|
@@ -6,7 +6,7 @@ import{w,m,N}from"./chunk-1mzegrft.js";import{n}from"./chunk-2ts3evzh.js";import
|
|
|
6
6
|
`,`@@ -${C.length?1:0},${C.length} +${c.length?1:0},${c.length} @@
|
|
7
7
|
`,...C.map((k)=>`-${k}
|
|
8
8
|
`),A(a,C.length),...c.map((k)=>`+${k}
|
|
9
|
-
`),A(x,c.length)].join("")}async function
|
|
9
|
+
`),A(x,c.length)].join("")}async function te(d,a){try{await d.remove(a)}catch(x){if(D(x))return;if(x instanceof e&&x.code==="provider"&&!await d.exists(a))return;throw x}}function Z(d){return t(d)||d instanceof Uint8Array}var re=(d)=>d.split(/(\*\*\/|\*\*|\*|\?)/);function ee(d,a){let x=re(a).map((b)=>b==="**/"?"(?:.*/)?":b==="**"?".*":b==="*"?"[^/]*":b==="?"?".":b.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")).join("");return new RegExp(`^${x}$`).test(d)||!a.includes("/")&&new RegExp(`^${x}$`).test(T.basename(d))}function xe(d){let x=(b)=>Array.from({length:b.length},(C,c)=>`\\u${b.charCodeAt(c).toString(16).padStart(4,"0")}`).join("");return re(d).map((b)=>b==="**/"?"(?:[^\\n\\r\\u2028\\u2029]*/)?":b==="**"?"[^\\n\\r\\u2028\\u2029]*":b==="*"?"[^/]*":b==="?"?"[^\\n\\r\\u2028\\u2029]":x(b)).join("")}var be=`import json,os,stat,sys
|
|
10
10
|
try:
|
|
11
11
|
a=json.loads(os.environ.get("SANDBOX_SDK_INPUT") or sys.stdin.buffer.read());p=os.path.realpath(a["path"]);f=a["find"].encode();r=a["replace"].encode();w=a["write"]
|
|
12
12
|
s=os.stat(p)
|
|
@@ -59,7 +59,7 @@ try:
|
|
|
59
59
|
if q in line:
|
|
60
60
|
print(json.dumps([shown,i+1,base64.b64encode(line).decode()]));n+=1
|
|
61
61
|
if n>=mx:sys.exit(0)
|
|
62
|
-
except Exception:sys.exit(70)`,ne=(d)=>!/\p{Cs}|[\uFEFF\uFFFD]/u.test(d),X=(d)=>!/\p{Cs}/u.test(d),Se=(d)=>`python3 -I -S -c ${n(d)}`,_e=new Set(["auth","invalid_argument","unsupported","quota","not_found"]),Ce=(d)=>
|
|
62
|
+
except Exception:sys.exit(70)`,ne=(d)=>!/\p{Cs}|[\uFEFF\uFFFD]/u.test(d),X=(d)=>!/\p{Cs}/u.test(d),Se=(d)=>`python3 -I -S -c ${n(d)}`,_e=new Set(["auth","invalid_argument","unsupported","quota","not_found"]),Ce=(d)=>W(d)||d instanceof e&&_e.has(d.code),ie=(d,a)=>new e(`Edit failed at ${d}. ${a.length?`Matches on lines ${a.join(", ")}`:"Text not found"}. Supply a unique exact match.`,{code:a.length?"edit_not_unique":"edit_not_found"});function Pe(d){return Array.isArray(d)&&d.length===3&&t(d[0])&&Number.isSafeInteger(d[1])&&t(d[2])}var se=new WeakMap;function ve(d,a,x){let b=se.get(d);return b?b(a,x):d.read(a,{as:"bytes"})}function pe(d,a,x,b=()=>{},C=async()=>{}){let c=d.files,A=new Set,k=ge(me);async function R(i){if((await d.exec(a,{command:i,cwd:"/workspace",env:w,timeoutMs:120000,onChunk(){}})).exitCode!==0)throw new e("File transfer failed. The remote archive command failed. Ensure tar is installed and paths are accessible.",{code:"provider"})}let q=d.name!=="memory";async function z(i,o,l){if(!q)return{exitCode:70,stdout:""};let u="",f=JSON.stringify(o),m=Buffer.byteLength(f)<=32768,h=await c.guestInput?.(a)??"stdin";if(h==="none"||h==="env"&&!m)return{exitCode:70,stdout:""};let g;try{g=await d.exec(a,{command:Se(i),cwd:"/",env:{...w,SANDBOX_SDK_INPUT:m?f:""},stdin:m?void 0:f,timeoutMs:120000,onChunk(y){if(y.stream==="stdout")u+=y.text}})}catch(y){if(!l||Ce(y))throw y;throw new e("File edit outcome unknown. The guest command may have run before the call failed. Read the file to check its state before retrying.",{code:"outcome_unknown",provider:d.name,sandboxId:a,cause:x.error(y,d.name,a)})}if(g.timedOut||g.exitCode===null||g.exitCode>=128){if(!l)return{exitCode:70,stdout:""};throw new e("File edit outcome unknown. The guest command was stopped before it reported. Read the file to check its state before retrying.",{code:"outcome_unknown"})}if(g.exitCode===126||g.exitCode===127)q=!1;return{exitCode:g.exitCode,stdout:u}}let E=async(i)=>{try{return b(),await C().finally(b),await i()}catch(o){throw x.error(o,d.name,a)}};async function G(i=".",o={}){let l=p(i),u=[];async function f(m){for(let h of await c.list(a,m)){if(!o.glob||ee(T.relative(l,h.path),o.glob))u.push(h);if(o.recursive&&h.type==="directory")await f(h.path)}}return await f(l),u}async function L(i,o){let l=await E(()=>c.read(a,p(i)));return o?.as==="bytes"?l:new TextDecoder().decode(l)}async function j(i,o,l){let u=t(i),f=u?[[i,Z(o)?o:""]]:Object.entries(i),m=(u?l:Z(o)?void 0:o)??{},{mode:h}=m,g=new Set;await E(async()=>{if(h!==void 0&&(!Number.isSafeInteger(h)||h<0||h>4095))s("mode must be an integer from 0 to 0o7777, such as 0o600");let y=[];for(let[O,F]of f){let _=p(O),v=T.dirname(_);if(!c.writeCreatesParents&&!g.has(v))await c.mkdir(a,v),g.add(v);await c.write(a,_,t(F)?new TextEncoder().encode(F):F,m),y.push(_)}if(h===void 0||c.writeSupportsMode||!y.length)return;let S=await d.exec(a,{command:`chmod ${h.toString(8)} ${y.map(n).join(" ")}`,cwd:"/workspace",env:w,timeoutMs:30000,onChunk(){}});if(S.timedOut||S.exitCode!==0)throw new e(`File mode not applied. chmod ${S.timedOut?"timed out":`exited with ${S.exitCode}`}; the files were written with default permissions. Check that the paths are writable and retry.`,{code:"provider"})})}let U="/tmp/.sandbox-sdk/changes.git";async function M(i,o){let l="";if((await d.exec(a,{command:`git --git-dir=${n(U)} --work-tree=/workspace ${i}`,cwd:"/workspace",env:{...w,GIT_INDEX_FILE:`${U}/sdk.index`},stdin:o,timeoutMs:120000,onChunk(f){if(f.stream==="stdout")l+=f.text}})).exitCode!==0)throw new e("File checkpoint failed. Git could not update the hidden index. Ensure git is installed and /workspace is readable.",{code:"provider"});return l}async function J(i){let o=["-name .git",...(c.internal??[]).map((m)=>`-path ${n(`./${T.relative("/workspace",p(m))}`)}`)].join(" -o "),l=`command -v git >/dev/null 2>&1 || exit 69
|
|
63
63
|
command -v find >/dev/null 2>&1 || exit 78
|
|
64
64
|
g=${n(U)}
|
|
65
65
|
# A fresh index per call: a killed attempt leaves no index.lock to block later checkpoints.
|
|
@@ -70,9 +70,9 @@ git --git-dir="$g" --work-tree=/workspace read-tree --empty || exit 1
|
|
|
70
70
|
git --git-dir="$g" --work-tree=/workspace update-index --add --remove -z --stdin < "$paths" || exit 1
|
|
71
71
|
tree=$(git --git-dir="$g" --work-tree=/workspace write-tree) || exit 1
|
|
72
72
|
${i?`mkdir -p ${n(T.dirname(i))} && printf '%s' "$tree" > ${n(i)} || exit 1
|
|
73
|
-
`:""}printf '%s\\n' "$tree"`,u="",f=await d.exec(a,{command:l,cwd:"/workspace",env:w,timeoutMs:120000,onChunk(
|
|
74
|
-
`).length),h=f.indexOf(o,h+1);if(
|
|
75
|
-
`)&&ne(i)&&X(f)){let
|
|
76
|
-
`)){if(!y)continue;let S=JSON.parse(y);if(!Pe(S)){l.length=0;break}let O=new TextDecoder("utf-8",{ignoreBOM:S[1]!==1}).decode(Buffer.from(S[2],"base64"));if(!O.includes(i)){l.length=0;break}l.push({path:S[0],line:S[1],text:x.text(O)})}if(l.length||!g)return l}}for(let
|
|
77
|
-
`);for(let[g,y]of h.entries())if(y.includes(i)){if(l.push({path:
|
|
78
|
-
export{
|
|
73
|
+
`:""}printf '%s\\n' "$tree"`,u="",f=await d.exec(a,{command:l,cwd:"/workspace",env:w,timeoutMs:120000,onChunk(m){if(m.stream==="stdout")u+=m.text}});if(f.exitCode===78){let m=await ce();if(i)await j(i,m);return m}if(f.exitCode===69)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"});if(f.exitCode!==0)throw new e("File checkpoint failed. Git could not update the hidden index. Ensure git is installed and /workspace is readable.",{code:"provider"});return u.trim()}async function ce(){if(!await K(U)){if((await d.exec(a,{command:`git init --bare ${n(U)}`,cwd:"/workspace",env:w,timeoutMs:1e4,onChunk(){}})).exitCode!==0)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"})}let i=[],o=new Set((c.internal??[]).map((u)=>p(u)));async function l(u){for(let f of await c.list(a,u)){if(T.basename(f.path)===".git"||o.has(f.path))continue;if(f.type==="directory")await l(f.path);else i.push(T.relative("/workspace",f.path))}}if(await l("/workspace"),await M("read-tree --empty"),i.length)await M("update-index --add --remove -z --stdin",i.join("\x00")+"\x00");return(await M("write-tree")).trim()}async function K(i){try{return await c.stat(a,i),!0}catch(o){if(D(o))return!1;throw o}}async function Y(){let i={};for(let o of await G(".",{recursive:!0}))if(o.type==="file")i[o.path]=Buffer.from(await c.read(a,o.path)).toString("base64");return i}let B=(i)=>`/tmp/.sandbox-sdk/marks/${encodeURIComponent(i)}.json`;async function de(i){let o=JSON.parse(new TextDecoder().decode(await c.read(a,B(i))));if(!r(o)||Array.isArray(o))s("Invalid file checkpoint");let l={};for(let[u,f]of Object.entries(o)){if(!t(f))s("Invalid file checkpoint content");l[u]=f}return l}async function V(i,o){try{return await o()}catch(l){if((i??"start")==="start"&&!await K(B("start")).catch(()=>!0))throw new e("No start checkpoint. createSandbox records one only with trackChanges: true. Pass trackChanges: true or call files.mark() and changes({ since }).",{code:"invalid_argument"});throw l}}let le=(i)=>V(i,()=>L(B(i??"start"))),H={[Symbol.dispose](){for(let i of A)i()},read:L,write:j,list:(i,o)=>E(()=>G(i,o)),stat:(i)=>E(()=>c.stat(a,p(i))),exists:(i)=>E(async()=>{try{return await c.stat(a,p(i)),!0}catch(o){if(D(o))return!1;throw o}}),remove:(i,o)=>E(()=>c.remove(a,p(i),{recursive:o?.recursive??!1})),edit:(i,{find:o,replace:l})=>E(async()=>{if(!o)s("find cannot be empty");let u=p(i);if(c.editInGuest&&ne(o)&&X(l)&&X(u)){let{exitCode:g,stdout:y}=await z(be,{path:u,find:o,replace:l,write:c.editInGuest},!0);if(g===0)return;if(g===3)throw ie(i,y.trim()?y.trim().split(" ").map(Number):[]);if(g===71)throw new e(`File edit outcome unknown at ${i}. Writing the file failed and its original contents could not be restored. Read the file to check its state before retrying.`,{code:"outcome_unknown"})}let f=await L(i),m=[],h=f.indexOf(o);while(h!==-1)m.push(f.slice(0,h).split(`
|
|
74
|
+
`).length),h=f.indexOf(o,h+1);if(m.length!==1)throw ie(i,m);await c.write(a,u,new TextEncoder().encode(f.replace(o,()=>l)))}),upload:(i,o,l)=>E(async()=>{let u=I(i);if(c.transfer!=="files"&&(await P.lstat(u)).isDirectory()){let m=await P.mkdtemp(I(Q(),"sandbox-sdk-upload-")),h=`/tmp/.sandbox-sdk/upload-${crypto.randomUUID()}.tar`;try{let g=I(m,"files.tar");await k("tar",["-cf",g,"-C",u,...(l?.ignore??[]).flatMap((y)=>["--exclude",y]),"."],{timeout:120000}),await j(h,new Uint8Array(await P.readFile(g))),await c.mkdir(a,p(o)),await R(`tar -xf ${n(h)} -C ${n(p(o))} --no-same-owner`)}finally{await P.rm(m,{recursive:!0,force:!0}),await c.remove(a,h,{recursive:!1}).catch(()=>{})}return}async function f(m,h){let g=await P.lstat(m);if(g.isSymbolicLink())s("Uploading symlinks is unsupported");if(g.isDirectory()){await c.mkdir(a,p(h));for(let y of await P.readdir(m))if(!l?.ignore?.some((S)=>ee(ue(u,I(m,y)),S)||S===y))await f(I(m,y),T.join(h,y))}else await j(h,new Uint8Array(await P.readFile(m)))}await f(u,o)}),download:(i,o)=>E(async()=>{if(c.transfer!=="files"&&(await c.stat(a,p(i))).type==="directory"){let u=await P.mkdtemp(I(Q(),"sandbox-sdk-download-")),f=`/tmp/.sandbox-sdk/download-${crypto.randomUUID()}.tar`;try{await R(`mkdir -p ${n(T.dirname(f))} && tar -cf ${n(f)} -C ${n(p(i))} .`);let m=I(u,"files.tar");await P.writeFile(m,await c.read(a,f)),await P.mkdir(I(o),{recursive:!0}),await k("tar",["-xf",m,"-C",I(o),"--no-same-owner","--no-same-permissions"],{timeout:120000})}finally{await P.rm(u,{recursive:!0,force:!0}),await c.remove(a,f,{recursive:!1}).catch(()=>{})}return}async function l(u,f){let m=await c.stat(a,u);if(m.type==="symlink")s("Downloading symlinks is unsupported");if(m.type==="directory"){await P.mkdir(f,{recursive:!0});for(let h of await c.list(a,u))await l(h.path,I(f,T.basename(h.path)))}else await P.mkdir(I(f,".."),{recursive:!0}),await P.writeFile(f,await c.read(a,u))}await l(p(i),I(o))}),search:(i,o={})=>E(async()=>{let l=[],u=o.maxMatches??200;if(!Number.isSafeInteger(u)||u<1)s("maxMatches must be positive");let f=p(o.path);if(c.listOrder&&i&&!i.includes(`
|
|
75
|
+
`)&&ne(i)&&X(f)){let m=o.glob??"",{exitCode:h,stdout:g}=await z($e,{root:f,query:i,pattern:m&&xe(m),base:m!==""&&!m.includes("/"),max:u,order:c.listOrder},!1);if(h===0){for(let y of g.split(`
|
|
76
|
+
`)){if(!y)continue;let S=JSON.parse(y);if(!Pe(S)){l.length=0;break}let O=new TextDecoder("utf-8",{ignoreBOM:S[1]!==1}).decode(Buffer.from(S[2],"base64"));if(!O.includes(i)){l.length=0;break}l.push({path:S[0],line:S[1],text:x.text(O)})}if(l.length||!g)return l}}for(let m of await G(o.path,{recursive:!0,glob:o.glob}))if(m.type==="file"){let h=(await L(m.path)).split(`
|
|
77
|
+
`);for(let[g,y]of h.entries())if(y.includes(i)){if(l.push({path:m.path,line:g+1,text:x.text(y)}),l.length>=u)return l}}return l}),watch(i,o,l={}){b();let u=!1,f,m,h=()=>{},g=new AbortController,y=async()=>{try{if(await C(),u)return;let _=new Map((await G(i,l)).map((v)=>[v.path,`${v.size}:${v.modifiedAt}`]));if(f){for(let[v,fe]of _)if(!f.has(v)||f.get(v)!==fe){if(!u)o({type:f.has(v)?"modified":"added",path:v})}for(let v of f.keys())if(!_.has(v)&&!u)o({type:"removed",path:v})}f=_}catch(_){l.onError?.(x.error(_,d.name,a))}if(!u)m=setTimeout(()=>void y(),l.intervalMs??250),m.unref?.()},S=(_)=>new Promise((v)=>{h=v,m=setTimeout(v,_),m.unref?.()}),O=async(_)=>{while(!u){try{if(await C(),u)return;await _.call(c,a,p(i),{recursive:l.recursive??!1,signal:g.signal,onEvent(v){if(!u)o(v)}})}catch(v){if(u)return;if(v instanceof e&&v.code==="unsupported"){y();return}l.onError?.(x.error(v,d.name,a))}if(!u)await S(1000)}},F=()=>{u=!0,clearTimeout(m),h(),g.abort(),A.delete(F)};if(A.add(F),c.watch)O(c.watch);else y();return F},mark:(i=`mark-${Date.now()}-${Math.random().toString(36).slice(2)}`)=>E(async()=>{if(c.checkpoints==="files")await j(B(i),JSON.stringify(await Y()));else await J(B(i));return i}),changes:(i={})=>E(async()=>{if(c.checkpoints!=="files"){let g=(await le(i.since)).trim(),y=await J();if(!/^[0-9a-f]{40,64}$/.test(g))s("Invalid git checkpoint");let S=(await M(`diff --no-renames --name-status -z ${g} ${y}`)).split("\x00"),O={added:[],modified:[],removed:[],patch:x.text(await M(`diff --no-ext-diff --binary ${g} ${y}`))};for(let F=0;F+1<S.length;F+=2){let _=S[F],v=S[F+1];if(v)(_==="A"?O.added:_==="D"?O.removed:O.modified).push(p(v))}return O}let o=await V(i.since,()=>de(i.since??"start")),l=await Y(),u=Object.keys(l).filter((g)=>!(g in o)),f=Object.keys(o).filter((g)=>!(g in l)),m=Object.keys(l).filter((g)=>(g in o)&&o[g]!==l[g]),h=[...u,...m,...f].map((g)=>ye(T.relative("/workspace",g),g in o?Buffer.from(o[g]??"","base64").toString():void 0,g in l?Buffer.from(l[g]??"","base64").toString():void 0)).join("");return{added:u,modified:m,removed:f,patch:x.text(h)}})};return se.set(H,(i,o)=>E(()=>c.readRange?c.readRange(a,p(i),{offset:0,length:o+1}):c.read(a,p(i)))),H}import{stripVTControlCharacters as Ee}from"node:util";var oe=new WeakMap;function ke(d,a){oe.set(d,a)}function ae(d){let a=oe.get(d);if(!a)throw Error("Unknown sandbox handle. Secret redaction cannot be guaranteed. Use createSandbox or connectSandbox.");return a}function he(d,a){return ae(d).text(Ee(a))}function we(d,a){let x={stdout:"plain",stderr:"plain"},b=N(ae(d),a,!0);return{push(C){let c=x[C.stream],A="";for(let k of C.text)switch(c){case"plain":if(k==="\x1B")c="escape";else if(k==="")c="csi";else if("".includes(k))c="string";else A+=k;break;case"escape":c=k==="["?"csi":"]PX^_".includes(k)?"string":k>=" "&&k<="/"?"escape":"plain";break;case"csi":if(k>="@"&&k<="~")c="plain";break;case"string":if(k==="\x07"||k==="")c="plain";else if(k==="\x1B")c="string_escape";break;case"string_escape":c=k==="\\"?"plain":"string";break;default:return c}if(x[C.stream]=c,A)b.push({stream:C.stream,text:A})},flush(){b.flush()}}}
|
|
78
|
+
export{te,ve,pe,ke,he,we};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function t(n){return typeof n==="string"}function o(n){return typeof n==="number"}function V(n){return typeof n==="boolean"}function r(n){return typeof n==="object"&&n!==null}function
|
|
1
|
+
function t(n){return typeof n==="string"}function o(n){return typeof n==="number"}function V(n){return typeof n==="boolean"}function r(n){return typeof n==="object"&&n!==null}function re(n){return r(n)&&!Array.isArray(n)&&Object.values(n).every(t)}var x={auth:"Set the provider's API key environment variable or pass it to the provider factory.",not_found:"Create a new sandbox, or pass a key to createSandbox so it recreates one for you.",quota:"Wait and retry, destroy unused sandboxes with reapSandboxes, or raise the provider plan.",unavailable:"Retry with backoff. Check the provider's status page if it persists.",unsupported:"Remove the option or choose a provider that supports it. Check box.capabilities.",timeout:"Retry, or raise the relevant timeout option.",aborted:"Retry with a fresh AbortSignal if you still need the result.",outcome_unknown:"Check the sandbox state before retrying. If in doubt, destroy it.",process_exited:"Read the exit code and log tail in the message, fix the command, and start it again.",port_not_ready:"Check that the server listens on 0.0.0.0 and the right port, then read its logs.",edit_not_found:"Read the file again and use text that is in it.",edit_not_unique:"Add surrounding lines to find so it matches exactly once.",file_not_found:"Check the path. Relative paths resolve against /workspace.",invalid_argument:"Fix the input. Retrying the same call will not help.",provider:"Read the message and cause. Report it if it looks like an SDK bug."};class e extends Error{code;retryable;hint;provider;sandboxId;constructor(n,d){super(n,{cause:d.cause});this.name="SandboxError",this.code=d.code,this.retryable=d.retryable??!1,this.hint=d.hint??x[d.code]??x.provider,this.provider=d.provider??"unknown",this.sandboxId=d.sandboxId}static{Object.defineProperty(this,"name",{value:"SandboxError"})}[Symbol.for("nodejs.util.inspect.custom")](n,d,c){let l=this.stack??"",p=l.indexOf(`
|
|
2
2
|
at `)>=0?l.slice(l.indexOf(`
|
|
3
|
-
at `)):"",h={code:this.code,provider:this.provider,sandboxId:this.sandboxId,retryable:this.retryable,hint:this.hint,cause:this.cause};return`SandboxError [${this.code}]: ${this.message}${p} ${c(h,
|
|
4
|
-
export{t,o,V,r,
|
|
3
|
+
at `)):"",h={code:this.code,provider:this.provider,sandboxId:this.sandboxId,retryable:this.retryable,hint:this.hint,cause:this.cause};return`SandboxError [${this.code}]: ${this.message}${p} ${c(h,d)}`}}function D(n){return n instanceof e&&(n.code==="file_not_found"||n.code==="not_found")}class P{values=new Set;add(n){for(let d of n)if(d)this.values.add(d)}text(n){for(let d of[...this.values].sort((c,l)=>l.length-c.length))n=n.split(d).join("[REDACTED]");return n}get secrets(){return[...this.values].sort((n,d)=>d.length-n.length)}get maxLength(){return Math.max(1,...[...this.values].map((n)=>n.length))}error(n,d,c){if(n instanceof e)return new e(y(this.text(n.message)),{code:n.code,retryable:n.retryable,hint:y(this.text(n.hint)),provider:d,sandboxId:c??n.sandboxId,cause:n.cause===void 0?void 0:k(n.cause instanceof Error?n.cause.message:String(n.cause),(p)=>this.text(p))});let l=O(this.text(n instanceof Error?n.message:t(n)?n:"Non-Error value thrown"));return new e(`${l}. Provider request failed. Check the provider settings and retry.`,{code:"provider",hint:x.provider,provider:d,sandboxId:c,cause:g(n,(p)=>this.text(p))})}}var _=[[/https?:\/\/[^\s"'<>]+/gi,"[URL REDACTED]"],[/(\bauthorization["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\r\n;]+)/gi,"$1[REDACTED]"],[/\bBearer\s+[^\s"',;]+/gi,"Bearer [REDACTED]"],[/((?:["']?(?:api[-_]?key|access[-_]?token|token|password|secret)["']?)\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/gi,"$1[REDACTED]"]];function y(n){for(let[d,c]of _)n=n.replace(d,c);return n}function O(n,d=1000){return y(n).replace(/\p{Cc}+/gu," ").slice(0,d)}var E=/(?:api[-_]?key|token|password|secret|authorization)$/i;function w(n){if(!n.startsWith("{"))return;let d;try{d=JSON.parse(n)}catch{return}if(!r(d)||Array.isArray(d))return;let c=[];for(let[l,p]of Object.entries(d)){if(!(t(p)||o(p)||V(p)||p===null))return;c.push([l,p])}return c}function k(n,d){let c=w(n);if(c===void 0)return O(d(n));let l=c.map(([b,f])=>{let v=O(d(b)).slice(0,64);if(E.test(b)&&f!==null)return[v,"[REDACTED]"];if(t(f))return[v,O(d(f))];return[v,f!==null&&d(String(f))!==String(f)?"[REDACTED]":f]}),p=(b,f)=>JSON.stringify(Object.fromEntries(b.map(([v,m])=>[v,t(m)?m.slice(0,f):m])));for(let b of[300,120,40]){let f=p(l,b);if(f.length<=1000)return f}let h=[...l];while(h.length>0&&p(h,40).length>1000)h.pop();return p(h,40)}function g(n,d=(l)=>l,c=0){if(!(n instanceof Error))return;let l=O(d(n.message?`${n.name}: ${n.message}`:n.name)),p=c<2?g(n.cause,d,c+1):void 0;return p===void 0?l:`${l}; caused by ${p}`}var C={auth:"the credentials are missing or were rejected",not_found:"the sandbox does not exist",quota:"a provider limit or billing stopped the request",unavailable:"the service is down or unreachable",unsupported:"the provider cannot do what was asked",timeout:"the operation took too long",aborted:"the request was aborted",outcome_unknown:"the request may or may not have happened",process_exited:"the process exited before it was ready",port_not_ready:"the port did not become ready",edit_not_found:"the text to replace was not found",edit_not_unique:"the text to replace matched more than once",file_not_found:"the path does not exist",invalid_argument:"the provider rejected the request as invalid",provider:"the provider returned an unexpected error"};function i(n,d){let l=!(d.known??d.code!=="provider")&&d.status===void 0?g(n,d.redact):void 0,p=[n instanceof Error?n.name:void 0,d.status].filter((h)=>h!==void 0).join(" ");return{detail:l,cause:l??(p||void 0)}}function R(n){return Object.assign(Error(JSON.stringify(n)),n)}function u(n){let d=new P;for(let c of n)if(c)d.add([c]);return(c)=>d.text(c)}function a(n,d){return d??C[n]}function I(n){if(n===400||n===422)return"invalid_argument";if(n===401||n===403)return"auth";if(n===402||n===429)return"quota";if(n===404||n===410)return"not_found";if(n===408||n===504)return"timeout";if(n===413)return"unsupported";if(n>=500&&n<=599)return"unavailable";return"provider"}function s(n){throw new e(`${n}. The request is invalid. Check the supplied options.`,{code:"invalid_argument"})}
|
|
4
|
+
export{t,o,V,r,re,e,D,P,O,g,i,R,u,a,I,s};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{w,p,J,Ee,Ie,U,ne,N,ye}from"./chunk-zygv9qfq.js";export{U as BufferCap,ne as OutputBus,Ee as activityScanCommand,N as chunkRedactor,w as defaults,Ie as isRunActive,ye as makeRun,p as pathOf,J as secretRecoveryCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{e,D,P,s}from"./chunk-xx9znywe.js";var y=new WeakMap,k=(t,n)=>y.get(t)?.get(n);function S(t,n,a){let r=y.get(t);if(!r)r=new Map,y.set(t,r);if(r.delete(n),r.set(n,a),r.size>256){let o=r.keys().next().value;if(o!==void 0)r.delete(o)}}function b(t,n){y.get(t)?.delete(n)}function ee(t,n){let a=y.get(t);if(!a)return;for(let[r,o]of a)if(o===n)a.delete(r)}var g=new WeakMap;async function ae(t,n,a,r){let o=g.get(t);if(!o)o=new Map,g.set(t,o);let i=o.get(n)??Promise.resolve(),c=a.locator,l=i.catch(()=>{}).then(()=>a.keyMode==="exact"&&t.keyMode==="best-effort"&&c?.withLock?c.withLock(n,r):r());o.set(n,l);try{return await l}finally{if(o.get(n)===l)o.delete(n)}}var w=new WeakMap;function le(t,n){let a=w.get(t);if(!a)a=new Map,w.set(t,a);a.set(n,(a.get(n)??0)+1)}function xe(t,n){let a=w.get(t),r=a?.get(n)??0;if(r>1)return a?.set(n,r-1),!1;return a?.delete(n),!0}function fe(t,n){return t.capabilities.has(n)}var O={"sandbox-sdk":"1"};function v(t,n){for(let a of Object.keys({...n.env,...n.secrets}))if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(a))s("Invalid environment variable name");for(let a of t.capabilities)if(a==="pause"&&(!t.pause||!t.resume)||a==="snapshot"&&!t.snapshot||a==="terminal"&&!t.terminal||a==="snapshot-delete"&&!t.deleteSnapshot||a==="templates"&&!t.buildTemplate)throw new e("Invalid adapter capabilities. A declared method is missing. Fix the adapter contract.",{code:"provider"});if(n.size!==void 0&&!t.capabilities.has("size"))throw new e("Creation refused. Provider cannot enforce size. Choose a provider with size support.",{code:"unsupported"});if(n.network!==void 0&&n.network!=="all"&&!t.capabilities.has("network-policy"))throw new e("Creation refused. Provider cannot enforce network policy. Choose a provider with network-policy support.",{code:"unsupported"});if(n.from!==void 0&&!t.capabilities.has("snapshot"))throw new e("Creation refused. Provider cannot restore snapshots. Choose a provider with snapshot support.",{code:"unsupported"});if(n.keyMode==="exact"&&t.keyMode!=="exact"&&!n.locator?.withLock)throw new e("Exact key mode unavailable. Two-function locator storage cannot enforce distributed uniqueness. Supply locator.withLock or use an exact provider.",{code:"unsupported"});for(let a of n.ports??[])if(!Number.isInteger(a)||a<1||a>65535)s("Invalid port");for(let a of[n.timeoutMs,n.idleTimeoutMs])if(a!==void 0&&(!Number.isFinite(a)||a<=0))s("Timeouts must be positive milliseconds")}async function j(t,n={}){let a=new P;a.add(Object.values(n.secrets??{}));async function r(){let o;try{if(v(t,n),n.signal?.aborted)throw new e("Creation aborted. Signal was already aborted. Retry with a fresh signal.",{code:"aborted"});let i;if(n.key){let m=await n.locator?.get(n.key)??k(t,n.key);if(m){try{i=await t.connect(m)}catch(d){if(!(d instanceof e)||d.code!=="not_found")throw d;b(t,n.key)}if(t.readsMetadataOnlyWhenRunning&&i!==void 0&&i.state!=="running")i=void 0}if(i?.state==="stopped")i=void 0,b(t,n.key);i??=await t.find(n.key)}let c=!i;if(!i){let{secrets:m,locator:d,keyMode:F,trackChanges:_,...M}=n,h={...M,env:{...n.env,...m},labels:{...n.labels,...O}};if(t.recordsSecretNames)h.secretNames=Object.keys(m??{});let x=t.create(h).catch(async(u)=>{if(n.key&&t.keyMode==="exact"&&!n.signal?.aborted){let f=await t.find(n.key).catch(()=>{throw u});if(f)return c=!1,f}throw u});if(n.signal){let u=n.signal,f=()=>{},R=new Promise((p,K)=>{if(f=()=>K(new e("Creation aborted. The signal was cancelled. Any late sandbox will be destroyed.",{code:"aborted"})),u.addEventListener("abort",f,{once:!0}),u.aborted)f()}),I=x.then(async(p)=>{if(u.aborted){if(c)await t.destroy(p.id);throw new e("Creation aborted. Late sandbox destroyed. Retry with a fresh signal.",{code:"aborted"})}return p});try{i=await Promise.race([I,R])}finally{u.removeEventListener("abort",f)}}else i=await x;if(c)o=i}if(n.signal?.aborted){if(o)await t.destroy(o.id);throw o=void 0,new e("Creation aborted. Sandbox arrived after cancellation and was destroyed. Retry with a fresh signal.",{code:"aborted"})}if(n.key)await n.locator?.set(n.key,i.id),S(t,n.key,i.id);let{makeHandle:l}=await import("./chunk-bvwsd99g.js");return await l(t,i,c,n,a)}catch(i){if(o)ee(t,o.id),await t.destroy(o.id).catch(()=>{});throw a.error(i,t.name)}}if(!n.key)return r();return ae(t,n.key,n,r)}async function G(t,n,a={}){let r=new P;r.add(Object.values(a.secrets??{}));try{v(t,a);let o=await t.connect(n),{makeHandle:i}=await import("./chunk-bvwsd99g.js"),c=t.readsMetadataOnlyWhenRunning===!0&&o.state!=="running";return await i(t,o,!1,{...a,key:o.key},r,a.recoverSecrets??!0,c)}catch(o){throw r.error(o,t.name,n)}}async function de(t,n={}){try{return(await t.list({...n.labels,...O})).filter((a)=>a.labels["sandbox-sdk"]==="1")}catch(a){throw new P().error(a,t.name)}}async function me(t,n={}){if(n.olderThanMs!==void 0&&(!Number.isFinite(n.olderThanMs)||n.olderThanMs<0))s("olderThanMs must be non-negative");let a=n.idleOnly?(await import("./chunk-y86x0kmz.js")).isRunActive:()=>!1,r=n.olderThanMs??0,o=0;try{for(let i of await de(t,n)){if(Date.now()-i.createdAt<r)continue;if(n.idleOnly){if(a(t.name,i.id))continue;let c=await B(t,i.id);if(c==="gone"){o++;continue}if(c==="busy")continue}if(a(t.name,i.id))continue;ee(t,i.id);try{await t.destroy(i.id)}catch(c){if(!(c instanceof e)||c.code!=="not_found")throw c}o++}return o}catch(i){throw new P().error(i,t.name)}}function T(t,n,a,r){if(!t.capabilities.has(n))throw new e(`${a} unavailable. Provider ${t.name} lacks the "${n}" capability. Choose a provider that has it.`,{code:"unsupported",provider:t.name});if(r===void 0)throw new e("Invalid adapter capabilities. A declared method is missing. Fix the adapter contract.",{code:"provider",provider:t.name});return r}async function Se(t,n){try{let a=T(t,"snapshot-delete","Snapshot deletion",t.deleteSnapshot);if(!n)s("snapshotId cannot be empty");return await a.call(t,n)}catch(a){throw new P().error(a,t.name)}}async function Pe(t,n,a={}){try{let r=T(t,"templates","Template building",t.buildTemplate),o=n;if(!o.name)s("Template name cannot be empty");if(o.run?.some((i)=>!i.trim()))s("Template run steps must be non-empty commands");if(a.timeoutMs!==void 0&&(!Number.isFinite(a.timeoutMs)||a.timeoutMs<=0))s("Timeouts must be positive milliseconds");return await r.call(t,o,a)}catch(r){throw new P().error(r,t.name)}}var C="/tmp/.sandbox-sdk/runs";async function L(t,n){if(!t.procActivity)return!1;let{activityScanCommand:a}=await import("./chunk-y86x0kmz.js");try{let r=await t.exec(n,{command:a,cwd:"/",env:{},timeoutMs:30000,onChunk(){}});return r.timedOut||r.exitCode!==0}catch{return!0}}async function B(t,n){let a;try{let r=await t.connect(n);if(t.readsMetadataOnlyWhenRunning&&r.state!=="running")return"busy";let{makeHandle:o}=await import("./chunk-bvwsd99g.js");a=await o(t,r,!1,{},new P,!1)}catch(r){if(r instanceof e&&r.code==="not_found")return"gone";throw r}try{let r=Promise.all([a.processes(),A(a),L(t,n)]),o;try{o=await r}catch(d){if(t.readsMetadataOnlyWhenRunning)return"busy";throw d}let[i,c,l]=o;return i.some((d)=>d.status==="running"||d.status==="starting")||c.length>0||l?"busy":"idle"}finally{await a.close()}}async function A(t){try{return await t.files.list(C)}catch(n){if(D(n))return[];if(n instanceof e&&n.code==="provider"&&!await t.files.exists(C))return[];throw n}}
|
|
2
|
+
export{ee,ae,le,xe,fe,j,G,de,me,Se,Pe};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-
|
|
1
|
+
import{n}from"./chunk-2ts3evzh.js";import{s}from"./chunk-xx9znywe.js";import{posix as F}from"node:path";var L="SANDBOX_SDK_RUN",w={CI:"1",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",DEBIAN_FRONTEND:"noninteractive",TERM:"dumb",NO_COLOR:"1",[L]:"1"},p=(t=".")=>F.resolve("/workspace",t),J="if [ -f /tmp/.sandbox-sdk/secret-names.json ]; then cat /tmp/.sandbox-sdk/secret-names.json || exit 1; printf '\\000'; env -0; fi",H=`[ -d "\${2%/*}" ] || (umask 077; mkdir -p "\${2%/*}") || exit 1
|
|
2
2
|
trap 'rm -f -- "$2"' EXIT
|
|
3
3
|
: > "$2" || exit 1
|
|
4
4
|
{ { "$3" -c "$1" 3>&- 4>&-; printf '%s\\n' "$?" > "$2"; } 2>&1 >&3 | cat >&4; } 3>&1 4>&2 | cat
|
|
@@ -22,5 +22,5 @@ done
|
|
|
22
22
|
[ "$(id -u)" = 0 ] && exit 11
|
|
23
23
|
sudo -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`,M=new Map,Ie=(t,e)=>(M.get(t)?.get(e)??0)>0;function X(t,e){let o=M.get(t);if(!o)o=new Map,M.set(t,o);let a=o;return a.set(e,(a.get(e)??0)+1),()=>{let c=(a.get(e)??1)-1;if(c)a.set(e,c);else a.delete(e);if(!a.size)M.delete(t)}}class U{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+`
|
|
24
24
|
[${this.total-Buffer.byteLength(t)-Buffer.byteLength(o)} bytes cut]
|
|
25
|
-
`+o}}class
|
|
26
|
-
export{w,
|
|
25
|
+
`+o}}class ne{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=(c)=>{if(c){let d=Buffer.byteLength(c.text)>1048576?Buffer.from(c.text).subarray(-1048576).toString():c.text;t.push({...c,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 c=t.shift();if(c)e-=Buffer.byteLength(c.text),yield c;else await new Promise((d)=>{o=d})}if(this.failure)throw this.failure}finally{this.listeners.delete(a)}}}function N(t,e,o=!1){let a=[];function c(d=!1){let g=t.secrets,R=new Set(g.map((i)=>i[0]));while(a.length){let i=a[0];if(!i)break;if(!R.has(i.text[0])){let r=1;while(r<i.text.length&&!R.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 b=a.flatMap((r)=>o||r.stream===i.stream?[r.text]:[]).join(""),y=g.find((r)=>b.startsWith(r));if(y){e({stream:i.stream,text:"[REDACTED]"});let r=y.length;for(let h of a)if((o||h.stream===i.stream)&&r){let x=Math.min(r,h.text.length);h.text=h.text.slice(x),r-=x}}else{if(!d&&g.some((h)=>h.startsWith(b))){if(a.reduce((h,x)=>h+Buffer.byteLength(x.text),0)<=1048576)break;e({stream:i.stream,text:"[REDACTED]"}),a.shift();continue}let r=1;while(r<i.text.length&&!R.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}),c()},flush(){c(!0)}}}function ye(t,e,o,a,c,d=()=>{}){return(g,R={})=>{let i={...R},b,y=new ne,r=(u=!1)=>b??=h(u).catch((m)=>{let f=o.error(m,t.name,e);throw y.fail(f),f});async function h(u){await d();let m=i.timeoutMs??120000,f=i.maxOutputBytes??1048576;if(!Number.isFinite(m)||m<=0||!Number.isSafeInteger(f)||f<1)s("timeoutMs and maxOutputBytes must be positive");let D=p(i.cwd),I=Date.now(),C=new U(f),O=new U(f),_=new U(f*2),S=new AbortController,v=i.signal?.aborted??!1,B=()=>{v=!0,S.abort()};i.signal?.addEventListener("abort",B,{once:!0});let q=setTimeout(B,m),E=`/tmp/.sandbox-sdk/runs/${crypto.randomUUID()}`,P=!1,j=X(t.name,e),A=N(o,(l)=>{_.add(l.text),y.emit(l)},!0),T=N(o,(l)=>{(l.stream==="stdout"?C:O).add(l.text),A.push(l)});try{if(v)S.abort();let l=v?{exitCode:null,timedOut:!0}:await t.exec(e,{command:t.inlineActivity?g:t.procActivity?W(g,t.commandShell):z(g,E,t.commandShell),cwd:D,env:{...a,...i.env,...w},stdin:i.stdin,timeoutMs:m,signal:S.signal,streaming:u,envMode:i.env===void 0?"sandbox":void 0,activityPath:t.inlineActivity?E:void 0,onChunk:(k)=>T.push(k)});return P=l.exitCode!==null&&l.exitCode>=0&&l.exitCode<128&&!l.timedOut&&!S.signal.aborted,v||=l.timedOut,T.flush(),A.flush(),c(C.total+O.total),{ok:!v&&l.exitCode===0,exitCode:v?null:l.exitCode,stdout:C.text(),stderr:O.text(),output:_.text(),durationMs:Date.now()-I,truncated:C.truncated||O.truncated||_.truncated,timedOut:v,cwd:D,command:o.text(g)}}catch(l){T.flush(),A.flush();let k=o.error(l,t.name,e);throw y.fail(k),k}finally{if(clearTimeout(q),i.signal?.removeEventListener("abort",B),!P&&!t.inlineActivity&&!t.procActivity)await Promise.resolve().then(()=>t.files.remove(e,E,{recursive:!0})).catch(()=>{});j(),y.end()}}let x={[Symbol.toStringTag]:"RunHandle",then(u,m){return r().then(u,m)},catch(u){return r().catch(u)},finally(u){return r().finally(u)},[Symbol.asyncIterator](){let u=y.stream(),m=u.next();r(!0).catch(()=>{});let f=!0;return{next:()=>{if(f)return f=!1,m;return u.next()},return:()=>u.return(void 0)}},cwd(u){if(b)s("Run already started");return i.cwd=u,x},env(u){if(b)s("Run already started");return i.env={...i.env,...u},x},timeout(u){if(b)s("Run already started");return i.timeoutMs=u,x}};return x}}
|
|
26
|
+
export{w,p,J,Ee,Ie,U,ne,N,ye};
|
package/dist/handle.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { Provider, SandboxInfo } from "./provider.js";
|
|
2
2
|
import type { CreateOptions, SandboxBase } from "./types.js";
|
|
3
3
|
import { Redactor } from "./errors.js";
|
|
4
|
-
export declare function makeHandle<N>(provider: Provider<N>, info: SandboxInfo, created: boolean, options: CreateOptions, redactor: Redactor, recoverSecrets?: boolean
|
|
4
|
+
export declare function makeHandle<N>(provider: Provider<N>, info: SandboxInfo, created: boolean, options: CreateOptions, redactor: Redactor, recoverSecrets?: boolean,
|
|
5
|
+
/** Dispose by close even without a key: the provider could not read whether the sandbox is keyed. */
|
|
6
|
+
closeOnDispose?: boolean): Promise<SandboxBase<N>>;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{fe,j,G,de,me,Se,Pe}from"./chunk-z1pmcdka.js";import{e}from"./chunk-xx9znywe.js";export{e as SandboxError,Pe as buildTemplate,G as connectSandbox,j as createSandbox,Se as deleteSnapshot,fe as hasCapability,de as listSandboxes,me as reapSandboxes};
|
package/dist/mastra.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-zygv9qfq.js";import{L}from"./chunk-9a843q9b.js";import"./chunk-xw0znbmg.js";import{createTool as s}from"@mastra/core/tools";import{z as e}from"zod";function c(p,r){return Object.fromEntries(L(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-xx9znywe.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-zygv9qfq.js";import{L}from"./chunk-9a843q9b.js";import"./chunk-xw0znbmg.js";import{tool as r}from"@openai/agents";function m(t,e){return L(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
|
@@ -28,6 +28,12 @@ export interface CreateInput {
|
|
|
28
28
|
diskGb?: number;
|
|
29
29
|
};
|
|
30
30
|
env?: Record<string, string>;
|
|
31
|
+
/**
|
|
32
|
+
* The names in `env` that are secrets. The core records them in the sandbox after create; an
|
|
33
|
+
* adapter that publishes its own readiness marker writes the same record first, so a second
|
|
34
|
+
* client that finds the sandbox can always recover them.
|
|
35
|
+
*/
|
|
36
|
+
secretNames?: readonly string[];
|
|
31
37
|
network?: "all" | "none" | {
|
|
32
38
|
allow: string[];
|
|
33
39
|
};
|
|
@@ -242,6 +248,19 @@ export interface Provider<Native = unknown, C extends Capability = Capability, X
|
|
|
242
248
|
* core then runs commands without a marker and idle reaping scans `/proc` for the SDK's env tag.
|
|
243
249
|
*/
|
|
244
250
|
readonly procActivity?: boolean;
|
|
251
|
+
/**
|
|
252
|
+
* The adapter writes the secret-names record from `CreateInput.secretNames` itself, atomically and
|
|
253
|
+
* before the sandbox can be found, so the core does not rewrite it after create.
|
|
254
|
+
*/
|
|
255
|
+
readonly recordsSecretNames?: boolean;
|
|
256
|
+
/**
|
|
257
|
+
* A paused or stopped sandbox's key and labels can be read only by waking it (Archil keeps them in
|
|
258
|
+
* a file inside the sandbox). `connect` then reports such a sandbox without them and wakes nothing;
|
|
259
|
+
* the core reopens a keyed sandbox that is not running through `find`, which wakes and verifies it,
|
|
260
|
+
* idle-only reaping leaves it alone rather than wake it to look, and `await using` on a handle
|
|
261
|
+
* connected while it slept closes rather than destroys it.
|
|
262
|
+
*/
|
|
263
|
+
readonly readsMetadataOnlyWhenRunning?: boolean;
|
|
245
264
|
/** Native command dialect for portable run wrappers; defaults to POSIX sh. */
|
|
246
265
|
readonly commandShell?: "bash";
|
|
247
266
|
/** Durable absolute directory for core-owned process records. */
|
package/dist/provider.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-g5n5xcmp.js";import{H,
|
|
1
|
+
import"./chunk-g5n5xcmp.js";import{H,se,ie}from"./chunk-szwxave3.js";import{b,E,T}from"./chunk-08jjwqh4.js";import{h,y,v}from"./chunk-kq1xms6a.js";import{e,i,u,a}from"./chunk-xx9znywe.js";export{e as SandboxError,ie as connectEnvelope,se as connectEnvelopes,h as createDeadline,v as createHttpClient,b as createNativeApi,i as describeNative,a as reason,u as redacting,T as sdkCall,E as sdkConstruct,y as sleep,H as streamFault};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f}from"../../chunk-
|
|
2
|
-
${r.command}`,{cwd:r.cwd,env:r.env,timeoutMs:r.timeoutMs,signal:r.signal,output:{capture:"none"},onStdout(
|
|
1
|
+
import{f}from"../../chunk-bfvk7mnq.js";import{m}from"../../chunk-n0f7xz7g.js";import{n}from"../../chunk-2ts3evzh.js";import{e,g,i,a}from"../../chunk-xx9znywe.js";import{randomUUID as I}from"node:crypto";import{posix as V}from"node:path";function y(o,d="provider",w,l){return new e(`${o}. Check the agentOS runtime or use local() with Docker.`,{code:d,provider:"agentos",sandboxId:w,cause:l})}function E(o,d,w=!1){if(o instanceof e)return o;let{message:l}=f(o),k=/ENOENT|not found|no such file/i.test(l)?w?"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",b=i(o,{code:k});return y(`agentOS operation failed: ${a(k,b.detail)}`,k,d,b.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 w="file";if(d.isSymbolicLink)w="symlink";else if(d.isDirectory)w="directory";return{path:o,type:w,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,w){if(!(w??(d!=="/"&&(await o.filesystem.readdirEntries(V.dirname(d))).find((b)=>b.name===V.basename(d))?.isSymbolicLink)))return F(d,await o.filesystem.stat(d));let k=await o.javascript.evaluate(`(() => { const s = require("node:fs").lstatSync(${JSON.stringify(d)}); return { size: s.size, modifiedAt: s.mtimeMs }; })()`);if(k.outcome!=="succeeded"||!_(k.value))throw y("agentOS could not read symbolic link metadata","provider");return{path:d,type:"symlink",size:k.value.size,modifiedAt:k.value.modifiedAt}}async function q(o,d,w){let l=await o.javascript.evaluate(`(() => { require("node:fs").chmodSync(${JSON.stringify(d)}, ${w}); return true; })()`);if(l.outcome!=="succeeded"||l.value!==!0)throw y("agentOS could not set the file mode","provider")}function T(o,d,w){let{entries:l,keys:k,destroying:b}=w,L,N=()=>L??=m("@rivet-dev/agentos-core","agentos",d).catch((t)=>{throw y("Install @rivet-dev/agentos-core@0.4.1 and its platform sidecar package","unavailable",void 0,g(t))});function P(t){let r=l.get(t);if(!r)throw y("Sandbox does not exist in this application process","not_found",t);return r}async function x(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 y("agentOS cannot enforce machine sizes or restore SDK snapshots","unsupported");if(t.idleTimeoutMs!==void 0||t.timeoutMs!==void 0)throw y("agentOS adapter does not enforce sandbox lifetime or idle deadlines","unsupported");if(t.signal?.aborted)throw y("Creation aborted","aborted");let r=t.network??"all",s={network:r==="none"?"deny":"allow"};if(r!=="all"&&r!=="none"){for(let u of r.allow)if(!/^(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(u))throw y("Network allow-list entries must be literal hostnames","unsupported");s={network:{default:"deny",rules:r.allow.map((u)=>({mode:"allow",operations:["*"],patterns:[`dns://${u}`,`tcp://${u}:*`]}))}}}async function c(){let u;try{let{AgentOs:A}=await N(),p={permissions:s};if(Object.keys(t.env??{}).length)p.environment={PATH:"/opt/agentos/bin:/usr/local/bin:/usr/bin:/bin",HOME:"/home/agentos",...t.env};if(o.software?.length)p.software=o.software;if(o.mounts?.length)p.mounts=o.mounts;if(o.limits)p.limits=o.limits;if(u=await A.create(p),await u.software.install(o.gitPackagePath?{type:"path",path:o.gitPackagePath}:{type:"url",url:j,expectedDigest:R}),await u.filesystem.mkdir("/workspace",{recursive:!0}),t.signal?.aborted)throw y("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:u,info:C}),S(C)}catch(A){if(u)await u.dispose().catch(()=>{});throw E(A)}}if(!t.key)return c();if(await M.find(t.key))throw y("Key already exists in this application process","invalid_argument");let h=k.get(t.key);if(h)throw await h,y("Key was created concurrently in this application process","invalid_argument");let O=c();k.set(t.key,O);try{return await O}finally{k.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=b.get(t);if(s)return s;let c=x(t,(v)=>v.dispose()).then(()=>{l.delete(t)});b.set(t,c);try{await c}finally{b.delete(t)}},async exec(t,r){if(r.signal?.aborted)return{exitCode:null,timedOut:!0};return x(t,async(s)=>{let c=new TextDecoder,v=new TextDecoder,h=`/tmp/.sandbox-sdk/stdin-${I()}`;if(r.stdin!==void 0)await s.filesystem.mkdir("/tmp/.sandbox-sdk",{recursive:!0}),await s.filesystem.writeFile(h,r.stdin);try{if(r.signal?.aborted)return{exitCode:null,timedOut:!0};let O=await s.process.exec(`exec < ${r.stdin===void 0?"/dev/null":n(h)}
|
|
2
|
+
${r.command}`,{cwd:r.cwd,env:r.env,timeoutMs:r.timeoutMs,signal:r.signal,output:{capture:"none"},onStdout(A){let p=c.decode(A,{stream:!0});if(p)r.onChunk({stream:"stdout",text:p})},onStderr(A){let p=v.decode(A,{stream:!0});if(p)r.onChunk({stream:"stderr",text:p})}});for(let[A,p]of[["stdout",c.decode()],["stderr",v.decode()]])if(p)r.onChunk({stream:A,text:p});let u=O.outcome==="timed_out"||O.outcome==="cancelled";if(!u&&O.exitCode===void 0)throw y("agentOS did not report a command exit","outcome_unknown",t);return{exitCode:u?null:O.exitCode??null,timedOut:u}}finally{if(r.stdin!==void 0)await s.filesystem.remove(h).catch(()=>{})}})},files:{writeCreatesParents:!0,writeSupportsMode:!0,transfer:"files",read:(t,r)=>x(t,async(s)=>new Uint8Array(await s.filesystem.readFile(r)),!0),write:(t,r,s,c)=>x(t,async(v)=>{if(await v.filesystem.mkdir(V.dirname(r),{recursive:!0}),await v.filesystem.writeFile(r,s),c?.mode!==void 0)await q(v,r,c.mode)},!0),stat:(t,r)=>x(t,async(s)=>z(s,r),!0),list:(t,r)=>x(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)=>x(t,(s)=>s.filesystem.mkdir(r,{recursive:!0}),!0),remove:(t,r,s)=>x(t,(c)=>c.filesystem.remove(r,s),!0)},async previewUrl(t){throw P(t),y("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,16 @@
|
|
|
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 an `ArchilError` from `disk` (API, file transfer, pause or image errors). */
|
|
4
|
+
export declare function nativeStatus(cause: unknown): number | undefined;
|
|
5
|
+
/** Archil's machine-readable error code, such as `sandbox_name_conflict`. Never its message. */
|
|
6
|
+
export declare function nativeCode(cause: unknown): string | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* `disk` loads its HTTP transport, undici, with a computed `import()` on first use, so a bundle
|
|
9
|
+
* that inlines `disk` cannot resolve it (undici is `disk`'s own dependency, not a top-level one).
|
|
10
|
+
* Nothing was sent when this fails.
|
|
11
|
+
*/
|
|
12
|
+
export declare function isTransportMissing(cause: unknown): boolean;
|
|
13
|
+
/** An Archil failure as a SandboxError, keeping only the error's name, HTTP status and code. */
|
|
14
|
+
export declare function archilError(cause: unknown, sandboxId?: string): SandboxError;
|
|
15
|
+
/** Whether Archil refused because the sandbox is not running (paused, stopped or still starting). */
|
|
16
|
+
export declare function notRunning(cause: unknown): boolean;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { ExecInput, ExecResult } from "../../provider.js";
|
|
2
|
+
/** How a `disk` process ended, as `SandboxProcess.wait()` reports it. */
|
|
3
|
+
export interface ArchilProcessResult {
|
|
4
|
+
status: "completed" | "failed" | "cancelled" | "timed_out";
|
|
5
|
+
exitCode?: number;
|
|
6
|
+
}
|
|
7
|
+
/** The parts of a `disk` `SandboxProcess` the adapter uses. */
|
|
8
|
+
export interface ArchilProcess {
|
|
9
|
+
sendInput(data: string | Uint8Array): Promise<void>;
|
|
10
|
+
closeStdin(): Promise<void>;
|
|
11
|
+
resize(size: {
|
|
12
|
+
cols: number;
|
|
13
|
+
rows: number;
|
|
14
|
+
}): Promise<void>;
|
|
15
|
+
wait(): Promise<ArchilProcessResult>;
|
|
16
|
+
kill(): Promise<void>;
|
|
17
|
+
disconnect(): Promise<void>;
|
|
18
|
+
/** Output bytes the process has produced so far, both streams; final once it has exited. */
|
|
19
|
+
readonly cursor: number;
|
|
20
|
+
}
|
|
21
|
+
export interface ArchilRunOptions {
|
|
22
|
+
env?: Record<string, string>;
|
|
23
|
+
timeoutSeconds?: number;
|
|
24
|
+
terminal?: {
|
|
25
|
+
cols: number;
|
|
26
|
+
rows: number;
|
|
27
|
+
};
|
|
28
|
+
collectOutput?: boolean;
|
|
29
|
+
onOutput?: (output: ArchilOutput) => void;
|
|
30
|
+
}
|
|
31
|
+
/** One output message. `offset` counts every output byte before `data`, stdout and stderr together. */
|
|
32
|
+
export interface ArchilOutput {
|
|
33
|
+
stream: "stdout" | "stderr";
|
|
34
|
+
offset: number;
|
|
35
|
+
data: Uint8Array;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Archil's output stream can skip bytes when a command writes faster than they are delivered
|
|
39
|
+
* (measured 2026-11-21: a 10 MiB `cat` arrived 1.3 MiB short, with one jump in `offset`). This
|
|
40
|
+
* follows the offset, which Archil counts across both streams, and reports how many bytes a
|
|
41
|
+
* message skipped, so a loss is never silent.
|
|
42
|
+
*/
|
|
43
|
+
export declare class OutputGaps {
|
|
44
|
+
#private;
|
|
45
|
+
lost: number;
|
|
46
|
+
/** Bytes skipped before this message, 0 when it follows on. */
|
|
47
|
+
take({ offset, data }: ArchilOutput): number;
|
|
48
|
+
/** Bytes missing after the last delivered message, given the process's final cursor. */
|
|
49
|
+
tail(cursor: number): number;
|
|
50
|
+
}
|
|
51
|
+
/** The part of a `disk` `Sandbox` that starts processes. Each `run` opens one process connection. */
|
|
52
|
+
export interface ArchilRunner {
|
|
53
|
+
run(command: string, options: ArchilRunOptions): Promise<ArchilProcess>;
|
|
54
|
+
}
|
|
55
|
+
/** Runs `command` in `cwd` the way a fresh POSIX shell would: a missing directory is exit 1. */
|
|
56
|
+
export declare function inDirectory(cwd: string, command: string): string;
|
|
57
|
+
/** The promise, or "late" once `ms` pass first. */
|
|
58
|
+
export declare function bounded<T>(promise: Promise<T>, ms: number): Promise<T | "late">;
|
|
59
|
+
/** Kills a process and waits for Archil to report its end, the kill included, within one window. */
|
|
60
|
+
export declare function terminate(process: ArchilProcess): Promise<boolean>;
|
|
61
|
+
/** Closes a process connection, bounded; a connection that will not close is left to Archil. */
|
|
62
|
+
export declare function disconnect(process: ArchilProcess): Promise<void>;
|
|
63
|
+
/** Runs one command, streaming its output in arrival order. Timeout and abort kill it first. */
|
|
64
|
+
export declare function execute({ runner, sandboxId, input, }: {
|
|
65
|
+
runner: ArchilRunner;
|
|
66
|
+
sandboxId: string;
|
|
67
|
+
input: ExecInput;
|
|
68
|
+
}): Promise<ExecResult>;
|
|
69
|
+
/**
|
|
70
|
+
* `collect` for output that must be whole (JSON records, file metadata): a read whose stream skipped
|
|
71
|
+
* bytes is run again, up to three times, then fails `unavailable` instead of returning a damaged record.
|
|
72
|
+
*/
|
|
73
|
+
export declare function collectExact(runner: ArchilRunner, sandboxId: string, command: string, options?: {
|
|
74
|
+
env?: Record<string, string>;
|
|
75
|
+
timeoutMs?: number;
|
|
76
|
+
}): Promise<CollectedRun>;
|
|
77
|
+
export interface CollectedRun {
|
|
78
|
+
exitCode: number | undefined;
|
|
79
|
+
stdout: Uint8Array;
|
|
80
|
+
stderr: string;
|
|
81
|
+
/** Output bytes Archil's stream skipped. Nonzero means stdout is incomplete. */
|
|
82
|
+
lost: number;
|
|
83
|
+
}
|
|
84
|
+
/** Runs a short helper command to completion and collects its raw output. For guest file operations. */
|
|
85
|
+
export declare function collect(runner: ArchilRunner, sandboxId: string, command: string, options?: {
|
|
86
|
+
env?: Record<string, string>;
|
|
87
|
+
stdin?: Uint8Array;
|
|
88
|
+
timeoutMs?: number;
|
|
89
|
+
}): Promise<CollectedRun>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import{J}from"../../chunk-zygv9qfq.js";import{k}from"../../chunk-16kht6jp.js";import{m}from"../../chunk-n0f7xz7g.js";import{n}from"../../chunk-2ts3evzh.js";import{t,o,r,re,e,i,a,I}from"../../chunk-xx9znywe.js";import{createHash as Oe}from"node:crypto";function h(c,d="provider",w){return new e(d==="auth"||d==="file_not_found"?c:`${c}. Check Archil and retry.`,{code:d,provider:"archil",sandboxId:w})}function B(c){if(!(c instanceof Error)||!("status"in c))return;return o(c.status)?c.status:void 0}function Me(c){if(!r(c)||!("code"in c)||!t(c.code))return;return/^[A-Za-z0-9_.-]{1,64}$/.test(c.code)?c.code:void 0}var Te=/_plan_required$/,$e=/quota|limit/i;function Ce(c,d){return c!==void 0&&[402,403,429].includes(c)&&d!==void 0&&$e.test(d)}function ie(c){for(let d=c,w=0;r(d)&&w<3;w++){if("code"in d&&d.code==="ERR_MODULE_NOT_FOUND"&&d instanceof Error&&d.message.includes("'undici'"))return!0;d="cause"in d?d.cause:void 0}return!1}var pe="Keep disk external when bundling (it loads undici at run time), or install undici next to the bundle.";function W(c,d){if(c instanceof e)return c;if(ie(c))return new e(`disk could not load its undici dependency in this bundle. ${pe}`,{code:"unavailable",provider:"archil",sandboxId:d,hint:pe});let w=B(c),x=Me(c),g=c instanceof Error?c.name:void 0,v=x!==void 0&&Te.test(x)?"unsupported":Ce(w,x)?"quota":w!==void 0?I(w):g==="AbortError"?"aborted":c instanceof TypeError?"unavailable":"provider",K=i(c,{code:v,known:!0,status:w===void 0?void 0:`HTTP ${w}${x===void 0?"":` ${x}`}`});return new e(`Archil request failed: ${a(v,K.detail)}. Check Archil and retry.`,{code:v,provider:"archil",sandboxId:d,cause:K.cause})}function se(c){return B(c)===409}class ae{#e=0;lost=0;take({offset:c,data:d}){let w=Math.max(0,c-this.#e);return this.#e=Math.max(this.#e,c+d.length),this.lost+=w,w}tail(c){let d=Math.max(0,c-this.#e);return this.#e=Math.max(this.#e,c),this.lost+=d,d}}var Z={exitCode:null,timedOut:!0},we=1048576,ee=1e4,De=5000,ye=5,Ee='read -r l < /proc/$$/stat; set -- ${l##*) }; g=$3; i=0; r=; while [ "$i" -lt 100 ]; do w=; o=; for f in /proc/[0-9]*/stat; do [ "$f" = /proc/$$/stat ] && continue; { read -r l < "$f"; } 2>/dev/null || continue; case "$l" in *"(nohup) "*|*"(setsid) "*) set -- ${l##*) }; [ "$3" = "$g" ] && w=1;; *) set -- ${l##*) }; [ "$3" = "$g" ] && o=1;; esac; done; if [ -z "$w" ]; then { [ -z "$o" ] || [ -n "$r" ]; } && break; r=1; fi; sleep 0.01; i=$((i+1)); done';function ce(c,d){return`cd -- ${n(c)} || exit 1
|
|
2
|
+
(
|
|
3
|
+
${d}
|
|
4
|
+
)
|
|
5
|
+
c=$?
|
|
6
|
+
${Ee}
|
|
7
|
+
exit "$c"`}function N(c,d){let w;return Promise.race([c,new Promise((x)=>{w=setTimeout(()=>x("late"),d)})]).finally(()=>clearTimeout(w))}async function H(c){let d=(async()=>{await c.kill(),await c.wait()})();try{return await N(d,ee)!=="late"}catch{return!1}}async function X(c){await N(c.disconnect().catch(()=>{}),De)}async function be(c,d){if(d!==void 0)for(let w=0;w<d.length;w+=we)await c.sendInput(d.subarray(w,w+we));await c.closeStdin()}async function ge(c,d,w,x){try{return await c.run(w,x)}catch(g){if(g instanceof e||B(g)!==void 0)throw W(g,d);throw h("Archil process connection failed; the command may have started","outcome_unknown",d)}}async function xe({runner:c,sandboxId:d,input:w}){if(w.signal?.aborted)return Z;let x={stdout:new TextDecoder,stderr:new TextDecoder},g=new ae,v=(T,R)=>{if(R)w.onChunk({stream:T,text:R})},K=()=>{},j=!1,S=new Promise((T)=>{K=()=>{j=!0,T("stop")}}),q=setTimeout(()=>K(),w.timeoutMs);w.signal?.addEventListener("abort",K,{once:!0});let z=()=>h("Process termination could not be confirmed","outcome_unknown",d);try{let T=ce(w.cwd,w.command),R={env:w.env,timeoutSeconds:Math.ceil(w.timeoutMs/1000)+ye,collectOutput:!1,onOutput:(P)=>{let{stream:D,data:M}=P,s=g.take(P);if(s>0)v(D,`${x[D].decode()}
|
|
8
|
+
[sandbox-sdk: Archil's output stream skipped ${s} bytes here]
|
|
9
|
+
`);v(D,x[D].decode(M,{stream:!0}))}},G=(async()=>{try{return{ok:!0,process:await ge(c,d,T,R)}}catch(P){return{ok:!1,error:W(P,d)}}})(),C=await Promise.race([G,S]);if(C==="stop"){let P=await N(G,ee);if(P==="late")throw G.then(async(M)=>{if(!M.ok)return;try{await H(M.process)}finally{await X(M.process)}}),z();if(!P.ok){if(P.error.code!=="outcome_unknown")return Z;throw P.error}try{if(!await H(P.process))throw z()}finally{await X(P.process)}for(let M of["stdout","stderr"])v(M,x[M].decode());let D=g.tail(P.process.cursor);if(D>0)v("stdout",`
|
|
10
|
+
[sandbox-sdk: Archil's output stream skipped the last ${D} bytes]
|
|
11
|
+
`);return Z}if(!C.ok)throw C.error;let{process:_}=C,U=()=>{for(let D of["stdout","stderr"])v(D,x[D].decode());let P=g.tail(_.cursor);if(P>0)v("stdout",`
|
|
12
|
+
[sandbox-sdk: Archil's output stream skipped the last ${P} bytes]
|
|
13
|
+
`)};try{let P=w.stdin===void 0?void 0:new TextEncoder().encode(w.stdin),D=N(be(_,P).catch(()=>{}),w.timeoutMs+ee),M=await Promise.race([_.wait().then((l)=>({kind:"exit",result:l})),S.then(()=>({kind:"stop"}))]).catch(()=>({kind:"broken"}));if(M.kind!=="exit"){if(!await H(_))throw z();if(U(),M.kind==="broken"&&!j)throw h("Archil process stream broke; the command was stopped and its outcome is unknown","outcome_unknown",d);return Z}U();let{result:s}=M;if(s.status==="timed_out")return Z;if(s.exitCode!==void 0&&s.status!=="cancelled")return{exitCode:s.exitCode,timedOut:!1};throw h(s.status==="cancelled"?"Archil cancelled the command before it finished":"Archil could not run the command","provider",d)}finally{await X(_)}}finally{clearTimeout(q),w.signal?.removeEventListener("abort",K)}}async function te(c,d,w,x={}){for(let g=0;g<3;g++){let v=await Y(c,d,w,x);if(v.lost===0)return v}throw h("Archil helper output was incomplete three times","unavailable",d)}async function Y(c,d,w,x={}){let g=x.timeoutMs??120000,v=[],K=new TextDecoder,j="",S=new ae,q=Date.now()+g,z=ge(c,d,w,{env:x.env,timeoutSeconds:Math.ceil(g/1000)+ye,collectOutput:!1,onOutput:(C)=>{let{stream:_,data:U}=C;if(S.take(C),_==="stdout")v.push(U.slice());else j+=K.decode(U,{stream:!0})}}),T=await N(z,g);if(T==="late"){let C=(async()=>{try{return{ok:!0,process:await z}}catch(U){return{ok:!1,error:W(U,d)}}})(),_=await N(C,ee);if(_!=="late"&&!_.ok)throw _.error;if(_==="late")throw h("Archil guest operation start was never answered","outcome_unknown",d);try{if(!await H(_.process))throw h("Archil guest operation timed out and could not be stopped","outcome_unknown",d)}finally{await X(_.process)}throw h("Archil guest operation timed out starting","timeout",d)}let R=T,G=async()=>{if(!await H(R))return h("Archil guest operation timed out and could not be stopped","outcome_unknown",d);return h("Archil guest operation timed out","timeout",d)};try{let C;try{C=await N(be(R,x.stdin),Math.max(0,q-Date.now()))}catch{if(!await H(R))throw h("Archil helper input failed and the helper could not be stopped","outcome_unknown",d);throw h("Archil helper input failed; the helper was stopped","provider",d)}if(C==="late")throw await G();let _;try{_=await N(R.wait(),Math.max(0,q-Date.now()))}catch{if(!await H(R))throw h("Archil helper stream broke and the helper could not be stopped","outcome_unknown",d);throw h("Archil helper stream broke; the helper was stopped","provider",d)}if(_==="late")throw await G();S.tail(R.cursor);let U=v.reduce((M,s)=>M+s.length,0),P=new Uint8Array(U),D=0;for(let M of v)P.set(M,D),D+=M.length;return{exitCode:_.status==="completed"?_.exitCode:void 0,stdout:P,stderr:j+K.decode(),lost:S.lost}}catch(C){throw W(C,d)}finally{await X(R)}}var ve="sbxsdk-",de=/^sbxsdk-(?:k[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/,ke={"sandbox-sdk":"1"},Re="SANDBOX_SDK_ATTEMPT",Ne=`printf '%s' "$SANDBOX_SDK_ATTEMPT"`,he=86400,ue=(c)=>new Promise((d)=>setTimeout(d,c)),le=180000,Ie=60000;function Ae(c){return`${ve}k${Oe("sha256").update(c).digest("hex").slice(0,40)}`}var Ke={small:{cpu:1,memoryMb:2048},medium:{cpu:2,memoryMb:4096},large:{cpu:4,memoryMb:8192}};function Ue(c){if(c===void 0)return{};let d=t(c)?Ke[c]:c;if(!t(c)&&c.diskGb!==void 0)throw h("Archil sandboxes have no disk size option","unsupported");if(!Number.isInteger(d.cpu)||d.cpu<1||d.cpu>32)throw h("Archil sandboxes take 1 to 32 whole vCPUs","unsupported");if(!Number.isInteger(d.memoryMb)||d.memoryMb<256||d.memoryMb>65536)throw h("Archil sandboxes take 256 to 65536 MiB of memory, in whole MiB","unsupported");return{vcpuCount:d.cpu,memSizeMiB:d.memoryMb}}function Fe(c,d){if(c===void 0)return;if(d?.length)throw h("Archil resumes a paused sandbox on traffic to an exposed port, so timeoutMs can't be a hard limit with ports","unsupported");let w=Math.min(Math.floor(c/1000),he-1);if(c<60000||c>he*1000)throw h("Archil sandbox lifetimes are 60 seconds to 24 hours","unsupported");return w}function Le(c){if(c===void 0)return;let d=Math.ceil(c/1000);if(d<1||d>86400)throw h("Archil idle timeouts are 1 second to 24 hours","unsupported");return d}function je(c){if(c===void 0)return;if(c==="all")return{egress:{default:"allow"}};if(c==="none")return{egress:{default:"deny"}};return{egress:{default:"deny",allow:[...c.allow]}}}function V(c){switch(c){case"pending":case"running":return"running";case"pausing":case"paused":return"paused";case"stopping":case"stopped":case"exited":case"failed":return"stopped";case"deleting":case"deleted":return;default:{let d=c;return}}}var ne="/var/lib/sandbox-sdk/metadata.json",fe="/tmp/.sandbox-sdk/secret-names.json",qe=`mkdir -p /workspace /var/lib/sandbox-sdk /tmp/.sandbox-sdk && printf '%s' "$SANDBOX_SDK_SECRET_NAMES" > ${fe}.tmp && mv -f ${fe}.tmp ${fe} && printf '%s' "$SANDBOX_SDK_MARKER" > ${ne}.tmp && mv -f ${ne}.tmp ${ne}`;function Be(c){let d;try{d=JSON.parse(new TextDecoder().decode(c))}catch{return}if(!r(d)||!("labels"in d)||!re(d.labels))return;return{key:"key"in d&&t(d.key)?d.key:void 0,labels:{...d.labels}}}function ze(c,d){return Object.entries(d).every(([w,x])=>c.labels[w]===x)}var He=["import os,sys,stat,tempfile","def no(code,why):"," sys.stderr.write(why+'\\n'); sys.exit(code)","def check(p):"," try: st=os.stat(p)"," except FileNotFoundError: return None"," if stat.S_ISDIR(st.st_mode): no(21,'is a directory')"," if not stat.S_ISREG(st.st_mode): no(23,'not a regular file')"," return st","p=os.environb[b'SANDBOX_SDK_PATH']","m=sys.argv[1]","def walk(d):"," out=b'/' if d.startswith(b'/') else os.getcwdb()"," todo=[c for c in d.split(b'/') if c and c!=b'.']"," hops=0"," while todo:"," c=todo.pop(0)"," if c==b'..': out=os.path.dirname(out); continue"," nxt=os.path.join(out,c)"," if os.path.islink(nxt):"," hops+=1"," if hops>40: no(22,'too many levels of symbolic links')"," t=os.readlink(nxt)"," if t.startswith(b'/'): out=b'/'"," todo=[x for x in t.split(b'/') if x and x!=b'.']+todo"," continue"," if not os.path.lexists(nxt):"," try: os.mkdir(nxt)"," except FileExistsError: todo.insert(0,c); continue"," elif not os.path.isdir(nxt): no(24,'a parent is not a directory')"," out=nxt"," return out","n=0","while True:"," if not os.path.basename(p): no(21,'is a directory')"," d=walk(os.path.dirname(p))"," p=os.path.join(d,os.path.basename(p))"," if not os.path.islink(p): break"," n+=1"," if n>40: no(22,'too many levels of symbolic links')"," p=os.path.join(d,os.readlink(p))","check(p)","fd,t=tempfile.mkstemp(dir=d,prefix=b'.sandbox-sdk-write.')","try:"," with os.fdopen(fd,'wb') as f:"," while True:"," b=sys.stdin.buffer.read(1048576)"," if not b: break"," f.write(b)"," st=check(p)"," if st is not None and st.st_nlink>1:"," try:"," with open(t,'rb') as s, open(p,'wb') as f:"," while True:"," b=s.read(1048576)"," if not b: break"," f.write(b)"," except IsADirectoryError: no(21,'is a directory')"," if m: os.chmod(p,int(m,8))"," else:"," os.chmod(t,int(m,8) if m else stat.S_IMODE(st.st_mode) if st else 0o644)"," try: os.rename(t,p)"," except IsADirectoryError: no(21,'is a directory')","finally:"," if os.path.lexists(t): os.unlink(t)"].join(`
|
|
14
|
+
`),Se=(c,...d)=>`python3 -I -S -c ${n(c)} ${d.map(n).join(" ")}`,Xe=(c)=>Se(He,c===void 0?"":c.toString(8)),Ge=`import os,sys
|
|
15
|
+
p=sys.argv[1]
|
|
16
|
+
if not os.path.isfile(p): sys.exit(3)
|
|
17
|
+
with open(p,'rb') as f:
|
|
18
|
+
f.seek(int(sys.argv[2]))
|
|
19
|
+
n=int(sys.argv[3])
|
|
20
|
+
o=sys.stdout.buffer
|
|
21
|
+
while n!=0:
|
|
22
|
+
b=f.read(1048576 if n<0 else min(n,1048576))
|
|
23
|
+
if not b: break
|
|
24
|
+
o.write(b)
|
|
25
|
+
if n>0: n-=len(b)`;function Pe(c,d){let w,x,g=new Map,v=new Map;async function K(){let s=c.apiKey??process.env.ARCHIL_API_KEY;if(!s?.trim())throw h("Archil API key is missing. Authentication is required. Set ARCHIL_API_KEY or pass apiKey.","auth");let l=c.region??process.env.ARCHIL_REGION??"aws-us-east-1",{Archil:f}=await m("disk","archil",d);return x=new f({apiKey:s.trim(),region:l})}async function j(){w??=K();try{return await w}catch(s){throw w=void 0,s}}async function S(s,l){try{return await l()}catch(f){throw W(f,s)}}async function q(s){let l=g.get(s);if(l)return l;let f;try{f=await(await j()).sandboxes.get(s)}catch(p){if([400,404].includes(B(p)??0))throw h("Sandbox not found","not_found",s);throw p}if(!de.test(f.name)||V(f.status)===void 0)throw h("Sandbox not found","not_found",s);return g.set(s,f),f}async function z(s){let l=Date.now()+le;await s.refresh();while(["pending","pausing","stopping"].includes(s.status)){if(Date.now()>l)throw h(`Sandbox stayed ${s.status} too long`,"timeout",s.id);await ue(250),await s.refresh()}let f=!1;try{if(s.status==="paused")await s.resume(),f=!0;else if(s.status==="stopped"||s.status==="exited")await s.start(),f=!0}catch(p){if(!se(p))throw p;if(await s.refresh(),s.status!=="running")throw p}if(V(s.status)===void 0)throw h("Sandbox not found","not_found",s.id);if(s.status!=="running")throw h(`Sandbox ${s.id} is ${s.status} on Archil, not running; destroy it and create another`,"unavailable",s.id);return f}function T(s){return{run:async(l,f)=>{let p=await q(s);try{return await p.run(l,f)}catch(y){if(!se(y))throw y;throw h("Sandbox is paused or stopped (Archil pauses an idle sandbox after idleTimeoutMs, 30 minutes by default). Call box.resume() first","unavailable",s)}}}}function R(s){let l=T(s);return{name:"archil",raw:async(f)=>{let p=await te(l,s,f);if(p.exitCode!==0)throw h("Guest operation failed","provider",s);return new TextDecoder().decode(p.stdout)},upload:async(f,p,y)=>{let u=await Y(l,s,Xe(y),{env:{SANDBOX_SDK_PATH:f},stdin:p});if(u.exitCode===21)throw h("Path is a directory","invalid_argument",s);if(u.exitCode===22)throw h("Path is a symlink loop","invalid_argument",s);if(u.exitCode===23)throw h("Path is not a regular file","invalid_argument",s);if(u.exitCode===24)throw h("A parent of the path is not a directory","invalid_argument",s);if(u.exitCode!==0)throw h("File write failed","provider",s)},read:async(f,p)=>{if(p){let u=await Y(l,s,Se(Ge,f,String(p.offset),String(p.length)));if(u.exitCode===3)throw h("File does not exist","file_not_found",s);if(u.exitCode!==0)throw h("File read failed","provider",s);if(u.lost===0)return u.stdout}let y=await G(s,f);return p?y.subarray(p.offset,p.offset+p.length):y}}}async function G(s,l){let f=[],p=async()=>{f.length=0,await(await q(s)).files.downloadFile(l,(b)=>{f.push(b.slice())})};try{await p()}catch{if((await Y(T(s),s,`[ -f ${n(l)} ]`)).exitCode!==0)throw h("File does not exist","file_not_found",s);try{await p()}catch{throw h("File read failed","provider",s)}}let y=new Uint8Array(f.reduce((b,O)=>b+O.length,0)),u=0;for(let b of f)y.set(b,u),u+=b.length;return y}async function C(s){let l=await te(T(s),s,`cat -- ${n(ne)}`,{timeoutMs:30000});return l.exitCode===0?Be(l.stdout):void 0}async function _(s){let l=V(s.status);if(!de.test(s.name)||l===void 0)return;let f={id:s.id,state:l,createdAt:s.createdAt.getTime()};if(l!=="running")return{info:{...f,labels:{...ke}},readable:!1};g.set(s.id,s);let p;try{p=await C(s.id)}catch(y){if(!(y instanceof e))throw y;await s.refresh();let u=V(s.status);if(u===void 0)return;if(u==="running")throw y;return{info:{...f,state:u,labels:{...ke}},readable:!1}}if(!p)return;return{info:{...f,key:p.key,labels:p.labels},readable:!0}}async function U(s,l){let f=Date.now()+120000,p=async(y)=>Date.now()>=f?"late":N(y(),f-Date.now());for(;;){let y;try{y=await p(()=>s.sandboxes.get(l))}catch(u){if([400,404].includes(B(u)??0))return"gone";throw u}if(y==="late")return"late";if(y.status==="deleting"||y.status==="deleted")return"gone";try{if(!["stopped","exited","failed","stopping"].includes(y.status)){if(await p(()=>y.stop({wait:!1}))==="late")return"late"}if(["stopped","exited","failed"].includes(y.status)){let u=f-Date.now();if(u<=0)return"late";if(await N(y.delete(),u)==="late")return"unconfirmed";return"gone"}}catch(u){if(B(u)===404)return"gone";if(B(u)!==409)throw u}if(Date.now()>=f)return"late";await new Promise((u)=>setTimeout(u,Math.min(500,f-Date.now())))}}async function P(s){let l=v.get(s);if(v.delete(s),l)await Promise.all([...l].map((f)=>X(f)))}async function D(s,l){let f=new Set,p=new TextDecoder,y=await T(s).run(ce(l.cwd??"/workspace","exec /bin/bash -l || exec /bin/sh"),{env:{TERM:"xterm-256color",...l.env},terminal:{cols:l.cols,rows:l.rows},collectOutput:!1,onOutput:({data:A})=>{let F=p.decode(A,{stream:!0});if(F)for(let L of f)L(F)}}),u=v.get(s);if(!u)u=new Set,v.set(s,u);u.add(y);let b=y.wait(),O=()=>{let A=v.get(s);if(A?.delete(y),A?.size===0)v.delete(s);X(y)};return b.then(O,O),{write:(A)=>S(s,()=>y.sendInput(A)),resize:(A,F)=>S(s,()=>y.resize({cols:A,rows:F})),onData(A){return f.add(A),()=>f.delete(A)},close:()=>S(s,async()=>{try{if(!await H(y))throw h("Terminal could not be closed","outcome_unknown",s)}finally{v.get(s)?.delete(y),await X(y)}}),wait:()=>S(s,async()=>{let A=await b;return{exitCode:A.status==="completed"?A.exitCode??null:null}})}}return{name:"archil",keyMode:"exact",procActivity:!0,recordsSecretNames:!0,readsMetadataOnlyWhenRunning:!0,readSecretEnvironment:(s)=>S(s,async()=>{for(let l=0;l<3;l++){let f=await Y(T(s),s,J,{timeoutMs:30000});if(f.exitCode!==0)throw h("Secret recovery failed","provider",s);if(f.lost>0)continue;let p=new TextDecoder().decode(f.stdout);if(!p)return;let y=p.indexOf("\x00");if(y<0)throw h("Secret recovery record is malformed","provider",s);let u={};for(let b of p.slice(y+1).split("\x00")){let O=b.indexOf("=");if(O>=0)u[b.slice(0,O)]=b.slice(O+1)}return{record:p.slice(0,y),environment:u}}throw h("Secret recovery output was incomplete three times","unavailable",s)}),capabilities:new Set(["pause","terminal","network-policy","size"]),create:(s)=>S(void 0,async()=>{if(s.from!==void 0)throw h("Archil adapter has no snapshot restore","unsupported");let l=crypto.randomUUID(),f={name:s.key===void 0?`${ve}${crypto.randomUUID()}`:Ae(s.key),...Ue(s.size),...c.imageId===void 0?c.image===void 0?{}:{baseImage:c.image}:{imageId:c.imageId},env:{...s.env,[Re]:l},network:je(s.network),ports:s.ports?.length?[...s.ports]:void 0,maxTtlSeconds:Fe(s.timeoutMs,s.ports),idleTtlSeconds:Le(s.idleTimeoutMs)};if(s.signal?.aborted)throw h("Creation aborted","aborted");let p=await j(),y=()=>h(`Sandbox creation outcome is unknown; delete sandbox ${f.name??""} if it exists before retrying`,"outcome_unknown"),u,b=!1;try{u=await p.sandboxes.create(f,{wait:!1})}catch(A){let F=B(A);if(F!==void 0&&F<500||ie(A))throw A;let L=await p.sandboxes.list().then((Q)=>Q.find((oe)=>oe.name===f.name)).catch(()=>{return});if(!L)throw y();u=L,b=s.key!==void 0}let O=JSON.stringify({key:s.key,labels:s.labels});try{let A=Date.now()+le;while(u.status==="pending"){if(s.signal?.aborted)throw h("Creation aborted","aborted",u.id);if(Date.now()>A)throw h("Sandbox did not start in time","timeout",u.id);await ue(250),await u.refresh()}if(u.status!=="running")throw h(`Sandbox did not start (${u.status})`,"provider",u.id);if(g.set(u.id,u),b){let L=await te(T(u.id),u.id,Ne,{timeoutMs:30000}).catch(()=>{return});if(L===void 0||L.exitCode!==0)throw y();if(new TextDecoder().decode(L.stdout)!==l)throw h("Another client created this keyed sandbox first","provider",u.id);b=!1}if((await Y(T(u.id),u.id,qe,{env:{SANDBOX_SDK_MARKER:O,SANDBOX_SDK_SECRET_NAMES:JSON.stringify(s.secretNames??[])}})).exitCode!==0)throw h("Sandbox setup failed","provider",u.id);return{id:u.id,key:s.key,labels:{...s.labels},state:"running",createdAt:u.createdAt.getTime()}}catch(A){if(g.delete(u.id),b)throw h(`Sandbox creation outcome is unknown; sandbox ${u.id} may be this create's; delete it if no other client uses this key`,"outcome_unknown",u.id);if(await U(p,u.id).catch(()=>"late")!=="gone")throw h(`Sandbox ${u.id} did not become usable and could not be deleted; delete it before retrying`,"outcome_unknown",u.id);throw W(A,u.id)}}),find:(s)=>S(void 0,async()=>{let l=Ae(s),f=Date.now()+le+Ie,p=(E)=>h("Keyed sandbox is still being set up by another client","timeout",E),y=async(E,_e)=>{let me=await N(E,Math.max(0,f-Date.now()));if(me==="late")throw p(_e);return me},u=await j(),b=(await y(u.sandboxes.list())).find((E)=>E.name===l);if(!b)return;g.set(b.id,b);let O=()=>{g.delete(b.id);return},A,F=!1,L,Q,oe=()=>(Q??=(async()=>{if(!await L?.catch(()=>!1))return;if(A==="paused")await b.pause().catch(()=>{});else if(A==="stopped")await b.stop().catch(()=>{})})(),N(Q,30000));for(;;){if(V(b.status)===void 0)return O();if(b.status==="failed")throw h(`Sandbox ${b.id} under this key failed on Archil; destroy it (connectSandbox(provider, id).destroy()) and retry`,"unavailable",b.id);try{if(b.status!=="running"&&b.status!=="pending"&&!F){F=!0,A=b.status==="paused"||b.status==="pausing"?"paused":"stopped",L=z(b),await y(L,b.id);continue}if(b.status==="running"){let E=await y(C(b.id).catch(()=>{return}),b.id);if(E&&E.key!==s)return await oe(),O();if(E)return{id:b.id,key:s,labels:E.labels,state:"running",createdAt:b.createdAt.getTime()}}if(Date.now()>f)throw p(b.id);await ue(500),await y(b.refresh(),b.id)}catch(E){if(B(E)===404)return O();if(E instanceof e&&E.code==="not_found")return O();throw E}}}),connect:(s)=>S(s,async()=>{g.delete(s);let l=await _(await q(s));if(!l)throw h("Sandbox not found","not_found",s);return l.info}),list:(s)=>S(void 0,async()=>{let l=[],f=(await(await j()).sandboxes.list()).filter((p)=>de.test(p.name)&&V(p.status)!==void 0);for(let p=0;p<f.length;p+=8){let y=await Promise.all(f.slice(p,p+8).map((u)=>_(u).catch(()=>{return})));for(let u of y)if(u?.readable&&ze(u.info,s))l.push(u.info)}return l}),destroy:(s)=>S(s,async()=>{let l=await j();g.delete(s),await P(s);let f=await U(l,s);if(f==="late")throw h("Sandbox was not stopped and deleted within 2 minutes; it still exists, destroy it again","timeout",s);if(f==="unconfirmed")throw h("Sandbox deletion was not confirmed within 2 minutes; it may still complete","outcome_unknown",s)}),async close(s){g.delete(s),await P(s)},exec:(s,l)=>S(s,()=>xe({runner:T(s),sandboxId:s,input:l})),files:{...k(async(s)=>R(s),S),writeSupportsMode:!0},previewUrl:(s,l)=>S(s,async()=>{let f=await q(s);if(f.maxTtlSeconds<he)throw h("This sandbox has a timeoutMs lifetime, and Archil resumes a paused sandbox on traffic to an exposed port. Create it without timeoutMs to use previews","unsupported",s);return{url:`https://${await f.exposePort(l)}`}}),pause:(s)=>S(s,async()=>{await(await q(s)).pause()}),resume:(s)=>S(s,async()=>{let l=await q(s);if(await l.refresh(),l.status==="failed")throw h(`Sandbox ${s} failed on Archil and can't be resumed; destroy it and create another`,"unavailable",s);await z(l)}),terminal:(s,l)=>S(s,()=>D(s,l)),native(s){let l=g.get(s);if(!l)throw h("Connect the sandbox first","not_found",s);if(!x)throw h("Client is detached","not_found",s);return{sandbox:l,client:x}}}}function ft(c={}){return Pe(c,()=>import("disk"))}export{ft as archil};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Archil, ArchilOptions as ArchilClientOptions, Sandbox } from "disk";
|
|
2
|
+
import type { Provider } from "../../provider.js";
|
|
3
|
+
export interface ArchilOptions {
|
|
4
|
+
/** Defaults to ARCHIL_API_KEY. Keys are made per region in the Archil console. */
|
|
5
|
+
apiKey?: string;
|
|
6
|
+
/** The key's region, such as `aws-us-east-1` (the default) or `aws-eu-west-1`. Defaults to ARCHIL_REGION. */
|
|
7
|
+
region?: string;
|
|
8
|
+
/** Public OCI image for new sandboxes. Unset uses Archil's default, `node:24-bookworm`. */
|
|
9
|
+
image?: string;
|
|
10
|
+
/** A ready image ID from Archil's image builds, instead of `image`. */
|
|
11
|
+
imageId?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface ArchilNative {
|
|
14
|
+
sandbox: Sandbox;
|
|
15
|
+
client: Archil;
|
|
16
|
+
}
|
|
17
|
+
type ArchilCapability = "pause" | "terminal" | "network-policy" | "size";
|
|
18
|
+
export type ArchilProvider = Provider<ArchilNative, ArchilCapability>;
|
|
19
|
+
/** The `disk` module, or a test fixture with the same shape. */
|
|
20
|
+
export interface ArchilModule {
|
|
21
|
+
Archil: new (options: ArchilClientOptions) => Archil;
|
|
22
|
+
}
|
|
23
|
+
/** @internal The adapter behind `archil()`. `load` imports `disk`; tests pass a fixture. */
|
|
24
|
+
export declare function createArchilProvider(options: ArchilOptions, load: () => Promise<ArchilModule>): ArchilProvider;
|
|
25
|
+
export {};
|