@opencoredev/sandbox-sdk 1.0.3 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +9 -6
- package/dist/ai.js +1 -1
- package/dist/chunk-0eeyc0aq.js +4 -0
- package/dist/chunk-0wp6x4wb.js +2 -0
- package/dist/chunk-2999xbh7.js +2 -0
- package/dist/chunk-3h6c1ack.js +2 -0
- package/dist/{chunk-19gteae8.js → chunk-7rkcx5cx.js} +2 -2
- package/dist/{chunk-rnksrxfc.js → chunk-7s9pxk1v.js} +3 -3
- package/dist/chunk-aek8n3a4.js +78 -0
- package/dist/{chunk-r8xnq6v3.js → chunk-aq6fmgdx.js} +2 -2
- package/dist/chunk-drhcb2hx.js +2 -0
- package/dist/{chunk-2z6fxyg5.js → chunk-ek44atpe.js} +2 -2
- package/dist/chunk-g5n5xcmp.js +0 -0
- package/dist/{chunk-6bemkxcx.js → chunk-kdecey83.js} +12 -12
- package/dist/{chunk-drgkmewv.js → chunk-pdgnaxp9.js} +2 -2
- package/dist/{chunk-3zd78ha4.js → chunk-qfhee1t8.js} +2 -2
- package/dist/chunk-rx9318sh.js +5 -0
- package/dist/chunk-sjnk17y5.js +26 -0
- package/dist/chunk-w8nk1xf2.js +17 -0
- package/dist/{chunk-g0vk7g1k.js → chunk-x05t86n3.js} +2 -2
- package/dist/{chunk-c1wemt0y.js → chunk-x4rrgmxf.js} +11 -11
- package/dist/chunk-xqtzts2q.js +1 -0
- package/dist/errors.d.ts +19 -9
- package/dist/files.d.ts +2 -5
- package/dist/index.d.ts +24 -3
- package/dist/index.js +1 -1
- package/dist/mastra.js +1 -1
- package/dist/memory.js +1 -1
- package/dist/openai.js +1 -1
- package/dist/provider.d.ts +102 -7
- package/dist/provider.js +1 -1
- package/dist/providers/agentos/index.js +2 -2
- package/dist/providers/baseten/errors.d.ts +6 -0
- package/dist/providers/baseten/execute.d.ts +68 -0
- package/dist/providers/baseten/index.d.ts +3 -0
- package/dist/providers/baseten/index.js +97 -0
- package/dist/providers/baseten/provider.d.ts +39 -0
- package/dist/providers/boat/index.js +1 -1
- package/dist/providers/boxd/errors.d.ts +25 -3
- package/dist/providers/boxd/index.js +7 -5
- package/dist/providers/boxd/provider.d.ts +16 -2
- package/dist/providers/daytona/api.d.ts +2 -2
- package/dist/providers/daytona/index.js +15 -15
- package/dist/providers/e2b/envd.d.ts +32 -2
- package/dist/providers/e2b/errors.d.ts +1 -2
- package/dist/providers/e2b/index.d.ts +40 -4
- package/dist/providers/e2b/index.js +1 -1
- package/dist/providers/e2b/narrow.d.ts +7 -0
- package/dist/providers/freestyle/index.js +6 -6
- package/dist/providers/instabox/api.d.ts +56 -0
- package/dist/providers/instabox/errors.d.ts +49 -0
- package/dist/providers/instabox/index.d.ts +4 -0
- package/dist/providers/instabox/index.js +7 -0
- package/dist/providers/instabox/provider.d.ts +28 -0
- package/dist/providers/local/index.js +2 -2
- package/dist/providers/modal/errors.d.ts +4 -0
- package/dist/providers/modal/index.d.ts +14 -0
- package/dist/providers/modal/index.js +2 -0
- package/dist/providers/modal/provider.d.ts +94 -0
- package/dist/providers/modal/transport.d.ts +50 -0
- package/dist/providers/railway/index.js +1 -1
- package/dist/providers/sandboxer/index.js +1 -1
- package/dist/providers/superserve/index.js +5 -5
- package/dist/providers/tenki/deadline.d.ts +1 -1
- package/dist/providers/tenki/index.js +13 -13
- package/dist/providers/tenki/provider.d.ts +12 -12
- package/dist/providers/tenki/records.d.ts +1 -1
- package/dist/providers/upstash/index.js +11 -11
- package/dist/providers/vercel/index.js +1 -1
- package/dist/providers/vercel/transport.d.ts +1 -1
- package/dist/shared/native-error.d.ts +2 -0
- package/dist/streams.d.ts +2 -1
- package/dist/testing.js +3 -3
- package/dist/tools.js +1 -1
- package/dist/types.d.ts +32 -13
- package/dist/version.d.ts +4 -0
- package/package.json +28 -4
- package/dist/chunk-11mbpwem.js +0 -17
- package/dist/chunk-1k6yz176.js +0 -1
- package/dist/chunk-305dymgq.js +0 -2
- package/dist/chunk-348pdz09.js +0 -5
- package/dist/chunk-5gnqph3c.js +0 -78
- package/dist/chunk-6nf686jb.js +0 -26
- package/dist/chunk-ea8y7y2p.js +0 -2
- package/dist/chunk-n7x9ha44.js +0 -4
- package/dist/chunk-tvw3kb8b.js +0 -2
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{N,b,S,P}from"../../chunk-ek44atpe.js";import{f,w,v}from"../../chunk-2999xbh7.js";import{t,o,r,e,i,d,a}from"../../chunk-0eeyc0aq.js";import{posix as We}from"node:path";var Fe=new Set(["FILE_NOT_FOUND","QUOTA_EXCEEDED"]),je=/^(?:[a-f0-9]{16,64}|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/i,Ue=/^(request|create|restore|list|connect|destroy|exec|process|preview|snapshot|files)$/,qe=(n)=>n instanceof Error&&typeof("operation"in n?n.operation:void 0)==="string";function W(n,c,h=!1,D=h?"files":"request",T=process.env.DAYTONA_API_KEY,g=[]){let F=Ue.test(D)?D:"request";if(n instanceof e){if(!qe(n.cause)||n.cause.operation===F)return n;let{status:L,providerCode:q,requestId:H,source:_,native:j}=n.cause,z={operation:F};if(L!==void 0)z.status=L;if(q!==void 0)z.providerCode=q;if(H!==void 0)z.requestId=H;if(_!==void 0)z.source=_;if(j!==void 0)z.native=j;return new e(n.message,{code:n.code,provider:n.provider,sandboxId:n.sandboxId,retryable:n.retryable,hint:n.hint,cause:Object.assign(Error(JSON.stringify(z)),z)})}let x=n&&r(n)&&"statusCode"in n?n.statusCode:void 0,u=n&&r(n)&&"code"in n?n.code:void 0,E=n instanceof Error?n.name:"",l=h&&x===400&&n instanceof Error&&/(?:\bENOENT\b|no such file or directory|\bnot found\b|\bdoes not exist\b)/i.test(n.message),m="provider";if(x===401||x===403)m="auth";else if(u==="FILE_NOT_FOUND"||h&&x===404||l)m="file_not_found";else if(x===404||x===410)m="not_found";else if(x===429||x===402||u==="QUOTA_EXCEEDED")m="quota";else if(x===408||x===504||E.includes("Timeout"))m="timeout";else if(o(x)&&x>=500||E.includes("Connection"))m="unavailable";else if(x===400||x===422||E.includes("InvalidArgument"))m="invalid_argument";let y={operation:F},A=[...g,T,process.env.DAYTONA_API_KEY].filter((L)=>typeof L==="string"&&L.length>0),O=(L,q)=>typeof L==="string"&&q.test(L)&&!A.some((H)=>L.includes(H));if(o(x)&&Number.isInteger(x)&&x>=100&&x<=599)y.status=x;if(O(u,/^[A-Z_]{1,64}$/)&&Fe.has(u))y.providerCode=u;if(n&&r(n)){if("source"in n&&O(n.source,/^DAYTONA_(API|DAEMON|PROXY)$/))y.source=n.source;if("headers"in n&&n.headers&&r(n.headers)){let L=n.headers;for(let q of["x-request-id"in L?L["x-request-id"]:void 0,"x-daytona-request-id"in L?L["x-daytona-request-id"]:void 0])if(O(q,je)){y.requestId=q;break}}}let{detail:M}=i(n,{code:m,status:x===void 0?void 0:String(x),redact:d(A)});if(M!==void 0)y.native=M;let U=Object.assign(Error(JSON.stringify(y)),y);return new e(`Daytona request failed: ${a(m,y.native)}. Check the sandbox and provider configuration.`,{code:m,provider:"daytona",sandboxId:c,cause:U,retryable:["quota","unavailable","timeout"].includes(m),hint:"Check Daytona credentials, quotas, sandbox state, and request options before retrying."})}function ze(n){return n.plane==="toolbox"&&/^[A-Z]+ \/files(?:\/|$)/.test(n.operation)}function Ke(n){let c=n.body.json,h=r(c)?"source"in c?c.source:void 0:void 0,D={};for(let T of["x-request-id","x-daytona-request-id"]){let g=n.headers.get(T);if(g!==null)D[T]=g}return Object.assign(Error(n.body.message??""),{statusCode:n.status,code:n.body.code,source:h,headers:D})}function Te(n){let c=(h,D)=>h.kind==="status"?W(Ke(h),D.sandboxId,ze(D),"request",void 0,n()):void 0;return{mapError:(h,D)=>c(h,D)?.code,cause:(h,D)=>{let T=c(h,D)?.cause;return T instanceof Error?T:void 0}}}function oe(n){throw new e(`${n}. Daytona cannot enforce this request. Choose supported settings.`,{code:"unsupported",provider:"daytona"})}var ye=new TextEncoder,pe=ye.encode(`\r
|
|
2
2
|
\r
|
|
3
|
-
`);function Ee(n){if(!n||!/^multipart\//i.test(n.trim()))return;let c=/;\s*boundary=(?:"([^"]{1,70})"|([^\s;"]{1,70}))/i.exec(n);return c?.[1]??c?.[2]}function
|
|
4
|
-
--${c}`),
|
|
5
|
-
`)){let j=
|
|
3
|
+
`);function Ee(n){if(!n||!/^multipart\//i.test(n.trim()))return;let c=/;\s*boundary=(?:"([^"]{1,70})"|([^\s;"]{1,70}))/i.exec(n);return c?.[1]??c?.[2]}function de(n,c,h=0){let D=c[0];for(let T=n.indexOf(D??0,h);T>=0&&T+c.length<=n.length;T=n.indexOf(D??0,T+1)){let g=!0;for(let F=1;F<c.length;F++)if(n[T+F]!==c[F]){g=!1;break}if(g)return T}return-1}function Be(n,c){if(!n.byteLength)return c;let h=new Uint8Array(n.byteLength+c.byteLength);return h.set(n),h.set(c,n.byteLength),h}function Ie(n,c){return(new RegExp(`(?:^|;)\\s*${c}="([^"]*)"`,"i").exec(n)??new RegExp(`(?:^|;)\\s*${c}=([^;\\s]*)`,"i").exec(n))?.[1]}async function Ae(n,c,h){let D=(m,y)=>new e(`${y}. The ${h.provider} download response ${m?"ended early":"is not valid multipart"}. Retry the read.`,{code:m?"unavailable":"provider",provider:h.provider,sandboxId:h.sandboxId,retryable:m}),T=h.maxHeaderBytes??16384,g=ye.encode(`--${c}`),F=ye.encode(`\r
|
|
4
|
+
--${c}`),x=n.getReader(),u=new Uint8Array,E=!1,l=async()=>{let m=await x.read();if(m.done)return E=!0,!1;return u=Be(u,m.value),!0};try{let m;while((m=de(u,g))<0||u.length<m+g.length+2){if(u.length>T)throw D(!1,"No part delimiter in the first bytes");if(!await l())throw D(!0,"The body ended before the first part")}if(u[m+g.length]===45&&u[m+g.length+1]===45)throw D(!1,"The body has no parts");let y;while((y=de(u,pe.subarray(0,2),m+g.length))<0){if(u.length>T)throw D(!1,"The part delimiter line is too long");if(!await l())throw D(!0,"The body ended in the part delimiter")}let A;while((A=de(u,pe,y))<0){if(u.length-y>T)throw D(!1,"The part headers are too large");if(!await l())throw D(!0,"The body ended in the part headers")}let O={};for(let _ of new TextDecoder().decode(u.subarray(y+2,A)).split(`\r
|
|
5
|
+
`)){let j=_.indexOf(":");if(j>0)O[_.slice(0,j).trim().toLowerCase()]=_.slice(j+1).trim()}let M=O["content-disposition"]??"",U=O["content-length"]===void 0?void 0:Number(O["content-length"]);if(U!==void 0&&!(Number.isSafeInteger(U)&&U>=0))throw D(!1,"The part has an invalid Content-Length");u=u.subarray(A+pe.length);let L=0,q=!1,H=new ReadableStream({async pull(_){try{for(;;){let j=de(u,F),z=!1;while(j>=0){let s=j+F.length;if(u.length<s+2){z=!0;break}if(u[s]===45&&u[s+1]===45||u[s]===13&&u[s+1]===10)break;j=de(u,F,j+1)}if(j>=0&&!z){if(j)_.enqueue(u.slice(0,j));if(L+=j,q=!0,U!==void 0&&U!==L)throw D(!1,`The part has ${L} bytes but declares ${U}`);await x.cancel().catch(()=>{}),_.close();return}let B=z?j:u.length-(F.length+1);if(B>0){if(_.enqueue(u.slice(0,B)),L+=B,u=u.subarray(B),U!==void 0&&L>U)throw D(!1,`The part is longer than its declared ${U} bytes`);return}if(E||!await l())throw D(!0,"The body ended inside the part")}}catch(j){throw q=!0,await x.cancel().catch(()=>{}),j}},async cancel(_){if(!q)await x.cancel(_).catch(()=>{})}},{highWaterMark:0});return{name:Ie(M,"name"),filename:Ie(M,"filename"),headers:O,body:H}}catch(m){throw await x.cancel().catch(()=>{}),m}}async function we(n){let c=n.getReader(),h=[],D=0;try{for(;;){let{done:F,value:x}=await c.read();if(F)break;h.push(x),D+=x.byteLength}}finally{c.releaseLock()}let T=new Uint8Array(D),g=0;for(let F of h)T.set(F,g),g+=F.byteLength;return T}var X=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n),Q=(n,c)=>c(n)?n:void 0,J=(n)=>typeof n==="string",re=(n)=>typeof n==="number"&&Number.isFinite(n),Ce=(n)=>typeof n==="boolean";function te(n,c){return new e(`Daytona returned ${n} the adapter cannot read. Check the Daytona API version.`,{code:"provider",provider:"daytona",sandboxId:c})}function le(n){if(!X(n)||!J(n.id)||!n.id)throw te("a sandbox");let c=X(n.labels)?Object.fromEntries(Object.entries(n.labels).filter((h)=>typeof h[1]==="string")):{};return{id:n.id,labels:c,state:Q(n.state,J),createdAt:Q(n.createdAt,J),public:Q(n.public,Ce),cpu:Q(n.cpu,re),memory:Q(n.memory,re),disk:Q(n.disk,re),toolboxProxyUrl:Q(n.toolboxProxyUrl,J)}}function Se(n,c){if(!X(n)||!J(n.name)||!Ce(n.isDir))throw te("file information",c);return{name:n.name,isDir:n.isDir,size:Q(n.size,re),mode:Q(n.mode,J),modifiedAt:Q(n.modifiedAt,J),modTime:Q(n.modTime,J)}}var Ge=new Set(["error","build_failed"]),Ye=(n,c)=>n<5000?100:Math.min(c*1.1,1000);function _e(n){let c=new Map,h=(l)=>{if(l.toolboxProxyUrl)c.set(l.id,l.toolboxProxyUrl);return l},D=()=>{let{apiKey:l,jwtToken:m,organizationId:y}=n.credentials();return l?{authorization:`Bearer ${l}`}:{authorization:`Bearer ${m??""}`,"x-daytona-organization-id":y??""}},T=v({provider:"daytona",label:"Daytona",defaultPlane:"api",timeoutMs:n.requestTimeoutMs,fetch:n.fetch,authHint:"Set DAYTONA_API_KEY to a valid Daytona API key, or DAYTONA_JWT_TOKEN with DAYTONA_ORGANIZATION_ID.",secrets:()=>{let{apiKey:l,jwtToken:m}=n.credentials();return[l,m,...n.secrets()]},...Te(()=>{let{apiKey:l,jwtToken:m}=n.credentials();return[l,m,...n.secrets()].filter(J)}),planes:{api:{baseUrl:n.baseUrl,auth:D,headers:{accept:"application/json"}},toolbox:{async baseUrl({sandboxId:l,signal:m}){if(l===void 0)throw new e("The toolbox plane belongs to one sandbox. Use box.native, or pass the sandbox to a sandbox-bound client.",{code:"invalid_argument",provider:"daytona"});let y=c.get(l);if(y===void 0){let A=await T.json({method:"GET",path:"/sandbox/{sandboxId}/toolbox-proxy-url",params:{sandboxId:l},sandboxId:l,signal:m});if(!X(A)||!J(A.url)||!A.url)throw te("a toolbox proxy URL",l);y=A.url,c.set(l,y)}return`${y.replace(/\/+$/,"")}/${encodeURIComponent(l)}`},auth:D}}});async function g(l,m){return h(le(await T.json({method:"GET",path:"/sandbox/{sandboxId}",params:{sandboxId:l},sandboxId:l,deadline:m})))}async function F(l,m,y,A,O=!1){let M=Date.now(),U=100;for(;;){let L;try{L=await g(l,y)}catch(q){if(O&&q instanceof e&&q.code==="not_found")return;throw q}if(L.state!==void 0&&Ge.has(L.state))throw new e(`Sandbox ${A} failed with state ${L.state}. Inspect the sandbox in the Daytona dashboard.`,{code:"provider",provider:"daytona",sandboxId:l});if(m(L.state))return L;U=Ye(Date.now()-M,U),await w(Math.min(U,Math.max(1,y.remaining())),y,"daytona")}}let x=(l,m)=>f(l,m),u=async(l,m,y,A)=>h(le(await T.json({method:"POST",path:`/sandbox/{sandboxId}/${m}`,params:{sandboxId:l},sandboxId:l,body:A,deadline:y}))),E={get:g,waitFor:F,async create(l,m){return h(le(await T.json({method:"POST",path:"/sandbox",body:l,deadline:m})))},async*list(l){let m;do{let y=await T.json({method:"GET",path:"/sandbox",query:{labels:JSON.stringify(l),cursor:m}});if(!X(y)||!Array.isArray(y.items))throw te("a sandbox list");for(let A of y.items)yield h(le(A));m=J(y.nextCursor)&&y.nextCursor?y.nextCursor:void 0}while(m!==void 0)},async remove(l,m,y=60000){let A=x(y),O=await T.json({method:"DELETE",path:"/sandbox/{sandboxId}",params:{sandboxId:l},sandboxId:l,deadline:A});if(c.delete(l),!m||X(O)&&O.state==="destroyed")return;await F(l,(M)=>M==="destroyed",A,"deletion",!0)},async cleanup(l){await T.cleanup({method:"DELETE",path:"/sandbox/{sandboxId}",params:{sandboxId:l},sandboxId:l}),c.delete(l)},async stop(l,m=60000){let y=x(m),A=await u(l,"stop",y);if(A.state!=="stopped"&&A.state!=="destroyed")await F(l,(O)=>O==="stopped"||O==="destroyed",y,"stop",!0)},async start(l,m=60000){let y=x(m);if((await u(l,"start",y)).state!=="started")await F(l,(O)=>O==="started",y,"start")},async resize(l,m,y=60000){let A=x(y);if((await u(l,"resize",A,m)).state==="resizing")await F(l,(M)=>M!=="resizing",A,"resize")},async snapshot(l,m,y){let A=x(y);await u(l,"snapshot",A,{name:m}),await F(l,(O)=>O!=="snapshotting",A,"snapshot")},async previewLink(l,m){let y=await T.json({method:"GET",path:"/sandbox/{sandboxId}/ports/{port}/preview-url",params:{sandboxId:l,port:m},sandboxId:l});if(!X(y)||!J(y.url)||!J(y.token))throw te("a preview link",l);return{url:y.url,token:y.token}}};return{http:T,control:E,toolbox:(l)=>Je(T,E,l,n.requestTimeoutMs)}}var Pe=5000;function Je(n,c,h,D){let T={plane:"toolbox",sandboxId:h},g=(u,E,l={})=>n.request({...T,method:u,path:E,...l}),F=(u)=>{if(!X(u))throw te("a command result",h);return{exitCode:re(u.exitCode)?u.exitCode:0,result:J(u.result)?u.result:""}};async function x(u,E={}){let l=await n.stream({...T,method:"POST",path:"/files/bulk-download",body:{paths:[u]},readOnly:!0,signal:E.signal,timeoutMs:E.timeoutMs}),m=Ee(l.headers.get("content-type"));if(!m||!l.body)throw await l.body?.cancel().catch(()=>{}),te("a download that is not multipart",h);let y=await Ae(l.body,m,{provider:"daytona",sandboxId:h});if(y.name==="file")return y.body;if(y.name!=="error")throw await y.body.cancel().catch(()=>{}),te(`a download part named ${JSON.stringify(y.name??"").slice(0,32)}`,h);let A=new TextDecoder().decode((await we(y.body)).subarray(0,65536)),O;try{O=JSON.parse(A)}catch{O=void 0}let M=X(O)&&re(O.statusCode)?O.statusCode:500,U=X(O)&&J(O.code)?O.code:void 0,L=X(O)&&J(O.message)?O.message:A,q=U==="FILE_NOT_FOUND"||M===404||M===400&&/no such file or directory|\bnot found\b/i.test(L);throw new e(`Daytona POST /files/bulk-download failed (HTTP ${M}${U&&/^[A-Z_]{1,64}$/.test(U)?` ${U}`:""}).`,{code:q?"file_not_found":M===400?"invalid_argument":M===401||M===403?"auth":"provider",provider:"daytona",sandboxId:h})}return{id:h,fs:{async upload(u,E){let l=new FormData;l.append("files[0].path",E),l.append("files[0].file",new Blob([Uint8Array.from(u)]),E),await g("POST","/files/bulk-upload",{body:l})},async download(u){return we(await x(u,{timeoutMs:D}))},downloadStream:(u,E)=>x(u,E),async deleteFile(u,E){await g("DELETE","/files",{query:{path:u,recursive:E}})},async createFolder(u,E){await g("POST","/files/folder",{query:{path:u,mode:E}})},async setFilePermissions(u,E){await g("POST","/files/permissions",{query:{path:u,mode:E}})},async getFileDetails(u){return Se((await g("GET","/files/info",{query:{path:u}})).json(),h)},async listFiles(u){let E=(await g("GET","/files",{query:{path:u}})).json();if(!Array.isArray(E))throw te("a file list",h);return E.map((l)=>Se(l,h))}},process:{async executeCommand(u,E,l,m){return F((await g("POST","/process/execute",{body:{command:u,cwd:E,timeout:m,envs:l&&Object.keys(l).length?l:void 0},timeoutMs:m?m*1000+Pe:void 0})).json())},async codeRun(u,E){return F((await g("POST","/process/code-run",{body:{code:u,language:"python",timeout:E},timeoutMs:E*1000+Pe})).json())},async createSession(u){await g("POST","/process/session",{body:{sessionId:u}})},async executeSessionCommand(u,E){let l=(await g("POST","/process/session/{session}/exec",{params:{session:u},body:E})).json();return{cmdId:X(l)&&J(l.cmdId)?l.cmdId:void 0}},async getSessionCommand(u,E){let l=(await g("GET","/process/session/{session}/command/{command}",{params:{session:u,command:E}})).json();return{exitCode:X(l)&&re(l.exitCode)?l.exitCode:void 0}},async followSessionCommandLogs(u,E,l,m){let y=await n.stream({...T,method:"GET",path:"/process/session/{session}/command/{command}/logs",params:{session:u,command:E},query:{follow:!0},signal:m,startupTimeoutMs:2147483647});if(!y.body)return;let A=new TextDecoder,O=y.body.getReader();try{for(;;){let{done:U,value:L}=await O.read();if(U)break;let q=A.decode(L,{stream:!0});if(q)l(q)}let M=A.decode();if(M)l(M)}finally{await O.cancel().catch(()=>{})}},async deleteSession(u){await g("DELETE","/process/session/{session}",{params:{session:u}})}},stop:()=>c.stop(h)}}var He=`import base64,os,selectors,signal,subprocess,sys,time,shutil,fcntl
|
|
6
6
|
command,directory,cwd,limit,activity=sys.argv[1:]
|
|
7
7
|
if activity:
|
|
8
8
|
os.makedirs(os.path.dirname(activity),exist_ok=True)
|
|
@@ -64,9 +64,9 @@ for attempt in range(3):
|
|
|
64
64
|
break
|
|
65
65
|
except FileNotFoundError:
|
|
66
66
|
if attempt==2: raise
|
|
67
|
-
`;async function Oe(n,c,h=
|
|
68
|
-
`),z=/^R:(\d+):([01]):([01])$/.exec(j.pop()??"");if(
|
|
69
|
-
`))>=0)q(
|
|
67
|
+
`;async function Oe(n,c,h=se,D){if(c.signal?.aborted)return{exitCode:null,timedOut:!0};let T=Date.now()+c.timeoutMs,g=new AbortController,F,x=!1,u=()=>{},E=new Promise((_)=>{u=_}),l=`/tmp/.sandbox-sdk/exec/sdk-${crypto.randomUUID()}`,m=!0,y=!1,A,O,M=()=>{if(x=!0,u(),g.abort(),F?.cancel().catch(()=>{}),y)return;A??=n.process.executeCommand(`python3 -c ${G(Ve)} ${G(l)}`,"/",void 0,10).then((_)=>{if(_.exitCode!==0)throw Error("Cancellation failed")}).catch((_)=>{O=_})},U={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},L=()=>new e("Buffered output is incomplete or malformed. Daytona did not confirm exact output and exit. Inspect or destroy the sandbox before retrying.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id}),q=(_)=>{let j=/^(O|E):([A-Za-z0-9+/]*={0,2})$/.exec(_);if(!j||_.length>5466||Buffer.from(j[2]??"","base64").toString("base64")!==j[2])throw L();let z=j[1]==="O"?"stdout":"stderr",B=U[z].decode(Buffer.from(j[2]??"","base64"),{stream:!0});if(B)c.onChunk({stream:z,text:B})};c.signal?.addEventListener("abort",M,{once:!0});let H=setTimeout(M,Math.max(0,T-Date.now()));try{let _=await n.process.executeCommand(`${h?`${h} && `:""}python3 -u -c ${G(He)} ${G(c.command)} ${G(l)} ${G(c.cwd)} ${G(String(c.timeoutMs/1000))} ${G(c.activityPath??"")}`,"/",c.env,Math.ceil(c.timeoutMs/1000)+15),j=_.result.trimEnd().split(`
|
|
68
|
+
`),z=/^R:(\d+):([01]):([01])$/.exec(j.pop()??"");if(_.exitCode!==0||!z)throw L();y=!0,D?.(),m=z[3]==="1";for(let s of j)if(s)q(s);if(z[3]==="1"){if(Date.now()>=T)M();if(!x){let p=(async()=>{let R=(await n.fs.downloadStream(`${l}/output`,{signal:g.signal})).getReader();if(F=R,x){await R.cancel().catch(()=>{});return}let I="";for(;;){let{done:Y,value:V}=await R.read();if(Y)break;if(x)return;I+=Buffer.from(V).toString("ascii");let Z;while((Z=I.indexOf(`
|
|
69
|
+
`))>=0)q(I.slice(0,Z)),I=I.slice(Z+1);if(I.length>5466)throw L()}if(I)throw L()})();p.catch(()=>{}),await Promise.race([p,E])}if(x)return{exitCode:null,timedOut:!0}}for(let s of["stdout","stderr"]){let p=U[s].decode();if(p)c.onChunk({stream:s,text:p})}if(await A,O!==void 0)throw L();let B=z[2]==="1"||x;return{exitCode:B?null:Number(z[1]),timedOut:B}}catch(_){if(y&&x)return{exitCode:null,timedOut:!0};if(!y)M(),await A,await n.stop();if(await A,O!==void 0)throw L();throw _}finally{if(clearTimeout(H),g.abort(),c.signal?.removeEventListener("abort",M),await A,A||m)await n.fs.deleteFile(l,!0).catch(()=>{});if(c.activityPath&&A)await n.fs.deleteFile(c.activityPath,!0).catch(()=>{})}}var G=(n)=>`'${n.replace(/'/g,"'\\''")}'`,Ze=`import base64,os,selectors,subprocess,sys,shutil
|
|
70
70
|
a=sys.argv[3]
|
|
71
71
|
if a:
|
|
72
72
|
os.makedirs(os.path.dirname(a),exist_ok=True)
|
|
@@ -84,13 +84,13 @@ code=p.wait()
|
|
|
84
84
|
if a: shutil.rmtree(a,ignore_errors=True)
|
|
85
85
|
print("X:",flush=True)
|
|
86
86
|
sys.exit(code if code>=0 else 128-code)
|
|
87
|
-
`,
|
|
88
|
-
`))>=0){let ee=B.slice(0,K).replace(/\r$/,"");if(B=B.slice(K+1),!ee)continue;if(p)throw new e("Session output continued after completion. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});if(ee==="X:"){p=!0,
|
|
89
|
-
`});continue}let
|
|
90
|
-
`}:void 0,cpu:V?.cpu,memory:V?.memory,disk:V?.disk,env:s.env??{},labels:
|
|
91
|
-
subprocess.run(["sh","-c",${JSON.stringify(
|
|
87
|
+
`,ue=(n)=>new Promise((c)=>setTimeout(c,n)),se='if [ ! -w /workspace ]; then sudo -n install -d -o "$(id -u)" -g "$(id -g)" -m 755 /workspace; fi; test -w /workspace';async function be(n,c,h,D=se){let T=`sdk-${crypto.randomUUID()}`,g=`/tmp/.sandbox-sdk/exec/${T}`,F=`${g}/pid`,x=c.signal?.aborted??!1,u,E,l=!1,m=!1,y=!1,A=!1,O=h===void 0,M=()=>{x=!0},U=new AbortController,L=h===void 0?void 0:setTimeout(M,h);c.signal?.addEventListener("abort",M,{once:!0});async function q(_){if(u===void 0)return;if((await n.process.executeCommand(`/bin/kill -${_} -- -${u} 2>/dev/null || ! /bin/kill -0 -- -${u} 2>/dev/null`,"/",void 0,10)).exitCode!==0)throw new e("Remote process group could not be killed. Cancellation is unconfirmed. Destroy the sandbox before retrying.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id})}async function H(){if(clearTimeout(L),c.signal?.removeEventListener("abort",M),c.activityPath&&!A)await n.fs.deleteFile(c.activityPath,!0).catch(()=>{});if(U.abort(),l)try{await n.process.deleteSession(T)}catch(_){if(W(_).code!=="not_found")throw _}try{await n.fs.deleteFile(g,!0)}catch(_){if(W(_,n.id,!0).code!=="file_not_found")throw _}}try{if(c.stdin!==void 0)await n.fs.createFolder(g,"700"),await n.fs.upload(Buffer.from(c.stdin),`${g}/stdin`);if(x)return await H(),{pid:0,wait:async()=>({exitCode:null,signal:"SIGKILL"}),stop:async()=>{},detach(){}};await n.process.createSession(T),l=!0;let _=Object.entries(c.env).map(([C,K])=>G(`${C}=${K}`)).join(" "),j=`umask 077; mkdir -p ${G(g)} || exit 1; echo $$ > ${G(`${F}.tmp`)}; mv ${G(`${F}.tmp`)} ${G(F)}; cd ${G(c.cwd)} || exit 1; exec env ${_} python3 -u -c ${G(Ze)} ${G(c.command)} ${G(c.stdin===void 0?"/dev/null":`${g}/stdin`)} ${G(c.activityPath??"")}`;if(E=(await n.process.executeSessionCommand(T,{command:`${D?`${D} && `:""}setsid --wait sh -c ${G(j)}`,runAsync:!0,suppressInputEcho:!0})).cmdId,!E)throw new e("Session command has no ID. Daytona did not confirm launch. Inspect or destroy the sandbox.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id});let B="",s,p=!1,k={stdout:new TextDecoder("utf-8",{ignoreBOM:!0}),stderr:new TextDecoder("utf-8",{ignoreBOM:!0})},R=(C)=>{B+=C;let K;while((K=B.indexOf(`
|
|
88
|
+
`))>=0){let ee=B.slice(0,K).replace(/\r$/,"");if(B=B.slice(K+1),!ee)continue;if(p)throw new e("Session output continued after completion. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});if(ee==="X:"){p=!0,A=!0;for(let ke of["stdout","stderr"]){let De=k[ke].decode();if(!m&&De)c.onChunk({stream:ke,text:De})}continue}if(!/^[OE]:/.test(ee)){if(!m)c.onChunk({stream:"stderr",text:`${ee}
|
|
89
|
+
`});continue}let ie=/^(O|E):([A-Za-z0-9+/]*={0,2})$/.exec(ee);if(!ie||ee.length>5466||Buffer.from(ie[2]??"","base64").toString("base64")!==ie[2])throw new e("Session output is malformed. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});let xe=ie[1]==="O"?"stdout":"stderr",ve=k[xe].decode(Buffer.from(ie[2]??"","base64"),{stream:!0});if(!m&&ve)c.onChunk({stream:xe,text:ve})}if(p&&B.length)throw new e("Session output continued after completion. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});if(B.length>5466)throw new e("Session output frame is too large. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id})},I=(C)=>{try{if(s===void 0)R(C)}catch(K){s=K}},Y=O?Promise.resolve():n.process.followSessionCommandLogs(T,E,I,U.signal).then(()=>{if(s===void 0&&B.trim()&&!p&&!/^[OEX]/.test(B)){if(!m)c.onChunk({stream:"stderr",text:B});B=""}if(B.trim())throw new e("Session output is incomplete. Exact output could not be recovered. Retry the command.",{code:"provider",provider:"daytona",sandboxId:n.id});for(let C of["stdout","stderr"]){let K=k[C].decode();if(!m&&K)c.onChunk({stream:C,text:K})}}),V=!1;Y.then(()=>{V=!0},(C)=>{s=C,V=!0});let Z=Date.now();while(u===void 0)try{let C=Number(Buffer.from(await n.fs.download(F)).toString());if(!Number.isSafeInteger(C)||C<=1)throw new e("Invalid process group ID. Remote launch was not confirmed. Destroy the sandbox.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id});u=C}catch(C){if(!(C instanceof e)||C.code!=="file_not_found"&&C.code!=="unavailable")throw C;if((await n.process.getSessionCommand(T,E)).exitCode!==void 0){u=0;break}if(Date.now()-Z>1e4)throw new e("Process launch was not confirmed. No PID arrived in ten seconds. Destroy the sandbox.",{code:"outcome_unknown",provider:"daytona",sandboxId:n.id});await ue(10)}let me=E,ne=(async()=>{try{let C;while(!0){if(y)await new Promise(()=>{});if(s!==void 0&&!x)throw s;if(x&&u)await q("KILL");let K;try{K=await n.process.getSessionCommand(T,me)}catch(ee){if(!O||x)throw ee;if(W(ee).code==="not_found")return{exitCode:137,signal:"SIGKILL"};await ue(1000);continue}if(s!==void 0&&!x)throw s;if(K.exitCode!==void 0){if(x)C??=Date.now();if(V||p||C!==void 0&&Date.now()-C>=1000)return{exitCode:x?null:K.exitCode,signal:x?"SIGKILL":null}}await ue(20)}}catch(C){if(u&&!O)await q("KILL");throw C}finally{m=!0,await H().catch(()=>{})}})();ne.catch(()=>{});let ae=!1;return{pid:u,wait:()=>ne,detach(){y=!0},async stop({graceMs:C}){if(ae)return;if(u)await q("TERM");if(await ue(C),u)await q("KILL");await ne,ae=!0}}}catch(_){try{if(u)await q("KILL");else if(l)await n.stop()}finally{await H()}throw _}}async function Me(n,c,h=se,D){if(c.streaming!==!0&&c.stdin===void 0)return Oe(n,c,h,D);let T=await be(n,c,c.timeoutMs,h);if(T.pid>0)D?.();let g=await T.wait();return{exitCode:g.exitCode,timedOut:g.signal==="SIGKILL"}}var $e={"sandbox-sdk":"1"},ce="sandbox-sdk-key",ge="sandbox-sdk-create",Re="code-toolbox-language",Xe=new Set([ce,ge,Re]),Qe=1e4,et={small:{cpu:1,memoryMb:1024,diskGb:10},medium:{cpu:2,memoryMb:4096,diskGb:10},large:{cpu:4,memoryMb:8192,diskGb:10}};function tt(n){let c=t(n)?et[n]:n,h=c?.diskGb??10;if(!c||!Number.isInteger(c.cpu)||c.cpu<=0||!Number.isInteger(c.memoryMb)||c.memoryMb<=0||c.memoryMb%1024||!Number.isInteger(h)||h<=0)oe("Size requires positive integer CPUs, whole GiB memory (memoryMb divisible by 1024), and integer diskGb");return{cpu:c.cpu,memory:c.memoryMb/1024,disk:h}}function he(n,c=!1){if(!Number.isFinite(n)||n<0||n===0&&!c)throw new e(`Timeout must be ${c?"zero or positive":"positive"}. Invalid milliseconds supplied. Use a ${c?"non-negative":"positive"} finite duration.`,{code:"invalid_argument",provider:"daytona"});return Math.ceil(n/60000)}function nt(n){if(!r(n))return{networkBlockAll:n==="none"};if(!n.allow.length)return{networkBlockAll:!0};if(n.allow.some((c)=>!/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(c)||c.length>253))oe("Network allow entries must be DNS hostnames without schemes, ports, commas, or wildcards");return{networkBlockAll:!1,domainAllowList:n.allow.join(",")}}function fe(n,c){let h=Date.parse(n.createdAt??"")||c;if(h===void 0||!Number.isFinite(h))throw new e("Sandbox creation time is missing. Daytona returned incomplete metadata. Refresh the sandbox metadata.",{code:"provider",provider:"daytona",sandboxId:n.id});return{id:n.id,key:n.labels[ce],labels:Object.fromEntries(Object.entries(n.labels).filter(([D])=>!Xe.has(D))),createdAt:h,state:n.state==="started"?"running":n.state==="paused"?"paused":"stopped"}}async function Le(n){let c;await Promise.race([n.catch(()=>{}),new Promise((h)=>{c=setTimeout(h,Qe),c.unref?.()})]),clearTimeout(c)}async function ot(n,c){let h=!1,D=!1;return await Le((async()=>{for(let T=0;T<5&&!h;T++){for await(let g of n.list({[ge]:c})){await n.cleanup(g.id),D=!0;return}await new Promise((g)=>setTimeout(g,1000))}})()),h=!0,D}function Ne(n,c){return{path:n,type:c.isDir?"directory":c.mode?.startsWith("L")||c.mode?.startsWith("l")?"symlink":"file",size:c.size??0,modifiedAt:Date.parse(c.modifiedAt||c.modTime||"")||0}}function Pt(n={}){let c=new Set,h=(s={})=>{for(let p of Object.values(s))if(p)c.add(p)},D=new Map,T=new Map,g=new Set,F=se,x=new Map,u=new Map,E=new Map;for(let s of[n.jwtToken,process.env.DAYTONA_JWT_TOKEN])if(s)c.add(s);let l=()=>n.baseUrl??n.apiUrl??process.env.DAYTONA_API_URL??process.env.DAYTONA_SERVER_URL??"https://app.daytona.io/api",m=()=>n.target??process.env.DAYTONA_TARGET??"us",y;function A(){if(y)return y;let s=n.apiKey??(n.jwtToken?void 0:process.env.DAYTONA_API_KEY),p=s?void 0:n.jwtToken??process.env.DAYTONA_JWT_TOKEN,k=n.organizationId??process.env.DAYTONA_ORGANIZATION_ID;if(p&&!k)throw new e("Daytona organization is missing. JWT authentication needs an organization ID. Set DAYTONA_ORGANIZATION_ID or pass organizationId.",{code:"auth",provider:"daytona"});if(!s&&!p)throw new e("Daytona API key is missing. Authentication is required. Set DAYTONA_API_KEY or pass apiKey.",{code:"auth",provider:"daytona"});return y=s?{apiKey:s}:{jwtToken:p,organizationId:k}}let{http:O,control:M,toolbox:U}=_e({baseUrl:l,credentials:A,requestTimeoutMs:n.requestTimeoutMs??30000,secrets:()=>c}),L=!1;function q(){if(L)return;if(!Number.isSafeInteger(n.snapshotTimeoutMs??600000)||(n.snapshotTimeoutMs??600000)<=0||(n.snapshotTimeoutMs??600000)>900000)throw new e("snapshotTimeoutMs must be an integer from 1 to 900000.",{code:"invalid_argument",provider:"daytona"});if(n.createTimeoutMs!==void 0&&(!Number.isSafeInteger(n.createTimeoutMs)||n.createTimeoutMs<=0))throw new e("createTimeoutMs must be a positive integer.",{code:"invalid_argument",provider:"daytona"});A(),L=!0}let H={package:"@daytonaio/sdk",async connect(s,p){let{apiKey:k,jwtToken:R,organizationId:I}=A(),Y=S(s,"Daytona",[{...k?{apiKey:k}:{jwtToken:R,organizationId:I},apiUrl:l(),target:m()}],"@daytonaio/sdk");return p===void 0?Y:N(await P(Y,"get",[p],"@daytonaio/sdk"),"Daytona.get","@daytonaio/sdk")}};async function _(s,p,k=!1,R=k?"files":"request"){try{return q(),await s()}catch(I){throw W(I,p,k,R,n.apiKey??process.env.DAYTONA_API_KEY,c)}}async function j(s){let p=D.get(s);if(p)return p;let k=await M.get(s);return D.set(s,k),g.add(s),k}let z=(s,p)=>_(async()=>(await j(s),p(U(s))),s,!0),B={name:"daytona",inlineActivity:!0,keyMode:"best-effort",capabilities:new Set(["snapshot","size","network-policy"]),api:b({http:O,placeholder:"sandboxId",sdk:H}),async create(s){return h(s.env),_(async()=>{if(n.image&&n.snapshot)oe("Choose either image or snapshot");let p=s.from===void 0?n.image:void 0,k=s.size===void 0?void 0:tt(s.size);if(s.timeoutMs!==void 0&&(s.timeoutMs<60000||!Number.isFinite(s.timeoutMs)))oe("Daytona hard lifetime must be at least one minute");let R=crypto.randomUUID(),I={...s.labels,...$e};if(delete I[ce],s.key!==void 0)I[ce]=s.key;I[ge]=R,I[Re]="python";let Y=p?void 0:s.from??n.snapshot??(k?.cpu===4&&k.memory===8&&k.disk===10?"daytona-large":void 0),V=p?k:void 0,Z={snapshot:Y,buildInfo:p?{dockerfileContent:`FROM ${p}
|
|
90
|
+
`}:void 0,cpu:V?.cpu,memory:V?.memory,disk:V?.disk,env:s.env??{},labels:I,public:n.public??!1,target:m(),...nt(s.network),autoStopInterval:s.idleTimeoutMs===void 0?void 0:he(s.idleTimeoutMs),autoPauseInterval:0,autoArchiveInterval:n.autoArchiveMs===void 0?void 0:he(n.autoArchiveMs),autoDeleteInterval:n.autoDeleteMs===void 0?void 0:he(n.autoDeleteMs,!0),volumes:n.volumes,outboundProxyUrl:n.outboundProxyUrl,ttlMinutes:s.timeoutMs===void 0?void 0:Math.floor(s.timeoutMs/60000)},me=Date.now(),ne=n.createTimeoutMs??60000,ae=f(ne),C;try{C=await M.create(Z,ae)}catch(K){if(!(K instanceof e)||K.code!=="outcome_unknown"||!await ot(M,R))throw K;throw new e(`Sandbox creation did not answer within ${Math.ceil(ne/1000)} seconds. The sandbox it made was deleted. Retry, or raise createTimeoutMs.`,{code:"timeout",provider:"daytona",retryable:!0})}try{if(C.state!=="started")try{C=await M.waitFor(C.id,(K)=>K==="started",f(ae.remaining(),s.signal),"start")??C}catch(K){if(!(K instanceof e)||K.code!=="timeout")throw K;throw new e(`Sandbox did not start within ${Math.ceil(ne/1000)} seconds. It was deleted. Retry, or raise createTimeoutMs.`,{code:"timeout",provider:"daytona",sandboxId:C.id,retryable:!0})}if(s.signal?.aborted)throw new e("Creation aborted. The caller cancelled. Retry when ready.",{code:"aborted",provider:"daytona"});if(k&&!p&&(k.cpu!==C.cpu||k.memory!==C.memory||k.disk!==C.disk)){if(k.disk<(C.disk??0))oe("Snapshot disk cannot shrink; choose diskGb at least as large as the snapshot");await M.stop(C.id),await M.resize(C.id,k),await M.start(C.id),C=await M.get(C.id)}return D.set(C.id,C),g.add(C.id),x.set(C.id,{expiresAt:Date.now()+30000}),fe(C,me)}catch(K){throw await Le(M.remove(C.id,!0)),D.delete(C.id),x.delete(C.id),K}},void 0,!1,s.from?"restore":"create")},async list(s){return _(async()=>{let p={...s,...$e},k=(I)=>Object.entries(p).every(([Y,V])=>I.labels[Y]===V),R=new Map;for await(let I of M.list(p))if(k(I)){if(!D.has(I.id))g.add(I.id);D.set(I.id,I),R.set(I.id,fe(I)),x.delete(I.id)}for(let[I,Y]of x){if(Date.now()>=Y.expiresAt){x.delete(I);continue}let V=D.get(I);if(!V||!k(V))continue;try{let Z=await M.get(I);if(x.get(I)!==Y||u.has(I)||Date.now()>=Y.expiresAt)continue;if(k(Z))D.set(I,Z),R.set(I,fe(Z))}catch(Z){if(W(Z).code!=="not_found")throw Z;x.delete(I),D.delete(I)}}return[...R.values()]},void 0,!1,"list")},async find(s){return(await B.list({[ce]:s}))[0]},async connect(s){return _(async()=>{let p=await M.get(s);return D.set(s,p),g.add(s),fe(p)},s,!1,"connect")},async destroy(s){let p=u.get(s);if(p)return p;let k=_(async()=>{try{await M.remove(s,!0)}catch(R){if(W(R).code!=="not_found")throw R}finally{D.delete(s),T.delete(s),x.delete(s),g.delete(s)}},s,!1,"destroy");u.set(s,k);try{await k}finally{u.delete(s)}},exec:(s,p)=>(h(p.env),_(async()=>(await j(s),Me(U(s),p,g.has(s)?F:"",()=>g.delete(s))),s,!1,"exec")),startProcess:(s,p)=>(h(p.env),_(async()=>{await j(s);let k=await be(U(s),p,void 0,g.has(s)?F:"");if(k.pid>0)g.delete(s);let R=E.get(s);if(!R)R=new Set,E.set(s,R);return R.add(k.detach),k.wait().finally(()=>R.delete(k.detach)).catch(()=>{}),{pid:k.pid,wait:()=>_(k.wait,s,!1,"process"),stop:(I)=>_(()=>k.stop(I),s,!1,"process")}},s,!1,"process")),async close(s){for(let p of E.get(s)??[])p();E.delete(s)},files:{writeCreatesParents:!0,writeSupportsMode:!0,read:(s,p)=>z(s,(k)=>k.fs.download(p)),write:(s,p,k,R)=>z(s,async(I)=>{let Y=R?.mode;if(!g.has(s)){if(await I.fs.upload(k,p),Y!==void 0)await I.fs.setFilePermissions(p,Y.toString(8));return}if((await I.process.codeRun(`import os,base64,subprocess
|
|
91
|
+
subprocess.run(["sh","-c",${JSON.stringify(F)}],check=True)
|
|
92
92
|
p=${JSON.stringify(p)}
|
|
93
93
|
os.makedirs(os.path.dirname(p),exist_ok=True)
|
|
94
|
-
fd=os.open(p,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,${
|
|
95
|
-
os.fchmod(fd,${
|
|
96
|
-
with os.fdopen(fd,"wb") as f: f.write(base64.b64decode(${JSON.stringify(Buffer.from(
|
|
94
|
+
fd=os.open(p,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,${Y??438})${Y===void 0?"":`
|
|
95
|
+
os.fchmod(fd,${Y})`}
|
|
96
|
+
with os.fdopen(fd,"wb") as f: f.write(base64.b64decode(${JSON.stringify(Buffer.from(k).toString("base64"))}))`,120)).exitCode!==0)throw new e("File write failed. Workspace setup or the native code operation failed. Check guest permissions.",{code:"provider",provider:"daytona",sandboxId:s});g.delete(s)}),list:(s,p)=>z(s,async(k)=>{try{return(await k.fs.listFiles(p)).map((R)=>Ne(We.join(p,R.name),R))}catch(R){if(p!=="/workspace"||!g.has(s)||W(R,s,!0).code!=="file_not_found")throw R;return[]}}),stat:(s,p)=>z(s,async(k)=>{try{return Ne(p,await k.fs.getFileDetails(p))}catch(R){if(p!=="/workspace"||!g.has(s)||W(R,s,!0).code!=="file_not_found")throw R;return{path:p,type:"directory",size:0,modifiedAt:Date.parse(D.get(s)?.createdAt??"")||Date.now()}}}),remove:(s,p,k)=>z(s,async(R)=>{try{await R.fs.deleteFile(p,k.recursive)}catch(I){if(p!=="/workspace"||!g.has(s)||W(I,s,!0).code!=="file_not_found")throw I}if(p==="/workspace")g.delete(s)}),mkdir:(s,p)=>z(s,async(k)=>{if(!g.has(s))return k.fs.createFolder(p,"755");if((await k.process.executeCommand(`${F} && mkdir -p ${G(p)}`,"/",void 0,10)).exitCode!==0)throw new e("Directory creation failed. Check guest permissions.",{code:"provider",provider:"daytona",sandboxId:s});g.delete(s)})},previewUrl:(s,p)=>_(async()=>{let k=await j(s),R=await M.previewLink(s,p),I={url:R.url};if(!k.public)I.headers={"X-Daytona-Preview-Token":R.token};return I},s,!1,"preview"),snapshot:(s,p)=>_(async()=>{if(p?.expiresInMs)oe("Snapshot expiry is unavailable; Daytona keeps snapshots until you delete them. Omit expiresInMs, or pass 0");let k=`sdk-${crypto.randomUUID()}`;await j(s);try{await M.snapshot(s,k,n.snapshotTimeoutMs??600000)}catch(R){let I=W(R,s,!1,"snapshot",n.apiKey??process.env.DAYTONA_API_KEY,c);throw new e(`Snapshot ${k} did not complete. It may still be creating. Inspect or delete this name with the native snapshot API before retrying.`,{code:I.code,cause:I.cause,provider:"daytona",sandboxId:s,retryable:!1,hint:`Recover snapshot ${k} from source sandbox ${s}.`})}return{id:k}},s,!1,"snapshot"),native(s){if(!D.has(s))throw new e("Sandbox is not connected. No local native object exists. Connect the sandbox first.",{code:"not_found",provider:"daytona",sandboxId:s});let p=T.get(s);if(!p)p=b({http:O,placeholder:"sandboxId",sandboxId:s,sdk:H}),T.set(s,p);return p}};return B}export{Pt as daytona};
|
|
@@ -10,8 +10,7 @@
|
|
|
10
10
|
* - Protobuf JSON: `bytes` fields are base64, int64 fields are strings, defaults (exit code 0, empty lists) are
|
|
11
11
|
* left out, enums are names.
|
|
12
12
|
*/
|
|
13
|
-
import type
|
|
14
|
-
import type { HttpClient } from "../../http.js";
|
|
13
|
+
import { type HttpClient, type JsonValue } from "../../provider.js";
|
|
15
14
|
export type E2BPlane = "api" | "envd";
|
|
16
15
|
/** What the API returns for a created or connected sandbox: what envd calls need. */
|
|
17
16
|
export interface Connection {
|
|
@@ -27,6 +26,7 @@ export declare function versionAtLeast(version: string, minimum: string): boolea
|
|
|
27
26
|
/** The envd versions the SDK checks before it uses a feature. */
|
|
28
27
|
export declare const envdGates: {
|
|
29
28
|
readonly minimum: "0.1.0";
|
|
29
|
+
readonly recursiveWatch: "0.1.4";
|
|
30
30
|
readonly stdinFlag: "0.3.0";
|
|
31
31
|
readonly defaultUser: "0.4.0";
|
|
32
32
|
readonly closeStdin: "0.5.2";
|
|
@@ -38,6 +38,11 @@ export interface EntryInfo {
|
|
|
38
38
|
/** Epoch ms, when envd sent one. */
|
|
39
39
|
modifiedTime?: number;
|
|
40
40
|
}
|
|
41
|
+
/** One change from WatchDir, as envd names it: the path relative to the watched directory. */
|
|
42
|
+
export interface WatchEvent {
|
|
43
|
+
name: string;
|
|
44
|
+
type: "create" | "write" | "remove" | "rename" | "chmod";
|
|
45
|
+
}
|
|
41
46
|
export interface StartOptions {
|
|
42
47
|
/** Run as `/bin/bash -l -c <command>`, as `commands.run` does. */
|
|
43
48
|
command: string;
|
|
@@ -69,6 +74,10 @@ export interface Command {
|
|
|
69
74
|
kill(): Promise<boolean>;
|
|
70
75
|
sendStdin(data: string): Promise<void>;
|
|
71
76
|
closeStdin(): Promise<void>;
|
|
77
|
+
/** PTY input, for a command started with `terminal`. */
|
|
78
|
+
sendPty(data: string): Promise<void>;
|
|
79
|
+
/** Change the PTY size. */
|
|
80
|
+
resize(cols: number, rows: number): Promise<void>;
|
|
72
81
|
/** Stop reading without signalling the process. No callback fires after this. */
|
|
73
82
|
disconnect(): void;
|
|
74
83
|
}
|
|
@@ -96,10 +105,31 @@ export declare function createEnvd(options: {
|
|
|
96
105
|
/** Creates parents too. An existing directory is not an error, as in the SDK. */
|
|
97
106
|
mkdir(sandboxId: string, path: string, user: string): Promise<void>;
|
|
98
107
|
remove(sandboxId: string, path: string, user: string): Promise<void>;
|
|
108
|
+
/**
|
|
109
|
+
* WatchDir, a server stream: a start event once the watch is set up, then one event per change, with
|
|
110
|
+
* keepalives between. Resolves when `signal` aborts, rejects when the stream fails or ends.
|
|
111
|
+
*/
|
|
112
|
+
watch(sandboxId: string, path: string, options: {
|
|
113
|
+
recursive: boolean;
|
|
114
|
+
user: string;
|
|
115
|
+
signal: AbortSignal;
|
|
116
|
+
onEvent(event: WatchEvent): void;
|
|
117
|
+
}): Promise<void>;
|
|
99
118
|
};
|
|
100
119
|
process: {
|
|
101
120
|
/** Every Start carries a fresh tag, so a start whose outcome is unknown can still be found and stopped. */
|
|
102
121
|
start(sandboxId: string, options: StartOptions): Promise<Command>;
|
|
122
|
+
/** A login shell on a PTY, as `pty.create` starts it. Output arrives through `onPty`; no deadline. */
|
|
123
|
+
terminal(sandboxId: string, options: {
|
|
124
|
+
cols: number;
|
|
125
|
+
rows: number;
|
|
126
|
+
cwd: string;
|
|
127
|
+
envs: Record<string, string>;
|
|
128
|
+
user: string;
|
|
129
|
+
onPty(text: string): void;
|
|
130
|
+
/** Stops a shell whose start outcome is unknown, found by its tag, as for `start`. */
|
|
131
|
+
abandon(tag: string): Promise<void>;
|
|
132
|
+
}): Promise<Command>;
|
|
103
133
|
/** Reattach to a running process. Output printed while detached is lost: envd does not buffer it. */
|
|
104
134
|
connect(sandboxId: string, pid: number): Promise<Command>;
|
|
105
135
|
list(sandboxId: string): Promise<ProcessEntry[]>;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { SandboxError, type ErrorCode } from "../../
|
|
2
|
-
import type { FailedRequest, HttpFailure } from "../../http.js";
|
|
1
|
+
import { SandboxError, type ErrorCode, type FailedRequest, type HttpFailure } from "../../provider.js";
|
|
3
2
|
/** The envd file routes: a missing path there is `file_not_found`, not a missing sandbox. */
|
|
4
3
|
export declare function isFileOperation(operation: string): boolean;
|
|
5
4
|
/** Maps a Connect error code. `file` turns `not_found` into `file_not_found`. */
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { type NativeApi } from "../../native.js";
|
|
1
|
+
import { type NativeApi, type Provider, type TemplateBuildOptions, type TemplateInfo, type TemplateSpec } from "../../provider.js";
|
|
3
2
|
import { type E2BPlane } from "./envd.js";
|
|
4
3
|
export type { E2BPlane } from "./envd.js";
|
|
5
4
|
export interface E2BOptions {
|
|
@@ -43,10 +42,47 @@ export type E2BClientSdk = <M extends {
|
|
|
43
42
|
}>(load: () => Promise<M>) => Promise<InstanceType<M["E2B"]>>;
|
|
44
43
|
/** `box.native` for E2B: the control plane (`"api"`, default) and the sandbox's envd (`"envd"`). `{sandboxId}` fills itself. */
|
|
45
44
|
export type E2BNative = NativeApi<E2BPlane, E2BSandboxSdk>;
|
|
46
|
-
|
|
45
|
+
/** One sample from E2B's sandbox metrics. Times are epoch ms, sizes bytes. */
|
|
46
|
+
export interface E2BMetric {
|
|
47
|
+
timestamp: number;
|
|
48
|
+
cpuCount: number;
|
|
49
|
+
cpuUsedPct: number;
|
|
50
|
+
memUsed: number;
|
|
51
|
+
memTotal: number;
|
|
52
|
+
diskUsed: number;
|
|
53
|
+
diskTotal: number;
|
|
54
|
+
}
|
|
55
|
+
/** The window `box.ext.e2b.metrics()` reads. Default: what E2B keeps for the sandbox. */
|
|
56
|
+
export interface E2BMetricsRange {
|
|
57
|
+
startMs?: number;
|
|
58
|
+
endMs?: number;
|
|
59
|
+
}
|
|
60
|
+
/** E2B-only features on `box.ext.e2b`. */
|
|
61
|
+
export type E2BExtension = {
|
|
62
|
+
/** Every metric sample in the window, oldest first. `box.usage()` reports the newest one. */
|
|
63
|
+
metrics(range?: E2BMetricsRange): Promise<E2BMetric[]>;
|
|
64
|
+
};
|
|
65
|
+
/** `buildTemplate(e2b(), spec)`: the portable spec plus E2B's template fields. */
|
|
66
|
+
export interface E2BTemplateSpec extends TemplateSpec {
|
|
67
|
+
/** Start from another E2B template instead of an image. */
|
|
68
|
+
fromTemplate?: string;
|
|
69
|
+
/** Command every sandbox from the template starts with, kept running in the snapshot. */
|
|
70
|
+
startCommand?: string;
|
|
71
|
+
/** Command that must exit 0 before the snapshot is taken, such as a port check. Needs `startCommand`. */
|
|
72
|
+
readyCommand?: string;
|
|
73
|
+
/** Tags for this build, such as `["v2"]`. */
|
|
74
|
+
tags?: readonly string[];
|
|
75
|
+
/** Rebuild every layer instead of reusing cached ones. */
|
|
76
|
+
skipCache?: boolean;
|
|
77
|
+
}
|
|
78
|
+
export type E2BCapability = "pause" | "snapshot" | "snapshot-delete" | "templates" | "terminal" | "network-policy";
|
|
79
|
+
export type E2BProvider = Provider<E2BNative, E2BCapability, {
|
|
80
|
+
e2b: E2BExtension;
|
|
81
|
+
}> & {
|
|
47
82
|
/** The E2B API with this provider's credentials and no sandbox bound, for account calls such as `GET /templates`. */
|
|
48
83
|
readonly api: NativeApi<E2BPlane, E2BClientSdk>;
|
|
49
|
-
|
|
84
|
+
buildTemplate(spec: E2BTemplateSpec, options: TemplateBuildOptions): Promise<TemplateInfo>;
|
|
85
|
+
} & Required<Pick<Provider, "terminal" | "deleteSnapshot">>;
|
|
50
86
|
/** E2B's template fixes CPU, RAM and disk; explicit size requests fail closed.
|
|
51
87
|
* Talks to E2B's control plane and to envd directly over HTTP; the `e2b` package is not needed.
|
|
52
88
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{J,ue,fe}from"../../chunk-g0vk7g1k.js";import{w,v}from"../../chunk-2z6fxyg5.js";import{x}from"../../chunk-305dymgq.js";import{t,o,_,r,e,i,l,a}from"../../chunk-n7x9ha44.js";import{posix as oe}from"node:path";var ve=new Map([["invalid_argument","invalid_argument"],["unauthenticated","auth"],["permission_denied","auth"],["not_found","not_found"],["resource_exhausted","quota"],["unavailable","unavailable"],["canceled","timeout"],["deadline_exceeded","timeout"]]);function $e(s){return/ \/files(?:\?|$)/.test(s)||s.includes(" /filesystem.Filesystem/")}function ke(s,m){let y=ve.get(s)??"provider";return y==="not_found"&&m?"file_not_found":y}function xe(s,m){if(s.kind!=="status")return;let y=m.plane==="envd"&&$e(m.operation),S=s.body.code;if(m.plane==="envd"&&S!==void 0&&ve.has(S))return ke(S,y);if(s.status===507)return"quota";if(s.status===404&&y)return"file_not_found";return}function ye(s){let m=ke(s.code,s.file??!1),y=/^[a-z_]{1,32}$/.test(s.code)?s.code:"unknown";return new e(`E2B ${s.method} failed (rpc ${y}).`,{code:m,provider:"e2b",sandboxId:s.sandboxId,retryable:["quota","unavailable","timeout"].includes(m),cause:`rpc ${y}`})}function Ee(s,m){if(s instanceof e)return s;let y=r(s)&&"name"in s&&s.name==="AbortError"?"aborted":"provider",S=i(s,{code:y,redact:l([process.env.E2B_API_KEY])});return new e(`E2B request failed: ${a(y,S.detail)}. Check the sandbox, template and E2B service, then retry.`,{code:y,provider:"e2b",sandboxId:m,cause:S.cause})}function ne(s,m){let y=s.split(/[.+-]/).map(Number),S=m.split(".").map(Number);for(let C=0;C<S.length;C++){let g=Number.isFinite(y[C])?y[C]??0:0,B=S[C]??0;if(g!==B)return g>B}return!0}var re={minimum:"0.1.0",stdinFlag:"0.3.0",defaultUser:"0.4.0",closeStdin:"0.5.2"},U=(s)=>typeof s==="object"&&s!==null&&!Array.isArray(s),Me=new Map([["FILE_TYPE_FILE","file"],["FILE_TYPE_DIRECTORY","dir"],["FILE_TYPE_SYMLINK","symlink"]]),Re=/^[A-Za-z0-9+/_-]*={0,2}$/,Pe="application/connect+json";function we(s){if(s===void 0)return 0;let m=t(s)&&/^-?\d+$/.test(s)?Number(s):s;return o(m)&&Number.isSafeInteger(m)?m:void 0}function Se(s){if(!U(s)||!t(s.path))return;let m=s.isSymlink===!0?"symlink":t(s.type)?Me.get(s.type):void 0;if(m===void 0)return;let y=t(s.modifiedTime)?Date.parse(s.modifiedTime):Number.NaN;return{path:s.path,type:m,size:we(s.size)??0,modifiedTime:Number.isFinite(y)?y:void 0}}function Ie(s){let m=U(s)?s.event:void 0;if(!U(m))return;let{start:y,data:S,end:C}=m;if(U(y)){let g=we(y.pid);return g===void 0||g<=0?void 0:{kind:"start",pid:g}}if(U(S)){for(let g of["stdout","stderr"]){let B=S[g];if(B===void 0)continue;if(!t(B)||!Re.test(B))return;return{kind:"data",stream:g,bytes:new Uint8Array(Buffer.from(B,"base64"))}}return{kind:"other"}}if(U(C)){let g=we(C.exitCode);return g===void 0?void 0:{kind:"end",exitCode:g}}return{kind:"other"}}function te(s,m){return new e(`E2B envd sent ${m}. The command stream cannot be read further.`,{code:"provider",provider:"e2b",sandboxId:s})}function Te(s){let{http:m,connection:y,startupTimeoutMs:S}=s,C=(f)=>({authorization:`Basic ${Buffer.from(`${f}:`).toString("base64")}`});async function g(f,h,k,p={}){return m.json({method:"POST",plane:"envd",path:`/${h}`,sandboxId:f,body:k,headers:p.user===void 0?void 0:C(p.user),readOnly:p.readOnly})}let B=(f,h,k)=>g(f,"process.Process/SendSignal",{process:h,signal:k});async function M(f,h,k,p){let b=`process.Process/${h}`,R=new AbortController,G=!1,pe=setTimeout(()=>{G=!0,R.abort()},S),X=()=>R.abort();if(p.signal?.aborted)X();else p.signal?.addEventListener("abort",X,{once:!0});let K=()=>{clearTimeout(pe),p.signal?.removeEventListener("abort",X)},se=async()=>{let E={"content-type":Pe,"keepalive-ping-interval":"50"},O=p.timeoutMs>0?{...E,"connect-timeout-ms":String(p.timeoutMs)}:E,q=await m.stream({method:"POST",plane:"envd",path:`/${b}`,sandboxId:f,body:fe(k),signal:R.signal,startupTimeoutMs:S,readOnly:h==="Connect",headers:{...O,...p.headers}});if(!(q.headers.get("content-type")??"").startsWith(Pe)||!q.body)throw await q.body?.cancel().catch(()=>{}),te(f,"a response that is not a Connect stream");let V=ue(q.body,{provider:"e2b",sandboxId:f,signal:R.signal});try{let n=await V.next();if(n.done)throw te(f,"an empty stream");if(n.value.kind==="end"){if(n.value.error)throw ye({code:n.value.error.code,method:b,sandboxId:f});throw te(f,"an end frame before the start event")}let d=Ie(n.value.message);if(d?.kind!=="start")throw te(f,"no start event first");return{frames:V,pid:d.pid}}catch(n){throw await V.return(),n}},T;try{T=await se()}catch(E){K();let O=G||J(E)!==void 0||E instanceof e&&["aborted","timeout","outcome_unknown"].includes(E.code),q=p.tag;if(!(O&&q!==void 0&&p.abandon?await p.abandon(q).then(()=>!0,()=>!1):!0))throw new e(`E2B ${b} failed before its start event, and stopping a command that may have started failed too. It may still be running.`,{code:"outcome_unknown",provider:"e2b",sandboxId:f});if(G)throw new e(`E2B ${b} sent no start event within ${S} ms, so the command may or may not have started. It was stopped if it did.`,{code:"outcome_unknown",provider:"e2b",sandboxId:f});if(p.signal?.aborted)throw new e("Command start aborted. The signal was cancelled.",{code:"aborted",provider:"e2b",sandboxId:f});throw E}let{frames:Z,pid:Y}=T;K();let F={stdout:new TextDecoder,stderr:new TextDecoder},z=!1,Q,H=(E,O)=>{if(!O||z)return;if(E==="stdout")p.onStdout?.(O);else p.onStderr?.(O)},ee=(async()=>{try{for await(let E of Z){if(E.kind==="end"){if(E.error)throw ye({code:E.error.code,method:b,sandboxId:f});continue}let O=Ie(E.message);if(O===void 0)throw te(f,"a malformed process event");if(O.kind==="data")H(O.stream,F[O.stream].decode(O.bytes,{stream:!0}));else if(O.kind==="end"){Q=O.exitCode;for(let q of["stdout","stderr"])H(q,F[q].decode())}}}catch(E){for(let O of["stdout","stderr"])H(O,F[O].decode());if(z)throw new e("Disconnected from the E2B command. It keeps running; reconnect to wait for it.",{code:"aborted",provider:"e2b",sandboxId:f});throw E}if(Q===void 0)throw new e("The E2B command stream ended without the command's result.",{code:"provider",provider:"e2b",sandboxId:f});return Q})();return ee.catch(()=>{}),{pid:Y,get exitCode(){return Q},wait:()=>ee,async kill(){try{return await B(f,{pid:Y},"SIGNAL_SIGKILL"),!0}catch(E){if(E instanceof e&&E.code==="not_found")return!1;throw E}},async sendStdin(E){await g(f,"process.Process/SendInput",{process:{pid:Y},input:{stdin:Buffer.from(E).toString("base64")}})},async closeStdin(){let{envdVersion:E}=y(f);if(!ne(E,re.closeStdin))throw new e(`envd ${E.slice(0,16)} cannot close stdin. Rebuild the template to pick up a newer envd.`,{code:"unsupported",provider:"e2b",sandboxId:f});await g(f,"process.Process/CloseStdin",{process:{pid:Y}})},disconnect(){z=!0,R.abort()}}}return{files:{async read(f,h,k){return(await m.request({method:"GET",plane:"envd",path:"/files",sandboxId:f,query:{path:h,username:k},maxBytes:Number.POSITIVE_INFINITY})).body},async write(f,h,k){let p=new FormData;for(let R of h)p.append("file",new Blob([t(R.data)?R.data:new Uint8Array(R.data)]),R.path);let b=h.length===1?h[0]?.path:void 0;await m.request({method:"POST",plane:"envd",path:"/files",sandboxId:f,body:p,query:{path:b,username:k}})}},fs:{async stat(f,h,k){let p=await g(f,"filesystem.Filesystem/Stat",{path:h},{user:k,readOnly:!0}),b=Se(U(p)?p.entry:void 0);if(!b)throw te(f,"a Stat answer without a known entry");return b},async list(f,h,k){let p=await g(f,"filesystem.Filesystem/ListDir",{path:h,depth:1},{user:k,readOnly:!0});return(U(p)&&Array.isArray(p.entries)?p.entries:[]).map(Se).filter((R)=>R!==void 0)},async mkdir(f,h,k){try{await g(f,"filesystem.Filesystem/MakeDir",{path:h},{user:k})}catch(p){if(!(p instanceof e&&/\balready_exists\b/.test(p.message)))throw p}},async remove(f,h,k){await g(f,"filesystem.Filesystem/Remove",{path:h},{user:k})}},process:{async start(f,h){let{envdVersion:k}=y(f);if(!h.stdin&&!ne(k,re.stdinFlag))throw new e(`envd ${k.slice(0,16)} always opens stdin. Rebuild the template to pick up a newer envd.`,{code:"unsupported",provider:"e2b",sandboxId:f});let p=`sandbox-sdk-${crypto.randomUUID()}`,b={process:{cmd:"/bin/bash",args:["-l","-c",h.command],envs:h.envs??{},cwd:h.cwd},stdin:h.stdin,tag:p};return M(f,"Start",b,{...h,tag:p,headers:C(h.user)})},connect(f,h){return M(f,"Connect",{process:{pid:h}},{timeoutMs:0})},async list(f){let h=await g(f,"process.Process/List",{},{readOnly:!0});return(U(h)&&Array.isArray(h.processes)?h.processes:[]).filter(U).flatMap((p)=>{let b=we(p.pid);return b===void 0?[]:[{pid:b,tag:t(p.tag)?p.tag:void 0}]})},signal:B}}}var me="sandbox-sdk-key",W="/tmp/.sandbox-sdk-workspace-ready",he="sandbox-sdk-deadline",Ae=49983,De=new Set(["e2b.app","e2b.dev","e2b.pro","e2b-staging.dev"]),ae=(s)=>`'${s.replace(/'/g,`'"'"'`)}'`,be=`[ -e ${W} ] || { flock -x 9 && { [ -e ${W} ] || { mkdir -p /workspace && printf ready > ${W}; }; }; } 9>${W}.lock || exit 125`,ie=(s)=>s instanceof e&&s.code==="file_not_found",Le=(s)=>new Promise((m)=>setTimeout(m,s)),ge=(s)=>Math.ceil(s/1000),ce=(s)=>new e(`${s}. E2B cannot enforce this option. Choose a compatible template or omit the option.`,{code:"unsupported",provider:"e2b"}),le=(s)=>typeof s==="object"&&s!==null&&!Array.isArray(s),Ce=(s)=>Array.isArray(s)?s.filter((m)=>t(m)):void 0,Be=(s)=>({path:s.path,type:s.type==="dir"?"directory":s.type,size:s.size,modifiedAt:s.modifiedTime??0});function de(s,m){return new e(`E2B returned ${s}. Check the E2B service, then retry.`,{code:"provider",provider:"e2b",sandboxId:m})}function _e(s){if(!le(s)||!t(s.sandboxID)||!s.sandboxID)throw de("a sandbox without an ID");let m=le(s.metadata)?Object.fromEntries(Object.entries(s.metadata).filter((C)=>typeof C[1]==="string")):{},y=t(s.startedAt)?Date.parse(s.startedAt):Number.NaN,S=le(s.network)?s.network:void 0;return{id:s.sandboxID,metadata:m,state:s.state==="paused"?"paused":"running",startedAt:Number.isFinite(y)?y:0,allowInternetAccess:_(s.allowInternetAccess)?s.allowInternetAccess:void 0,network:S?{allowOut:Ce(S.allowOut),denyOut:Ce(S.denyOut),allowPublicTraffic:_(S.allowPublicTraffic)?S.allowPublicTraffic:void 0}:void 0}}var Oe=(s)=>({id:s.id,key:s.metadata[me],labels:Object.fromEntries(Object.entries(s.metadata).filter(([m])=>![me,he].includes(m))),state:s.state,createdAt:s.startedAt});function et(s={}){let m=()=>s.domain??(process.env.E2B_DOMAIN||"e2b.app"),y=()=>{let n=s.apiKey??process.env.E2B_API_KEY;if(!n?.trim())throw new e("E2B API key is missing. Authentication is required. Set E2B_API_KEY or pass apiKey.",{code:"auth",provider:"e2b"});return n},S=s.requestTimeoutMs??60000,C=new Map;function g(n){let d=C.get(n);if(!d)throw new e("Sandbox is detached. No local client exists. Connect first.",{code:"not_found",provider:"e2b",sandboxId:n});return d}let B=x({provider:"e2b",label:"E2B",defaultPlane:"api",timeoutMs:S,mapError:xe,authHint:"Check E2B_API_KEY and the E2B domain.",secrets:()=>[s.apiKey,process.env.E2B_API_KEY,...[...C.values()].flatMap((n)=>[n.envdAccessToken,n.trafficAccessToken])],planes:{api:{baseUrl:()=>process.env.E2B_API_URL||`https://api.${m()}`,auth:()=>({"x-api-key":y()})},envd:{headers:{"connect-protocol-version":"1"},baseUrl:({sandboxId:n})=>{if(n===void 0)throw new e("The envd plane belongs to one sandbox. Use box.native, not provider.api.",{code:"invalid_argument",provider:"e2b"});let{domain:d}=g(n);return process.env.E2B_SANDBOX_URL||(De.has(d)?`https://sandbox.${d}`:`https://${Ae}-${n}.${d}`)},auth:({sandboxId:n})=>{let{envdAccessToken:d}=g(n??""),c={"e2b-sandbox-id":n??"","e2b-sandbox-port":String(Ae)};return d?{...c,"x-access-token":d}:c}}}}),M=Te({http:B,connection:g,startupTimeoutMs:S}),f={idempotencyKey:"replayable",readOnly:!0};function h(n){if(!le(n)||!t(n.sandboxID)||!n.sandboxID||!t(n.envdVersion))throw de("a sandbox connection without an ID or envd version");let d=(P)=>{let I=n[P];return t(I)&&I?I:void 0},c=d("envdAccessToken"),u=d("trafficAccessToken");return{sandboxId:n.sandboxID,envdVersion:n.envdVersion,envdAccessToken:c,trafficAccessToken:u,domain:d("domain")??m()}}let k={async info(n){return _e(await B.json({method:"GET",path:"/sandboxes/{id}",params:{id:n},sandboxId:n}))},async connect(n,d){return h(await B.json({method:"POST",path:"/v2/sandboxes/{id}/connect",params:{id:n},sandboxId:n,body:d===void 0?{}:{timeout:ge(d)},...f}))},async setTimeout(n,d){await B.request({method:"POST",path:"/sandboxes/{id}/timeout",params:{id:n},sandboxId:n,body:{timeout:ge(d)},...f})},async kill(n){try{return await B.request({method:"DELETE",path:"/sandboxes/{id}",params:{id:n},sandboxId:n}),!0}catch(d){if(d instanceof e&&d.code==="not_found")return!1;throw d}},async list(n){let d=new URLSearchParams(Object.fromEntries(Object.entries(n).map(([u,P])=>[encodeURIComponent(u),encodeURIComponent(P)]))).toString(),c=[];for(let u,P=0;P<1000;P++){let I=await B.request({method:"GET",path:"/v2/sandboxes",query:{metadata:d,state:"running,paused",nextToken:u}}),A=I.json();if(!Array.isArray(A))throw de("a sandbox list that is not an array");if(c.push(...A.map(_e)),u=I.headers.get("x-next-token")||void 0,u===void 0)return c}throw de("more than 1000 pages of sandboxes")}},p=new Map,b=new Map,R=new Map,G=new Map;function pe(n){if(G.has(n))return;let d=()=>{},c=new Promise((u)=>{d=u});G.set(n,{wait:c,release:d})}function X(n){G.get(n)?.release(),G.delete(n)}let K=new Map;function se(n){for(let d of K.get(n)??[])d.disconnect();K.delete(n)}async function T(n,d){try{return await d()}catch(c){throw Ee(c,n)}}let Z=(n,d)=>M.fs.stat(n,d,"root");async function Y(n){let d=await k.info(n),c=Number(d.metadata[he]);if(Number.isFinite(c)&&c>0){if(p.set(n,c),c<=Date.now())throw await k.kill(n),new e("Sandbox lifetime expired. Its hard deadline passed. Create another sandbox.",{code:"not_found",provider:"e2b",sandboxId:n})}C.set(n,await k.connect(n,p.has(n)?Math.max(1,(p.get(n)??0)-Date.now()):void 0));try{await Z(n,"/workspace"),await M.files.write(n,[{path:W,data:"ready"}],"root"),b.delete(n)}catch(u){if(!ie(u))throw u;try{await Z(n,W),b.delete(n)}catch(P){if(!ie(P))throw P;b.set(n,d.startedAt)}}if(p.has(n))await k.setTimeout(n,Math.max(1,(p.get(n)??0)-Date.now()));return X(n),{...d,state:"running"}}async function F(n){if(!C.has(n))await Y(n);g(n)}async function z(n){if(!b.has(n))return;try{await Z(n,W),b.delete(n)}catch(d){if(!ie(d))throw d}}async function Q(n){return(await k.list({...n,"sandbox-sdk":"1"})).map(Oe)}async function H(n,d,c=60000){return(await M.process.start(n,{command:d,cwd:"/",user:"root",stdin:!1,timeoutMs:c,abandon:(u)=>E(n,u)})).wait()}async function ee(n,d,c){await H(n,`kill -${c} -- -${d} 2>/dev/null || true`,1e4)}async function E(n,d){let c=(await M.process.list(n)).find((u)=>u.tag===d);if(c){await M.process.signal(n,{pid:c.pid},"SIGNAL_SIGKILL").catch((u)=>{if(!(u instanceof e&&u.code==="not_found"))throw u}),await ee(n,c.pid,"KILL");return}await M.process.signal(n,{tag:d},"SIGNAL_SIGKILL").catch((u)=>{if(!(u instanceof e&&u.code==="not_found"))throw u})}async function O(n,d,c){await F(n);let u=b.has(n),P=`${u?`${be}; `:""}cd ${ae(d.cwd)} && exec sh -c ${ae(d.command)}`,I=`set -- "$(</proc/$$/stat)" || exit 125; set -- \${1##*) }; [[ "$3" =~ ^[0-9]+$ ]] || exit 125; if [[ "$3" = "$$" ]]; then exec sh -c ${ae(P)}; else exec setsid -w sh -c ${ae(P)}; fi`,A=await M.process.start(n,{command:I,cwd:"/",envs:d.env,user:"root",stdin:d.stdin!==void 0,timeoutMs:0,signal:c,onStdout:(D)=>d.onChunk({stream:"stdout",text:D}),onStderr:(D)=>d.onChunk({stream:"stderr",text:D}),abandon:(D)=>E(n,D)}),L=K.get(n)??new Set;K.set(n,L),L.add(A);let N=A.wait().then((D)=>({exitCode:D,signal:null}));N.catch(()=>{});try{if(d.stdin!==void 0)try{await A.sendStdin(d.stdin),await A.closeStdin()}catch(j){if(A.exitCode===void 0)throw j}let D=N.then(async(j)=>{if(u)if(j.exitCode>=0&&j.exitCode<128&&j.exitCode!==125)b.delete(n);else await z(n);return j}).finally(()=>L.delete(A));return D.catch(()=>{}),{handle:A,pid:A.pid,result:D}}catch(D){throw await V.destroy(n),D}}let q={package:"e2b",connect(n,d){let c={apiKey:y(),domain:m(),requestTimeoutMs:S};if(d===void 0)return v(n,"E2B",[c],"e2b");let{envdVersion:u,envdAccessToken:P,trafficAccessToken:I,domain:A}=g(d);return v(n,"Sandbox",[{...c,sandboxId:d,sandboxDomain:A,envdVersion:u,envdAccessToken:P,trafficAccessToken:I}],"e2b")}},V={name:"e2b",keyMode:"best-effort",capabilities:new Set(["pause","snapshot","network-policy"]),procActivity:!0,api:w({http:B,placeholder:"sandboxId",sdk:q}),create:(n)=>T(void 0,async()=>{Ne(n,s);let d=Date.now(),c=n.timeoutMs===void 0||s.autoPause?void 0:d+n.timeoutMs,u=r(n.network)?n.network.allow:void 0,P=u!==void 0||s.public===!1?{denyOut:u===void 0?void 0:["0.0.0.0/0"],allowOut:u,allowPublicTraffic:s.public===!1?!1:void 0}:void 0,I=h(await B.json({method:"POST",path:"/v2/sandboxes",body:{templateID:n.from??s.template??"base",metadata:{...n.labels,"sandbox-sdk":"1",[me]:n.key,[he]:c===void 0?void 0:String(c)},envVars:n.env,timeout:n.timeoutMs===void 0?void 0:ge(n.timeoutMs),allow_internet_access:n.network==="none"?!1:r(n.network)?void 0:!0,network:P,autoPause:s.autoPause===!0,autoResume:{enabled:s.autoPause===!0&&s.autoResume===!0},volumeMounts:s.volumes===void 0?void 0:Object.entries(s.volumes).map(([L,N])=>({name:N,path:L}))}})),A=I.sandboxId;if(C.set(A,I),c!==void 0)p.set(A,c);try{if(!ne(I.envdVersion,re.minimum))throw new e("The template's envd is too old for this SDK. Rebuild the template.",{code:"provider",provider:"e2b",sandboxId:A});if(n.signal?.aborted)throw new e("Creation aborted. Cancellation arrived during E2B creation. Retry with a fresh signal.",{code:"aborted",provider:"e2b"});let L=n.network==="none"||r(n.network)||s.public===!1?await k.info(A):void 0;if(n.network==="none"&&L?.allowInternetAccess!==!1&&!(L?.network?.denyOut?.includes("0.0.0.0/0")&&!L?.network.allowOut?.length))throw ce("E2B did not confirm that internet access is disabled");if(r(n.network)){let N=n.network.allow,D=L?.network?.allowOut??[];if(!L?.network?.denyOut?.includes("0.0.0.0/0")||N.some((j)=>!D.includes(j))||D.some((j)=>!N.includes(j)))throw ce("E2B did not confirm the requested outbound allow list")}if(s.public===!1&&(L?.network?.allowPublicTraffic!==!1||!I.trafficAccessToken))throw ce("E2B did not confirm that preview URLs require a traffic access token");if(b.set(A,d),n.from!==void 0)await z(A);if(n.signal?.aborted)throw new e("Creation aborted during E2B policy confirmation",{code:"aborted",provider:"e2b"});return{id:A,key:n.key,labels:{...n.labels,"sandbox-sdk":"1"},state:"running",createdAt:d}}catch(L){throw await V.destroy(A),L}}),find:(n)=>T(void 0,async()=>{let d=(await Q({[me]:n}))[0];return d?V.connect(d.id):void 0}),connect:(n)=>T(n,async()=>Oe(await Y(n))),list:(n)=>T(void 0,()=>Q(n)),destroy:(n)=>T(n,async()=>{await k.kill(n),C.delete(n),R.delete(n),b.delete(n),p.delete(n),X(n),se(n)}),close:(n)=>T(n,async()=>{pe(n),se(n),C.delete(n),R.delete(n)}),native(n){if(!C.has(n))throw new e("Sandbox client is detached. There is no cached native object. Connect the sandbox first.",{code:"not_found",provider:"e2b",sandboxId:n});let d=R.get(n);if(!d)d=w({http:B,placeholder:"sandboxId",sandboxId:n,sdk:q}),R.set(n,d);return d},exec:(n,d)=>T(n,async()=>{if(d.signal?.aborted)return{exitCode:null,timedOut:!0};let c=Date.now(),u=new AbortController,P=!1,I=()=>{},A=new Promise((N)=>{I=()=>{P=!0,u.abort(),N("cancelled")}});d.signal?.addEventListener("abort",I,{once:!0});let L=setTimeout(I,d.timeoutMs);try{let N;try{N=await O(n,d,u.signal)}catch(j){if(!P)throw j;if(!(j instanceof e&&j.code==="aborted"))await V.destroy(n);return{exitCode:null,timedOut:!0}}if(d.signal?.aborted||Date.now()-c>=d.timeoutMs)I();let D=P?"cancelled":await Promise.race([N.result,A]);if(D!=="cancelled")return{exitCode:D.exitCode,timedOut:!1};try{await N.handle.kill(),await ee(n,N.pid,"KILL")}catch(j){throw await V.destroy(n),j}return await N.result.catch(()=>{}),N.handle.disconnect(),{exitCode:null,timedOut:!0}}finally{clearTimeout(L),d.signal?.removeEventListener("abort",I)}}),files:{writeCreatesParents:!0,editInGuest:"in-place",listOrder:"name",guestInput:(n)=>T(n,async()=>{await F(n);let{envdVersion:d}=g(n);return ne(d,re.closeStdin)?"stdin":ne(d,re.stdinFlag)?"env":"none"}),read:(n,d)=>T(n,async()=>(await F(n),M.files.read(n,d,"root"))),write:(n,d,c)=>T(n,async()=>{if(await F(n),K.get(n)?.size)await z(n);if(oe.normalize(d)==="/workspace"&&b.has(n))throw new e("Cannot write a file over the workspace directory",{code:"invalid_argument",provider:"e2b",sandboxId:n});if(b.has(n)&&oe.normalize(d).startsWith("/workspace/"))await M.files.write(n,[{path:d,data:c},{path:W,data:"ready"}],"root"),b.delete(n);else await M.files.write(n,[{path:d,data:c}],"root")}),list:(n,d)=>T(n,async()=>{await F(n);try{let c=(await M.fs.list(n,d,"root")).map(Be);if(K.get(n)?.size)await z(n);let u=b.get(n);if(oe.normalize(d)==="/"&&u!==void 0&&!c.some((P)=>P.path==="/workspace"))c.push({path:"/workspace",type:"directory",size:0,modifiedAt:u});return c}catch(c){if(K.get(n)?.size)await z(n);if(oe.normalize(d)==="/workspace"&&b.has(n)&&ie(c))return[];throw c}}),stat:(n,d)=>T(n,async()=>{await F(n);try{return Be(await Z(n,d))}catch(c){if(K.get(n)?.size)await z(n);let u=b.get(n);if(oe.normalize(d)==="/workspace"&&u!==void 0&&ie(c))return{path:d,type:"directory",size:0,modifiedAt:u};throw c}}),mkdir:(n,d)=>T(n,async()=>{if(await F(n),b.has(n)){let c=await H(n,`${be}; mkdir -p ${ae(d)}`);if(c!==0)throw new e(`Creating the directory failed with exit code ${c}. Check the path and its parents.`,{code:"provider",provider:"e2b",sandboxId:n});b.delete(n)}else await M.fs.mkdir(n,d,"root")}),remove:(n,d,c)=>T(n,async()=>{if(await F(n),oe.normalize(d)==="/workspace"&&b.has(n)){let u=await H(n,`${be}; if [ -L /workspace ]; then rm /workspace; else ${c.recursive?"rm -rf":"rmdir"} /workspace; fi`);if(u!==0){if(!c.recursive)throw new e("Directory is not empty. Pass recursive: true.",{code:"invalid_argument",provider:"e2b",sandboxId:n});throw new e(`Removing /workspace failed with exit code ${u}.`,{code:"provider",provider:"e2b",sandboxId:n})}b.delete(n);return}if(!c.recursive&&(await Z(n,d)).type==="dir"&&(await M.fs.list(n,d,"root")).length)throw new e("Directory is not empty. Recursive removal was not requested. Pass recursive: true.",{code:"invalid_argument",provider:"e2b",sandboxId:n});await M.fs.remove(n,d,"root")})},previewUrl:(n,d)=>T(n,async()=>{await F(n);let{domain:c,trafficAccessToken:u}=g(n),P=`https://${d}-${n}.${c}`;if(s.public!==!1)return{url:P};if(!u)throw new e("Preview access token is missing. E2B returned no traffic access token for this private sandbox. Reconnect, or create it with public previews.",{code:"unsupported",provider:"e2b",sandboxId:n});return{url:P,headers:{"e2b-traffic-access-token":u}}}),pause:(n)=>T(n,async()=>{pe(n);try{try{await B.request({method:"POST",path:"/sandboxes/{id}/pause",params:{id:n},sandboxId:n,body:{},...f})}catch(d){if(!(d instanceof e&&/\(HTTP 409\b/.test(d.message)))throw d}C.delete(n),R.delete(n),se(n)}catch(d){throw X(n),d}}),resume:(n)=>T(n,async()=>{await Y(n)}),snapshot:(n,d)=>T(n,async()=>{if(d?.expiresInMs)throw new e("Snapshot expiry is unavailable. E2B keeps snapshots until you delete them. Omit expiresInMs, or pass 0.",{code:"unsupported",provider:"e2b",sandboxId:n});if(await F(n),b.has(n)){let u=await H(n,be);if(u!==0)throw new e(`Preparing /workspace for the snapshot failed with exit code ${u}.`,{code:"provider",provider:"e2b",sandboxId:n});b.delete(n)}let c=await B.json({method:"POST",path:"/sandboxes/{id}/snapshots",params:{id:n},sandboxId:n,body:{}});if(!le(c)||!t(c.snapshotID)||!c.snapshotID)throw de("a snapshot without an ID",n);return{id:c.snapshotID}}),startProcess:(n,d)=>T(n,async()=>{let c=await O(n,d),u=!1,P=(I)=>({exitCode:I>=0?I:u?143:null,signal:null});return{pid:c.pid,wait:()=>T(n,async()=>{try{return P((await c.result).exitCode)}catch{}return await G.get(n)?.wait,await F(n),P(await(await M.process.connect(n,c.pid)).wait())}),stop:(I)=>T(n,async()=>{u=!0,await ee(n,c.pid,"TERM"),await Le(I.graceMs),await c.handle.kill(),await ee(n,c.pid,"KILL")})}})};return V}function Ne(s,m){if(m.autoResume&&!m.autoPause)throw new e("autoResume requires autoPause. E2B can only wake a sandbox it paused. Set autoPause: true or drop autoResume.",{code:"invalid_argument",provider:"e2b"});if(s.size!==void 0)throw ce("Machine size is fixed by the E2B template; small, medium, large and custom sizes are unavailable at creation");if(s.idleTimeoutMs!==void 0)throw ce("E2B timeouts measure elapsed time, not idle time; idleTimeoutMs is unavailable");if(s.labels[me]!==void 0||s.labels[he]!==void 0)throw new e("Reserved E2B metadata key. SDK lifecycle metadata must not be overwritten. Rename the label.",{code:"invalid_argument",provider:"e2b"})}export{et as e2b};
|
|
1
|
+
import"../../chunk-g5n5xcmp.js";import{z,te,ne}from"../../chunk-x05t86n3.js";import{b,S}from"../../chunk-ek44atpe.js";import{f,w,v}from"../../chunk-2999xbh7.js";import{e,i,d,a}from"../../chunk-0eeyc0aq.js";import{posix as de}from"node:path";var O=(r)=>typeof r==="string",he=(r)=>typeof r==="number",Te=(r)=>typeof r==="boolean",se=(r)=>typeof r==="object"&&r!==null,D=(r)=>typeof r==="object"&&r!==null&&!Array.isArray(r);var Ce=new Map([["invalid_argument","invalid_argument"],["unauthenticated","auth"],["permission_denied","auth"],["not_found","not_found"],["resource_exhausted","quota"],["unavailable","unavailable"],["canceled","timeout"],["deadline_exceeded","timeout"]]);function Ue(r){return/ \/files(?:\?|$)/.test(r)||r.includes(" /filesystem.Filesystem/")}function Be(r,u){let g=Ce.get(r)??"provider";return g==="not_found"&&u?"file_not_found":g}function Ae(r,u){if(r.kind!=="status")return;let g=u.plane==="envd"&&Ue(u.operation),I=r.body.code;if(u.plane==="envd"&&I!==void 0&&Ce.has(I))return Be(I,g);if(r.status===507)return"quota";if(r.status===404&&g)return"file_not_found";return}function ge(r){let u=Be(r.code,r.file??!1),g=/^[a-z_]{1,32}$/.test(r.code)?r.code:"unknown";return new e(`E2B ${r.method} failed (rpc ${g}).`,{code:u,provider:"e2b",sandboxId:r.sandboxId,retryable:["quota","unavailable","timeout"].includes(u),cause:`rpc ${g}`})}function Me(r,u){if(r instanceof e)return r;let g=se(r)&&"name"in r&&r.name==="AbortError"?"aborted":"provider",I=i(r,{code:g,redact:d([process.env.E2B_API_KEY])});return new e(`E2B request failed: ${a(g,I.detail)}. Check the sandbox, template and E2B service, then retry.`,{code:g,provider:"e2b",sandboxId:u,cause:I.cause})}function oe(r,u){let g=r.split(/[.+-]/).map(Number),I=u.split(".").map(Number);for(let _=0;_<I.length;_++){let C=Number.isFinite(g[_])?g[_]??0:0,A=I[_]??0;if(C!==A)return C>A}return!0}var ie={minimum:"0.1.0",recursiveWatch:"0.1.4",stdinFlag:"0.3.0",defaultUser:"0.4.0",closeStdin:"0.5.2"},qe=new Map([["FILE_TYPE_FILE","file"],["FILE_TYPE_DIRECTORY","dir"],["FILE_TYPE_SYMLINK","symlink"]]),je=new Map([["EVENT_TYPE_CREATE","create"],["EVENT_TYPE_WRITE","write"],["EVENT_TYPE_REMOVE","remove"],["EVENT_TYPE_RENAME","rename"],["EVENT_TYPE_CHMOD","chmod"]]),ze=/^[A-Za-z0-9+/_-]*={0,2}$/,Ke=120000,ve="application/connect+json";function Ee(r){if(r===void 0)return 0;let u=O(r)&&/^-?\d+$/.test(r)?Number(r):r;return he(u)&&Number.isSafeInteger(u)?u:void 0}function _e(r){if(!D(r)||!O(r.path))return;let u=r.isSymlink===!0?"symlink":O(r.type)?qe.get(r.type):void 0;if(u===void 0)return;let g=O(r.modifiedTime)?Date.parse(r.modifiedTime):Number.NaN;return{path:r.path,type:u,size:Ee(r.size)??0,modifiedTime:Number.isFinite(g)?g:void 0}}function Oe(r){let u=D(r)?r.event:void 0;if(!D(u))return;let{start:g,data:I,end:_}=u;if(D(g)){let C=Ee(g.pid);return C===void 0||C<=0?void 0:{kind:"start",pid:C}}if(D(I)){for(let C of["stdout","stderr","pty"]){let A=I[C];if(A===void 0)continue;if(!O(A)||!ze.test(A))return;return{kind:"data",stream:C,bytes:new Uint8Array(Buffer.from(A,"base64"))}}return{kind:"other"}}if(D(_)){let C=Ee(_.exitCode);return C===void 0?void 0:{kind:"end",exitCode:C}}return{kind:"other"}}function ae(r,u){return new e(`E2B envd sent ${u}. The command stream cannot be read further.`,{code:"provider",provider:"e2b",sandboxId:r})}function $e(r){let{http:u,connection:g,startupTimeoutMs:I}=r,_=(c)=>({authorization:`Basic ${Buffer.from(`${c}:`).toString("base64")}`});async function C(c,m,h,l={}){return u.json({method:"POST",plane:"envd",path:`/${m}`,sandboxId:c,body:h,headers:l.user===void 0?void 0:_(l.user),readOnly:l.readOnly})}let A=(c,m,h)=>C(c,"process.Process/SendSignal",{process:m,signal:h});async function F(c,m,h,l){let E=`process.Process/${m}`,L=new AbortController,U=!1,J=setTimeout(()=>{U=!0,L.abort()},I),K=()=>L.abort();if(l.signal?.aborted)K();else l.signal?.addEventListener("abort",K,{once:!0});let q=()=>{clearTimeout(J),l.signal?.removeEventListener("abort",K)},le=async()=>{let P={"content-type":ve,"keepalive-ping-interval":"50"},R=l.timeoutMs>0?{...P,"connect-timeout-ms":String(l.timeoutMs)}:P,j=await u.stream({method:"POST",plane:"envd",path:`/${E}`,sandboxId:c,body:ne(h),signal:L.signal,startupTimeoutMs:I,readOnly:m==="Connect",headers:{...R,...l.headers}});if(!(j.headers.get("content-type")??"").startsWith(ve)||!j.body)throw await j.body?.cancel().catch(()=>{}),ae(c,"a response that is not a Connect stream");let H=te(j.body,{provider:"e2b",sandboxId:c,signal:L.signal});try{let G=await H.next();if(G.done)throw ae(c,"an empty stream");if(G.value.kind==="end"){if(G.value.error)throw ge({code:G.value.error.code,method:E,sandboxId:c});throw ae(c,"an end frame before the start event")}let me=Oe(G.value.message);if(me?.kind!=="start")throw ae(c,"no start event first");return{frames:H,pid:me.pid}}catch(G){throw await H.return(),G}},T;try{T=await le()}catch(P){q();let R=U||z(P)!==void 0||P instanceof e&&["aborted","timeout","outcome_unknown"].includes(P.code),j=l.tag;if(!(R&&j!==void 0&&l.abandon?await l.abandon(j).then(()=>!0,()=>!1):!0))throw new e(`E2B ${E} failed before its start event, and stopping a command that may have started failed too. It may still be running.`,{code:"outcome_unknown",provider:"e2b",sandboxId:c});if(U)throw new e(`E2B ${E} sent no start event within ${I} ms, so the command may or may not have started. It was stopped if it did.`,{code:"outcome_unknown",provider:"e2b",sandboxId:c});if(l.signal?.aborted)throw new e("Command start aborted. The signal was cancelled.",{code:"aborted",provider:"e2b",sandboxId:c});throw P}let{frames:ee,pid:W}=T;q();let V={stdout:new TextDecoder,stderr:new TextDecoder,pty:new TextDecoder},Y=!1,X,ce=(P,R)=>{if(!R||Y)return;if(P==="stdout")l.onStdout?.(R);else if(P==="stderr")l.onStderr?.(R);else l.onPty?.(R)},be=(async()=>{try{for await(let P of ee){if(P.kind==="end"){if(P.error)throw ge({code:P.error.code,method:E,sandboxId:c});continue}let R=Oe(P.message);if(R===void 0)throw ae(c,"a malformed process event");if(R.kind==="data")ce(R.stream,V[R.stream].decode(R.bytes,{stream:!0}));else if(R.kind==="end"){X=R.exitCode;for(let j of["stdout","stderr","pty"])ce(j,V[j].decode())}}}catch(P){for(let R of["stdout","stderr","pty"])ce(R,V[R].decode());if(Y)throw new e("Disconnected from the E2B command. It keeps running; reconnect to wait for it.",{code:"aborted",provider:"e2b",sandboxId:c});throw P}if(X===void 0)throw new e("The E2B command stream ended without the command's result.",{code:"provider",provider:"e2b",sandboxId:c});return X})();return be.catch(()=>{}),{pid:W,get exitCode(){return X},wait:()=>be,async kill(){try{return await A(c,{pid:W},"SIGNAL_SIGKILL"),!0}catch(P){if(P instanceof e&&P.code==="not_found")return!1;throw P}},async sendStdin(P){await C(c,"process.Process/SendInput",{process:{pid:W},input:{stdin:Buffer.from(P).toString("base64")}})},async closeStdin(){let{envdVersion:P}=g(c);if(!oe(P,ie.closeStdin))throw new e(`envd ${P.slice(0,16)} cannot close stdin. Rebuild the template to pick up a newer envd.`,{code:"unsupported",provider:"e2b",sandboxId:c});await C(c,"process.Process/CloseStdin",{process:{pid:W}})},async sendPty(P){await C(c,"process.Process/SendInput",{process:{pid:W},input:{pty:Buffer.from(P).toString("base64")}})},async resize(P,R){await C(c,"process.Process/Update",{process:{pid:W},pty:{size:{cols:P,rows:R}}})},disconnect(){Y=!0,L.abort()}}}return{files:{async read(c,m,h){return(await u.request({method:"GET",plane:"envd",path:"/files",sandboxId:c,query:{path:m,username:h},maxBytes:Number.POSITIVE_INFINITY})).body},async write(c,m,h){let l=new FormData;for(let L of m)l.append("file",new Blob([O(L.data)?L.data:new Uint8Array(L.data)]),L.path);let E=m.length===1?m[0]?.path:void 0;await u.request({method:"POST",plane:"envd",path:"/files",sandboxId:c,body:l,query:{path:E,username:h}})}},fs:{async stat(c,m,h){let l=await C(c,"filesystem.Filesystem/Stat",{path:m},{user:h,readOnly:!0}),E=_e(D(l)?l.entry:void 0);if(!E)throw ae(c,"a Stat answer without a known entry");return E},async list(c,m,h){let l=await C(c,"filesystem.Filesystem/ListDir",{path:m,depth:1},{user:h,readOnly:!0});return(D(l)&&Array.isArray(l.entries)?l.entries:[]).map(_e).filter((L)=>L!==void 0)},async mkdir(c,m,h){try{await C(c,"filesystem.Filesystem/MakeDir",{path:m},{user:h})}catch(l){if(!(l instanceof e&&/\balready_exists\b/.test(l.message)))throw l}},async remove(c,m,h){await C(c,"filesystem.Filesystem/Remove",{path:m},{user:h})},async watch(c,m,h){let{envdVersion:E}=g(c);if(h.recursive&&!oe(E,ie.recursiveWatch))throw new e(`envd ${E.slice(0,16)} cannot watch recursively. Rebuild the template to pick up a newer envd.`,{code:"unsupported",provider:"e2b",sandboxId:c});if(h.signal.aborted)return;let L;try{let U=await u.stream({method:"POST",plane:"envd",path:"/filesystem.Filesystem/WatchDir",sandboxId:c,body:ne({path:m,recursive:h.recursive}),signal:h.signal,startupTimeoutMs:I,idleTimeoutMs:Ke,readOnly:!0,headers:{"content-type":ve,"keepalive-ping-interval":"50",..._(h.user)}});if(!(U.headers.get("content-type")??"").startsWith(ve)||!U.body)throw await U.body?.cancel().catch(()=>{}),ae(c,"a watch response that is not a Connect stream");L=te(U.body,{provider:"e2b",sandboxId:c,signal:h.signal});for await(let J of L){if(J.kind==="end"){if(J.error)throw ge({code:J.error.code,method:"filesystem.Filesystem/WatchDir",sandboxId:c,file:!0});continue}let K=D(J.message)?J.message.filesystem:void 0;if(!D(K))continue;let q=O(K.type)?je.get(K.type):void 0;if(q&&O(K.name))h.onEvent({name:K.name,type:q})}}catch(U){if(h.signal.aborted)return;throw U}finally{await L?.return()}if(!h.signal.aborted)throw new e("The E2B watch stream ended. The watch stopped; start it again.",{code:"unavailable",provider:"e2b",sandboxId:c})}},process:{async start(c,m){let{envdVersion:h}=g(c);if(!m.stdin&&!oe(h,ie.stdinFlag))throw new e(`envd ${h.slice(0,16)} always opens stdin. Rebuild the template to pick up a newer envd.`,{code:"unsupported",provider:"e2b",sandboxId:c});let l=`sandbox-sdk-${crypto.randomUUID()}`,E={process:{cmd:"/bin/bash",args:["-l","-c",m.command],envs:m.envs??{},cwd:m.cwd},stdin:m.stdin,tag:l};return F(c,"Start",E,{...m,tag:l,headers:_(m.user)})},async terminal(c,m){let h=`sandbox-sdk-${crypto.randomUUID()}`,l={process:{cmd:"/bin/bash",args:["-i","-l"],envs:m.envs,cwd:m.cwd},pty:{size:{cols:m.cols,rows:m.rows}},tag:h};return F(c,"Start",l,{timeoutMs:0,tag:h,abandon:m.abandon,onPty:m.onPty,headers:_(m.user)})},connect(c,m){return F(c,"Connect",{process:{pid:m}},{timeoutMs:0})},async list(c){let m=await C(c,"process.Process/List",{},{readOnly:!0});return(D(m)&&Array.isArray(m.processes)?m.processes:[]).filter(D).flatMap((l)=>{let E=Ee(l.pid);return E===void 0?[]:[{pid:E,tag:O(l.tag)?l.tag:void 0}]})},signal:A}}}var ye="sandbox-sdk-key",Q="/tmp/.sandbox-sdk-workspace-ready",xe="sandbox-sdk-deadline",Re=49983,Ge=new Set(["e2b.app","e2b.dev","e2b.pro","e2b-staging.dev"]),fe=(r)=>`'${r.replace(/'/g,`'"'"'`)}'`,ke=`[ -e ${Q} ] || { flock -x 9 && { [ -e ${Q} ] || { mkdir -p /workspace && printf ready > ${Q}; }; }; } 9>${Q}.lock || exit 125`,pe=(r)=>r instanceof e&&r.code==="file_not_found",De=(r)=>new Promise((u)=>setTimeout(u,r)),Pe=(r)=>Math.ceil(r/1000),we=(r)=>new e(`${r}. E2B cannot enforce this option. Choose a compatible template or omit the option.`,{code:"unsupported",provider:"e2b"}),Ne=(r)=>Array.isArray(r)?r.filter((u)=>O(u)):void 0,Je=1000,We=1800000,Ye=65536,He={create:"added",write:"modified",chmod:"modified",remove:"removed",rename:"removed"},Xe=(r)=>{let u=O(r)&&/^-?\d+(\.\d+)?$/.test(r)?Number(r):r;return he(u)&&Number.isFinite(u)?u:void 0};function Ze(r){if(!D(r)||!O(r.timestamp))return;let u=Date.parse(r.timestamp),g=(I)=>Xe(r[I])??0;if(!Number.isFinite(u))return;return{timestamp:u,cpuCount:g("cpuCount"),cpuUsedPct:g("cpuUsedPct"),memUsed:g("memUsed"),memTotal:g("memTotal"),diskUsed:g("diskUsed"),diskTotal:g("diskTotal")}}function Qe(r){let u=[],g=Object.entries(r.env??{});if(g.length)u.push({type:"ENV",args:g.flat(),force:!1});if(r.workdir!==void 0)u.push({type:"WORKDIR",args:[r.workdir],force:!1});for(let I of r.run??[])u.push({type:"RUN",args:[I,"root"],force:!1});return u}var Le=(r)=>({path:r.path,type:r.type==="dir"?"directory":r.type,size:r.size,modifiedAt:r.modifiedTime??0});function Z(r,u){return new e(`E2B returned ${r}. Check the E2B service, then retry.`,{code:"provider",provider:"e2b",sandboxId:u})}function Fe(r){if(!D(r)||!O(r.sandboxID)||!r.sandboxID)throw Z("a sandbox without an ID");let u=D(r.metadata)?Object.fromEntries(Object.entries(r.metadata).filter((_)=>typeof _[1]==="string")):{},g=O(r.startedAt)?Date.parse(r.startedAt):Number.NaN,I=D(r.network)?r.network:void 0;return{id:r.sandboxID,metadata:u,state:r.state==="paused"?"paused":"running",startedAt:Number.isFinite(g)?g:0,allowInternetAccess:Te(r.allowInternetAccess)?r.allowInternetAccess:void 0,network:I?{allowOut:Ne(I.allowOut),denyOut:Ne(I.denyOut),allowPublicTraffic:Te(I.allowPublicTraffic)?I.allowPublicTraffic:void 0}:void 0}}var Ve=(r)=>({id:r.id,key:r.metadata[ye],labels:Object.fromEntries(Object.entries(r.metadata).filter(([u])=>![ye,xe].includes(u))),state:r.state,createdAt:r.startedAt});function pt(r={}){let u=()=>r.domain??(process.env.E2B_DOMAIN||"e2b.app"),g=()=>{let t=r.apiKey??process.env.E2B_API_KEY;if(!t?.trim())throw new e("E2B API key is missing. Authentication is required. Set E2B_API_KEY or pass apiKey.",{code:"auth",provider:"e2b"});return t},I=r.requestTimeoutMs??60000,_=new Map;function C(t){let n=_.get(t);if(!n)throw new e("Sandbox is detached. No local client exists. Connect first.",{code:"not_found",provider:"e2b",sandboxId:t});return n}let A=v({provider:"e2b",label:"E2B",defaultPlane:"api",timeoutMs:I,mapError:Ae,authHint:"Check E2B_API_KEY and the E2B domain.",secrets:()=>[r.apiKey,process.env.E2B_API_KEY,...[..._.values()].flatMap((t)=>[t.envdAccessToken,t.trafficAccessToken])],planes:{api:{baseUrl:()=>process.env.E2B_API_URL||`https://api.${u()}`,auth:()=>({"x-api-key":g()})},envd:{headers:{"connect-protocol-version":"1"},baseUrl:({sandboxId:t})=>{if(t===void 0)throw new e("The envd plane belongs to one sandbox. Use box.native, not provider.api.",{code:"invalid_argument",provider:"e2b"});let{domain:n}=C(t);return process.env.E2B_SANDBOX_URL||(Ge.has(n)?`https://sandbox.${n}`:`https://${Re}-${t}.${n}`)},auth:({sandboxId:t})=>{let{envdAccessToken:n}=C(t??""),s={"e2b-sandbox-id":t??"","e2b-sandbox-port":String(Re)};return n?{...s,"x-access-token":n}:s}}}}),F=$e({http:A,connection:C,startupTimeoutMs:I}),c={idempotencyKey:"replayable",readOnly:!0};function m(t){if(!D(t)||!O(t.sandboxID)||!t.sandboxID||!O(t.envdVersion))throw Z("a sandbox connection without an ID or envd version");let n=(x)=>{let k=t[x];return O(k)&&k?k:void 0},s=n("envdAccessToken"),o=n("trafficAccessToken");return{sandboxId:t.sandboxID,envdVersion:t.envdVersion,envdAccessToken:s,trafficAccessToken:o,domain:n("domain")??u()}}let h={async info(t){return Fe(await A.json({method:"GET",path:"/sandboxes/{id}",params:{id:t},sandboxId:t}))},async connect(t,n){return m(await A.json({method:"POST",path:"/v2/sandboxes/{id}/connect",params:{id:t},sandboxId:t,body:n===void 0?{}:{timeout:Pe(n)},...c}))},async setTimeout(t,n){await A.request({method:"POST",path:"/sandboxes/{id}/timeout",params:{id:t},sandboxId:t,body:{timeout:Pe(n)},...c})},async kill(t){try{return await A.request({method:"DELETE",path:"/sandboxes/{id}",params:{id:t},sandboxId:t}),!0}catch(n){if(n instanceof e&&n.code==="not_found")return!1;throw n}},async list(t){let n=new URLSearchParams(Object.fromEntries(Object.entries(t).map(([o,x])=>[encodeURIComponent(o),encodeURIComponent(x)]))).toString(),s=[];for(let o,x=0;x<1000;x++){let k=await A.request({method:"GET",path:"/v2/sandboxes",query:{metadata:n,state:"running,paused",nextToken:o}}),y=k.json();if(!Array.isArray(y))throw Z("a sandbox list that is not an array");if(s.push(...y.map(Fe)),o=k.headers.get("x-next-token")||void 0,o===void 0)return s}throw Z("more than 1000 pages of sandboxes")}},l=new Map,E=new Map,L=new Map,U=new Map;function J(t){if(U.has(t))return;let n=()=>{},s=new Promise((o)=>{n=o});U.set(t,{wait:s,release:n})}function K(t){U.get(t)?.release(),U.delete(t)}let q=new Map;function le(t){for(let n of q.get(t)??[])n.disconnect();q.delete(t)}async function T(t,n){try{return await n()}catch(s){throw Me(s,t)}}let ee=(t,n)=>F.fs.stat(t,n,"root");async function W(t){let n=await h.info(t),s=Number(n.metadata[xe]);if(Number.isFinite(s)&&s>0){if(l.set(t,s),s<=Date.now())throw await h.kill(t),new e("Sandbox lifetime expired. Its hard deadline passed. Create another sandbox.",{code:"not_found",provider:"e2b",sandboxId:t})}_.set(t,await h.connect(t,l.has(t)?Math.max(1,(l.get(t)??0)-Date.now()):void 0));try{await ee(t,"/workspace"),await F.files.write(t,[{path:Q,data:"ready"}],"root"),E.delete(t)}catch(o){if(!pe(o))throw o;try{await ee(t,Q),E.delete(t)}catch(x){if(!pe(x))throw x;E.set(t,n.startedAt)}}if(l.has(t))await h.setTimeout(t,Math.max(1,(l.get(t)??0)-Date.now()));return K(t),{...n,state:"running"}}async function V(t){if(!_.has(t))await W(t);C(t)}async function Y(t){if(!E.has(t))return;try{await ee(t,Q),E.delete(t)}catch(n){if(!pe(n))throw n}}async function X(t,n){if(!E.has(t))return;let s=await j(t,ke);if(s!==0)throw new e(`Preparing /workspace for ${n} failed with exit code ${s}.`,{code:"provider",provider:"e2b",sandboxId:t});E.delete(t)}async function ce(t,n={}){let s=await A.json({method:"GET",path:"/sandboxes/{id}/metrics",params:{id:t},sandboxId:t,query:{start:n.startMs===void 0?void 0:Math.floor(n.startMs/1000),end:n.endMs===void 0?void 0:Math.ceil(n.endMs/1000)}});if(!Array.isArray(s))throw Z("metrics that are not an array",t);let o=n.startMs??Number.NEGATIVE_INFINITY,x=n.endMs??Number.POSITIVE_INFINITY;return s.flatMap((k)=>{let y=Ze(k);return y&&y.timestamp>=o&&y.timestamp<=x?[y]:[]}).sort((k,y)=>k.timestamp-y.timestamp)}async function be(t,n){await V(t);let s=n.cwd??"/workspace";if(s==="/workspace"||s.startsWith("/workspace/"))await X(t,"the terminal");let o=new Set,x=[],k=0,y=await F.process.terminal(t,{cols:n.cols,rows:n.rows,cwd:s,envs:{TERM:"xterm-256color",LANG:"C.UTF-8",LC_ALL:"C.UTF-8",...n.env},user:"root",abandon:(p)=>G(t,p),onPty(p){if(o.size){for(let M of o)M(p);return}x.push(p),k+=p.length;while(k>Ye&&x.length>1)k-=x.shift()?.length??0}}),N=q.get(t)??new Set;q.set(t,N),N.add(y);let B=y.wait().finally(()=>N.delete(y));return B.catch(()=>{}),{write:(p)=>T(t,()=>y.sendPty(p)),resize:(p,M)=>T(t,()=>y.resize(p,M)),onData(p){o.add(p);for(let M of x.splice(0))p(M);return k=0,()=>{o.delete(p)}},close:()=>T(t,async()=>{try{if(await j(t,`pkill -KILL -s ${y.pid} 2>/dev/null || kill -KILL -- -${y.pid} 2>/dev/null; true`,1e4).catch(()=>{}),y.exitCode===void 0)await y.kill();await Promise.race([B.catch(()=>{}),De(5000)])}finally{y.disconnect(),N.delete(y),o.clear()}}),wait:()=>T(t,async()=>{let p=await B;return{exitCode:p>=0?p:null}})}}async function P(t,n){if(t.image!==void 0&&t.fromTemplate!==void 0)throw new e("Pass image or fromTemplate, not both.",{code:"invalid_argument",provider:"e2b"});if(t.readyCommand!==void 0&&t.startCommand===void 0)throw new e("readyCommand needs startCommand. Add the command to wait for.",{code:"invalid_argument",provider:"e2b"});let s=f(n.timeoutMs??We,n.signal),o=await A.json({method:"POST",path:"/v3/templates",deadline:s,body:{name:t.name,tags:t.tags,cpuCount:t.size?.cpu,memoryMB:t.size?.memoryMb}});if(!D(o)||!O(o.templateID)||!O(o.buildID))throw Z("a template build without template and build IDs");let{templateID:x,buildID:k}=o,y={templateID:x,buildID:k},N=(B)=>{if(!(B instanceof e)||!["timeout","aborted","outcome_unknown"].includes(B.code))return B;return new e(`Stopped waiting for E2B template build ${k} of ${x}. The build may still finish on E2B. Check its status, or delete the template.`,{code:B.code,provider:"e2b",cause:B})};try{await A.request({method:"POST",path:"/v2/templates/{templateID}/builds/{buildID}",params:y,deadline:s,body:{...t.fromTemplate===void 0?{fromImage:t.image??"e2bdev/base"}:{fromTemplate:t.fromTemplate},steps:Qe(t),startCmd:t.startCommand,readyCmd:t.readyCommand,force:t.skipCache===!0}});for(let B=0;;){let p=await A.json({method:"GET",path:"/templates/{templateID}/builds/{buildID}/status",params:y,query:{logsOffset:B},deadline:s});if(!D(p)||!O(p.status))throw Z("a template build status without a state");let M=Array.isArray(p.logEntries)?p.logEntries:[];B+=M.length;for(let re of M)if(D(re)&&O(re.message))n.onLog?.(re.message);if((p.status==="ready"||p.status==="error")&&M.length===0){if(p.status==="ready")return{id:x,name:t.name,buildId:k};let re=D(p.reason)?p.reason:void 0,Ie=O(re?.step)&&/^[\w-]{1,32}$/.test(re.step)?re.step:void 0;throw new e(`E2B template build ${k} failed${Ie===void 0?"":` at step ${Ie}`}. The build logs passed to onLog say why. Fix the step and build again.`,{code:"provider",provider:"e2b"})}if(p.status!=="ready"&&p.status!=="error")await w(Je,s,"e2b")}}catch(B){throw N(B)}}async function R(t){return(await h.list({...t,"sandbox-sdk":"1"})).map(Ve)}async function j(t,n,s=60000){return(await F.process.start(t,{command:n,cwd:"/",user:"root",stdin:!1,timeoutMs:s,abandon:(o)=>G(t,o)})).wait()}async function H(t,n,s){await j(t,`kill -${s} -- -${n} 2>/dev/null || true`,1e4)}async function G(t,n){let s=(await F.process.list(t)).find((o)=>o.tag===n);if(s){await F.process.signal(t,{pid:s.pid},"SIGNAL_SIGKILL").catch((o)=>{if(!(o instanceof e&&o.code==="not_found"))throw o}),await H(t,s.pid,"KILL");return}await F.process.signal(t,{tag:n},"SIGNAL_SIGKILL").catch((o)=>{if(!(o instanceof e&&o.code==="not_found"))throw o})}async function me(t,n,s){await V(t);let o=E.has(t),x=`${o?`${ke}; `:""}cd ${fe(n.cwd)} && exec sh -c ${fe(n.command)}`,k=`set -- "$(</proc/$$/stat)" || exit 125; set -- \${1##*) }; [[ "$3" =~ ^[0-9]+$ ]] || exit 125; if [[ "$3" = "$$" ]]; then exec sh -c ${fe(x)}; else exec setsid -w sh -c ${fe(x)}; fi`,y=await F.process.start(t,{command:k,cwd:"/",envs:n.env,user:"root",stdin:n.stdin!==void 0,timeoutMs:0,signal:s,onStdout:(p)=>n.onChunk({stream:"stdout",text:p}),onStderr:(p)=>n.onChunk({stream:"stderr",text:p}),abandon:(p)=>G(t,p)}),N=q.get(t)??new Set;q.set(t,N),N.add(y);let B=y.wait().then((p)=>({exitCode:p,signal:null}));B.catch(()=>{});try{if(n.stdin!==void 0)try{await y.sendStdin(n.stdin),await y.closeStdin()}catch(M){if(y.exitCode===void 0)throw M}let p=B.then(async(M)=>{if(o)if(M.exitCode>=0&&M.exitCode<128&&M.exitCode!==125)E.delete(t);else await Y(t);return M}).finally(()=>N.delete(y));return p.catch(()=>{}),{handle:y,pid:y.pid,result:p}}catch(p){throw await ue.destroy(t),p}}let Se={package:"e2b",connect(t,n){let s={apiKey:g(),domain:u(),requestTimeoutMs:I};if(n===void 0)return S(t,"E2B",[s],"e2b");let{envdVersion:o,envdAccessToken:x,trafficAccessToken:k,domain:y}=C(n);return S(t,"Sandbox",[{...s,sandboxId:n,sandboxDomain:y,envdVersion:o,envdAccessToken:x,trafficAccessToken:k}],"e2b")}},ue={name:"e2b",keyMode:"best-effort",capabilities:new Set(["pause","snapshot","snapshot-delete","templates","terminal","network-policy"]),procActivity:!0,api:b({http:A,placeholder:"sandboxId",sdk:Se}),create:(t)=>T(void 0,async()=>{et(t,r);let n=Date.now(),s=t.timeoutMs===void 0||r.autoPause?void 0:n+t.timeoutMs,o=se(t.network)?t.network.allow:void 0,x=o!==void 0||r.public===!1?{denyOut:o===void 0?void 0:["0.0.0.0/0"],allowOut:o,allowPublicTraffic:r.public===!1?!1:void 0}:void 0,k=m(await A.json({method:"POST",path:"/v2/sandboxes",body:{templateID:t.from??r.template??"base",metadata:{...t.labels,"sandbox-sdk":"1",[ye]:t.key,[xe]:s===void 0?void 0:String(s)},envVars:t.env,timeout:t.timeoutMs===void 0?void 0:Pe(t.timeoutMs),allow_internet_access:t.network==="none"?!1:se(t.network)?void 0:!0,network:x,autoPause:r.autoPause===!0,autoResume:{enabled:r.autoPause===!0&&r.autoResume===!0},volumeMounts:r.volumes===void 0?void 0:Object.entries(r.volumes).map(([N,B])=>({name:B,path:N}))}})),y=k.sandboxId;if(_.set(y,k),s!==void 0)l.set(y,s);try{if(!oe(k.envdVersion,ie.minimum))throw new e("The template's envd is too old for this SDK. Rebuild the template.",{code:"provider",provider:"e2b",sandboxId:y});if(t.signal?.aborted)throw new e("Creation aborted. Cancellation arrived during E2B creation. Retry with a fresh signal.",{code:"aborted",provider:"e2b"});let N=t.network==="none"||se(t.network)||r.public===!1?await h.info(y):void 0;if(t.network==="none"&&N?.allowInternetAccess!==!1&&!(N?.network?.denyOut?.includes("0.0.0.0/0")&&!N?.network.allowOut?.length))throw we("E2B did not confirm that internet access is disabled");if(se(t.network)){let B=t.network.allow,p=N?.network?.allowOut??[];if(!N?.network?.denyOut?.includes("0.0.0.0/0")||B.some((M)=>!p.includes(M))||p.some((M)=>!B.includes(M)))throw we("E2B did not confirm the requested outbound allow list")}if(r.public===!1&&(N?.network?.allowPublicTraffic!==!1||!k.trafficAccessToken))throw we("E2B did not confirm that preview URLs require a traffic access token");if(E.set(y,n),t.from!==void 0)await Y(y);if(t.signal?.aborted)throw new e("Creation aborted during E2B policy confirmation",{code:"aborted",provider:"e2b"});return{id:y,key:t.key,labels:{...t.labels,"sandbox-sdk":"1"},state:"running",createdAt:n}}catch(N){throw await ue.destroy(y),N}}),find:(t)=>T(void 0,async()=>{let n=(await R({[ye]:t}))[0];return n?ue.connect(n.id):void 0}),connect:(t)=>T(t,async()=>Ve(await W(t))),list:(t)=>T(void 0,()=>R(t)),destroy:(t)=>T(t,async()=>{await h.kill(t),_.delete(t),L.delete(t),E.delete(t),l.delete(t),K(t),le(t)}),close:(t)=>T(t,async()=>{J(t),le(t),_.delete(t),L.delete(t)}),native(t){if(!_.has(t))throw new e("Sandbox client is detached. There is no cached native object. Connect the sandbox first.",{code:"not_found",provider:"e2b",sandboxId:t});let n=L.get(t);if(!n)n=b({http:A,placeholder:"sandboxId",sandboxId:t,sdk:Se}),L.set(t,n);return n},exec:(t,n)=>T(t,async()=>{if(n.signal?.aborted)return{exitCode:null,timedOut:!0};let s=Date.now(),o=new AbortController,x=!1,k=()=>{},y=new Promise((B)=>{k=()=>{x=!0,o.abort(),B("cancelled")}});n.signal?.addEventListener("abort",k,{once:!0});let N=setTimeout(k,n.timeoutMs);try{let B;try{B=await me(t,n,o.signal)}catch(M){if(!x)throw M;if(!(M instanceof e&&M.code==="aborted"))await ue.destroy(t);return{exitCode:null,timedOut:!0}}if(n.signal?.aborted||Date.now()-s>=n.timeoutMs)k();let p=x?"cancelled":await Promise.race([B.result,y]);if(p!=="cancelled")return{exitCode:p.exitCode,timedOut:!1};try{await B.handle.kill(),await H(t,B.pid,"KILL")}catch(M){throw await ue.destroy(t),M}return await B.result.catch(()=>{}),B.handle.disconnect(),{exitCode:null,timedOut:!0}}finally{clearTimeout(N),n.signal?.removeEventListener("abort",k)}}),files:{writeCreatesParents:!0,editInGuest:"in-place",listOrder:"name",guestInput:(t)=>T(t,async()=>{await V(t);let{envdVersion:n}=C(t);return oe(n,ie.closeStdin)?"stdin":oe(n,ie.stdinFlag)?"env":"none"}),read:(t,n)=>T(t,async()=>(await V(t),F.files.read(t,n,"root"))),watch:(t,n,s)=>T(t,async()=>{if(await V(t),n==="/workspace"||n.startsWith("/workspace/"))await X(t,"the watch");await F.fs.watch(t,n,{recursive:s.recursive,user:"root",signal:s.signal,onEvent:(o)=>s.onEvent({type:He[o.type],path:de.join(n,o.name)})})}),write:(t,n,s)=>T(t,async()=>{if(await V(t),q.get(t)?.size)await Y(t);if(de.normalize(n)==="/workspace"&&E.has(t))throw new e("Cannot write a file over the workspace directory",{code:"invalid_argument",provider:"e2b",sandboxId:t});if(E.has(t)&&de.normalize(n).startsWith("/workspace/"))await F.files.write(t,[{path:n,data:s},{path:Q,data:"ready"}],"root"),E.delete(t);else await F.files.write(t,[{path:n,data:s}],"root")}),list:(t,n)=>T(t,async()=>{await V(t);try{let s=(await F.fs.list(t,n,"root")).map(Le);if(q.get(t)?.size)await Y(t);let o=E.get(t);if(de.normalize(n)==="/"&&o!==void 0&&!s.some((x)=>x.path==="/workspace"))s.push({path:"/workspace",type:"directory",size:0,modifiedAt:o});return s}catch(s){if(q.get(t)?.size)await Y(t);if(de.normalize(n)==="/workspace"&&E.has(t)&&pe(s))return[];throw s}}),stat:(t,n)=>T(t,async()=>{await V(t);try{return Le(await ee(t,n))}catch(s){if(q.get(t)?.size)await Y(t);let o=E.get(t);if(de.normalize(n)==="/workspace"&&o!==void 0&&pe(s))return{path:n,type:"directory",size:0,modifiedAt:o};throw s}}),mkdir:(t,n)=>T(t,async()=>{if(await V(t),E.has(t)){let s=await j(t,`${ke}; mkdir -p ${fe(n)}`);if(s!==0)throw new e(`Creating the directory failed with exit code ${s}. Check the path and its parents.`,{code:"provider",provider:"e2b",sandboxId:t});E.delete(t)}else await F.fs.mkdir(t,n,"root")}),remove:(t,n,s)=>T(t,async()=>{if(await V(t),de.normalize(n)==="/workspace"&&E.has(t)){let o=await j(t,`${ke}; if [ -L /workspace ]; then rm /workspace; else ${s.recursive?"rm -rf":"rmdir"} /workspace; fi`);if(o!==0){if(!s.recursive)throw new e("Directory is not empty. Pass recursive: true.",{code:"invalid_argument",provider:"e2b",sandboxId:t});throw new e(`Removing /workspace failed with exit code ${o}.`,{code:"provider",provider:"e2b",sandboxId:t})}E.delete(t);return}if(!s.recursive&&(await ee(t,n)).type==="dir"&&(await F.fs.list(t,n,"root")).length)throw new e("Directory is not empty. Recursive removal was not requested. Pass recursive: true.",{code:"invalid_argument",provider:"e2b",sandboxId:t});await F.fs.remove(t,n,"root")})},previewUrl:(t,n)=>T(t,async()=>{await V(t);let{domain:s,trafficAccessToken:o}=C(t),x=`https://${n}-${t}.${s}`;if(r.public!==!1)return{url:x};if(!o)throw new e("Preview access token is missing. E2B returned no traffic access token for this private sandbox. Reconnect, or create it with public previews.",{code:"unsupported",provider:"e2b",sandboxId:t});return{url:x,headers:{"e2b-traffic-access-token":o}}}),pause:(t)=>T(t,async()=>{J(t);try{try{await A.request({method:"POST",path:"/sandboxes/{id}/pause",params:{id:t},sandboxId:t,body:{},...c})}catch(n){if(!(n instanceof e&&/\(HTTP 409\b/.test(n.message)))throw n}_.delete(t),L.delete(t),le(t)}catch(n){throw K(t),n}}),resume:(t)=>T(t,async()=>{await W(t)}),snapshot:(t,n)=>T(t,async()=>{if(n?.expiresInMs)throw new e("Snapshot expiry is unavailable. E2B keeps snapshots until you delete them. Omit expiresInMs, or pass 0.",{code:"unsupported",provider:"e2b",sandboxId:t});await V(t),await X(t,"the snapshot");let s=await A.json({method:"POST",path:"/sandboxes/{id}/snapshots",params:{id:t},sandboxId:t,body:{}});if(!D(s)||!O(s.snapshotID)||!s.snapshotID)throw Z("a snapshot without an ID",t);return{id:s.snapshotID}}),deleteSnapshot:(t)=>T(void 0,async()=>{try{return await A.request({method:"DELETE",path:"/templates/{id}",params:{id:t}}),!0}catch(n){if(n instanceof e&&n.code==="not_found")return!1;throw n}}),buildTemplate:(t,n)=>T(void 0,()=>P(t,n)),terminal:(t,n)=>T(t,()=>be(t,n)),usage:(t)=>T(t,async()=>{let n=(await ce(t).catch(()=>[])).at(-1);if(!n)return{};return{cpuCount:n.cpuCount,cpuPercent:n.cpuUsedPct,memoryBytes:n.memUsed,memoryLimitBytes:n.memTotal,diskBytes:n.diskUsed,diskLimitBytes:n.diskTotal,metricsAt:n.timestamp}}),extensions:{e2b:(t)=>({metrics:(n)=>T(t,()=>ce(t,n))})},startProcess:(t,n)=>T(t,async()=>{let s=await me(t,n),o=!1,x=(k)=>({exitCode:k>=0?k:o?143:null,signal:null});return{pid:s.pid,wait:()=>T(t,async()=>{try{return x((await s.result).exitCode)}catch{}return await U.get(t)?.wait,await V(t),x(await(await F.process.connect(t,s.pid)).wait())}),stop:(k)=>T(t,async()=>{o=!0,await H(t,s.pid,"TERM"),await De(k.graceMs),await s.handle.kill(),await H(t,s.pid,"KILL")})}})};return ue}function et(r,u){if(u.autoResume&&!u.autoPause)throw new e("autoResume requires autoPause. E2B can only wake a sandbox it paused. Set autoPause: true or drop autoResume.",{code:"invalid_argument",provider:"e2b"});if(r.size!==void 0)throw we("Machine size is fixed by the E2B template; small, medium, large and custom sizes are unavailable at creation");if(r.idleTimeoutMs!==void 0)throw we("E2B timeouts measure elapsed time, not idle time; idleTimeoutMs is unavailable");if(r.labels[ye]!==void 0||r.labels[xe]!==void 0)throw new e("Reserved E2B metadata key. SDK lifecycle metadata must not be overwritten. Rename the label.",{code:"invalid_argument",provider:"e2b"})}export{pt as e2b};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { JsonObject, JsonValue } from "../../provider.js";
|
|
2
|
+
export declare const isString: (value: unknown) => value is string;
|
|
3
|
+
export declare const isNumber: (value: unknown) => value is number;
|
|
4
|
+
export declare const isBoolean: (value: unknown) => value is boolean;
|
|
5
|
+
/** A non-null object, so `"key" in value` narrows its properties. */
|
|
6
|
+
export declare const isObject: (value: unknown) => value is object;
|
|
7
|
+
export declare const isRecord: (value: JsonValue | undefined) => value is JsonObject;
|