@opencoredev/sandbox-sdk 1.0.2 → 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.
Files changed (94) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +9 -6
  3. package/dist/ai.js +1 -1
  4. package/dist/chunk-0eeyc0aq.js +4 -0
  5. package/dist/chunk-0wp6x4wb.js +2 -0
  6. package/dist/chunk-2999xbh7.js +2 -0
  7. package/dist/chunk-3h6c1ack.js +2 -0
  8. package/dist/{chunk-q5vqajhg.js → chunk-7rkcx5cx.js} +2 -2
  9. package/dist/{chunk-hzbssbep.js → chunk-7s9pxk1v.js} +4 -4
  10. package/dist/chunk-aek8n3a4.js +78 -0
  11. package/dist/{chunk-8786zrns.js → chunk-aq6fmgdx.js} +2 -2
  12. package/dist/chunk-drhcb2hx.js +2 -0
  13. package/dist/chunk-ek44atpe.js +2 -0
  14. package/dist/chunk-g5n5xcmp.js +0 -0
  15. package/dist/chunk-kdecey83.js +290 -0
  16. package/dist/{chunk-bd481sb7.js → chunk-pdgnaxp9.js} +2 -2
  17. package/dist/{chunk-k60b4r27.js → chunk-qfhee1t8.js} +2 -2
  18. package/dist/chunk-rx9318sh.js +5 -0
  19. package/dist/chunk-sjnk17y5.js +26 -0
  20. package/dist/chunk-w8nk1xf2.js +17 -0
  21. package/dist/{chunk-bfzdkjjw.js → chunk-x05t86n3.js} +2 -2
  22. package/dist/{chunk-nw845a93.js → chunk-x4rrgmxf.js} +10 -10
  23. package/dist/chunk-xqtzts2q.js +1 -0
  24. package/dist/errors.d.ts +19 -9
  25. package/dist/files.d.ts +2 -5
  26. package/dist/http.d.ts +3 -0
  27. package/dist/index.d.ts +24 -3
  28. package/dist/index.js +1 -1
  29. package/dist/mastra.js +1 -1
  30. package/dist/memory.js +1 -1
  31. package/dist/openai.js +1 -1
  32. package/dist/provider.d.ts +127 -7
  33. package/dist/provider.js +1 -1
  34. package/dist/providers/agentos/index.js +2 -2
  35. package/dist/providers/baseten/errors.d.ts +6 -0
  36. package/dist/providers/baseten/execute.d.ts +68 -0
  37. package/dist/providers/baseten/index.d.ts +3 -0
  38. package/dist/providers/baseten/index.js +97 -0
  39. package/dist/providers/baseten/provider.d.ts +39 -0
  40. package/dist/providers/boat/index.js +1 -1
  41. package/dist/providers/boxd/errors.d.ts +25 -3
  42. package/dist/providers/boxd/index.js +14 -14
  43. package/dist/providers/boxd/provider.d.ts +16 -2
  44. package/dist/providers/daytona/api.d.ts +2 -2
  45. package/dist/providers/daytona/index.js +15 -15
  46. package/dist/providers/e2b/envd.d.ts +32 -2
  47. package/dist/providers/e2b/errors.d.ts +1 -2
  48. package/dist/providers/e2b/index.d.ts +40 -4
  49. package/dist/providers/e2b/index.js +1 -1
  50. package/dist/providers/e2b/narrow.d.ts +7 -0
  51. package/dist/providers/freestyle/execute.d.ts +3 -1
  52. package/dist/providers/freestyle/index.js +7 -16
  53. package/dist/providers/instabox/api.d.ts +56 -0
  54. package/dist/providers/instabox/errors.d.ts +49 -0
  55. package/dist/providers/instabox/index.d.ts +4 -0
  56. package/dist/providers/instabox/index.js +7 -0
  57. package/dist/providers/instabox/provider.d.ts +28 -0
  58. package/dist/providers/local/index.js +2 -2
  59. package/dist/providers/modal/errors.d.ts +4 -0
  60. package/dist/providers/modal/index.d.ts +14 -0
  61. package/dist/providers/modal/index.js +2 -0
  62. package/dist/providers/modal/provider.d.ts +94 -0
  63. package/dist/providers/modal/transport.d.ts +50 -0
  64. package/dist/providers/railway/index.js +1 -1
  65. package/dist/providers/sandboxer/index.js +1 -1
  66. package/dist/providers/superserve/execute.d.ts +3 -1
  67. package/dist/providers/superserve/index.js +22 -24
  68. package/dist/providers/tenki/deadline.d.ts +1 -1
  69. package/dist/providers/tenki/index.js +16 -26
  70. package/dist/providers/tenki/provider.d.ts +12 -12
  71. package/dist/providers/tenki/records.d.ts +1 -1
  72. package/dist/providers/upstash/index.js +11 -11
  73. package/dist/providers/upstash/provider.d.ts +1 -1
  74. package/dist/providers/vercel/index.js +1 -1
  75. package/dist/providers/vercel/transport.d.ts +1 -1
  76. package/dist/run.d.ts +9 -0
  77. package/dist/shared/guest.d.ts +28 -1
  78. package/dist/shared/native-error.d.ts +2 -0
  79. package/dist/streams.d.ts +2 -1
  80. package/dist/testing.js +3 -3
  81. package/dist/tools.js +1 -1
  82. package/dist/types.d.ts +37 -14
  83. package/dist/version.d.ts +4 -0
  84. package/package.json +28 -4
  85. package/dist/chunk-23tjmd39.js +0 -8
  86. package/dist/chunk-6a3wkj84.js +0 -2
  87. package/dist/chunk-8wq767xb.js +0 -17
  88. package/dist/chunk-9w9rddra.js +0 -2
  89. package/dist/chunk-ckym4cht.js +0 -23
  90. package/dist/chunk-hgrwyjrb.js +0 -2
  91. package/dist/chunk-kk1hw8wa.js +0 -1
  92. package/dist/chunk-vz47a139.js +0 -5
  93. package/dist/chunk-x681p5d2.js +0 -68
  94. package/dist/chunk-xgxfy2n8.js +0 -4
@@ -1,27 +1,27 @@
1
- import{A}from"./chunk-23tjmd39.js";import{ue,te,ne}from"./chunk-ckym4cht.js";import{t,e,s}from"./chunk-xgxfy2n8.js";import{createHash as le}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),P={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()},fe={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."},de=["run","read_file","write_file","edit_file","start_process","process_logs","stop_process"],ee=(p)=>le("sha256").update(p).digest("hex");function M(p,L={}){te(p,"");let E=K.resolve("/workspace",L.root??"."),V=new Set(L.allow??de);for(let n of L.deny??[])V.delete(n);function oe(n="."){let l=K.resolve(E,n);if(l!==E&&!l.startsWith(E==="/"?"/":`${E}/`))s("Path escapes tool root. Use a path inside the configured root");return l}async function j(n="."){let l=oe(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 L.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)=>te(p,n),O=new Map;function J(n,l){let u=O.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);O.set(n,{buffer:N,base:y-N.length,total:y});while(O.size>8){let T=O.keys().next().value;if(T)O.delete(T)}}let S=new Map,F=new Map;function re(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:ne(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 se(n,l,u){let r=re(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,B=Math.min(r.end,l+u);while(T<r.end&&N(T))T++;while(B>T&&B<r.end&&N(B))B--;let I=y.subarray(T-r.base,B-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:I,end:B,more:B<r.end||r.more}}async function ae(n,l,u){let r=(F.get(n)??Promise.resolve()).catch(()=>{}).then(()=>se(n,l,u));F.set(n,r);try{return await r}finally{if(F.get(n)===r)F.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 ie(n){let l=P[n],u=L.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:fe[n],inputSchema:l,async execute(y,N,T){let B=Date.now(),I=!1;function U(d){try{L.onEvent?.(d)}catch{I=!0}try{N?.(d)}catch{I=!0}}function f(d,o,a="",c,x=""){let g=R(`${d?"OK":"FAILED"}${a?` ${a}`:""} ${((Date.now()-B)/1000).toFixed(1)}s${c?` cwd=${c}`:""}`),_=new A(Math.floor(r/4));_.add(g);let w=_.text(),h=new A(Math.max(1,r-Buffer.byteLength(w)-Buffer.byteLength(x)-100));return h.add(R(o+(I?`
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
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=pe.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 A(Math.max(1,r-512)),g=`run_${crypto.randomUUID().replaceAll("-","")}`;J(g,"");let _=ne(p,(v)=>{x.add(v.text),J(g,v.text);let k={tool:n,kind:"output",stream:v.stream,text:R(v.text)};U(k)});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?`
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 ue(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,k=[],C=0;for(let[z,ce]of h.slice(v,v+(o.limit??200)).entries()){let H=`${v+z+1}: ${ce}`;if(k.length&&C+Buffer.byteLength(H)>r-600)break;k.push(H),C+=Buffer.byteLength(H)+1}let D=v+k.length,X="";if(C>r-600){let z=`read_${crypto.randomUUID().replaceAll("-","")}`;J(z,k.join(`
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,`${k.join(`
11
+ `}return f(!0,`${M.join(`
12
12
  `)}
13
- ${D<h.length?"[more lines; use read_file with nextOffset as offset]":""}`,"",void 0,`sha=${_} lines=${h.length} nextOffset=${D<h.length?D:"end"}
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=O.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=(C)=>{let D=a.buffer[C-a.base];return D!==void 0&&(D&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(),k={tool:n,kind:"output",stream:"stdout",text:R(v)};return U(k),f(!0,`cursor=${h} more=${h<a.total}
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 ae(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?`
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)=>ie(n))}var pe=i.discriminatedUnion("tool",[i.object({tool:i.literal("run"),input:P.run}),i.object({tool:i.literal("read_file"),input:P.read_file}),i.object({tool:i.literal("write_file"),input:P.write_file}),i.object({tool:i.literal("edit_file"),input:P.edit_file}),i.object({tool:i.literal("start_process"),input:P.start_process}),i.object({tool:i.literal("process_logs"),input:P.process_logs}),i.object({tool:i.literal("stop_process"),input:P.stop_process}),i.object({tool:i.literal("search"),input:P.search}),i.object({tool:i.literal("list_files"),input:P.list_files}),i.object({tool:i.literal("changes"),input:P.changes}),i.object({tool:i.literal("preview"),input:P.preview})]);
27
- export{P,M};
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
- * @internal `Name: message` of a native failure, redacted, scrubbed and bounded, with up to two nested causes.
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
- /** @internal What {@link describeNative} keeps: text for the message, and the error's cause. */
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
- * @internal What an adapter keeps from a native failure. Only a failure the adapter did not recognize
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 message, body, headers or URL;
92
- * `native` is at most the scrubbed text {@link describeNative} keeps.
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
- /** Tenki create: the session this call created, and how far it got. */
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
- /** @internal A redact function for values an adapter knows, such as its API key. Empty values are skipped. */
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
- /** @internal Why an adapter request failed, as a clause, never the code itself: the kept detail, or what `code` means. */
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 interface FileEvent {
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/http.d.ts CHANGED
@@ -218,6 +218,9 @@ export declare function httpStatus(cause: unknown): {
218
218
  status: number;
219
219
  code?: string;
220
220
  } | undefined;
221
+ /** @internal Whether a rejection proves the request never left this process, so no server saw it:
222
+ * a fetch failure, an error caused by one, or this client's failure for such a request. */
223
+ export declare const neverSent: (cause: unknown) => boolean;
221
224
  /** Pulls the code and message out of the error shapes providers use: `{ code, message }`, `{ error: { code, message } }`, `{ error: "text" }`, RFC 7807. */
222
225
  export declare function parseErrorBody(text: string): ErrorBody;
223
226
  /** Builds the client. Planes are fixed; their base URLs and credentials are read per request. */
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{X,O,j,W,Q}from"./chunk-hgrwyjrb.js";import{e}from"./chunk-xgxfy2n8.js";export{e as SandboxError,j as connectSandbox,O as createSandbox,X as hasCapability,W as listSandboxes,Q as reapSandboxes};
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-23tjmd39.js";import{M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import{createTool as s}from"@mastra/core/tools";import{z as e}from"zod";function c(p,r){return Object.fromEntries(M(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};
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-xgxfy2n8.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?"":`
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-23tjmd39.js";import{M}from"./chunk-nw845a93.js";import"./chunk-ckym4cht.js";import{tool as r}from"@openai/agents";function m(t,e){return M(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};
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};
@@ -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
- export type Capability = "pause" | "snapshot" | "terminal" | "network-policy" | "size";
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";
@@ -78,6 +90,25 @@ export interface ProviderFiles {
78
90
  readonly checkpoints?: "files";
79
91
  /** Write handles missing parents itself, avoiding an unconditional mkdir RPC. */
80
92
  readonly writeCreatesParents?: boolean;
93
+ /**
94
+ * One exec carrying a small environment variable costs less than a read plus a write, so `files.edit`
95
+ * runs as one guest python3 call that changes the file the way `write` does: `"in-place"` when `write`
96
+ * truncates and rewrites the existing inode, `"replace"` when it renames a new file over it. Leave it
97
+ * unset where extra env is staged through more requests; edit then reads and writes.
98
+ */
99
+ readonly editInGuest?: "in-place" | "replace";
100
+ /**
101
+ * The order `list` returns entries in: `"name"` sorted by name bytes, `"directory"` the filesystem's
102
+ * own order (what `os.listdir` returns). When set, `files.search` walks the tree in one guest python3
103
+ * call in that order, so `maxMatches` stops at the same files. Unset, search lists and reads each file.
104
+ */
105
+ readonly listOrder?: "name" | "directory";
106
+ /**
107
+ * How guest file commands (edit and search above) may take their input in this sandbox: `"stdin"`,
108
+ * the default, also accepts input over 32 KiB on stdin; `"env"` only the environment, so larger input
109
+ * uses the RPC path; `"none"` keeps those commands on the RPC path.
110
+ */
111
+ guestInput?(id: string): Promise<"stdin" | "env" | "none">;
81
112
  /** Write applies `options.mode` itself. Without it, the core runs `chmod` after the write. */
82
113
  readonly writeSupportsMode?: boolean;
83
114
  /** Top-level /workspace entries the provider itself owns. File checkpoints and changes() skip them. */
@@ -86,6 +117,16 @@ export interface ProviderFiles {
86
117
  offset: number;
87
118
  length: number;
88
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>;
89
130
  read(id: string, path: string): Promise<Uint8Array>;
90
131
  write(id: string, path: string, data: Uint8Array, options?: WriteOptions): Promise<void>;
91
132
  list(id: string, path: string): Promise<FileInfo[]>;
@@ -100,12 +141,77 @@ export interface Preview {
100
141
  headers?: Record<string, string>;
101
142
  expiresAt?: number;
102
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`. */
103
154
  export interface Terminal {
104
155
  write(data: string): void | Promise<void>;
105
156
  resize(cols: number, rows: number): void | Promise<void>;
106
157
  onData(callback: (data: string) => void): () => void;
107
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
+ }>;
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;
108
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
+ };
109
215
  /** Native hooks are optional optimizations. Persistent records remain core-owned. */
110
216
  export interface NativeProcess {
111
217
  pid: number;
@@ -117,7 +223,7 @@ export interface NativeProcess {
117
223
  graceMs: number;
118
224
  }): Promise<void>;
119
225
  }
120
- export interface Provider<Native = unknown, C extends Capability = Capability> {
226
+ export interface Provider<Native = unknown, C extends Capability = Capability, X extends Extensions = {}> {
121
227
  readonly name: string;
122
228
  readonly keyMode: "exact" | "best-effort";
123
229
  /** Omission uses native hooks or the portable shell process-record shim. "stream" is for
@@ -130,6 +236,12 @@ export interface Provider<Native = unknown, C extends Capability = Capability> {
130
236
  readonly previewMode?: "placeholder";
131
237
  /** Exec creates/removes input.activityPath without separate file RPCs. */
132
238
  readonly inlineActivity?: boolean;
239
+ /**
240
+ * Every exec from every client shares one Linux PID namespace with `/proc` mounted, and the exec user
241
+ * can read each process's environ (directly, or through passwordless sudo for root-owned ones). The
242
+ * core then runs commands without a marker and idle reaping scans `/proc` for the SDK's env tag.
243
+ */
244
+ readonly procActivity?: boolean;
133
245
  /** Native command dialect for portable run wrappers; defaults to POSIX sh. */
134
246
  readonly commandShell?: "bash";
135
247
  /** Durable absolute directory for core-owned process records. */
@@ -151,10 +263,13 @@ export interface Provider<Native = unknown, C extends Capability = Capability> {
151
263
  snapshot?(id: string, options?: SnapshotOptions): Promise<{
152
264
  id: string;
153
265
  }>;
154
- terminal?(id: string, options: {
155
- cols: number;
156
- rows: number;
157
- }): Promise<Terminal>;
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>;
158
273
  startProcess?(id: string, input: Omit<ExecInput, "timeoutMs">): Promise<NativeProcess>;
159
274
  /** Secret recovery without a shell, for runtimes that cannot run the core's recovery
160
275
  * command. Return the text of /tmp/.sandbox-sdk/secret-names.json and the environment a
@@ -165,7 +280,12 @@ export interface Provider<Native = unknown, C extends Capability = Capability> {
165
280
  environment: Record<string, string>;
166
281
  } | undefined>;
167
282
  }
168
- export { createHttpClient, createDeadline } from "./http.js";
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";
169
289
  export type { HttpClient, HttpClientOptions, HttpPlane, HttpRequest, StreamRequest, HttpResponse, HttpFailure, FailedRequest, ErrorBody, PlaneContext, Fetch, Deadline, StaleVerdict, } from "./http.js";
170
290
  export { createNativeApi, sdkConstruct, sdkCall } from "./native.js";
171
291
  export type { NativeApi, NativeApiOptions, NativeSdkBinding, NativeRequestOptions, NativeSdkLoader, AnyNativeSdk, HttpMethod, } from "./native.js";
package/dist/provider.js CHANGED
@@ -1 +1 @@
1
- import{d,x,h,v,k}from"./chunk-6a3wkj84.js";export{d as createDeadline,x as createHttpClient,h as createNativeApi,k as sdkCall,v as sdkConstruct};
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{m}from"../../chunk-bd481sb7.js";import{g}from"../../chunk-k60b4r27.js";import{n}from"../../chunk-2ts3evzh.js";import{e,w,i,a}from"../../chunk-xgxfy2n8.js";import{randomUUID as I}from"node:crypto";import{posix as V}from"node:path";function u(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}=m(o),k=/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",b=i(o,{code:k});return u(`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 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((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 u("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,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 u("agentOS could not set the file mode","provider")}function T(o,d,p){let{entries:l,keys:k,destroying:b}=p,L,N=()=>L??=g("@rivet-dev/agentos-core","agentos",d).catch((t)=>{throw u("Install @rivet-dev/agentos-core@0.4.1 and its platform sidecar package","unavailable",void 0,w(t))});function P(t){let r=l.get(t);if(!r)throw u("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 u("agentOS cannot enforce machine sizes or restore SDK snapshots","unsupported");if(t.idleTimeoutMs!==void 0||t.timeoutMs!==void 0)throw u("agentOS adapter does not enforce sandbox lifetime or idle deadlines","unsupported");if(t.signal?.aborted)throw u("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 u("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:A}=await N(),y={permissions:s};if(Object.keys(t.env??{}).length)y.environment={PATH:"/opt/agentos/bin:/usr/local/bin:/usr/bin:/bin",HOME:"/home/agentos",...t.env};if(o.software?.length)y.software=o.software;if(o.mounts?.length)y.mounts=o.mounts;if(o.limits)y.limits=o.limits;if(f=await A.create(y),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 u("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(A){if(f)await f.dispose().catch(()=>{});throw E(A)}}if(!t.key)return c();if(await M.find(t.key))throw u("Key already exists in this application process","invalid_argument");let h=k.get(t.key);if(h)throw await h,u("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 y=c.decode(A,{stream:!0});if(y)r.onChunk({stream:"stdout",text:y})},onStderr(A){let y=v.decode(A,{stream:!0});if(y)r.onChunk({stream:"stderr",text:y})}});for(let[A,y]of[["stdout",c.decode()],["stderr",v.decode()]])if(y)r.onChunk({stream:A,text:y});let f=O.outcome==="timed_out"||O.outcome==="cancelled";if(!f&&O.exitCode===void 0)throw u("agentOS did not report a command exit","outcome_unknown",t);return{exitCode:f?null:O.exitCode??null,timedOut:f}}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),u("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};
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;
@@ -0,0 +1,68 @@
1
+ import type { ExecInput, ExecResult } from "../../provider.js";
2
+ /** The parts of a Baseten sandbox's process API that exec uses. */
3
+ export interface BasetenProcesses {
4
+ execStream(request: {
5
+ command: string;
6
+ workingDir?: string;
7
+ env?: Record<string, string>;
8
+ timeoutMs?: number;
9
+ callOptions?: {
10
+ signal?: AbortSignal;
11
+ };
12
+ }): AsyncGenerator<{
13
+ type: "output";
14
+ stream: "stdout" | "stderr";
15
+ text: string;
16
+ } | {
17
+ type: "exit";
18
+ process: {
19
+ exitCode: number;
20
+ };
21
+ }, void, undefined>;
22
+ exec(request: {
23
+ command: string;
24
+ waitForCompletion?: boolean;
25
+ timeoutMs?: number;
26
+ }): Promise<{
27
+ exitCode: number;
28
+ stdout: string;
29
+ }>;
30
+ }
31
+ /** Where the launcher finds its spec: inline in the environment, or in a file uploaded first. */
32
+ export type SpecDelivery = {
33
+ kind: "env";
34
+ spec: string;
35
+ } | {
36
+ kind: "file";
37
+ path: string;
38
+ };
39
+ /** Specs above this size go through a file: one environment string is capped at 128 KiB. */
40
+ export declare const inlineSpecLimit: number;
41
+ type Frame = {
42
+ kind: "output";
43
+ stream: "stdout" | "stderr";
44
+ bytes: Uint8Array;
45
+ } | {
46
+ kind: "timeout";
47
+ } | {
48
+ kind: "exit";
49
+ code: number;
50
+ };
51
+ /** Splits launcher stdout into frames, keeping an unfinished frame for the next text. */
52
+ export declare class FrameReader {
53
+ #private;
54
+ push(text: string): Frame[];
55
+ get empty(): boolean;
56
+ }
57
+ export interface Execution {
58
+ processes: BasetenProcesses;
59
+ sandboxId: string;
60
+ input: ExecInput;
61
+ /** Uploads a spec too large for the environment, returning its guest path. Stops when `signal` aborts. */
62
+ uploadSpec(spec: string, signal: AbortSignal): Promise<string>;
63
+ /** Removes an uploaded spec that no launcher will read. */
64
+ removeSpec(path: string): Promise<void>;
65
+ }
66
+ /** Runs one command through the launcher, streaming its output in order. */
67
+ export declare function execute({ processes, sandboxId, input, uploadSpec, removeSpec, }: Execution): Promise<ExecResult>;
68
+ export {};
@@ -0,0 +1,3 @@
1
+ import { type BasetenOptions, type BasetenProvider } from "./provider.js";
2
+ export type { BasetenNative, BasetenOptions, BasetenProvider } from "./provider.js";
3
+ export declare function baseten(options?: BasetenOptions): BasetenProvider;