@e2b/cli 0.4.3-post-connection.4 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +201 -0
  2. package/dist/index.js +6 -6
  3. package/package.json +9 -10
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 FoundryLabs, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.js CHANGED
@@ -68,7 +68,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),Be=k,N=X);let se={code
68
68
  `:`
69
69
  `.charCodeAt(),n=typeof e=="string"?"\r":"\r".charCodeAt();return e[e.length-1]===t&&(e=e.slice(0,e.length-1)),e[e.length-1]===n&&(e=e.slice(0,e.length-1)),e}});var Dy=E((Yse,Fa)=>{"use strict";l();var Pa=require("path"),Ty=Fd(),by=e=>{e={cwd:process.cwd(),path:process.env[Ty()],execPath:process.execPath,...e};let t,n=Pa.resolve(e.cwd),r=[];for(;t!==n;)r.push(Pa.join(n,"node_modules/.bin")),t=n,n=Pa.resolve(n,"..");let i=Pa.resolve(e.cwd,e.execPath,"..");return r.push(i),r.concat(e.path).join(Pa.delimiter)};Fa.exports=by;Fa.exports.default=by;Fa.exports.env=e=>{e={env:process.env,...e};let t={...e.env},n=Ty({env:t});return e.path=t[n],t[n]=Fa.exports(e),t}});var Ry=E(($se,Vd)=>{"use strict";l();var Cy=(e,t)=>{for(let n of Reflect.ownKeys(t))Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n));return e};Vd.exports=Cy;Vd.exports.default=Cy});var Ay=E((Kse,Sl)=>{"use strict";l();var FH=Ry(),gl=new WeakMap,Oy=(e,t={})=>{if(typeof e!="function")throw new TypeError("Expected a function");let n,r=0,i=e.displayName||e.name||"<anonymous>",a=function(...s){if(gl.set(a,++r),r===1)n=e.apply(this,s),e=null;else if(t.throw===!0)throw new Error(`Function \`${i}\` can only be called once`);return n};return FH(a,e),gl.set(a,r),a};Sl.exports=Oy;Sl.exports.default=Oy;Sl.exports.callCount=e=>{if(!gl.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return gl.get(e)}});var Ny=E(hl=>{"use strict";l();Object.defineProperty(hl,"__esModule",{value:!0});hl.SIGNALS=void 0;var kH=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",standard:"other"},{name:"SIGTTOU",number:22,action:"pause",description:"Background process cannot write to terminal output",standard:"posix"},{name:"SIGURG",number:23,action:"ignore",description:"Socket received out-of-band data",standard:"bsd"},{name:"SIGXCPU",number:24,action:"core",description:"Process timed out",standard:"bsd"},{name:"SIGXFSZ",number:25,action:"core",description:"File too big",standard:"bsd"},{name:"SIGVTALRM",number:26,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGPROF",number:27,action:"terminate",description:"Timeout or timer",standard:"bsd"},{name:"SIGWINCH",number:28,action:"ignore",description:"Terminal window size changed",standard:"bsd"},{name:"SIGIO",number:29,action:"terminate",description:"I/O is available",standard:"other"},{name:"SIGPOLL",number:29,action:"terminate",description:"Watched event",standard:"other"},{name:"SIGINFO",number:29,action:"ignore",description:"Request for process information",standard:"other"},{name:"SIGPWR",number:30,action:"terminate",description:"Device running out of power",standard:"systemv"},{name:"SIGSYS",number:31,action:"core",description:"Invalid system call",standard:"other"},{name:"SIGUNUSED",number:31,action:"terminate",description:"Invalid system call",standard:"other"}];hl.SIGNALS=kH});var Kd=E(Di=>{"use strict";l();Object.defineProperty(Di,"__esModule",{value:!0});Di.SIGRTMAX=Di.getRealtimeSignals=void 0;var BH=function(){let e=yy-Iy+1;return Array.from({length:e},UH)};Di.getRealtimeSignals=BH;var UH=function(e,t){return{name:`SIGRT${t+1}`,number:Iy+t,action:"terminate",description:"Application-specific signal (realtime)",standard:"posix"}},Iy=34,yy=64;Di.SIGRTMAX=yy});var vy=E(Tl=>{"use strict";l();Object.defineProperty(Tl,"__esModule",{value:!0});Tl.getSignals=void 0;var GH=require("os"),HH=Ny(),YH=Kd(),qH=function(){let e=(0,YH.getRealtimeSignals)();return[...HH.SIGNALS,...e].map($H)};Tl.getSignals=qH;var $H=function({name:e,number:t,description:n,action:r,forced:i=!1,standard:a}){let{signals:{[e]:s}}=GH.constants,o=s!==void 0;return{name:e,number:o?s:t,description:n,supported:o,action:r,forced:i,standard:a}}});var My=E(Ci=>{"use strict";l();Object.defineProperty(Ci,"__esModule",{value:!0});Ci.signalsByNumber=Ci.signalsByName=void 0;var VH=require("os"),xy=vy(),KH=Kd(),WH=function(){return(0,xy.getSignals)().reduce(zH,{})},zH=function(e,{name:t,number:n,description:r,supported:i,action:a,forced:s,standard:o}){return{...e,[t]:{name:t,number:n,description:r,supported:i,action:a,forced:s,standard:o}}},QH=WH();Ci.signalsByName=QH;var XH=function(){let e=(0,xy.getSignals)(),t=KH.SIGRTMAX+1,n=Array.from({length:t},(r,i)=>jH(i,e));return Object.assign({},...n)},jH=function(e,t){let n=ZH(e,t);if(n===void 0)return{};let{name:r,description:i,supported:a,action:s,forced:o,standard:c}=n;return{[e]:{name:r,number:e,description:i,supported:a,action:s,forced:o,standard:c}}},ZH=function(e,t){let n=t.find(({name:r})=>VH.constants.signals[r]===e);return n!==void 0?n:t.find(r=>r.number===e)},JH=XH();Ci.signalsByNumber=JH});var wy=E((noe,Ly)=>{"use strict";l();var{signalsByName:eY}=My(),tY=({timedOut:e,timeout:t,errorCode:n,signal:r,signalDescription:i,exitCode:a,isCanceled:s})=>e?`timed out after ${t} milliseconds`:s?"was canceled":n!==void 0?`failed with ${n}`:r!==void 0?`was killed with ${r} (${i})`:a!==void 0?`failed with exit code ${a}`:"failed",nY=({stdout:e,stderr:t,all:n,error:r,signal:i,exitCode:a,command:s,escapedCommand:o,timedOut:c,isCanceled:u,killed:_,parsed:{options:{timeout:m}}})=>{a=a===null?void 0:a,i=i===null?void 0:i;let g=i===void 0?void 0:eY[i].description,C=r&&r.code,A=`Command ${tY({timedOut:c,timeout:m,errorCode:C,signal:i,signalDescription:g,exitCode:a,isCanceled:u})}: ${s}`,x=Object.prototype.toString.call(r)==="[object Error]",P=x?`${A}
70
70
  ${r.message}`:A,B=[P,t,e].filter(Boolean).join(`
71
- `);return x?(r.originalMessage=r.message,r.message=B):r=new Error(B),r.shortMessage=P,r.command=s,r.escapedCommand=o,r.exitCode=a,r.signal=i,r.signalDescription=g,r.stdout=e,r.stderr=t,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!c,r.isCanceled=u,r.killed=_&&!c,r};Ly.exports=nY});var Fy=E((ioe,Wd)=>{"use strict";l();var bl=["stdin","stdout","stderr"],rY=e=>bl.some(t=>e[t]!==void 0),Py=e=>{if(!e)return;let{stdio:t}=e;if(t===void 0)return bl.map(r=>e[r]);if(rY(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${bl.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);let n=Math.max(t.length,bl.length);return Array.from({length:n},(r,i)=>t[i])};Wd.exports=Py;Wd.exports.node=e=>{let t=Py(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]}});var ky=E((soe,Dl)=>{"use strict";l();Dl.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&Dl.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Dl.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var Xd=E((loe,Ai)=>{"use strict";l();var Fe=global.process,vr=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};vr(Fe)?(By=require("assert"),Ri=ky(),Uy=/^win/i.test(Fe.platform),ka=require("events"),typeof ka!="function"&&(ka=ka.EventEmitter),Fe.__signal_exit_emitter__?it=Fe.__signal_exit_emitter__:(it=Fe.__signal_exit_emitter__=new ka,it.count=0,it.emitted={}),it.infinite||(it.setMaxListeners(1/0),it.infinite=!0),Ai.exports=function(e,t){if(!vr(global.process))return function(){};By.equal(typeof e,"function","a callback must be provided for exit handler"),Oi===!1&&zd();var n="exit";t&&t.alwaysLast&&(n="afterexit");var r=function(){it.removeListener(n,e),it.listeners("exit").length===0&&it.listeners("afterexit").length===0&&Cl()};return it.on(n,e),r},Cl=function(){!Oi||!vr(global.process)||(Oi=!1,Ri.forEach(function(t){try{Fe.removeListener(t,Rl[t])}catch{}}),Fe.emit=Ol,Fe.reallyExit=Qd,it.count-=1)},Ai.exports.unload=Cl,xr=function(t,n,r){it.emitted[t]||(it.emitted[t]=!0,it.emit(t,n,r))},Rl={},Ri.forEach(function(e){Rl[e]=function(){if(vr(global.process)){var n=Fe.listeners(e);n.length===it.count&&(Cl(),xr("exit",null,e),xr("afterexit",null,e),Uy&&e==="SIGHUP"&&(e="SIGINT"),Fe.kill(Fe.pid,e))}}}),Ai.exports.signals=function(){return Ri},Oi=!1,zd=function(){Oi||!vr(global.process)||(Oi=!0,it.count+=1,Ri=Ri.filter(function(t){try{return Fe.on(t,Rl[t]),!0}catch{return!1}}),Fe.emit=Hy,Fe.reallyExit=Gy)},Ai.exports.load=zd,Qd=Fe.reallyExit,Gy=function(t){vr(global.process)&&(Fe.exitCode=t||0,xr("exit",Fe.exitCode,null),xr("afterexit",Fe.exitCode,null),Qd.call(Fe,Fe.exitCode))},Ol=Fe.emit,Hy=function(t,n){if(t==="exit"&&vr(global.process)){n!==void 0&&(Fe.exitCode=n);var r=Ol.apply(this,arguments);return xr("exit",Fe.exitCode,null),xr("afterexit",Fe.exitCode,null),r}else return Ol.apply(this,arguments)}):Ai.exports=function(){return function(){}};var By,Ri,Uy,ka,it,Cl,xr,Rl,Oi,zd,Qd,Gy,Ol,Hy});var qy=E((uoe,Yy)=>{"use strict";l();var iY=require("os"),aY=Xd(),sY=1e3*5,oY=(e,t="SIGTERM",n={})=>{let r=e(t);return lY(e,t,n,r),r},lY=(e,t,n,r)=>{if(!cY(t,n,r))return;let i=_Y(n),a=setTimeout(()=>{e("SIGKILL")},i);a.unref&&a.unref()},cY=(e,{forceKillAfterTimeout:t},n)=>uY(e)&&t!==!1&&n,uY=e=>e===iY.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",_Y=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return sY;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},dY=(e,t)=>{e.kill()&&(t.isCanceled=!0)},mY=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},pY=(e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let i,a=new Promise((o,c)=>{i=setTimeout(()=>{mY(e,n,c)},t)}),s=r.finally(()=>{clearTimeout(i)});return Promise.race([a,s])},EY=({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},fY=async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;let i=aY(()=>{e.kill()});return r.finally(()=>{i()})};Yy.exports={spawnedKill:oY,spawnedCancel:dY,setupTimeout:pY,validateTimeout:EY,setExitHandler:fY}});var Vy=E((doe,$y)=>{"use strict";l();var cn=e=>e!==null&&typeof e=="object"&&typeof e.pipe=="function";cn.writable=e=>cn(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object";cn.readable=e=>cn(e)&&e.readable!==!1&&typeof e._read=="function"&&typeof e._readableState=="object";cn.duplex=e=>cn.writable(e)&&cn.readable(e);cn.transform=e=>cn.duplex(e)&&typeof e._transform=="function";$y.exports=cn});var Wy=E((poe,Ky)=>{"use strict";l();var{PassThrough:gY}=require("stream");Ky.exports=e=>{e={...e};let{array:t}=e,{encoding:n}=e,r=n==="buffer",i=!1;t?i=!(n||r):n=n||"utf8",r&&(n=null);let a=new gY({objectMode:i});n&&a.setEncoding(n);let s=0,o=[];return a.on("data",c=>{o.push(c),i?s=o.length:s+=c.length}),a.getBufferedValue=()=>t?o:r?Buffer.concat(o,s):o.join(""),a.getBufferedLength=()=>s,a}});var Zd=E((foe,Ba)=>{"use strict";l();var{constants:SY}=require("buffer"),hY=require("stream"),{promisify:TY}=require("util"),bY=Wy(),DY=TY(hY.pipeline),Al=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function jd(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};let{maxBuffer:n}=t,r=bY(t);return await new Promise((i,a)=>{let s=o=>{o&&r.getBufferedLength()<=SY.MAX_LENGTH&&(o.bufferedData=r.getBufferedValue()),a(o)};(async()=>{try{await DY(e,r),i()}catch(o){s(o)}})(),r.on("data",()=>{r.getBufferedLength()>n&&s(new Al)})}),r.getBufferedValue()}Ba.exports=jd;Ba.exports.buffer=(e,t)=>jd(e,{...t,encoding:"buffer"});Ba.exports.array=(e,t)=>jd(e,{...t,array:!0});Ba.exports.MaxBufferError=Al});var Jd=E((Soe,zy)=>{"use strict";l();var{PassThrough:CY}=require("stream");zy.exports=function(){var e=[],t=new CY({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=r,t.on("unpipe",i),Array.prototype.slice.call(arguments).forEach(n),t;function n(a){return Array.isArray(a)?(a.forEach(n),this):(e.push(a),a.once("end",i.bind(null,a)),a.once("error",t.emit.bind(t,"error")),a.pipe(t,{end:!1}),this)}function r(){return e.length==0}function i(a){e=e.filter(function(s){return s!==a}),!e.length&&t.readable&&t.end()}}});var Zy=E((Toe,jy)=>{"use strict";l();var Xy=Vy(),Qy=Zd(),RY=Jd(),OY=(e,t)=>{t===void 0||e.stdin===void 0||(Xy(t)?t.pipe(e.stdin):e.stdin.end(t))},AY=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;let n=RY();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},em=async(e,t)=>{if(e){e.destroy();try{return await t}catch(n){return n.bufferedData}}},tm=(e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Qy(e,{encoding:t,maxBuffer:r}):Qy.buffer(e,{maxBuffer:r})},NY=async({stdout:e,stderr:t,all:n},{encoding:r,buffer:i,maxBuffer:a},s)=>{let o=tm(e,{encoding:r,buffer:i,maxBuffer:a}),c=tm(t,{encoding:r,buffer:i,maxBuffer:a}),u=tm(n,{encoding:r,buffer:i,maxBuffer:a*2});try{return await Promise.all([s,o,c,u])}catch(_){return Promise.all([{error:_,signal:_.signal,timedOut:_.timedOut},em(e,o),em(t,c),em(n,u)])}},IY=({input:e})=>{if(Xy(e))throw new TypeError("The `input` option cannot be a stream in sync mode")};jy.exports={handleInput:OY,makeAllStream:AY,getSpawnedResult:NY,validateInputSync:IY}});var ev=E((Doe,Jy)=>{"use strict";l();var yY=(async()=>{})().constructor.prototype,vY=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(yY,e)]),xY=(e,t)=>{for(let[n,r]of vY){let i=typeof t=="function"?(...a)=>Reflect.apply(r.value,t(),a):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:i})}return e},MY=e=>new Promise((t,n)=>{e.on("exit",(r,i)=>{t({exitCode:r,signal:i})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})});Jy.exports={mergePromise:xY,getSpawnedPromise:MY}});var rv=E((Roe,nv)=>{"use strict";l();var tv=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],LY=/^[\w.-]+$/,wY=/"/g,PY=e=>typeof e!="string"||LY.test(e)?e:`"${e.replace(wY,'\\"')}"`,FY=(e,t)=>tv(e,t).join(" "),kY=(e,t)=>tv(e,t).map(n=>PY(n)).join(" "),BY=/ +/g,UY=e=>{let t=[];for(let n of e.trim().split(BY)){let r=t[t.length-1];r&&r.endsWith("\\")?t[t.length-1]=`${r.slice(0,-1)} ${n}`:t.push(n)}return t};nv.exports={joinCommand:FY,getEscapedCommand:kY,parseCommand:UY}});var uv=E((Aoe,Ni)=>{"use strict";l();var GY=require("path"),nm=require("child_process"),HY=$d(),YY=hy(),qY=Dy(),$Y=Ay(),Nl=wy(),av=Fy(),{spawnedKill:VY,spawnedCancel:KY,setupTimeout:WY,validateTimeout:zY,setExitHandler:QY}=qy(),{handleInput:XY,getSpawnedResult:jY,makeAllStream:ZY,validateInputSync:JY}=Zy(),{mergePromise:iv,getSpawnedPromise:eq}=ev(),{joinCommand:sv,parseCommand:ov,getEscapedCommand:lv}=rv(),tq=1e3*1e3*100,nq=({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:i})=>{let a=t?{...process.env,...e}:e;return n?qY.env({env:a,cwd:r,execPath:i}):a},cv=(e,t,n={})=>{let r=HY._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:tq,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n},n.env=nq(n),n.stdio=av(n),process.platform==="win32"&&GY.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},Ua=(e,t,n)=>typeof t!="string"&&!Buffer.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?YY(t):t,Il=(e,t,n)=>{let r=cv(e,t,n),i=sv(e,t),a=lv(e,t);zY(r.options);let s;try{s=nm.spawn(r.file,r.args,r.options)}catch(C){let S=new nm.ChildProcess,A=Promise.reject(Nl({error:C,stdout:"",stderr:"",all:"",command:i,escapedCommand:a,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return iv(S,A)}let o=eq(s),c=WY(s,r.options,o),u=QY(s,r.options,c),_={isCanceled:!1};s.kill=VY.bind(null,s.kill.bind(s)),s.cancel=KY.bind(null,s,_);let g=$Y(async()=>{let[{error:C,exitCode:S,signal:A,timedOut:x},P,B,U]=await jY(s,r.options,u),q=Ua(r.options,P),te=Ua(r.options,B),Z=Ua(r.options,U);if(C||S!==0||A!==null){let re=Nl({error:C,exitCode:S,signal:A,stdout:q,stderr:te,all:Z,command:i,escapedCommand:a,parsed:r,timedOut:x,isCanceled:_.isCanceled,killed:s.killed});if(!r.options.reject)return re;throw re}return{command:i,escapedCommand:a,exitCode:0,stdout:q,stderr:te,all:Z,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return XY(s,r.options.input),s.all=ZY(s,r.options),iv(s,g)};Ni.exports=Il;Ni.exports.sync=(e,t,n)=>{let r=cv(e,t,n),i=sv(e,t),a=lv(e,t);JY(r.options);let s;try{s=nm.spawnSync(r.file,r.args,r.options)}catch(u){throw Nl({error:u,stdout:"",stderr:"",all:"",command:i,escapedCommand:a,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}let o=Ua(r.options,s.stdout,s.error),c=Ua(r.options,s.stderr,s.error);if(s.error||s.status!==0||s.signal!==null){let u=Nl({stdout:o,stderr:c,error:s.error,signal:s.signal,exitCode:s.status,command:i,escapedCommand:a,parsed:r,timedOut:s.error&&s.error.code==="ETIMEDOUT",isCanceled:!1,killed:s.signal!==null});if(!r.options.reject)return u;throw u}return{command:i,escapedCommand:a,exitCode:0,stdout:o,stderr:c,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}};Ni.exports.command=(e,t)=>{let[n,...r]=ov(e);return Il(n,r,t)};Ni.exports.commandSync=(e,t)=>{let[n,...r]=ov(e);return Il.sync(n,r,t)};Ni.exports.node=(e,t,n={})=>{t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);let r=av.node(n),i=process.execArgv.filter(o=>!o.startsWith("--inspect")),{nodePath:a=process.execPath,nodeOptions:s=i}=n;return Il(a,[...s,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:r,shell:!1})}});var Qq={};Vl(Qq,{pkg:()=>Yl});module.exports=LM(Qq);l();var hx=J(require("update-notifier"));var Kl={};Vl(Kl,{author:()=>UM,bin:()=>WM,bugs:()=>GM,default:()=>XM,dependencies:()=>zM,description:()=>FM,devDependencies:()=>VM,engines:()=>QM,files:()=>KM,homepage:()=>kM,license:()=>BM,name:()=>PM,publishConfig:()=>YM,repository:()=>HM,scripts:()=>$M,sideEffects:()=>qM,version:()=>Wl});var PM="@e2b/cli",Wl="0.4.3-post-connection.4",FM="CLI for managing e2b sandbox templates",kM="https://e2b.dev",BM="MIT",UM={name:"FoundryLabs, Inc.",email:"hello@e2b.dev",url:"https://e2b.dev"},GM="https://github.com/e2b-dev/e2b/issues",HM={type:"git",url:"https://github.com/e2b-dev/e2b",directory:"packages/cli"},YM={access:"public"},qM=!1,$M={prepublishOnly:"pnpm build",build:"tsc --noEmit --skipLibCheck && tsup --minify",dev:"tsup --watch",test:"pnpm build && cd testground/demo-basic && ../../dist/index.js template build","check-deps":"knip","update-deps":"ncu -u && pnpm i"},VM={"@types/command-exists":"^1.2.3","@types/inquirer":"^9.0.7","@types/node":"^18.18.6","@types/update-notifier":"6.0.5",knip:"^2.33.4","npm-check-updates":"^16.14.6",tsup:"^7.2.0",typescript:"^5.2.2",vitest:"^0.34.6"},KM=["dist","LICENSE","README","package.json"],WM={e2b:"dist/index.js"},zM={"@iarna/toml":"^2.2.5","async-listen":"^3.0.1",boxen:"^7.1.1",chalk:"^5.3.0","cli-highlight":"^2.1.11","command-exists":"^1.2.9",commander:"^11.1.0","console-table-printer":"^2.11.2",e2b:"^0.13.0",inquirer:"^9.2.12",open:"^9.1.0","strip-ansi":"^7.1.0","update-notifier":"5.1.0",yup:"^1.3.2"},QM={node:">=18"},XM={name:PM,version:Wl,description:FM,homepage:kM,license:BM,author:UM,bugs:GM,repository:HM,publishConfig:YM,sideEffects:qM,scripts:$M,devDependencies:VM,files:KM,bin:WM,dependencies:zM,engines:QM};l();l();var Zm=J(jm(),1),{program:m$,createCommand:p$,createArgument:E$,createOption:f$,CommanderError:g$,InvalidArgumentError:S$,InvalidOptionArgumentError:h$,Command:Ce,Argument:T$,Option:Mr,Help:b$}=Zm.default;l();l();l();var Jm=(e=0)=>t=>`\x1B[${t+e}m`,ep=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,tp=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,we={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},C$=Object.keys(we.modifier),pL=Object.keys(we.color),EL=Object.keys(we.bgColor),R$=[...pL,...EL];function fL(){let e=new Map;for(let[t,n]of Object.entries(we)){for(let[r,i]of Object.entries(n))we[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=we[r],e.set(i[0],i[1]);Object.defineProperty(we,t,{value:n,enumerable:!1})}return Object.defineProperty(we,"codes",{value:e,enumerable:!1}),we.color.close="\x1B[39m",we.bgColor.close="\x1B[49m",we.color.ansi=Jm(),we.color.ansi256=ep(),we.color.ansi16m=tp(),we.bgColor.ansi=Jm(10),we.bgColor.ansi256=ep(10),we.bgColor.ansi16m=tp(10),Object.defineProperties(we,{rgbToAnsi256:{value(t,n,r){return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(a=>a+a).join(""));let i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>we.rgbToAnsi256(...we.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,i;if(t>=232)n=((t-232)*10+8)/255,r=n,i=n;else{t-=16;let o=t%36;n=Math.floor(t/36)/5,r=Math.floor(o/6)/5,i=o%6/5}let a=Math.max(n,r,i)*2;if(a===0)return 30;let s=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(n));return a===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,n,r)=>we.ansi256ToAnsi(we.rgbToAnsi256(t,n,r)),enumerable:!1},hexToAnsi:{value:t=>we.ansi256ToAnsi(we.hexToAnsi256(t)),enumerable:!1}}),we}var gL=fL(),Ht=gL;l();var Za=J(require("process"),1),rp=J(require("os"),1),oc=J(require("tty"),1);function vt(e,t=globalThis.Deno?globalThis.Deno.args:Za.default.argv){let n=e.startsWith("-")?"":e.length===1?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return r!==-1&&(i===-1||r<i)}var{env:Ue}=Za.default,ja;vt("no-color")||vt("no-colors")||vt("color=false")||vt("color=never")?ja=0:(vt("color")||vt("colors")||vt("color=true")||vt("color=always"))&&(ja=1);function SL(){if("FORCE_COLOR"in Ue)return Ue.FORCE_COLOR==="true"?1:Ue.FORCE_COLOR==="false"?0:Ue.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Ue.FORCE_COLOR,10),3)}function hL(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function TL(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=SL();r!==void 0&&(ja=r);let i=n?ja:r;if(i===0)return 0;if(n){if(vt("color=16m")||vt("color=full")||vt("color=truecolor"))return 3;if(vt("color=256"))return 2}if("TF_BUILD"in Ue&&"AGENT_NAME"in Ue)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Ue.TERM==="dumb")return a;if(Za.default.platform==="win32"){let s=rp.default.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in Ue)return"GITHUB_ACTIONS"in Ue||"GITEA_ACTIONS"in Ue?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(s=>s in Ue)||Ue.CI_NAME==="codeship"?1:a;if("TEAMCITY_VERSION"in Ue)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ue.TEAMCITY_VERSION)?1:0;if(Ue.COLORTERM==="truecolor"||Ue.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in Ue){let s=Number.parseInt((Ue.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ue.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ue.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ue.TERM)||"COLORTERM"in Ue?1:a}function np(e,t={}){let n=TL(e,{streamIsTTY:e&&e.isTTY,...t});return hL(n)}var bL={stdout:np({isTTY:oc.default.isatty(1)}),stderr:np({isTTY:oc.default.isatty(2)})},ip=bL;l();function ap(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,s="";do s+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return s+=e.slice(a),s}function sp(e,t,n,r){let i=0,a="";do{let s=e[r-1]==="\r";a+=e.slice(i,s?r-1:r)+t+(s?`\r
71
+ `);return x?(r.originalMessage=r.message,r.message=B):r=new Error(B),r.shortMessage=P,r.command=s,r.escapedCommand=o,r.exitCode=a,r.signal=i,r.signalDescription=g,r.stdout=e,r.stderr=t,n!==void 0&&(r.all=n),"bufferedData"in r&&delete r.bufferedData,r.failed=!0,r.timedOut=!!c,r.isCanceled=u,r.killed=_&&!c,r};Ly.exports=nY});var Fy=E((ioe,Wd)=>{"use strict";l();var bl=["stdin","stdout","stderr"],rY=e=>bl.some(t=>e[t]!==void 0),Py=e=>{if(!e)return;let{stdio:t}=e;if(t===void 0)return bl.map(r=>e[r]);if(rY(e))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${bl.map(r=>`\`${r}\``).join(", ")}`);if(typeof t=="string")return t;if(!Array.isArray(t))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof t}\``);let n=Math.max(t.length,bl.length);return Array.from({length:n},(r,i)=>t[i])};Wd.exports=Py;Wd.exports.node=e=>{let t=Py(e);return t==="ipc"?"ipc":t===void 0||typeof t=="string"?[t,t,t,"ipc"]:t.includes("ipc")?t:[...t,"ipc"]}});var ky=E((soe,Dl)=>{"use strict";l();Dl.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&Dl.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Dl.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var Xd=E((loe,Ai)=>{"use strict";l();var Fe=global.process,vr=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};vr(Fe)?(By=require("assert"),Ri=ky(),Uy=/^win/i.test(Fe.platform),ka=require("events"),typeof ka!="function"&&(ka=ka.EventEmitter),Fe.__signal_exit_emitter__?it=Fe.__signal_exit_emitter__:(it=Fe.__signal_exit_emitter__=new ka,it.count=0,it.emitted={}),it.infinite||(it.setMaxListeners(1/0),it.infinite=!0),Ai.exports=function(e,t){if(!vr(global.process))return function(){};By.equal(typeof e,"function","a callback must be provided for exit handler"),Oi===!1&&zd();var n="exit";t&&t.alwaysLast&&(n="afterexit");var r=function(){it.removeListener(n,e),it.listeners("exit").length===0&&it.listeners("afterexit").length===0&&Cl()};return it.on(n,e),r},Cl=function(){!Oi||!vr(global.process)||(Oi=!1,Ri.forEach(function(t){try{Fe.removeListener(t,Rl[t])}catch{}}),Fe.emit=Ol,Fe.reallyExit=Qd,it.count-=1)},Ai.exports.unload=Cl,xr=function(t,n,r){it.emitted[t]||(it.emitted[t]=!0,it.emit(t,n,r))},Rl={},Ri.forEach(function(e){Rl[e]=function(){if(vr(global.process)){var n=Fe.listeners(e);n.length===it.count&&(Cl(),xr("exit",null,e),xr("afterexit",null,e),Uy&&e==="SIGHUP"&&(e="SIGINT"),Fe.kill(Fe.pid,e))}}}),Ai.exports.signals=function(){return Ri},Oi=!1,zd=function(){Oi||!vr(global.process)||(Oi=!0,it.count+=1,Ri=Ri.filter(function(t){try{return Fe.on(t,Rl[t]),!0}catch{return!1}}),Fe.emit=Hy,Fe.reallyExit=Gy)},Ai.exports.load=zd,Qd=Fe.reallyExit,Gy=function(t){vr(global.process)&&(Fe.exitCode=t||0,xr("exit",Fe.exitCode,null),xr("afterexit",Fe.exitCode,null),Qd.call(Fe,Fe.exitCode))},Ol=Fe.emit,Hy=function(t,n){if(t==="exit"&&vr(global.process)){n!==void 0&&(Fe.exitCode=n);var r=Ol.apply(this,arguments);return xr("exit",Fe.exitCode,null),xr("afterexit",Fe.exitCode,null),r}else return Ol.apply(this,arguments)}):Ai.exports=function(){return function(){}};var By,Ri,Uy,ka,it,Cl,xr,Rl,Oi,zd,Qd,Gy,Ol,Hy});var qy=E((uoe,Yy)=>{"use strict";l();var iY=require("os"),aY=Xd(),sY=1e3*5,oY=(e,t="SIGTERM",n={})=>{let r=e(t);return lY(e,t,n,r),r},lY=(e,t,n,r)=>{if(!cY(t,n,r))return;let i=_Y(n),a=setTimeout(()=>{e("SIGKILL")},i);a.unref&&a.unref()},cY=(e,{forceKillAfterTimeout:t},n)=>uY(e)&&t!==!1&&n,uY=e=>e===iY.constants.signals.SIGTERM||typeof e=="string"&&e.toUpperCase()==="SIGTERM",_Y=({forceKillAfterTimeout:e=!0})=>{if(e===!0)return sY;if(!Number.isFinite(e)||e<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`);return e},dY=(e,t)=>{e.kill()&&(t.isCanceled=!0)},mY=(e,t,n)=>{e.kill(t),n(Object.assign(new Error("Timed out"),{timedOut:!0,signal:t}))},pY=(e,{timeout:t,killSignal:n="SIGTERM"},r)=>{if(t===0||t===void 0)return r;let i,a=new Promise((o,c)=>{i=setTimeout(()=>{mY(e,n,c)},t)}),s=r.finally(()=>{clearTimeout(i)});return Promise.race([a,s])},EY=({timeout:e})=>{if(e!==void 0&&(!Number.isFinite(e)||e<0))throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${e}\` (${typeof e})`)},fY=async(e,{cleanup:t,detached:n},r)=>{if(!t||n)return r;let i=aY(()=>{e.kill()});return r.finally(()=>{i()})};Yy.exports={spawnedKill:oY,spawnedCancel:dY,setupTimeout:pY,validateTimeout:EY,setExitHandler:fY}});var Vy=E((doe,$y)=>{"use strict";l();var cn=e=>e!==null&&typeof e=="object"&&typeof e.pipe=="function";cn.writable=e=>cn(e)&&e.writable!==!1&&typeof e._write=="function"&&typeof e._writableState=="object";cn.readable=e=>cn(e)&&e.readable!==!1&&typeof e._read=="function"&&typeof e._readableState=="object";cn.duplex=e=>cn.writable(e)&&cn.readable(e);cn.transform=e=>cn.duplex(e)&&typeof e._transform=="function";$y.exports=cn});var Wy=E((poe,Ky)=>{"use strict";l();var{PassThrough:gY}=require("stream");Ky.exports=e=>{e={...e};let{array:t}=e,{encoding:n}=e,r=n==="buffer",i=!1;t?i=!(n||r):n=n||"utf8",r&&(n=null);let a=new gY({objectMode:i});n&&a.setEncoding(n);let s=0,o=[];return a.on("data",c=>{o.push(c),i?s=o.length:s+=c.length}),a.getBufferedValue=()=>t?o:r?Buffer.concat(o,s):o.join(""),a.getBufferedLength=()=>s,a}});var Zd=E((foe,Ba)=>{"use strict";l();var{constants:SY}=require("buffer"),hY=require("stream"),{promisify:TY}=require("util"),bY=Wy(),DY=TY(hY.pipeline),Al=class extends Error{constructor(){super("maxBuffer exceeded"),this.name="MaxBufferError"}};async function jd(e,t){if(!e)throw new Error("Expected a stream");t={maxBuffer:1/0,...t};let{maxBuffer:n}=t,r=bY(t);return await new Promise((i,a)=>{let s=o=>{o&&r.getBufferedLength()<=SY.MAX_LENGTH&&(o.bufferedData=r.getBufferedValue()),a(o)};(async()=>{try{await DY(e,r),i()}catch(o){s(o)}})(),r.on("data",()=>{r.getBufferedLength()>n&&s(new Al)})}),r.getBufferedValue()}Ba.exports=jd;Ba.exports.buffer=(e,t)=>jd(e,{...t,encoding:"buffer"});Ba.exports.array=(e,t)=>jd(e,{...t,array:!0});Ba.exports.MaxBufferError=Al});var Jd=E((Soe,zy)=>{"use strict";l();var{PassThrough:CY}=require("stream");zy.exports=function(){var e=[],t=new CY({objectMode:!0});return t.setMaxListeners(0),t.add=n,t.isEmpty=r,t.on("unpipe",i),Array.prototype.slice.call(arguments).forEach(n),t;function n(a){return Array.isArray(a)?(a.forEach(n),this):(e.push(a),a.once("end",i.bind(null,a)),a.once("error",t.emit.bind(t,"error")),a.pipe(t,{end:!1}),this)}function r(){return e.length==0}function i(a){e=e.filter(function(s){return s!==a}),!e.length&&t.readable&&t.end()}}});var Zy=E((Toe,jy)=>{"use strict";l();var Xy=Vy(),Qy=Zd(),RY=Jd(),OY=(e,t)=>{t===void 0||e.stdin===void 0||(Xy(t)?t.pipe(e.stdin):e.stdin.end(t))},AY=(e,{all:t})=>{if(!t||!e.stdout&&!e.stderr)return;let n=RY();return e.stdout&&n.add(e.stdout),e.stderr&&n.add(e.stderr),n},em=async(e,t)=>{if(e){e.destroy();try{return await t}catch(n){return n.bufferedData}}},tm=(e,{encoding:t,buffer:n,maxBuffer:r})=>{if(!(!e||!n))return t?Qy(e,{encoding:t,maxBuffer:r}):Qy.buffer(e,{maxBuffer:r})},NY=async({stdout:e,stderr:t,all:n},{encoding:r,buffer:i,maxBuffer:a},s)=>{let o=tm(e,{encoding:r,buffer:i,maxBuffer:a}),c=tm(t,{encoding:r,buffer:i,maxBuffer:a}),u=tm(n,{encoding:r,buffer:i,maxBuffer:a*2});try{return await Promise.all([s,o,c,u])}catch(_){return Promise.all([{error:_,signal:_.signal,timedOut:_.timedOut},em(e,o),em(t,c),em(n,u)])}},IY=({input:e})=>{if(Xy(e))throw new TypeError("The `input` option cannot be a stream in sync mode")};jy.exports={handleInput:OY,makeAllStream:AY,getSpawnedResult:NY,validateInputSync:IY}});var ev=E((Doe,Jy)=>{"use strict";l();var yY=(async()=>{})().constructor.prototype,vY=["then","catch","finally"].map(e=>[e,Reflect.getOwnPropertyDescriptor(yY,e)]),xY=(e,t)=>{for(let[n,r]of vY){let i=typeof t=="function"?(...a)=>Reflect.apply(r.value,t(),a):r.value.bind(t);Reflect.defineProperty(e,n,{...r,value:i})}return e},MY=e=>new Promise((t,n)=>{e.on("exit",(r,i)=>{t({exitCode:r,signal:i})}),e.on("error",r=>{n(r)}),e.stdin&&e.stdin.on("error",r=>{n(r)})});Jy.exports={mergePromise:xY,getSpawnedPromise:MY}});var rv=E((Roe,nv)=>{"use strict";l();var tv=(e,t=[])=>Array.isArray(t)?[e,...t]:[e],LY=/^[\w.-]+$/,wY=/"/g,PY=e=>typeof e!="string"||LY.test(e)?e:`"${e.replace(wY,'\\"')}"`,FY=(e,t)=>tv(e,t).join(" "),kY=(e,t)=>tv(e,t).map(n=>PY(n)).join(" "),BY=/ +/g,UY=e=>{let t=[];for(let n of e.trim().split(BY)){let r=t[t.length-1];r&&r.endsWith("\\")?t[t.length-1]=`${r.slice(0,-1)} ${n}`:t.push(n)}return t};nv.exports={joinCommand:FY,getEscapedCommand:kY,parseCommand:UY}});var uv=E((Aoe,Ni)=>{"use strict";l();var GY=require("path"),nm=require("child_process"),HY=$d(),YY=hy(),qY=Dy(),$Y=Ay(),Nl=wy(),av=Fy(),{spawnedKill:VY,spawnedCancel:KY,setupTimeout:WY,validateTimeout:zY,setExitHandler:QY}=qy(),{handleInput:XY,getSpawnedResult:jY,makeAllStream:ZY,validateInputSync:JY}=Zy(),{mergePromise:iv,getSpawnedPromise:eq}=ev(),{joinCommand:sv,parseCommand:ov,getEscapedCommand:lv}=rv(),tq=1e3*1e3*100,nq=({env:e,extendEnv:t,preferLocal:n,localDir:r,execPath:i})=>{let a=t?{...process.env,...e}:e;return n?qY.env({env:a,cwd:r,execPath:i}):a},cv=(e,t,n={})=>{let r=HY._parse(e,t,n);return e=r.command,t=r.args,n=r.options,n={maxBuffer:tq,buffer:!0,stripFinalNewline:!0,extendEnv:!0,preferLocal:!1,localDir:n.cwd||process.cwd(),execPath:process.execPath,encoding:"utf8",reject:!0,cleanup:!0,all:!1,windowsHide:!0,...n},n.env=nq(n),n.stdio=av(n),process.platform==="win32"&&GY.basename(e,".exe")==="cmd"&&t.unshift("/q"),{file:e,args:t,options:n,parsed:r}},Ua=(e,t,n)=>typeof t!="string"&&!Buffer.isBuffer(t)?n===void 0?void 0:"":e.stripFinalNewline?YY(t):t,Il=(e,t,n)=>{let r=cv(e,t,n),i=sv(e,t),a=lv(e,t);zY(r.options);let s;try{s=nm.spawn(r.file,r.args,r.options)}catch(C){let S=new nm.ChildProcess,A=Promise.reject(Nl({error:C,stdout:"",stderr:"",all:"",command:i,escapedCommand:a,parsed:r,timedOut:!1,isCanceled:!1,killed:!1}));return iv(S,A)}let o=eq(s),c=WY(s,r.options,o),u=QY(s,r.options,c),_={isCanceled:!1};s.kill=VY.bind(null,s.kill.bind(s)),s.cancel=KY.bind(null,s,_);let g=$Y(async()=>{let[{error:C,exitCode:S,signal:A,timedOut:x},P,B,U]=await jY(s,r.options,u),q=Ua(r.options,P),te=Ua(r.options,B),Z=Ua(r.options,U);if(C||S!==0||A!==null){let re=Nl({error:C,exitCode:S,signal:A,stdout:q,stderr:te,all:Z,command:i,escapedCommand:a,parsed:r,timedOut:x,isCanceled:_.isCanceled,killed:s.killed});if(!r.options.reject)return re;throw re}return{command:i,escapedCommand:a,exitCode:0,stdout:q,stderr:te,all:Z,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}});return XY(s,r.options.input),s.all=ZY(s,r.options),iv(s,g)};Ni.exports=Il;Ni.exports.sync=(e,t,n)=>{let r=cv(e,t,n),i=sv(e,t),a=lv(e,t);JY(r.options);let s;try{s=nm.spawnSync(r.file,r.args,r.options)}catch(u){throw Nl({error:u,stdout:"",stderr:"",all:"",command:i,escapedCommand:a,parsed:r,timedOut:!1,isCanceled:!1,killed:!1})}let o=Ua(r.options,s.stdout,s.error),c=Ua(r.options,s.stderr,s.error);if(s.error||s.status!==0||s.signal!==null){let u=Nl({stdout:o,stderr:c,error:s.error,signal:s.signal,exitCode:s.status,command:i,escapedCommand:a,parsed:r,timedOut:s.error&&s.error.code==="ETIMEDOUT",isCanceled:!1,killed:s.signal!==null});if(!r.options.reject)return u;throw u}return{command:i,escapedCommand:a,exitCode:0,stdout:o,stderr:c,failed:!1,timedOut:!1,isCanceled:!1,killed:!1}};Ni.exports.command=(e,t)=>{let[n,...r]=ov(e);return Il(n,r,t)};Ni.exports.commandSync=(e,t)=>{let[n,...r]=ov(e);return Il.sync(n,r,t)};Ni.exports.node=(e,t,n={})=>{t&&!Array.isArray(t)&&typeof t=="object"&&(n=t,t=[]);let r=av.node(n),i=process.execArgv.filter(o=>!o.startsWith("--inspect")),{nodePath:a=process.execPath,nodeOptions:s=i}=n;return Il(a,[...s,e,...Array.isArray(t)?t:[]],{...n,stdin:void 0,stdout:void 0,stderr:void 0,stdio:r,shell:!1})}});var Qq={};Vl(Qq,{pkg:()=>Yl});module.exports=LM(Qq);l();var hx=J(require("update-notifier"));var Kl={};Vl(Kl,{author:()=>UM,bin:()=>WM,bugs:()=>GM,default:()=>XM,dependencies:()=>zM,description:()=>FM,devDependencies:()=>VM,engines:()=>QM,files:()=>KM,homepage:()=>kM,license:()=>BM,name:()=>PM,publishConfig:()=>YM,repository:()=>HM,scripts:()=>$M,sideEffects:()=>qM,version:()=>Wl});var PM="@e2b/cli",Wl="0.4.3",FM="CLI for managing e2b sandbox templates",kM="https://e2b.dev",BM="MIT",UM={name:"FoundryLabs, Inc.",email:"hello@e2b.dev",url:"https://e2b.dev"},GM="https://github.com/e2b-dev/e2b/issues",HM={type:"git",url:"https://github.com/e2b-dev/e2b",directory:"packages/cli"},YM={access:"public"},qM=!1,$M={prepublishOnly:"pnpm build",build:"tsc --noEmit --skipLibCheck && tsup --minify",dev:"tsup --watch",test:"pnpm build && cd testground/demo-basic && ../../dist/index.js template build","check-deps":"knip","update-deps":"ncu -u && pnpm i"},VM={"@types/command-exists":"^1.2.3","@types/inquirer":"^9.0.7","@types/node":"^18.18.6","@types/update-notifier":"6.0.5",knip:"^2.33.4","npm-check-updates":"^16.14.6",tsup:"^7.2.0",typescript:"^5.2.2",vitest:"^0.34.6"},KM=["dist","LICENSE","README","package.json"],WM={e2b:"dist/index.js"},zM={"@iarna/toml":"^2.2.5","async-listen":"^3.0.1",boxen:"^7.1.1",chalk:"^5.3.0","cli-highlight":"^2.1.11","command-exists":"^1.2.9",commander:"^11.1.0","console-table-printer":"^2.11.2",e2b:"^0.13.0",inquirer:"^9.2.12",open:"^9.1.0","strip-ansi":"^7.1.0","update-notifier":"5.1.0",yup:"^1.3.2"},QM={node:">=18"},XM={name:PM,version:Wl,description:FM,homepage:kM,license:BM,author:UM,bugs:GM,repository:HM,publishConfig:YM,sideEffects:qM,scripts:$M,devDependencies:VM,files:KM,bin:WM,dependencies:zM,engines:QM};l();l();var Zm=J(jm(),1),{program:m$,createCommand:p$,createArgument:E$,createOption:f$,CommanderError:g$,InvalidArgumentError:S$,InvalidOptionArgumentError:h$,Command:Ce,Argument:T$,Option:Mr,Help:b$}=Zm.default;l();l();l();var Jm=(e=0)=>t=>`\x1B[${t+e}m`,ep=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,tp=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,we={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},C$=Object.keys(we.modifier),pL=Object.keys(we.color),EL=Object.keys(we.bgColor),R$=[...pL,...EL];function fL(){let e=new Map;for(let[t,n]of Object.entries(we)){for(let[r,i]of Object.entries(n))we[r]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},n[r]=we[r],e.set(i[0],i[1]);Object.defineProperty(we,t,{value:n,enumerable:!1})}return Object.defineProperty(we,"codes",{value:e,enumerable:!1}),we.color.close="\x1B[39m",we.bgColor.close="\x1B[49m",we.color.ansi=Jm(),we.color.ansi256=ep(),we.color.ansi16m=tp(),we.bgColor.ansi=Jm(10),we.bgColor.ansi256=ep(10),we.bgColor.ansi16m=tp(10),Object.defineProperties(we,{rgbToAnsi256:{value(t,n,r){return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[r]=n;r.length===3&&(r=[...r].map(a=>a+a).join(""));let i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:t=>we.rgbToAnsi256(...we.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,r,i;if(t>=232)n=((t-232)*10+8)/255,r=n,i=n;else{t-=16;let o=t%36;n=Math.floor(t/36)/5,r=Math.floor(o/6)/5,i=o%6/5}let a=Math.max(n,r,i)*2;if(a===0)return 30;let s=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(n));return a===2&&(s+=60),s},enumerable:!1},rgbToAnsi:{value:(t,n,r)=>we.ansi256ToAnsi(we.rgbToAnsi256(t,n,r)),enumerable:!1},hexToAnsi:{value:t=>we.ansi256ToAnsi(we.hexToAnsi256(t)),enumerable:!1}}),we}var gL=fL(),Ht=gL;l();var Za=J(require("process"),1),rp=J(require("os"),1),oc=J(require("tty"),1);function vt(e,t=globalThis.Deno?globalThis.Deno.args:Za.default.argv){let n=e.startsWith("-")?"":e.length===1?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return r!==-1&&(i===-1||r<i)}var{env:Ue}=Za.default,ja;vt("no-color")||vt("no-colors")||vt("color=false")||vt("color=never")?ja=0:(vt("color")||vt("colors")||vt("color=true")||vt("color=always"))&&(ja=1);function SL(){if("FORCE_COLOR"in Ue)return Ue.FORCE_COLOR==="true"?1:Ue.FORCE_COLOR==="false"?0:Ue.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(Ue.FORCE_COLOR,10),3)}function hL(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function TL(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=SL();r!==void 0&&(ja=r);let i=n?ja:r;if(i===0)return 0;if(n){if(vt("color=16m")||vt("color=full")||vt("color=truecolor"))return 3;if(vt("color=256"))return 2}if("TF_BUILD"in Ue&&"AGENT_NAME"in Ue)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if(Ue.TERM==="dumb")return a;if(Za.default.platform==="win32"){let s=rp.default.release().split(".");return Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in Ue)return"GITHUB_ACTIONS"in Ue||"GITEA_ACTIONS"in Ue?3:["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(s=>s in Ue)||Ue.CI_NAME==="codeship"?1:a;if("TEAMCITY_VERSION"in Ue)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(Ue.TEAMCITY_VERSION)?1:0;if(Ue.COLORTERM==="truecolor"||Ue.TERM==="xterm-kitty")return 3;if("TERM_PROGRAM"in Ue){let s=Number.parseInt((Ue.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(Ue.TERM_PROGRAM){case"iTerm.app":return s>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(Ue.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(Ue.TERM)||"COLORTERM"in Ue?1:a}function np(e,t={}){let n=TL(e,{streamIsTTY:e&&e.isTTY,...t});return hL(n)}var bL={stdout:np({isTTY:oc.default.isatty(1)}),stderr:np({isTTY:oc.default.isatty(2)})},ip=bL;l();function ap(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,s="";do s+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return s+=e.slice(a),s}function sp(e,t,n,r){let i=0,a="";do{let s=e[r-1]==="\r";a+=e.slice(i,s?r-1:r)+t+(s?`\r
72
72
  `:`
73
73
  `)+n,i=r+1,r=e.indexOf(`
74
74
  `,i)}while(r!==-1);return a+=e.slice(i),a}var{stdout:op,stderr:lp}=ip,lc=Symbol("GENERATOR"),Lr=Symbol("STYLER"),wi=Symbol("IS_EMPTY"),cp=["ansi","ansi","ansi256","ansi16m"],wr=Object.create(null),DL=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let n=op?op.level:0;e.level=t.level===void 0?n:t.level};var CL=e=>{let t=(...n)=>n.join(" ");return DL(t,e),Object.setPrototypeOf(t,Pi.prototype),t};function Pi(e){return CL(e)}Object.setPrototypeOf(Pi.prototype,Function.prototype);for(let[e,t]of Object.entries(Ht))wr[e]={get(){let n=Ja(this,uc(t.open,t.close,this[Lr]),this[wi]);return Object.defineProperty(this,e,{value:n}),n}};wr.visible={get(){let e=Ja(this,this[Lr],!0);return Object.defineProperty(this,"visible",{value:e}),e}};var cc=(e,t,n,...r)=>e==="rgb"?t==="ansi16m"?Ht[n].ansi16m(...r):t==="ansi256"?Ht[n].ansi256(Ht.rgbToAnsi256(...r)):Ht[n].ansi(Ht.rgbToAnsi(...r)):e==="hex"?cc("rgb",t,n,...Ht.hexToRgb(...r)):Ht[n][e](...r),RL=["rgb","hex","ansi256"];for(let e of RL){wr[e]={get(){let{level:n}=this;return function(...r){let i=uc(cc(e,cp[n],"color",...r),Ht.color.close,this[Lr]);return Ja(this,i,this[wi])}}};let t="bg"+e[0].toUpperCase()+e.slice(1);wr[t]={get(){let{level:n}=this;return function(...r){let i=uc(cc(e,cp[n],"bgColor",...r),Ht.bgColor.close,this[Lr]);return Ja(this,i,this[wi])}}}}var OL=Object.defineProperties(()=>{},{...wr,level:{enumerable:!0,get(){return this[lc].level},set(e){this[lc].level=e}}}),uc=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},Ja=(e,t,n)=>{let r=(...i)=>AL(r,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(r,OL),r[lc]=e,r[Lr]=t,r[wi]=n,r},AL=(e,t)=>{if(e.level<=0||!t)return e[wi]?"":t;let n=e[Lr];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes("\x1B"))for(;n!==void 0;)t=ap(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
@@ -83,11 +83,11 @@ ${r.message}`:A,B=[P,t,e].filter(Boolean).join(`
83
83
  `,St=" ",sa="none",iR=()=>{let{env:e,stdout:t,stderr:n}=aa.default;return t?.columns?t.columns:n?.columns?n.columns:e.COLUMNS?Number.parseInt(e.COLUMNS,10):80},eR=e=>typeof e=="number"?{top:e,right:e*3,bottom:e,left:e*3}:{top:0,right:0,bottom:0,left:0,...e},oa=e=>e===sa?0:2,rB=e=>{let t=["topLeft","topRight","bottomRight","bottomLeft","left","right","top","bottom"],n;if(e===sa){e={};for(let r of t)e[r]=""}if(typeof e=="string"){if(n=rR.default[e],!n)throw new TypeError(`Invalid border style: ${e}`)}else{typeof e?.vertical=="string"&&(e.left=e.vertical,e.right=e.vertical),typeof e?.horizontal=="string"&&(e.top=e.horizontal,e.bottom=e.horizontal);for(let r of t)if(e[r]===null||typeof e[r]!="string")throw new TypeError(`Invalid border style: ${r}`);n=e}return n},iB=(e,t,n)=>{let r="",i=tt(e);switch(n){case"left":{r=e+t.slice(i);break}case"right":{r=t.slice(i)+e;break}default:{t=t.slice(i),t.length%2===1?(t=t.slice(Math.floor(t.length/2)),r=t.slice(1)+e+t):(t=t.slice(t.length/2),r=t+e+t);break}}return r},aB=(e,{padding:t,width:n,textAlignment:r,height:i})=>{e=(0,ju.default)(e,{align:r});let a=e.split(Vn),s=ao(e),o=n-t.left-t.right;if(s>o){let _=[];for(let m of a){let g=oo(m,o,{hard:!0}),S=(0,ju.default)(g,{align:r}).split(`
84
84
  `),A=Math.max(...S.map(x=>tt(x)));for(let x of S){let P;switch(r){case"center":{P=St.repeat((o-A)/2)+x;break}case"right":{P=St.repeat(o-A)+x;break}default:{P=x;break}}_.push(P)}}a=_}r==="center"&&s<o?a=a.map(_=>St.repeat((o-s)/2)+_):r==="right"&&s<o&&(a=a.map(_=>St.repeat(o-s)+_));let c=St.repeat(t.left),u=St.repeat(t.right);return a=a.map(_=>c+_+u),a=a.map(_=>{if(n-tt(_)>0)switch(r){case"center":return _+St.repeat(n-tt(_));case"right":return _+St.repeat(n-tt(_));default:return _+St.repeat(n-tt(_))}return _}),t.top>0&&(a=[...Array.from({length:t.top}).fill(St.repeat(n)),...a]),t.bottom>0&&(a=[...a,...Array.from({length:t.bottom}).fill(St.repeat(n))]),i&&a.length>i?a=a.slice(0,i):i&&a.length<i&&(a=[...a,...Array.from({length:i-a.length}).fill(St.repeat(n))]),a.join(Vn)},sB=(e,t,n)=>{let r=_=>{let m=n.borderColor?cB(n.borderColor)(_):_;return n.dimBorder?Qe.dim(m):m},i=_=>n.backgroundColor?uB(n.backgroundColor)(_):_,a=rB(n.borderStyle),s=iR(),o=St.repeat(n.margin.left);if(n.float==="center"){let _=Math.max((s-t-oa(n.borderStyle))/2,0);o=St.repeat(_)}else if(n.float==="right"){let _=Math.max(s-t-n.margin.right-oa(n.borderStyle),0);o=St.repeat(_)}let c="";n.margin.top&&(c+=Vn.repeat(n.margin.top)),(n.borderStyle!==sa||n.title)&&(c+=r(o+a.topLeft+(n.title?iB(n.title,a.top.repeat(t),n.titleAlignment):a.top.repeat(t))+a.topRight)+Vn);let u=e.split(Vn);return c+=u.map(_=>o+r(a.left)+i(_)+r(a.right)).join(Vn),n.borderStyle!==sa&&(c+=Vn+r(o+a.bottomLeft+a.bottom.repeat(t)+a.bottomRight)),n.margin.bottom&&(c+=Vn.repeat(n.margin.bottom)),c},oB=e=>{if(e.fullscreen&&aa.default?.stdout){let t=[aa.default.stdout.columns,aa.default.stdout.rows];typeof e.fullscreen=="function"&&(t=e.fullscreen(...t)),e.width||(e.width=t[0]),e.height||(e.height=t[1])}return e.width&&(e.width=Math.max(1,e.width-oa(e.borderStyle))),e.height&&(e.height=Math.max(1,e.height-oa(e.borderStyle))),e},tR=(e,t)=>t===sa?e:` ${e} `,lB=(e,t)=>{t=oB(t);let n=t.width!==void 0,r=iR(),i=oa(t.borderStyle),a=r-t.margin.left-t.margin.right-i,s=ao(oo(e,r-i,{hard:!0,trim:!1}))+t.padding.left+t.padding.right;if(t.title&&n?(t.title=t.title.slice(0,Math.max(0,t.width-2)),t.title&&(t.title=tR(t.title,t.borderStyle))):t.title&&(t.title=t.title.slice(0,Math.max(0,a-2)),t.title&&(t.title=tR(t.title,t.borderStyle),tt(t.title)>s&&(t.width=tt(t.title)))),t.width=t.width?t.width:s,!n){if(t.margin.left&&t.margin.right&&t.width>a){let c=(r-t.width-i)/(t.margin.left+t.margin.right);t.margin.left=Math.max(0,Math.floor(t.margin.left*c)),t.margin.right=Math.max(0,Math.floor(t.margin.right*c))}t.width=Math.min(t.width,r-i-t.margin.left-t.margin.right)}return t.width-(t.padding.left+t.padding.right)<=0&&(t.padding.left=0,t.padding.right=0),t.height&&t.height-(t.padding.top+t.padding.bottom)<=0&&(t.padding.top=0,t.padding.bottom=0),t},Zu=e=>e.match(/^#(?:[0-f]{3}){1,2}$/i),nR=e=>typeof e=="string"&&(Qe[e]??Zu(e)),cB=e=>Zu(e)?Qe.hex(e):Qe[e],uB=e=>Zu(e)?Qe.bgHex(e):Qe[Vu(["bg",e])];function fr(e,t){if(t={padding:0,borderStyle:"single",dimBorder:!1,textAlignment:"left",float:"left",titleAlignment:"left",...t},t.align&&(t.textAlignment=t.align),t.borderColor&&!nR(t.borderColor))throw new Error(`${t.borderColor} is not a valid borderColor`);if(t.backgroundColor&&!nR(t.backgroundColor))throw new Error(`${t.backgroundColor} is not a valid backgroundColor`);return t.padding=eR(t.padding),t.margin=eR(t.margin),t=lB(e,t),e=aB(e,t),sB(e,t.width,t)}l();var ei=J(require("path"));function Kn(e){let t=process.cwd();return e?ei.isAbsolute(e)?e:ei.resolve(t,e):t}function aR(e){return ei.relative(process.cwd(),e)}var dB="#FFB766";function nt(e,t){let n=n_(e.aliases),r=n?be(n):"",i=t?mB(" <-> ")+rt(t):"";return`${`${e.templateID} `}${r}${i}`.trim()}function ti(e,t){return Qe.redBright(`${e?`${e}
85
85
  `:""}${t?t.stack:""}
86
- `)}function mB(e){return Qe.dim(e)}function be(e){return Qe.bold(e)}function Dt(e){return Qe.hex(dB)(e)}function Ct(e){return Qe.blue(e)}function rt(e){return e?Ct("./"+aR(e)):""}function t_(e){return Qe.blueBright(e)}function n_(e){if(e)return e.join(" | ")}function lR(e){return e_.default(e,{language:"typescript",ignoreIllegals:!0})}function cR(e){return e_.default(e,{language:"python",ignoreIllegals:!0})}var pB={topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",top:"",bottom:"",left:"",right:""},sR=2,oR=1;function r_(e,t,n){return fr(e,{borderStyle:{...pB,top:"\u2500",bottom:n?"\u2500":""},titleAlignment:"center",float:"left",title:t?be(t):void 0,margin:{top:0,bottom:0,left:1,right:0},fullscreen:r=>[r,0],padding:{bottom:n?oR:0,left:sR,right:sR,top:oR}})}l();l();var Ia=J(require("fs")),xn=J(require("path"));l();l();var i_={};Vl(i_,{ApiError:()=>Wn,Fetcher:()=>_R,arrayRequestBody:()=>dR});l();l();l();var _ee=Symbol(),Wn=class extends Error{constructor(t){super(t.statusText),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statusText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.setPrototypeOf(this,new.target.prototype),this.headers=t.headers,this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.data=t.data}};var la=function(e,t,n,r){function i(a){return a instanceof n?a:new n(function(s){s(a)})}return new(n||(n=Promise))(function(a,s){function o(_){try{u(r.next(_))}catch(m){s(m)}}function c(_){try{u(r.throw(_))}catch(m){s(m)}}function u(_){_.done?a(_.value):i(_.value).then(o,c)}u((r=r.apply(e,t||[])).next())})},uR=e=>e==="post"||e==="put"||e==="patch"||e==="delete";function EB(e){let t=[],n=(r,i)=>`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`;return Object.keys(e).forEach(r=>{let i=e[r];i!=null&&(Array.isArray(i)?i.forEach(a=>t.push(n(r,a))):t.push(n(r,i)))}),t.length>0?`?${t.join("&")}`:""}function fB(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=encodeURIComponent(t[r]);return delete t[r],i})}function gB(e,t,n){let r={};return uR(e)?n.forEach(i=>{r[i]=t[i],delete t[i]}):r=Object.assign({},t),EB(r)}function SB(e,t){let n=new Headers(t);return e!==void 0&&!n.has("Content-Type")&&n.append("Content-Type","application/json"),n.has("Accept")||n.append("Accept","application/json"),n}function hB(e,t){let n=uR(e)?JSON.stringify(t):void 0;return e==="delete"&&n==="{}"?void 0:n}function TB(e,t){let n=new Headers(e?.headers),r=new Headers(t?.headers);for(let i of r.keys()){let a=r.get(i);a!=null&&n.set(i,a)}return Object.assign(Object.assign(Object.assign({},e),t),{headers:n})}function bB(e){var t;let n=Object.assign(Array.isArray(e.payload)?[]:{},e.payload),r=fB(e.path,n),i=gB(e.method,n,e.queryParams),a=hB(e.method,n),s=SB(a,(t=e.init)===null||t===void 0?void 0:t.headers),o=e.baseUrl+r+i,c=Object.assign(Object.assign({},e.init),{method:e.method.toUpperCase(),headers:s,body:a});return{url:o,init:c}}function DB(e){return la(this,void 0,void 0,function*(){let t=e.headers.get("content-type");if(e.status===204)return;if(t&&t.indexOf("application/json")!==-1)return yield e.json();let n=yield e.text();try{return JSON.parse(n)}catch{return n}})}function CB(e,t){return la(this,void 0,void 0,function*(){let n=yield fetch(e,t),r=yield DB(n),i={headers:n.headers,url:n.url,ok:n.ok,status:n.status,statusText:n.statusText,data:r};if(i.ok)return i;throw new Wn(i)})}function RB(e,t){let n=(r,i,a)=>la(this,void 0,void 0,function*(){if(e==null||r===e.length)return t(i,a);let s=e[r];return yield s(i,a,(o,c)=>n(r+1,o,c))});return(r,i)=>n(0,r,i)}function OB(e){return la(this,void 0,void 0,function*(){let{url:t,init:n}=bB(e);return yield e.fetch(t,n)})}function AB(e){let t=(n,r)=>la(this,void 0,void 0,function*(){try{return yield e(n,r)}catch(i){throw i instanceof Wn?new t.Error(i):i}});return t.Error=class extends Wn{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype)}getActualType(){return{status:this.status,data:this.data}}},t}function NB(){let e="",t={},n=[],r=RB(n,CB);return{configure:i=>{e=i.baseUrl||"",t=i.init||{},n.splice(0),n.push(...i.use||[])},use:i=>n.push(i),path:i=>({method:a=>({create:s=>AB((o,c)=>OB({baseUrl:e||"",path:i,method:a,queryParams:Object.keys(s||{}),payload:o,init:TB(t,c),fetch:r}))})})}}var _R={for:()=>NB()};l();function dR(e,t){return Object.assign([...e],t)}l();var mR=process?.env?.E2B_DEBUG,pR=process?.env?.E2B_DOMAIN||"e2b.dev",a_=(process?.env?.E2B_SECURE||"true").toLowerCase()==="true",IB=mR?"localhost:3000":`api.${pR}`,s_=`${a_&&!mR?"https":"http"}://${IB}`,gr=pR,lo=49982,ER="/ws",fR="/file";l();var uo=J(gR());var SR="0.13.2-post-connection.4";var hR={browser:typeof window<"u"&&uo.default.name||"undefined",lang:"js",lang_version:uo.default.version||"unknown",package_version:SR,publisher:"e2b",sdk_runtime:typeof window>"u"?"node":"browser",system:uo.default.os?.family||"unknown"};var{Fetcher:vB}=i_,TR=vB.for();TR.configure({baseUrl:s_,init:{headers:hR}});function en(e){let t=(n,r,i)=>e(r,{...i,headers:{Authorization:`Bearer ${n}`,...i?.headers}});return t.Error=e.Error,t}function zn(e){let t=(n,r,i)=>e(r,{...i,headers:{"X-API-KEY":n,...i?.headers}});return t.Error=e.Error,t}var lt=TR;l();var Sr="terminal",_o=class{_data="";get data(){return this._data}addData(t){this._data+=t}},mo=class{constructor(t,n,r,i,a){this.terminalID=t;this.sandbox=n;this.triggerExit=r;this.output=a;this.finished=i}finished;get data(){return this.output.data}async kill(){try{await this.sandbox._call(Sr,"destroy",[this.terminalID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendData(t){await this.sandbox._call(Sr,"data",[this.terminalID,t])}async resize({cols:t,rows:n}){await this.sandbox._call(Sr,"resize",[this.terminalID,t,n])}};l();l();l();var o_=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},l_=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},bR=e=>globalThis.DOMException===void 0?new l_(e):new DOMException(e),DR=e=>{let t=e.reason===void 0?bR("This operation was aborted."):e.reason;return t instanceof Error?t:bR(t)};function c_(e,t){let{milliseconds:n,fallback:r,message:i,customTimers:a={setTimeout,clearTimeout}}=t,s,c=new Promise((u,_)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(t.signal){let{signal:g}=t;g.aborted&&_(DR(g)),g.addEventListener("abort",()=>{_(DR(g))})}if(n===Number.POSITIVE_INFINITY){e.then(u,_);return}let m=new o_;s=a.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){_(g)}return}typeof e.cancel=="function"&&e.cancel(),i===!1?u():i instanceof Error?_(i):(m.message=i??`Promise timed out after ${n} milliseconds`,_(m))},n),(async()=>{try{u(await e)}catch(g){_(g)}})()}).finally(()=>{c.clear()});return c.clear=()=>{a.clearTimeout.call(void 0,s),s=void 0},c}function CR(e){return e.status==="fulfilled"}function ua(e){if(!e.every(t=>t.status==="fulfilled"))return e.reduce((t,n,r)=>n.status==="rejected"?t+`
86
+ `)}function mB(e){return Qe.dim(e)}function be(e){return Qe.bold(e)}function Dt(e){return Qe.hex(dB)(e)}function Ct(e){return Qe.blue(e)}function rt(e){return e?Ct("./"+aR(e)):""}function t_(e){return Qe.blueBright(e)}function n_(e){if(e)return e.join(" | ")}function lR(e){return e_.default(e,{language:"typescript",ignoreIllegals:!0})}function cR(e){return e_.default(e,{language:"python",ignoreIllegals:!0})}var pB={topLeft:"",topRight:"",bottomLeft:"",bottomRight:"",top:"",bottom:"",left:"",right:""},sR=2,oR=1;function r_(e,t,n){return fr(e,{borderStyle:{...pB,top:"\u2500",bottom:n?"\u2500":""},titleAlignment:"center",float:"left",title:t?be(t):void 0,margin:{top:0,bottom:0,left:1,right:0},fullscreen:r=>[r,0],padding:{bottom:n?oR:0,left:sR,right:sR,top:oR}})}l();l();var Ia=J(require("fs")),xn=J(require("path"));l();l();var i_={};Vl(i_,{ApiError:()=>Wn,Fetcher:()=>_R,arrayRequestBody:()=>dR});l();l();l();var _ee=Symbol(),Wn=class extends Error{constructor(t){super(t.statusText),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"url",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"statusText",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.setPrototypeOf(this,new.target.prototype),this.headers=t.headers,this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.data=t.data}};var la=function(e,t,n,r){function i(a){return a instanceof n?a:new n(function(s){s(a)})}return new(n||(n=Promise))(function(a,s){function o(_){try{u(r.next(_))}catch(m){s(m)}}function c(_){try{u(r.throw(_))}catch(m){s(m)}}function u(_){_.done?a(_.value):i(_.value).then(o,c)}u((r=r.apply(e,t||[])).next())})},uR=e=>e==="post"||e==="put"||e==="patch"||e==="delete";function EB(e){let t=[],n=(r,i)=>`${encodeURIComponent(r)}=${encodeURIComponent(String(i))}`;return Object.keys(e).forEach(r=>{let i=e[r];i!=null&&(Array.isArray(i)?i.forEach(a=>t.push(n(r,a))):t.push(n(r,i)))}),t.length>0?`?${t.join("&")}`:""}function fB(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>{let i=encodeURIComponent(t[r]);return delete t[r],i})}function gB(e,t,n){let r={};return uR(e)?n.forEach(i=>{r[i]=t[i],delete t[i]}):r=Object.assign({},t),EB(r)}function SB(e,t){let n=new Headers(t);return e!==void 0&&!n.has("Content-Type")&&n.append("Content-Type","application/json"),n.has("Accept")||n.append("Accept","application/json"),n}function hB(e,t){let n=uR(e)?JSON.stringify(t):void 0;return e==="delete"&&n==="{}"?void 0:n}function TB(e,t){let n=new Headers(e?.headers),r=new Headers(t?.headers);for(let i of r.keys()){let a=r.get(i);a!=null&&n.set(i,a)}return Object.assign(Object.assign(Object.assign({},e),t),{headers:n})}function bB(e){var t;let n=Object.assign(Array.isArray(e.payload)?[]:{},e.payload),r=fB(e.path,n),i=gB(e.method,n,e.queryParams),a=hB(e.method,n),s=SB(a,(t=e.init)===null||t===void 0?void 0:t.headers),o=e.baseUrl+r+i,c=Object.assign(Object.assign({},e.init),{method:e.method.toUpperCase(),headers:s,body:a});return{url:o,init:c}}function DB(e){return la(this,void 0,void 0,function*(){let t=e.headers.get("content-type");if(e.status===204)return;if(t&&t.indexOf("application/json")!==-1)return yield e.json();let n=yield e.text();try{return JSON.parse(n)}catch{return n}})}function CB(e,t){return la(this,void 0,void 0,function*(){let n=yield fetch(e,t),r=yield DB(n),i={headers:n.headers,url:n.url,ok:n.ok,status:n.status,statusText:n.statusText,data:r};if(i.ok)return i;throw new Wn(i)})}function RB(e,t){let n=(r,i,a)=>la(this,void 0,void 0,function*(){if(e==null||r===e.length)return t(i,a);let s=e[r];return yield s(i,a,(o,c)=>n(r+1,o,c))});return(r,i)=>n(0,r,i)}function OB(e){return la(this,void 0,void 0,function*(){let{url:t,init:n}=bB(e);return yield e.fetch(t,n)})}function AB(e){let t=(n,r)=>la(this,void 0,void 0,function*(){try{return yield e(n,r)}catch(i){throw i instanceof Wn?new t.Error(i):i}});return t.Error=class extends Wn{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype)}getActualType(){return{status:this.status,data:this.data}}},t}function NB(){let e="",t={},n=[],r=RB(n,CB);return{configure:i=>{e=i.baseUrl||"",t=i.init||{},n.splice(0),n.push(...i.use||[])},use:i=>n.push(i),path:i=>({method:a=>({create:s=>AB((o,c)=>OB({baseUrl:e||"",path:i,method:a,queryParams:Object.keys(s||{}),payload:o,init:TB(t,c),fetch:r}))})})}}var _R={for:()=>NB()};l();function dR(e,t){return Object.assign([...e],t)}l();var mR=process?.env?.E2B_DEBUG,pR=process?.env?.E2B_DOMAIN||"e2b.dev",a_=(process?.env?.E2B_SECURE||"true").toLowerCase()==="true",IB=mR?"localhost:3000":`api.${pR}`,s_=`${a_&&!mR?"https":"http"}://${IB}`,gr=pR,lo=49982,ER="/ws",fR="/file";l();var uo=J(gR());var SR="0.13.1";var hR={browser:typeof window<"u"&&uo.default.name||"undefined",lang:"js",lang_version:uo.default.version||"unknown",package_version:SR,publisher:"e2b",sdk_runtime:typeof window>"u"?"node":"browser",system:uo.default.os?.family||"unknown"};var{Fetcher:vB}=i_,TR=vB.for();TR.configure({baseUrl:s_,init:{headers:hR}});function en(e){let t=(n,r,i)=>e(r,{...i,headers:{Authorization:`Bearer ${n}`,...i?.headers}});return t.Error=e.Error,t}function zn(e){let t=(n,r,i)=>e(r,{...i,headers:{"X-API-KEY":n,...i?.headers}});return t.Error=e.Error,t}var lt=TR;l();var Sr="terminal",_o=class{_data="";get data(){return this._data}addData(t){this._data+=t}},mo=class{constructor(t,n,r,i,a){this.terminalID=t;this.sandbox=n;this.triggerExit=r;this.output=a;this.finished=i}finished;get data(){return this.output.data}async kill(){try{await this.sandbox._call(Sr,"destroy",[this.terminalID])}finally{this.triggerExit(),await this.finished}}async wait(){return this.finished}async sendData(t){await this.sandbox._call(Sr,"data",[this.terminalID,t])}async resize({cols:t,rows:n}){await this.sandbox._call(Sr,"resize",[this.terminalID,t,n])}};l();l();l();var o_=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},l_=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},bR=e=>globalThis.DOMException===void 0?new l_(e):new DOMException(e),DR=e=>{let t=e.reason===void 0?bR("This operation was aborted."):e.reason;return t instanceof Error?t:bR(t)};function c_(e,t){let{milliseconds:n,fallback:r,message:i,customTimers:a={setTimeout,clearTimeout}}=t,s,c=new Promise((u,_)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(t.signal){let{signal:g}=t;g.aborted&&_(DR(g)),g.addEventListener("abort",()=>{_(DR(g))})}if(n===Number.POSITIVE_INFINITY){e.then(u,_);return}let m=new o_;s=a.setTimeout.call(void 0,()=>{if(r){try{u(r())}catch(g){_(g)}return}typeof e.cancel=="function"&&e.cancel(),i===!1?u():i instanceof Error?_(i):(m.message=i??`Promise timed out after ${n} milliseconds`,_(m))},n),(async()=>{try{u(await e)}catch(g){_(g)}})()}).finally(()=>{c.clear()});return c.clear=()=>{a.clearTimeout.call(void 0,s),s=void 0},c}function CR(e){return e.status==="fulfilled"}function ua(e){if(!e.every(t=>t.status==="fulfilled"))return e.reduce((t,n,r)=>n.status==="rejected"?t+`
87
87
  [${r}]: ${JSON.stringify(n)}`:t,`errors:
88
88
  `)}function _a(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),reject:t,resolve:e}}function tn(e,t=6e4){return t===void 0||t<=0||t===Number.POSITIVE_INFINITY?e:(...n)=>c_(e(...n),{milliseconds:t})}l();var nn="filesystem";var u_=class{constructor(t,n){this.sessConn=t;this.path=n;this.listeners=new Set}listeners;rpcSubscriptionID;async start(t){return await tn(async()=>{this.rpcSubscriptionID||(this.handleFilesystemEvents=this.handleFilesystemEvents.bind(this),this.rpcSubscriptionID=await this.sessConn._subscribe(nn,this.handleFilesystemEvents,"watchDir",this.path))},t?.timeout)()}async stop(){this.listeners.clear(),this.rpcSubscriptionID&&await this.sessConn._unsubscribe(this.rpcSubscriptionID)}addEventListener(t){return this.listeners.add(t),()=>this.listeners.delete(t)}handleFilesystemEvents(t){this.listeners.forEach(n=>{n(t)})}},RR=u_;l();var po=class extends Error{constructor(t){super(t),this.name="AuthenticationError"}},Eo=class extends Error{constructor(t){super(t),this.name="CurrentWorkingDirectoryDoesntExistError"}};l();var hr="process",da=class{constructor(t,n,r){this.line=t;this.timestamp=n;this.error=r}toString(){return this.line}},fo=class{delimiter=`
89
- `;messages=[];_finished=!1;_error=!1;_exitCode;get error(){return this._error}get exitCode(){if(!this._finished)throw new Error("Process has not finished yet");return this._exitCode}get stdout(){return this.messages.filter(t=>!t.error).map(t=>t.line).join(this.delimiter)}get stderr(){return this.messages.filter(t=>t.error).map(t=>t.line).join(this.delimiter)}addStdout(t){this.insertByTimestamp(t)}addStderr(t){this._error=!0,this.insertByTimestamp(t)}setExitCode(t){this._exitCode=t,this._finished=!0}insertByTimestamp(t){let n=this.messages.length-1;for(;n>=0&&this.messages[n].timestamp>t.timestamp;)n-=1;this.messages.splice(n+1,0,t)}},go=class{constructor(t,n,r,i,a){this.processID=t;this.sandbox=n;this.triggerExit=r;this.output=a;this.finished=i}finished;async kill(){try{await this.sandbox._call(hr,"kill",[this.processID])}finally{this.triggerExit(),await this.finished}}async wait(t){return await tn(()=>this.finished,t)()}async sendStdin(t,n){await this.sandbox._call(hr,"stdin",[this.processID,t],n)}};l();var cA=J(AR());l();function ni(e){let t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length;for(let i=0;i<e;i++)t+=n.charAt(Math.floor(Math.random()*r));return t}l();var NR="codeSnippet";l();l();var tA=J(eA());var xo=class{ws;onOpenHandlers=[];onAnyMessageHandlers=[];onNotification=[];onRequest=[];onSuccessResponse=[];onErrorResponse=[];onErrorHandlers=[];onCloseHandlers=[];config={responseTimeout:1e4};idAwaiter={};constructor(){this.ws=void 0}connect(t,n){return this.ws=new tA.default(t,n),this.listen()}onOpen(t){this.onOpenHandlers.push(t)}onAnyMessage(t){this.onAnyMessageHandlers.push(t)}onError(t){this.onErrorHandlers.push(t)}onClose(t){this.onCloseHandlers.push(t)}listenMessages(){let t;this.ws.onmessage&&(t=this.ws.onmessage.bind(this.ws)),this.ws.onmessage=n=>{t&&t(n);for(let i of this.onAnyMessageHandlers)i(n);let r=JSON.parse(n.data.toString());if(this.isNotification(r))for(let i of this.onNotification)i(r);else if(this.isRequest(r))for(let i of this.onRequest)i(r);else if(this.isSuccessResponse(r)){for(let i of this.onSuccessResponse)i(r);this.idAwaiter[r.id](r.result)}else if(this.isErrorResponse(r)){for(let i of this.onErrorResponse)i(r);this.idAwaiter[r.id](r.error)}}}call(t,n){return new Promise((r,i)=>{let a=this.buildRequest(t,n),s;this.config.responseTimeout&&(s=setTimeout(()=>{delete this.idAwaiter[a.id],i(new Error(`Awaiting response to "${t}" with id: ${a.id} timed out.`))},this.config.responseTimeout)),this.idAwaiter[a.id]=c=>{if(clearInterval(s),delete this.idAwaiter[a.id],this.isRpcError(c)){i(new Error(`RPC Error (${c.code}): ${c.message}`));return}r(c)};let o=JSON.stringify(a);this.ws.send(o)})}notify(t,n){this.ws.send(JSON.stringify(this.buildNotification(t,n)))}customId(t){this.idFn=t}noRpc(){this.buildRequest=this.buildRequestBase,this.buildNotification=this.buildNotificationBase,this.buildRpcSuccessResponse=this.buildRpcSuccessResponseBase,this.buildRpcErrorResponse=this.buildRpcErrorResponseBase}configure(t){Object.assign(this.config,t)}changeSocket(t){this.ws=t}listen(){return new Promise((t,n)=>{this.ws.onopen=r=>{for(let i of this.onOpenHandlers)i(r);t(r)},this.listenMessages(),this.ws.onerror=r=>{for(let i of this.onErrorHandlers)i(r)},this.ws.onclose=r=>{for(let i of this.onCloseHandlers)i(r);n(new Error(`WebSocket closed with code: ${r.code} and reason: ${r.reason}`))}})}buildRequest(t,n){let r=this.buildRequestBase(t,n);return r.jsonrpc="2.0",r}buildRequestBase(t,n){let r={};return r.id=this.idFn(),r.method=t,n&&(r.params=n),r}buildNotification(t,n){let r=this.buildNotificationBase(t,n);return r.jsonrpc="2.0",r}buildNotificationBase(t,n){let r={};return r.method=t,n&&(r.params=n),r}buildRpcSuccessResponse(t,n){let r=this.buildRpcSuccessResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcSuccessResponseBase(t,n){let r={};return r.id=t,r.result=n,r}buildRpcErrorResponse(t,n){let r=this.buildRpcErrorResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcErrorResponseBase(t,n){let r={};return r.id=t,r.error=n,r}idFn(){return ni(12)}isNotification(t){return!t.id}isRequest(t){return t.method}isSuccessResponse(t){return t.hasOwnProperty("result")}isErrorResponse(t){return t.hasOwnProperty("error")}isRpcError(t){return typeof t?.code<"u"}};l();function J6(e){return new Promise(t=>setTimeout(t,e))}var H_=J6;l();function Mo(e){if(e=e||process?.env?.E2B_API_KEY,!e)throw new po("API key is required, please visit https://e2b.dev/docs to get your API key. You can either set the environment variable `E2B_API_KEY` or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})");return e}var nA=zn(lt.path("/sandboxes").method("get").create()),rA=zn(lt.path("/sandboxes").method("post").create()),iA=zn(lt.path("/sandboxes/{sandboxID}").method("delete").create()),Y_=zn(lt.path("/sandboxes/{sandboxID}/refreshes").method("post").create()),Lo=class{constructor(t){this.opts=t;this.sandbox=t.__sandbox,this.apiKey=Mo(t.apiKey),this.cwd=t.cwd,this.cwd&&this.cwd.startsWith("~")&&(this.cwd=this.cwd.replace("~","/home/user"));let n={PYTHONUNBUFFERED:"1"};this.envVars={...n,...t.envVars||{}},this.logger=t.logger??{info:console.info,warn:console.warn,error:console.error},this.logger.debug?.(`Sandbox "${this.templateID}" initialized`)}cwd;envVars;logger;sandbox;isOpen=!1;apiKey;rpc=new xo;subscribers=[];get id(){return`${this.sandbox?.sandboxID}-${this.sandbox?.clientID}`}get templateID(){return this.opts.template||this.opts.id||"base"}static async list(t){t=Mo(t);try{return(await nA(t,{})).data.map(r=>({sandboxID:`${r.sandboxID}-${r.clientID}`,templateID:r.templateID,cpuCount:r.cpuCount,memoryMB:r.memoryMB,...r.alias&&{alias:r.alias},...r.metadata&&{metadata:r.metadata},startedAt:new Date(r.startedAt)}))}catch(n){if(n instanceof nA.Error){let r=n.getActualType();if(r.status===401)throw new Error(`Error listing sandboxes - (${r.status}) unauthenticated: ${r.data.message}`);if(r.status===500)throw new Error(`Error listing sandboxes - (${r.status}) server error: ${r.data.message}`)}throw n}}static async kill(t,n){n=Mo(n);let r=t.split("-")[0];try{await iA(n,{sandboxID:r})}catch(i){if(i instanceof iA.Error){let a=i.getActualType();if(a.status===401)throw new Error(`Error killing sandbox (${t}) - (${a.status}) unauthenticated: ${a.data.message}`);if(a.status===500)throw new Error(`Error killing sandbox (${t}) - (${a.status}) server error: ${a.data.message}`)}throw i}}async keepAlive(t){if(t=Math.round(t/1e3),t<0||t>3600)throw new Error("Duration must be between 0 and 3600 seconds");if(!this.sandbox)throw new Error("Cannot keep alive - sandbox is not initialized");await Y_(this.apiKey,{sandboxID:this.sandbox?.sandboxID,duration:t})}getHostname(t){if(this.opts.__debug_hostname)return t&&this.opts.__debug_devEnv==="remote"?`${t}-${this.opts.__debug_hostname}`:t?`${this.opts.__debug_hostname}:${t}`:this.opts.__debug_hostname;if(!this.sandbox)throw new Error("Cannot get sandbox's hostname - sandbox is not initialized");let n=`${this.id}.${gr}`;return t?`${t}-${n}`:n}getProtocol(t="http",n=a_){return n?`${t}s`:t}async close(){this.isOpen&&(this.logger.debug?.(`Closing sandbox "${this.id}"`),this.isOpen=!1,this.rpc.ws?.terminate?.(),this.rpc.ws?.close?.(),this.subscribers=[],this.logger.debug?.("Disconnected from the sandbox"))}async _call(t,n,r,i){return this.logger.debug?.(`Calling "${t}_${n}" with params:`,r),await tn(async(s,o)=>await this.rpc.call(s,o),i?.timeout)(`${t}_${n}`,r)}async _handleSubscriptions(...t){let n=await Promise.allSettled(t);if(n.every(r=>r.status==="fulfilled"))return n.map(r=>r.status==="fulfilled"?r.value:void 0);throw await Promise.all(n.filter(CR).map(r=>r.value?this._unsubscribe(r.value):void 0)),new Error(ua(n))}async _unsubscribe(t){let n=this.subscribers.find(r=>r.subID===t);n&&(await this._call(n.service,"unsubscribe",[n.subID]),this.subscribers=this.subscribers.filter(r=>r!==n),this.logger.debug?.(`Unsubscribed '${t}' from '${n.service}'`))}async _subscribe(t,n,r,...i){let a=await this._call(t,"subscribe",[r,...i]);if(typeof a!="string")throw new Error(`Cannot subscribe to ${t}_${r}${i.length>0?" with params ["+i.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(a)}`);return this.subscribers.push({handler:n,service:t,subID:a}),this.logger.debug?.(`Subscribed to "${t}_${r}"${i.length>0?" with params ["+i.join(", ")+"] and":""} with id "${a}"`),a}async _open(t){let n=async()=>{if(this.isOpen)throw new Error("Sandbox connect was already called");if(this.isOpen=!0,this.logger.debug?.("Opening sandbox..."),!this.sandbox&&!this.opts.__debug_hostname)try{let r=await rA(this.apiKey,{templateID:this.templateID,metadata:this.opts.metadata});this.sandbox=r.data,this.logger.debug?.(`Acquired sandbox "${this.id}"`)}catch(r){if(r instanceof rA.Error){let i=r.getActualType();if(i.status===400)throw new Error(`Error creating sandbox - (${i.status}) bad request: ${i.data.message}`);if(i.status===401)throw new Error(`Error creating sandbox - (${i.status}) unauthenticated: ${i.data.message}`);if(i.status===500)throw new Error(`Error creating sandbox - (${i.status}) server error: ${i.data.message}`)}throw r}return this.sandbox&&!this.opts.__debug_hostname&&this.refresh(this.sandbox.sandboxID),await this.connectRpc(),this};try{return await tn(n,t?.timeout)()}catch(r){throw await this.close(),r}}async connectRpc(){let t=this.getHostname(this.opts.__debug_port||lo),r=`${this.getProtocol("ws",this.opts.__debug_devEnv!=="local")}://${t}${ER}`,i=!1,a,s,o=new Promise((c,u)=>{a=()=>{i||(i=!0,c())},s=()=>{i||(i=!0,u())}});this.rpc.onOpen(()=>{this.logger.debug?.(`Connected to sandbox "${this.id}"`),a?.()}),this.rpc.onError(async c=>{if(this.logger.debug?.(`Error in WebSocket of sandbox "${this.id}": ${c.message??c.code??c.toString()}. Trying to reconnect...`),this.isOpen){await H_(150),this.logger.debug?.(`Reconnecting to sandbox "${this.id}"`);try{this.subscribers=[],await this.rpc.connect(r),this.logger.debug?.(`Reconnected to sandbox "${this.id}"`)}catch(u){this.logger.debug?.(`Failed reconnecting to sandbox "${this.id}": ${u.message??u.code??u.toString()}`)}}else s?.()}),this.rpc.onClose(async()=>{this.logger.debug?.(`WebSocket connection to sandbox "${this.id}" closed`)}),this.rpc.onNotification.push(this.handleNotification.bind(this)),(async()=>{try{this.logger.debug?.(`Connecting to sandbox "${this.id}"`),await this.rpc.connect(r)}catch(c){this.logger.debug?.(`Error connecting to sandbox "${this.id}": ${c.message??c.code??c.toString()}`)}})(),await o}handleNotification(t){this.logger.debug?.("Handling notification:",t),this.subscribers.filter(n=>n.subID===t.params?.subscription).forEach(n=>n.handler(t.params?.result))}async refresh(t){this.logger.debug?.(`Started refreshing sandbox "${t}"`);try{for(;;){if(!this.isOpen){this.logger.debug?.(`Cannot refresh sandbox ${this.id} - it was closed`);return}await H_(5e3);try{await Y_(this.apiKey,{sandboxID:t,duration:0}),this.logger.debug?.(`Refreshed sandbox "${t}"`)}catch(n){if(n instanceof Y_.Error){let r=n.getActualType();if(r.status===404){this.logger.warn?.(`Error refreshing sandbox - (${r.status}): ${r.data.message}`);return}this.logger.warn?.(`Refreshing sandbox "${t}" failed - (${r.status})`)}}}}finally{this.logger.debug?.(`Stopped refreshing sandbox "${t}"`),await this.close()}}};l();var Ca=J(oA()),lA=(e,t,n)=>{let r;return e.startsWith("./")?(r=Ca.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with './' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("../")?(r=Ca.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with '../' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("~/")?(r=Ca.default.posix.join(t||"/home/user",e.substring(2)),t||n.warn?.(`Path starts with '~/' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):!e.startsWith("/")&&t?Ca.default.posix.join(t,e):e};l();var wo=class{constructor(t){this.sandbox=t}async run(t){if(t.status!=="requires_action")return[];if(!t.required_action)return[];let n=[];for(let r of t.required_action.submit_tool_outputs.tool_calls){let i=this.sandbox._actions.get(r.function.name);if(!i){console.warn(`Action ${r.function.name} not found`);continue}let a=JSON.parse(r.function.arguments),s=await i(this.sandbox,a);n.push({tool_call_id:r.id,output:s})}return n}};var Nn=class extends Lo{terminal;filesystem;process;_actions=new Map;static afterConnectionEstablished=[];onScanPorts;constructor(t){t=t||{},super(t),this.onScanPorts=t.onScanPorts,this.filesystem={list:async(r,i)=>await this._call(nn,"list",[n(r)],i),read:async(r,i)=>await this._call(nn,"read",[n(r)],i),remove:async(r,i)=>{await this._call(nn,"remove",[n(r)],i)},write:async(r,i,a)=>{await this._call(nn,"write",[n(r),i],a)},writeBytes:async(r,i)=>{let a=Buffer.from(i).toString("base64");await this._call(nn,"writeBase64",[n(r),a])},readBytes:async r=>{let i=await this._call(nn,"readBase64",[n(r)]);return Buffer.from(i,"base64")},makeDir:async(r,i)=>{await this._call(nn,"makeDir",[n(r)],i)},watchDir:r=>{this.logger.debug?.(`Watching directory "${r}"`);let i=(0,cA.default)(n(r));return new RR(this,i)}},this.terminal={start:async({onData:r,size:i,onExit:a,envVars:s,cmd:o,cwd:c="",terminalID:u=ni(12),timeout:_=void 0})=>await tn(async({onData:g,size:C,onExit:S,envVars:A,cmd:x,cwd:P="",rootDir:B,terminalID:U=ni(12)})=>{this.logger.debug?.(`Starting terminal "${U}"`),!P&&B&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),P=B),!P&&this.cwd&&(P=this.cwd),A=A||{},A={...this.envVars,...A};let{promise:q,resolve:te}=_a(),Z=new _o;function re(ae){Z.addData(ae),g?.(ae)}let[M,w]=await this._handleSubscriptions(this._subscribe(Sr,re,"onData",U),this._subscribe(Sr,te,"onExit",U)),{promise:G,resolve:z}=_a();q.then(async()=>{Promise.allSettled([this._unsubscribe(w),this._unsubscribe(M)]).then(ae=>{let de=ua(ae);de&&this.logger.debug?.(de)}),this.logger.debug?.(`Terminal "${U}" exited`),S?.(),z(Z)});try{await this._call(Sr,"start",[U,C.cols,C.rows,...x!==void 0?[A,x,P]:[]])}catch(ae){throw te(),await G,ae}return new mo(U,this,te,G,Z)},_)({onData:r,size:i,onExit:a,envVars:s,cmd:o,cwd:c,terminalID:u})},this.process={start:async r=>{let i=typeof r=="string"?{cmd:r}:r,a=async({cmd:o,onStdout:c,onStderr:u,onExit:_,envVars:m={},cwd:g="",rootDir:C,processID:S=ni(12)})=>{if(!g&&C&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),g=C),!g&&this.cwd&&(g=this.cwd),!o)throw new Error("cmd is required");m=m||{},m={...this.envVars,...m},this.logger.debug?.(`Starting process "${S}", cmd: "${o}"`);let{promise:A,resolve:x}=_a(),P=new fo,B=G=>{P.setExitCode(G),x()},U=G=>{let z=new da(G.line,G.timestamp,!1);P.addStdout(z),c?c(z):this.opts.onStdout&&this.opts.onStdout(z)},q=G=>{let z=new da(G.line,G.timestamp,!0);P.addStderr(z),u?u(z):this.opts.onStderr&&this.opts.onStderr(z)},[te,Z,re]=await this._handleSubscriptions(this._subscribe(hr,B,"onExit",S),this._subscribe(hr,U,"onStdout",S),this._subscribe(hr,q,"onStderr",S)),{promise:M,resolve:w}=_a();A.then(async()=>{Promise.allSettled([this._unsubscribe(te),Z?this._unsubscribe(Z):void 0,re?this._unsubscribe(re):void 0]).then(G=>{let z=ua(G);z&&this.logger.debug?.(z)}),this.logger.debug?.(`Process "${S}" exited`),_?_(P.exitCode||0):this.opts.onExit&&this.opts.onExit(),w(P)});try{await this._call(hr,"start",[S,o,m,g])}catch(G){throw x(),await M,/error starting process '\w+': fork\/exec \/bin\/bash: no such file or directory/.test(G?.message)?new Eo(`Failed to start the process. You are trying set 'cwd' to a directory that does not exist.
90
- ${G?.message}`):G}return new go(S,this,x,M,P)},s=i.timeout;return await tn(a,s)(i)},startAndWait:async r=>{let i=typeof r=="string"?{cmd:r}:r;return await(await this.process.start(i)).wait()}};let n=r=>lA(r,this.cwd,this.logger)}get fileURL(){let t=this.getProtocol("http",this.opts.__debug_devEnv!=="local"),n=this.getHostname(this.opts.__debug_port||lo);return`${t}://${n}${fR}`}get actions(){return new Map(this._actions)}get openai(){return{actions:new wo(this)}}static async create(t){let n=typeof t=="string"?{template:t}:t,r=new this(n);return await r._open({timeout:n?.timeout},this.afterConnectionEstablished),r}static async reconnect(t){let n,r;typeof t=="string"?(n=t,r={}):(n=t.sandboxID,r=t);let i=n.split("-"),a=i[0],s=i[1];r.__sandbox={sandboxID:a,clientID:s,templateID:"unknown"};let o=new this(r);return await o._open({timeout:r?.timeout},this.afterConnectionEstablished),o}addAction(t,n){if(typeof t=="string"){if(!n)throw new Error("Action is required");return this._actions.set(t,n),this}else if(typeof t=="function"){if(n=t,!n.name)throw new Error("Action name is required");this._actions.set(n.name,n)}else throw new Error("Action or action name and action is required");return this}removeAction(t){return this._actions.delete(t),this}async uploadFile(t,n){let r=new FormData,i=t instanceof Blob?t:new Blob([t],{type:"application/octet-stream"});r.append("file",i,n);let a=await fetch(this.fileURL,{method:"POST",body:r});if(!a.ok){let s=await a.text();throw new Error(`Failed to upload file ${a.status} - ${a.statusText}: ${s}`)}return`/home/user/${n}`}async downloadFile(t,n){t=encodeURIComponent(t);let r=await fetch(`${this.fileURL}?path=${t}`);if(!r.ok){let i=await r.text();throw new Error(`Failed to download file '${t}': ${i}`)}switch(n){case"base64":return Buffer.from(await r.arrayBuffer()).toString("base64");case"blob":return await r.blob();case"buffer":return Buffer.from(await r.arrayBuffer());case"arraybuffer":return await r.arrayBuffer();case"text":return await r.text();default:return await r.arrayBuffer()}}async _open(t,n=[]){await super._open(t);let r=this.onScanPorts?i=>this.onScanPorts?.(i.map(a=>({ip:a.Ip,port:a.Port,state:a.State}))):void 0;await this._handleSubscriptions(r?this._subscribe(NR,r,"scanOpenedPorts"):void 0),this.cwd&&(this.logger.debug?.(`Custom cwd for Sandbox set: "${this.cwd}"`),await this.filesystem.makeDir(this.cwd)),(this.opts.onStdout||this.opts.onStderr)&&this.handleStartCmdLogs();for(let i of n)i(this);return this}async handleStartCmdLogs(){try{await this.process.startAndWait({cmd:"sudo journalctl --follow --lines=all -o cat _SYSTEMD_UNIT=start_cmd.service",envVars:{},cwd:"/"})}catch(t){this.logger.debug?.("start command not started",t)}}};var yN=J(gA());l();async function SA(e){return new Promise(t=>setTimeout(t,e))}l();l();var hA=J(require("os")),TA=J(require("path")),Fo=J(require("fs")),Zn=TA.join(hA.homedir(),".e2b","config.json"),K_=process.env.E2B_DOCS_BASE||"https://e2b.dev/docs";function Rr(){return Fo.existsSync(Zn)?JSON.parse(Fo.readFileSync(Zn,"utf8")):null}var ko=process.env.E2B_API_KEY,Bo=process.env.E2B_ACCESS_TOKEN,bA=fr(`You must be logged in to use this command. Run ${be("e2b auth login")}.
89
+ `;messages=[];_finished=!1;_error=!1;_exitCode;get error(){return this._error}get exitCode(){if(!this._finished)throw new Error("Process has not finished yet");return this._exitCode}get stdout(){return this.messages.filter(t=>!t.error).map(t=>t.line).join(this.delimiter)}get stderr(){return this.messages.filter(t=>t.error).map(t=>t.line).join(this.delimiter)}addStdout(t){this.insertByTimestamp(t)}addStderr(t){this._error=!0,this.insertByTimestamp(t)}setExitCode(t){this._exitCode=t,this._finished=!0}insertByTimestamp(t){let n=this.messages.length-1;for(;n>=0&&this.messages[n].timestamp>t.timestamp;)n-=1;this.messages.splice(n+1,0,t)}},go=class{constructor(t,n,r,i,a){this.processID=t;this.sandbox=n;this.triggerExit=r;this.output=a;this.finished=i}finished;async kill(){try{await this.sandbox._call(hr,"kill",[this.processID])}finally{this.triggerExit(),await this.finished}}async wait(t){return await tn(()=>this.finished,t)()}async sendStdin(t,n){await this.sandbox._call(hr,"stdin",[this.processID,t],n)}};l();var cA=J(AR());l();function ni(e){let t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=n.length;for(let i=0;i<e;i++)t+=n.charAt(Math.floor(Math.random()*r));return t}l();var NR="codeSnippet";l();l();var tA=J(eA());var xo=class{ws;onOpenHandlers=[];onAnyMessageHandlers=[];onNotification=[];onRequest=[];onSuccessResponse=[];onErrorResponse=[];onErrorHandlers=[];onCloseHandlers=[];config={responseTimeout:1e4};idAwaiter={};constructor(){this.ws=void 0}connect(t,n){return this.ws=new tA.default(t,n),this.listen()}onOpen(t){this.onOpenHandlers.push(t)}onAnyMessage(t){this.onAnyMessageHandlers.push(t)}onError(t){this.onErrorHandlers.push(t)}onClose(t){this.onCloseHandlers.push(t)}listenMessages(){let t;this.ws.onmessage&&(t=this.ws.onmessage.bind(this.ws)),this.ws.onmessage=n=>{t&&t(n);for(let i of this.onAnyMessageHandlers)i(n);let r=JSON.parse(n.data.toString());if(this.isNotification(r))for(let i of this.onNotification)i(r);else if(this.isRequest(r))for(let i of this.onRequest)i(r);else if(this.isSuccessResponse(r)){for(let i of this.onSuccessResponse)i(r);this.idAwaiter[r.id](r.result)}else if(this.isErrorResponse(r)){for(let i of this.onErrorResponse)i(r);this.idAwaiter[r.id](r.error)}}}call(t,n){return new Promise((r,i)=>{let a=this.buildRequest(t,n),s;this.config.responseTimeout&&(s=setTimeout(()=>{delete this.idAwaiter[a.id],i(new Error(`Awaiting response to "${t}" with id: ${a.id} timed out.`))},this.config.responseTimeout)),this.idAwaiter[a.id]=c=>{if(clearInterval(s),delete this.idAwaiter[a.id],this.isRpcError(c)){i(new Error(`RPC Error (${c.code}): ${c.message}`));return}r(c)};let o=JSON.stringify(a);this.ws.send(o)})}notify(t,n){this.ws.send(JSON.stringify(this.buildNotification(t,n)))}customId(t){this.idFn=t}noRpc(){this.buildRequest=this.buildRequestBase,this.buildNotification=this.buildNotificationBase,this.buildRpcSuccessResponse=this.buildRpcSuccessResponseBase,this.buildRpcErrorResponse=this.buildRpcErrorResponseBase}configure(t){Object.assign(this.config,t)}changeSocket(t){this.ws=t}listen(){return new Promise((t,n)=>{this.ws.onopen=r=>{for(let i of this.onOpenHandlers)i(r);t(r)},this.listenMessages(),this.ws.onerror=r=>{for(let i of this.onErrorHandlers)i(r)},this.ws.onclose=r=>{for(let i of this.onCloseHandlers)i(r);n(new Error(`WebSocket closed with code: ${r.code} and reason: ${r.reason}`))}})}buildRequest(t,n){let r=this.buildRequestBase(t,n);return r.jsonrpc="2.0",r}buildRequestBase(t,n){let r={};return r.id=this.idFn(),r.method=t,n&&(r.params=n),r}buildNotification(t,n){let r=this.buildNotificationBase(t,n);return r.jsonrpc="2.0",r}buildNotificationBase(t,n){let r={};return r.method=t,n&&(r.params=n),r}buildRpcSuccessResponse(t,n){let r=this.buildRpcSuccessResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcSuccessResponseBase(t,n){let r={};return r.id=t,r.result=n,r}buildRpcErrorResponse(t,n){let r=this.buildRpcErrorResponseBase(t,n);return r.jsonrpc="2.0",r}buildRpcErrorResponseBase(t,n){let r={};return r.id=t,r.error=n,r}idFn(){return ni(12)}isNotification(t){return!t.id}isRequest(t){return t.method}isSuccessResponse(t){return t.hasOwnProperty("result")}isErrorResponse(t){return t.hasOwnProperty("error")}isRpcError(t){return typeof t?.code<"u"}};l();function J6(e){return new Promise(t=>setTimeout(t,e))}var H_=J6;l();function Mo(e){if(e=e||process?.env?.E2B_API_KEY,!e)throw new po("API key is required, please visit https://e2b.dev/docs to get your API key. You can either set the environment variable `E2B_API_KEY` or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})");return e}var nA=zn(lt.path("/sandboxes").method("get").create()),rA=zn(lt.path("/sandboxes").method("post").create()),iA=zn(lt.path("/sandboxes/{sandboxID}").method("delete").create()),Y_=zn(lt.path("/sandboxes/{sandboxID}/refreshes").method("post").create()),Lo=class{constructor(t){this.opts=t;this.sandbox=t.__sandbox,this.apiKey=Mo(t.apiKey),this.cwd=t.cwd,this.cwd&&this.cwd.startsWith("~")&&(this.cwd=this.cwd.replace("~","/home/user"));let n={PYTHONUNBUFFERED:"1"};this.envVars={...n,...t.envVars||{}},this.logger=t.logger??{info:console.info,warn:console.warn,error:console.error},this.logger.debug?.(`Sandbox "${this.templateID}" initialized`)}cwd;envVars;logger;sandbox;isOpen=!1;apiKey;rpc=new xo;subscribers=[];get id(){return`${this.sandbox?.sandboxID}-${this.sandbox?.clientID}`}get templateID(){return this.opts.template||this.opts.id||"base"}static async list(t){t=Mo(t);try{return(await nA(t,{})).data.map(r=>({sandboxID:`${r.sandboxID}-${r.clientID}`,templateID:r.templateID,cpuCount:r.cpuCount,memoryMB:r.memoryMB,...r.alias&&{alias:r.alias},...r.metadata&&{metadata:r.metadata},startedAt:new Date(r.startedAt)}))}catch(n){if(n instanceof nA.Error){let r=n.getActualType();if(r.status===401)throw new Error(`Error listing sandboxes - (${r.status}) unauthenticated: ${r.data.message}`);if(r.status===500)throw new Error(`Error listing sandboxes - (${r.status}) server error: ${r.data.message}`)}throw n}}static async kill(t,n){n=Mo(n);let r=t.split("-")[0];try{await iA(n,{sandboxID:r})}catch(i){if(i instanceof iA.Error){let a=i.getActualType();if(a.status===401)throw new Error(`Error killing sandbox (${t}) - (${a.status}) unauthenticated: ${a.data.message}`);if(a.status===500)throw new Error(`Error killing sandbox (${t}) - (${a.status}) server error: ${a.data.message}`)}throw i}}async keepAlive(t){if(t=Math.round(t/1e3),t<0||t>3600)throw new Error("Duration must be between 0 and 3600 seconds");if(!this.sandbox)throw new Error("Cannot keep alive - sandbox is not initialized");await Y_(this.apiKey,{sandboxID:this.sandbox?.sandboxID,duration:t})}getHostname(t){if(this.opts.__debug_hostname)return t&&this.opts.__debug_devEnv==="remote"?`${t}-${this.opts.__debug_hostname}`:t?`${this.opts.__debug_hostname}:${t}`:this.opts.__debug_hostname;if(!this.sandbox)throw new Error("Cannot get sandbox's hostname - sandbox is not initialized");let n=`${this.id}.${gr}`;return t?`${t}-${n}`:n}getProtocol(t="http",n=a_){return n?`${t}s`:t}async close(){this.isOpen&&(this.logger.debug?.(`Closing sandbox "${this.id}"`),this.isOpen=!1,this.rpc.ws?.terminate?.(),this.rpc.ws?.close?.(),this.subscribers=[],this.logger.debug?.("Disconnected from the sandbox"))}async _call(t,n,r,i){return this.logger.debug?.(`Calling "${t}_${n}" with params:`,r),await tn(async(s,o)=>await this.rpc.call(s,o),i?.timeout)(`${t}_${n}`,r)}async _handleSubscriptions(...t){let n=await Promise.allSettled(t);if(n.every(r=>r.status==="fulfilled"))return n.map(r=>r.status==="fulfilled"?r.value:void 0);throw await Promise.all(n.filter(CR).map(r=>r.value?this._unsubscribe(r.value):void 0)),new Error(ua(n))}async _unsubscribe(t){let n=this.subscribers.find(r=>r.subID===t);n&&(await this._call(n.service,"unsubscribe",[n.subID]),this.subscribers=this.subscribers.filter(r=>r!==n),this.logger.debug?.(`Unsubscribed '${t}' from '${n.service}'`))}async _subscribe(t,n,r,...i){let a=await this._call(t,"subscribe",[r,...i]);if(typeof a!="string")throw new Error(`Cannot subscribe to ${t}_${r}${i.length>0?" with params ["+i.join(", ")+"]":""}. Expected response should have been a subscription ID, instead we got ${JSON.stringify(a)}`);return this.subscribers.push({handler:n,service:t,subID:a}),this.logger.debug?.(`Subscribed to "${t}_${r}"${i.length>0?" with params ["+i.join(", ")+"] and":""} with id "${a}"`),a}async _open(t){let n=async()=>{if(this.isOpen)throw new Error("Sandbox connect was already called");if(this.isOpen=!0,this.logger.debug?.("Opening sandbox..."),!this.sandbox&&!this.opts.__debug_hostname)try{let r=await rA(this.apiKey,{templateID:this.templateID,metadata:this.opts.metadata});this.sandbox=r.data,this.logger.debug?.(`Acquired sandbox "${this.id}"`)}catch(r){if(r instanceof rA.Error){let i=r.getActualType();if(i.status===400)throw new Error(`Error creating sandbox - (${i.status}) bad request: ${i.data.message}`);if(i.status===401)throw new Error(`Error creating sandbox - (${i.status}) unauthenticated: ${i.data.message}`);if(i.status===500)throw new Error(`Error creating sandbox - (${i.status}) server error: ${i.data.message}`)}throw r}return this.sandbox&&!this.opts.__debug_hostname&&this.refresh(this.sandbox.sandboxID),await this.connectRpc(),this};try{return await tn(n,t?.timeout)()}catch(r){throw await this.close(),r}}async connectRpc(){let t=this.getHostname(this.opts.__debug_port||lo),r=`${this.getProtocol("ws",this.opts.__debug_devEnv!=="local")}://${t}${ER}`,i=!1,a,s,o=new Promise((c,u)=>{a=()=>{i||(i=!0,c())},s=()=>{i||(i=!0,u())}});this.rpc.onOpen(()=>{this.logger.debug?.(`Connected to sandbox "${this.id}"`),a?.()}),this.rpc.onError(async c=>{if(this.logger.debug?.(`Error in WebSocket of sandbox "${this.id}": ${c.message??c.code??c.toString()}. Trying to reconnect...`),this.isOpen){await H_(150),this.logger.debug?.(`Reconnecting to sandbox "${this.id}"`);try{this.subscribers=[],await this.rpc.connect(r),this.logger.debug?.(`Reconnected to sandbox "${this.id}"`)}catch(u){this.logger.debug?.(`Failed reconnecting to sandbox "${this.id}": ${u.message??u.code??u.toString()}`)}}else s?.()}),this.rpc.onClose(async()=>{this.logger.debug?.(`WebSocket connection to sandbox "${this.id}" closed`)}),this.rpc.onNotification.push(this.handleNotification.bind(this)),(async()=>{try{this.logger.debug?.(`Connecting to sandbox "${this.id}"`),await this.rpc.connect(r)}catch(c){this.logger.debug?.(`Error connecting to sandbox "${this.id}": ${c.message??c.code??c.toString()}`)}})(),await o}handleNotification(t){this.logger.debug?.("Handling notification:",t),this.subscribers.filter(n=>n.subID===t.params?.subscription).forEach(n=>n.handler(t.params?.result))}async refresh(t){this.logger.debug?.(`Started refreshing sandbox "${t}"`);try{for(;;){if(!this.isOpen){this.logger.debug?.(`Cannot refresh sandbox ${this.id} - it was closed`);return}await H_(5e3);try{await Y_(this.apiKey,{sandboxID:t,duration:0}),this.logger.debug?.(`Refreshed sandbox "${t}"`)}catch(n){if(n instanceof Y_.Error){let r=n.getActualType();if(r.status===404){this.logger.warn?.(`Error refreshing sandbox - (${r.status}): ${r.data.message}`);return}this.logger.warn?.(`Refreshing sandbox "${t}" failed - (${r.status})`)}}}}finally{this.logger.debug?.(`Stopped refreshing sandbox "${t}"`),await this.close()}}};l();var Ca=J(oA()),lA=(e,t,n)=>{let r;return e.startsWith("./")?(r=Ca.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with './' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("../")?(r=Ca.default.posix.join(t||"/home/user",e),t||n.warn?.(`Path starts with '../' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):e.startsWith("~/")?(r=Ca.default.posix.join(t||"/home/user",e.substring(2)),t||n.warn?.(`Path starts with '~/' and cwd isn't set. The path '${e}' will evaluate to '${r}', which may not be what you want.`),r):!e.startsWith("/")&&t?Ca.default.posix.join(t,e):e};l();var wo=class{constructor(t){this.sandbox=t}async run(t){if(t.status!=="requires_action")return[];if(!t.required_action)return[];let n=[];for(let r of t.required_action.submit_tool_outputs.tool_calls){let i=this.sandbox._actions.get(r.function.name);if(!i){console.warn(`Action ${r.function.name} not found`);continue}let a=JSON.parse(r.function.arguments),s=await i(this.sandbox,a);n.push({tool_call_id:r.id,output:s})}return n}};var Nn=class extends Lo{terminal;filesystem;process;_actions=new Map;onScanPorts;constructor(t){t=t||{},super(t),this.onScanPorts=t.onScanPorts,this.filesystem={list:async(r,i)=>await this._call(nn,"list",[n(r)],i),read:async(r,i)=>await this._call(nn,"read",[n(r)],i),remove:async(r,i)=>{await this._call(nn,"remove",[n(r)],i)},write:async(r,i,a)=>{await this._call(nn,"write",[n(r),i],a)},writeBytes:async(r,i)=>{let a=Buffer.from(i).toString("base64");await this._call(nn,"writeBase64",[n(r),a])},readBytes:async r=>{let i=await this._call(nn,"readBase64",[n(r)]);return Buffer.from(i,"base64")},makeDir:async(r,i)=>{await this._call(nn,"makeDir",[n(r)],i)},watchDir:r=>{this.logger.debug?.(`Watching directory "${r}"`);let i=(0,cA.default)(n(r));return new RR(this,i)}},this.terminal={start:async({onData:r,size:i,onExit:a,envVars:s,cmd:o,cwd:c="",terminalID:u=ni(12),timeout:_=void 0})=>await tn(async({onData:g,size:C,onExit:S,envVars:A,cmd:x,cwd:P="",rootDir:B,terminalID:U=ni(12)})=>{this.logger.debug?.(`Starting terminal "${U}"`),!P&&B&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),P=B),!P&&this.cwd&&(P=this.cwd),A=A||{},A={...this.envVars,...A};let{promise:q,resolve:te}=_a(),Z=new _o;function re(ae){Z.addData(ae),g?.(ae)}let[M,w]=await this._handleSubscriptions(this._subscribe(Sr,re,"onData",U),this._subscribe(Sr,te,"onExit",U)),{promise:G,resolve:z}=_a();q.then(async()=>{Promise.allSettled([this._unsubscribe(w),this._unsubscribe(M)]).then(ae=>{let de=ua(ae);de&&this.logger.debug?.(de)}),this.logger.debug?.(`Terminal "${U}" exited`),S?.(),z(Z)});try{await this._call(Sr,"start",[U,C.cols,C.rows,...x!==void 0?[A,x,P]:[]])}catch(ae){throw te(),await G,ae}return new mo(U,this,te,G,Z)},_)({onData:r,size:i,onExit:a,envVars:s,cmd:o,cwd:c,terminalID:u})},this.process={start:async r=>{let i=typeof r=="string"?{cmd:r}:r,a=async({cmd:o,onStdout:c,onStderr:u,onExit:_,envVars:m={},cwd:g="",rootDir:C,processID:S=ni(12)})=>{if(!g&&C&&(this.logger.warn?.("The rootDir parameter is deprecated, use cwd instead."),g=C),!g&&this.cwd&&(g=this.cwd),!o)throw new Error("cmd is required");m=m||{},m={...this.envVars,...m},this.logger.debug?.(`Starting process "${S}", cmd: "${o}"`);let{promise:A,resolve:x}=_a(),P=new fo,B=G=>{P.setExitCode(G),x()},U=G=>{let z=new da(G.line,G.timestamp,!1);P.addStdout(z),c?c(z):this.opts.onStdout&&this.opts.onStdout(z)},q=G=>{let z=new da(G.line,G.timestamp,!0);P.addStderr(z),u?u(z):this.opts.onStderr&&this.opts.onStderr(z)},[te,Z,re]=await this._handleSubscriptions(this._subscribe(hr,B,"onExit",S),this._subscribe(hr,U,"onStdout",S),this._subscribe(hr,q,"onStderr",S)),{promise:M,resolve:w}=_a();A.then(async()=>{Promise.allSettled([this._unsubscribe(te),Z?this._unsubscribe(Z):void 0,re?this._unsubscribe(re):void 0]).then(G=>{let z=ua(G);z&&this.logger.debug?.(z)}),this.logger.debug?.(`Process "${S}" exited`),_?_(P.exitCode||0):this.opts.onExit&&this.opts.onExit(),w(P)});try{await this._call(hr,"start",[S,o,m,g])}catch(G){throw x(),await M,/error starting process '\w+': fork\/exec \/bin\/bash: no such file or directory/.test(G?.message)?new Eo(`Failed to start the process. You are trying set 'cwd' to a directory that does not exist.
90
+ ${G?.message}`):G}return new go(S,this,x,M,P)},s=i.timeout;return await tn(a,s)(i)},startAndWait:async r=>{let i=typeof r=="string"?{cmd:r}:r;return await(await this.process.start(i)).wait()}};let n=r=>lA(r,this.cwd,this.logger)}get fileURL(){let t=this.getProtocol("http",this.opts.__debug_devEnv!=="local"),n=this.getHostname(this.opts.__debug_port||lo);return`${t}://${n}${fR}`}get actions(){return new Map(this._actions)}get openai(){return{actions:new wo(this)}}static async create(t){let n=typeof t=="string"?{template:t}:t,r=new this(n);return await r._open({timeout:n?.timeout}),r}static async reconnect(t){let n,r;typeof t=="string"?(n=t,r={}):(n=t.sandboxID,r=t);let i=n.split("-"),a=i[0],s=i[1];r.__sandbox={sandboxID:a,clientID:s,templateID:"unknown"};let o=new this(r);return await o._open({timeout:r?.timeout}),o}addAction(t,n){if(typeof t=="string"){if(!n)throw new Error("Action is required");return this._actions.set(t,n),this}else if(typeof t=="function"){if(n=t,!n.name)throw new Error("Action name is required");this._actions.set(n.name,n)}else throw new Error("Action or action name and action is required");return this}removeAction(t){return this._actions.delete(t),this}async uploadFile(t,n){let r=new FormData,i=t instanceof Blob?t:new Blob([t],{type:"application/octet-stream"});r.append("file",i,n);let a=await fetch(this.fileURL,{method:"POST",body:r});if(!a.ok){let s=await a.text();throw new Error(`Failed to upload file ${a.status} - ${a.statusText}: ${s}`)}return`/home/user/${n}`}async downloadFile(t,n){t=encodeURIComponent(t);let r=await fetch(`${this.fileURL}?path=${t}`);if(!r.ok){let i=await r.text();throw new Error(`Failed to download file '${t}': ${i}`)}switch(n){case"base64":return Buffer.from(await r.arrayBuffer()).toString("base64");case"blob":return await r.blob();case"buffer":return Buffer.from(await r.arrayBuffer());case"arraybuffer":return await r.arrayBuffer();case"text":return await r.text();default:return await r.arrayBuffer()}}async _open(t){await super._open(t);let n=this.onScanPorts?r=>this.onScanPorts?.(r.map(i=>({ip:i.Ip,port:i.Port,state:i.State}))):void 0;return await this._handleSubscriptions(n?this._subscribe(NR,n,"scanOpenedPorts"):void 0),this.cwd&&(this.logger.debug?.(`Custom cwd for Sandbox set: "${this.cwd}"`),await this.filesystem.makeDir(this.cwd)),(this.opts.onStdout||this.opts.onStderr)&&this.handleStartCmdLogs(),this}async handleStartCmdLogs(){try{await this.process.startAndWait({cmd:"sudo journalctl --follow --lines=all -o cat _SYSTEMD_UNIT=start_cmd.service",envVars:{},cwd:"/"})}catch(t){this.logger.debug?.("start command not started",t)}}};var yN=J(gA());l();async function SA(e){return new Promise(t=>setTimeout(t,e))}l();l();var hA=J(require("os")),TA=J(require("path")),Fo=J(require("fs")),Zn=TA.join(hA.homedir(),".e2b","config.json"),K_=process.env.E2B_DOCS_BASE||"https://e2b.dev/docs";function Rr(){return Fo.existsSync(Zn)?JSON.parse(Fo.readFileSync(Zn,"utf8")):null}var ko=process.env.E2B_API_KEY,Bo=process.env.E2B_ACCESS_TOKEN,bA=fr(`You must be logged in to use this command. Run ${be("e2b auth login")}.
91
91
 
92
92
  If you are seeing this message in CI/CD you may need to set the ${be("E2B_ACCESS_TOKEN")} environment variable.
93
93
  Visit ${Dt("https://e2b.dev/docs/getting-started/api-key")} to get the access token.`,{width:70,float:"center",padding:.5,margin:1,borderStyle:"round",borderColor:"redBright"});function Jn(){if(ko||(ko=Rr()?.defaultTeamApiKey),!ko)console.error(bA),process.exit(1);else return ko}function li(){if(Bo||(Bo=Rr()?.accessToken),!Bo)console.error(bA),process.exit(1);else return Bo}l();var er=new Mr("-p, --path <path>",`change root directory where command is executed to ${be("<path>")} directory`),lre=new Mr("-s, --select","select multiple sandbox templates from interactive list"),DA=new Mr("-s, --select","select sandbox template from interactive list");l();var tr="e2b.Dockerfile",Uo="Dockerfile",CA=`# You can use most Debian-based base images
@@ -109,8 +109,8 @@ attempted value: ${s}
109
109
  # const sandbox = await Sandbox.create({ template: '${e.template_name||e.template_id}' })
110
110
 
111
111
  `}var ON=nd({template_id:_i().required(),template_name:_i().optional(),dockerfile:_i().required(),start_cmd:_i().optional(),cpu_count:tl().integer().min(1).optional(),memory_mb:tl().integer().min(128).optional()}),y7=[{from:"id",to:"template_id"},{from:"name",to:"template_name"}];function v7(e,t){for(let n of t){let r=n.from,i=n.to;e[r]&&(e[i]=e[r],delete e[r])}return e}async function Ei(e){let t=await mi.readFile(e,"utf-8"),n=cl.parse(t),r=v7(n,y7);return await ON.validate(r)}async function AN(e,t,n){try{if(!n&&CN.existsSync(e))throw new Error(`Config already exists on path ${rt(e)}`);let r=await ON.validate(t,{stripUnknown:!0}),i=cl.stringify(r);await mi.writeFile(e,I7(t)+i)}catch(r){throw new Error(`E2B sandbox template config ${nt({templateID:t.template_id},e)} cannot be saved: ${r.message}`)}}async function NN(e){await mi.unlink(e)}function fi(e){return RN.join(e,pi)}var ul=J(require("child_process")),x7=500,IN=en(lt.path("/templates/{templateID}/builds/{buildID}/status").method("get").create()),M7=en(lt.path("/templates").method("post").create()),L7=en(lt.path("/templates/{templateID}").method("post").create()),w7=en(lt.path("/templates/{templateID}/builds/{buildID}").method("post").create()),vN=new Ce("build").description(`build sandbox template defined by ${rt(tr)} or ${rt(Uo)} in root directory. By default the root directory is the current working directory. This command also creates ${Ct(pi)} config.`).argument("[template]",`specify ${be("[template]")} to rebuild it. If you don's specify ${be("[template]")} and there is no ${Ct("e2b.toml")} a new sandbox template will be created.`).addOption(er).option("-d, --dockerfile <file>",`specify path to Dockerfile. By default E2B tries to find ${Ct(tr)} or ${Ct(Uo)} in root directory.`).option("-n, --name <template-name>","specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores.").option("-c, --cmd <start-command>","specify command that will be executed when the sandbox is started.").option("--cpu-count <cpu-count>","specify the number of CPUs that will be used to run the sandbox. The default value is 2.",parseInt).option("--memory-mb <memory-mb>","specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512.",parseInt).alias("bd").action(async(e,t)=>{try{yN.default.sync("docker")||(console.error("Docker is required to build and push the sandbox template. Please install Docker and try again."),process.exit(1));let r=li();process.stdout.write(`
112
- `);let i=t.name?.trim();i&&!/[a-z0-9-_]+/.test(i)&&(console.error(`Name ${Ct(i)} is not valid. Name can only contain lowercase letters, numbers, dashes and underscores.`),process.exit(1));let a=t.dockerfile,s=t.cmd,o=t.cpuCount,c=t.memoryMb,u=Kn(t.path),_=fi(u),m=Ia.existsSync(_)?await Ei(_):void 0,g=xn.relative(u,_);m&&(console.log(`Found sandbox template ${nt({templateID:m.template_id,aliases:m.template_name?[m.template_name]:void 0},g)}`),e=m.template_id,a=t.dockerfile||m.dockerfile,s=t.cmd||m.start_cmd,o=t.cpuCount||m.cpu_count,c=t.memoryMb||m.memory_mb),m&&e&&m.template_id!==e&&(console.error("You can't specify different ID than the one in config. If you want to build a new sandbox template remove the config file."),process.exit(1)),i&&m?.template_name&&i!==m?.template_name&&console.log(`The sandbox template name will be changed from ${Ct(m.template_name)} to ${Ct(i)}.`);let C=i||m?.template_name,{dockerfileContent:S,dockerfileRelativePath:A}=F7(u,a);console.log(`Found ${rt(A)} that will be used to build the sandbox template.`);let x={alias:C,startCmd:s,cpuCount:o,memoryMB:c,dockerfile:S};t.memoryMb&&t.memoryMb%2!==0&&(console.error(`The memory in megabytes must be an even number. You provided ${Ct(t.memoryMb.toFixed(0))}.`),process.exit(1));let P=await k7(r,x,!!m,g,e);e=P.templateID,console.log(`Requested build for the sandbox template ${nt(P)} `),await AN(_,{template_id:P.templateID,dockerfile:A,template_name:C,start_cmd:s,cpu_count:o,memory_mb:c},!0);try{ul.execSync(`echo ${r} | docker login docker.${gr} -u _e2b_access_token --password-stdin`,{stdio:"inherit",cwd:u})}catch{console.error("Docker login failed. Please try to login with `e2b auth login` and try again."),process.exit(1)}console.log(`Docker login successful.
113
- `),console.log("Building docker image..."),ul.execSync(`DOCKER_CLI_HINTS=false docker build . -f ${A} --platform linux/amd64 -t docker.${gr}/e2b/custom-envs/${e}:${P.buildID}`,{stdio:"inherit",cwd:u}),console.log(`Docker image built.
112
+ `);let i=t.name?.trim();i&&!/[a-z0-9-_]+/.test(i)&&(console.error(`Name ${Ct(i)} is not valid. Name can only contain lowercase letters, numbers, dashes and underscores.`),process.exit(1));let a=t.dockerfile,s=t.cmd,o=t.cpuCount,c=t.memoryMb,u=Kn(t.path),_=fi(u),m=Ia.existsSync(_)?await Ei(_):void 0,g=xn.relative(u,_);m&&(console.log(`Found sandbox template ${nt({templateID:m.template_id,aliases:m.template_name?[m.template_name]:void 0},g)}`),e=m.template_id,a=t.dockerfile||m.dockerfile,s=t.cmd||m.start_cmd,o=t.cpuCount||m.cpu_count,c=t.memoryMb||m.memory_mb),m&&e&&m.template_id!==e&&(console.error("You can't specify different ID than the one in config. If you want to build a new sandbox template remove the config file."),process.exit(1)),i&&m?.template_name&&i!==m?.template_name&&console.log(`The sandbox template name will be changed from ${Ct(m.template_name)} to ${Ct(i)}.`);let C=i||m?.template_name,{dockerfileContent:S,dockerfileRelativePath:A}=F7(u,a);console.log(`Found ${rt(A)} that will be used to build the sandbox template.`);let x={alias:C,startCmd:s,cpuCount:o,memoryMB:c,dockerfile:S};t.memoryMb&&t.memoryMb%2!==0&&(console.error(`The memory in megabytes must be an even number. You provided ${Ct(t.memoryMb.toFixed(0))}.`),process.exit(1));let P=await k7(r,x,!!m,g,e);e=P.templateID,console.log(`Requested build for the sandbox template ${nt(P)} `),await AN(_,{template_id:P.templateID,dockerfile:A,template_name:C,start_cmd:s,cpu_count:o,memory_mb:c},!0);try{ul.execSync(`echo "${r}" | docker login docker.${gr} -u _e2b_access_token --password-stdin`,{stdio:"inherit",cwd:u})}catch{console.error("Docker login failed. Please try to login with `e2b auth login` and try again."),process.exit(1)}process.stdout.write(`
113
+ `),console.log("Building docker image..."),ul.execSync(`docker build . -f ${A} --platform linux/amd64 -t docker.${gr}/e2b/custom-envs/${e}:${P.buildID}`,{stdio:"inherit",cwd:u,env:{DOCKER_CLI_HINTS:"false"}}),console.log(`Docker image built.
114
114
  `),console.log("Pushing docker image..."),ul.execSync(`docker push docker.${gr}/e2b/custom-envs/${e}:${P.buildID}`,{stdio:"inherit",cwd:u}),console.log(`Docker image pushed.
115
115
  `),console.log("Triggering build..."),await B7(r,e,P.buildID),console.log(`Triggered build for the sandbox template ${nt(P)} `),console.log("Waiting for build to finish..."),await P7(r,e,P.buildID,C),process.exit(0)}catch(n){console.error(n),process.exit(1)}});async function P7(e,t,n,r){let i=0,a,s=r?[r]:void 0;process.stdout.write(`
116
116
  `);do{await SA(x7);try{a=await IN(e,{templateID:t,logsOffset:i,buildID:n})}catch(o){if(o instanceof IN.Error){let c=o.getActualType();if(c.status===401)throw new Error(`Error getting build info - (${c.status}) bad request: ${c.data.message}`);if(c.status===404)throw new Error(`Error getting build info - (${c.status}) not found: ${c.data.message}`);if(c.status===500)throw new Error(`Error getting build info - (${c.status}) server error: ${c.data.message}`)}throw o}switch(i+=a.data.logs.length,a.data.status){case"building":a.data.logs.forEach(o=>process.stdout.write(t_(Vt(o))));break;case"ready":{let o=cR(`from e2b import Sandbox
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e2b/cli",
3
- "version": "0.4.3-post-connection.4",
3
+ "version": "0.4.3",
4
4
  "description": "CLI for managing e2b sandbox templates",
5
5
  "homepage": "https://e2b.dev",
6
6
  "license": "MIT",
@@ -19,14 +19,6 @@
19
19
  "access": "public"
20
20
  },
21
21
  "sideEffects": false,
22
- "scripts": {
23
- "prepublishOnly": "pnpm build",
24
- "build": "tsc --noEmit --skipLibCheck && tsup --minify",
25
- "dev": "tsup --watch",
26
- "test": "pnpm build && cd testground/demo-basic && ../../dist/index.js template build",
27
- "check-deps": "knip",
28
- "update-deps": "ncu -u && pnpm i"
29
- },
30
22
  "devDependencies": {
31
23
  "@types/command-exists": "^1.2.3",
32
24
  "@types/inquirer": "^9.0.7",
@@ -65,5 +57,12 @@
65
57
  },
66
58
  "engines": {
67
59
  "node": ">=18"
60
+ },
61
+ "scripts": {
62
+ "build": "tsc --noEmit --skipLibCheck && tsup --minify",
63
+ "dev": "tsup --watch",
64
+ "test": "pnpm build && cd testground/demo-basic && ../../dist/index.js template build",
65
+ "check-deps": "knip",
66
+ "update-deps": "ncu -u && pnpm i"
68
67
  }
69
- }
68
+ }