@evolvingmachines/modal 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +19 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +207 -0
- package/dist/index.d.ts +207 -0
- package/dist/index.js +3 -0
- package/package.json +48 -0
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 2025 Swarmlink, 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/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Evolve SDK Modal Provider
|
|
2
|
+
|
|
3
|
+
Modal sandbox provider for [Evolve SDK](https://www.npmjs.com/package/@evolvingmachines/sdk).
|
|
4
|
+
|
|
5
|
+
**Note:** This package is automatically installed as a dependency of `@evolvingmachines/sdk`. You don't need to install it separately.
|
|
6
|
+
|
|
7
|
+
Check out the [official documentation](https://github.com/evolving-machines-lab/evolve/tree/main/docs) and [cookbooks](https://github.com/evolving-machines-lab/evolve/tree/main/cookbooks).
|
|
8
|
+
|
|
9
|
+
## Reporting Bugs
|
|
10
|
+
|
|
11
|
+
We welcome your feedback. File a [GitHub issue](https://github.com/evolving-machines-lab/evolve/issues) to report bugs or request features.
|
|
12
|
+
|
|
13
|
+
## Connect on Discord
|
|
14
|
+
|
|
15
|
+
Join the [Evolve SDK Developers Discord](https://discord.gg/Q36D8dGyNF) to connect with other developers using Evolve SDK. Get help, share feedback, and discuss your projects with the community.
|
|
16
|
+
|
|
17
|
+
## License
|
|
18
|
+
|
|
19
|
+
See [LICENSE](https://github.com/evolving-machines-lab/evolve/blob/main/LICENSE) for details.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var modal=require('modal'),tarStream=require('tar-stream');var b={"evolve-all":"evolvingmachines/evolve-all:latest"},h=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".pdf",".zip",".tar",".gz",".7z",".rar",".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".mp3",".wav",".ogg",".flac",".aac",".mp4",".avi",".mov",".mkv",".webm",".woff",".woff2",".ttf",".otf",".eot",".exe",".dll",".so",".dylib",".sqlite",".db",".pickle",".pkl",".parquet"]);function y(c){let t=c.substring(c.lastIndexOf(".")).toLowerCase();return h.has(t)}var l=class{constructor(t){this.sandbox=t;}wrapAsUser(t,e,n){let r="";n&&Object.keys(n).length>0&&(r=Object.entries(n).filter(([,o])=>o!=null).map(([o,a])=>`export ${o}='${String(a).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let s=e?`cd '${e.replace(/'/g,"'\\''")}' && ${r}${t}`:`${r}${t}`;return ["su","user","-c",`echo ${Buffer.from(s).toString("base64")} | base64 -d | bash`]}async run(t,e){let n=this.wrapAsUser(t,e?.cwd,e?.envs),r=await this.sandbox.exec(n,{timeoutMs:e?.timeoutMs}),{stdout:s,stderr:i}=await this.accumulateStreams(r,e?.onStdout,e?.onStderr);return {exitCode:await r.wait(),stdout:s,stderr:i}}async spawn(t,e){let n=this.wrapAsUser(t,e?.cwd,e?.envs),r=await this.sandbox.exec(n,{timeoutMs:e?.timeoutMs}),s="",i="",o=this.accumulateStreams(r,e?.onStdout?d=>{e.onStdout(d);}:void 0,e?.onStderr?d=>{e.onStderr(d);}:void 0).then(({stdout:d,stderr:m})=>{s=d,i=m;}).catch(()=>{});return {processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await o,{exitCode:await r.wait(),stdout:s,stderr:i}),kill:async()=>false}}async list(){let t=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await t.wait(),(await t.stdout.readText()).trim().split(`
|
|
2
|
+
`).slice(1).map(r=>{let s=r.trim().split(/\s+/);return {processId:s[0],cmd:s[1]||"",args:s.slice(2),envs:{}}})}async connect(t,e){throw new Error("Modal does not support connecting to existing processes")}async sendStdin(t,e){throw new Error("Modal does not support sendStdin by process ID")}async kill(t){return await(await this.sandbox.exec(["kill","-9",t],{timeoutMs:1e4})).wait()===0}async accumulateStreams(t,e,n){let r="",s="",i=[];return i.push((async()=>{try{for await(let o of t.stdout){let a=typeof o=="string"?o:new TextDecoder().decode(o);r+=a,e?.(a);}}catch{}})()),i.push((async()=>{try{for await(let o of t.stderr){let a=typeof o=="string"?o:new TextDecoder().decode(o);s+=a,n?.(a);}}catch{}})()),await Promise.all(i),{stdout:r,stderr:s}}},f=class{constructor(t){this.sandbox=t;}async read(t){if(y(t)){let r=await this.sandbox.exec(["cat",t],{timeoutMs:3e5,mode:"binary"}),s=await r.wait();if(s!==0){let i=await r.stderr.readText();throw new Error(`Failed to read file ${t}: ${i||`exit code ${s}`}`)}return await r.stdout.readBytes()}let e=await this.sandbox.exec(["cat",t],{timeoutMs:3e5}),n=await e.wait();if(n!==0){let r=await e.stderr.readText();throw new Error(`Failed to read file ${t}: ${r||`exit code ${n}`}`)}return await e.stdout.readText()}async write(t,e){let n=this.toBuffer(e),r=t.substring(0,t.lastIndexOf("/"));r&&await this.makeDir(r);let s=t.replace(/'/g,"'\\''"),i=await this.sandbox.exec(["bash","-c",`cat > '${s}'`],{mode:"binary"});await i.stdin.writeBytes(new Uint8Array(n)),await i.stdin.getWriter().close(),await i.wait(),await(await this.sandbox.exec(["chown","user:user",t],{timeoutMs:1e4})).wait();}async writeBatch(t){let e=tarStream.pack(),n=[],r=new Set;for(let a of t){let d=this.toBuffer(a.data),m=a.path.startsWith("/")?a.path.slice(1):a.path;e.entry({name:m},d);let u=a.path.substring(0,a.path.lastIndexOf("/"));u&&r.add(u);}e.finalize();for await(let a of e)n.push(Buffer.from(a));let s=Buffer.concat(n),i=await this.sandbox.exec(["tar","-xf","-","-C","/"],{mode:"binary"});if(await i.stdin.writeBytes(new Uint8Array(s)),await i.stdin.getWriter().close(),await i.wait(),r.size>0){let a=Array.from(r),d=new Set(a.map(m=>m.split("/").slice(0,4).join("/")));for(let m of d)await(await this.sandbox.exec(["chown","-R","user:user",m],{timeoutMs:3e4})).wait();}}async makeDir(t){await(await this.sandbox.exec(["mkdir","-p",t],{timeoutMs:1e4})).wait(),await(await this.sandbox.exec(["chown","-R","user:user",t],{timeoutMs:1e4})).wait();}async exists(t){return await(await this.sandbox.exec(["test","-e",t],{timeoutMs:1e4})).wait()===0}async list(t){let e=t.replace(/'/g,"'\\''"),n=await this.sandbox.exec(["bash","-c",`ls -la '${e}' | tail -n +2`],{timeoutMs:3e4});await n.wait();let r=await n.stdout.readText(),s=[];for(let i of r.trim().split(`
|
|
3
|
+
`)){if(!i)continue;let o=i.split(/\s+/);if(o.length<9)continue;let a=o[0],d=o.slice(8).join(" ");d==="."||d===".."||s.push({name:d,path:t.endsWith("/")?`${t}${d}`:`${t}/${d}`,type:a.startsWith("d")?"dir":"file"});}return s}async remove(t){await(await this.sandbox.exec(["rm","-rf",t],{timeoutMs:3e4})).wait();}async rename(t,e){await(await this.sandbox.exec(["mv",t,e],{timeoutMs:3e4})).wait();}async readStream(t){return (await this.sandbox.exec(["cat",t],{timeoutMs:3e5,mode:"binary"})).stdout}async writeStream(t,e){let n=t.substring(0,t.lastIndexOf("/"));n&&await this.makeDir(n);let r=t.replace(/'/g,"'\\''"),s=await this.sandbox.exec(["bash","-c",`cat > '${r}'`],{mode:"binary"}),i=e.getReader();try{for(;;){let{done:a,value:d}=await i.read();if(a)break;await s.stdin.writeBytes(d);}}finally{i.releaseLock();}await s.stdin.getWriter().close(),await s.wait();}async uploadUrl(t,e){throw new Error("Modal does not support pre-signed upload URLs")}async downloadUrl(t,e){throw new Error("Modal does not support pre-signed download URLs")}async watchDir(t,e,n){throw new Error("Modal does not support watchDir")}toBuffer(t){if(typeof t=="string")return Buffer.from(t,"utf-8");if(t instanceof Buffer)return t;if(t instanceof ArrayBuffer||t instanceof Uint8Array)return Buffer.from(t);throw new Error(`Unsupported data type: ${typeof t}`)}},p=class{constructor(t,e){this.sandbox=t;this.commands=new l(t),this.files=new f(t),this.image=e,this.startTime=new Date;}commands;files;image;startTime;get sandboxId(){return this.sandbox.sandboxId}async getHost(t){let n=(await this.sandbox.tunnels())[t];if(!n)throw new Error(`No tunnel found for port ${t}`);return n.url}async isRunning(){try{return await(await this.sandbox.exec(["echo","ping"],{timeoutMs:5e3})).wait(),!0}catch{return false}}async getInfo(){return {sandboxId:this.sandbox.sandboxId,image:this.image,metadata:{},startedAt:this.startTime.toISOString()}}async kill(){try{await this.sandbox.terminate();}catch{await new Promise(t=>setTimeout(t,500)),await this.sandbox.terminate();}}async pause(){throw new Error("Modal does not support pause. Use kill() instead.")}},g=class{providerType="modal";client;appName;defaultTimeoutMs;_app;constructor(t={}){this.client=new modal.ModalClient,this.appName=t.appName??"evolve-sandbox",this.defaultTimeoutMs=t.defaultTimeoutMs??36e5;}async getApp(){return this._app||(this._app=await this.client.apps.fromName(this.appName,{createIfMissing:true})),this._app}async create(t){let e=await this.getApp(),n=t.timeoutMs??this.defaultTimeoutMs,r=b[t.image]??t.image,s=this.client.images.fromRegistry(r),i=t.envs?Object.fromEntries(Object.entries(t.envs).filter(([,d])=>d!=null)):void 0,o=i&&Object.keys(i).length>0?i:void 0,a=await this.client.sandboxes.create(e,s,{timeoutMs:n,workdir:t.workingDirectory,env:o});return new p(a,r)}async connect(t,e){let n=await this.client.sandboxes.fromId(t);return new p(n,"unknown")}async list(t){let e=[],n=t?.limit??100;try{for await(let r of this.client.sandboxes.list())if(e.push({sandboxId:r.sandboxId,image:"unknown",metadata:{},startedAt:new Date().toISOString()}),e.length>=n)break}catch{}return e}};function M(c={}){return new g(c)}exports.ModalProvider=g;exports.createModalProvider=M;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modal Sandbox Provider - Clean Architecture
|
|
3
|
+
*
|
|
4
|
+
* @requires modal >= 0.3.0
|
|
5
|
+
* @requires Node.js >= 18 (for ReadableStream support)
|
|
6
|
+
*
|
|
7
|
+
* Design principles:
|
|
8
|
+
* - Single way to do things (no dual methods)
|
|
9
|
+
* - Options objects only (no positional args)
|
|
10
|
+
* - All interface methods required (no optional ?)
|
|
11
|
+
* - Configuration externalized (no hardcoded mappings)
|
|
12
|
+
* - Clear naming (run = blocking, spawn = background)
|
|
13
|
+
*
|
|
14
|
+
* Modal-specific notes:
|
|
15
|
+
* - No native file APIs - uses exec() with stdin/stdout
|
|
16
|
+
* - pause() not supported - throws error
|
|
17
|
+
* - Requires app context for sandbox creation
|
|
18
|
+
*/
|
|
19
|
+
/** Result of a completed sandbox command */
|
|
20
|
+
interface SandboxCommandResult {
|
|
21
|
+
exitCode: number;
|
|
22
|
+
stdout: string;
|
|
23
|
+
stderr: string;
|
|
24
|
+
}
|
|
25
|
+
/** Handle to a running background process in sandbox */
|
|
26
|
+
interface SandboxCommandHandle {
|
|
27
|
+
readonly processId: string;
|
|
28
|
+
wait(): Promise<SandboxCommandResult>;
|
|
29
|
+
kill(): Promise<boolean>;
|
|
30
|
+
}
|
|
31
|
+
/** Information about a running process */
|
|
32
|
+
interface ProcessInfo {
|
|
33
|
+
processId: string;
|
|
34
|
+
cmd: string;
|
|
35
|
+
args: string[];
|
|
36
|
+
envs: Record<string, string>;
|
|
37
|
+
cwd?: string;
|
|
38
|
+
tag?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Sandbox metadata and lifecycle info */
|
|
41
|
+
interface SandboxInfo {
|
|
42
|
+
sandboxId: string;
|
|
43
|
+
image: string;
|
|
44
|
+
name?: string;
|
|
45
|
+
metadata: Record<string, string>;
|
|
46
|
+
startedAt: string;
|
|
47
|
+
/** End time (undefined for running sandboxes) */
|
|
48
|
+
endAt?: string;
|
|
49
|
+
}
|
|
50
|
+
/** File or directory entry info */
|
|
51
|
+
interface FileInfo {
|
|
52
|
+
name: string;
|
|
53
|
+
path: string;
|
|
54
|
+
type: "file" | "dir";
|
|
55
|
+
}
|
|
56
|
+
/** Filesystem event from watchDir */
|
|
57
|
+
interface FilesystemEvent {
|
|
58
|
+
/** Relative path to the changed file/directory */
|
|
59
|
+
name: string;
|
|
60
|
+
/** Type of filesystem operation */
|
|
61
|
+
type: "create" | "remove" | "rename" | "chmod" | "write";
|
|
62
|
+
}
|
|
63
|
+
/** Handle to stop watching a directory */
|
|
64
|
+
interface WatchHandle {
|
|
65
|
+
stop(): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
/** Options for watching a directory */
|
|
68
|
+
interface WatchOptions {
|
|
69
|
+
recursive?: boolean;
|
|
70
|
+
timeoutMs?: number;
|
|
71
|
+
onExit?: (err?: Error) => void | Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
/** Options for blocking sandbox command execution */
|
|
74
|
+
interface SandboxRunOptions {
|
|
75
|
+
timeoutMs?: number;
|
|
76
|
+
envs?: Record<string, string>;
|
|
77
|
+
cwd?: string;
|
|
78
|
+
onStdout?: (data: string) => void;
|
|
79
|
+
onStderr?: (data: string) => void;
|
|
80
|
+
}
|
|
81
|
+
/** Options for spawning background sandbox processes */
|
|
82
|
+
interface SandboxSpawnOptions extends SandboxRunOptions {
|
|
83
|
+
stdin?: boolean;
|
|
84
|
+
}
|
|
85
|
+
/** Options for connecting to a running process */
|
|
86
|
+
interface SandboxConnectOptions {
|
|
87
|
+
onStdout?: (data: string) => void;
|
|
88
|
+
onStderr?: (data: string) => void;
|
|
89
|
+
timeoutMs?: number;
|
|
90
|
+
}
|
|
91
|
+
/** Options for creating a sandbox */
|
|
92
|
+
interface SandboxCreateOptions {
|
|
93
|
+
image: string;
|
|
94
|
+
envs?: Record<string, string>;
|
|
95
|
+
metadata?: Record<string, string>;
|
|
96
|
+
timeoutMs?: number;
|
|
97
|
+
workingDirectory?: string;
|
|
98
|
+
}
|
|
99
|
+
/** Options for listing sandboxes */
|
|
100
|
+
interface SandboxListOptions {
|
|
101
|
+
state?: ("running" | "paused")[];
|
|
102
|
+
metadata?: Record<string, string>;
|
|
103
|
+
limit?: number;
|
|
104
|
+
}
|
|
105
|
+
/** Command execution capabilities */
|
|
106
|
+
interface SandboxCommands {
|
|
107
|
+
/** Run command and wait for completion */
|
|
108
|
+
run(command: string, options?: SandboxRunOptions): Promise<SandboxCommandResult>;
|
|
109
|
+
/** Spawn background process, returns handle for control */
|
|
110
|
+
spawn(command: string, options?: SandboxSpawnOptions): Promise<SandboxCommandHandle>;
|
|
111
|
+
/** List running processes */
|
|
112
|
+
list(): Promise<ProcessInfo[]>;
|
|
113
|
+
/** Connect to existing process by ID */
|
|
114
|
+
connect(processId: string, options?: SandboxConnectOptions): Promise<SandboxCommandHandle>;
|
|
115
|
+
/** Send data to process stdin */
|
|
116
|
+
sendStdin(processId: string, data: string): Promise<void>;
|
|
117
|
+
/** Kill process by ID */
|
|
118
|
+
kill(processId: string): Promise<boolean>;
|
|
119
|
+
}
|
|
120
|
+
/** File system operations */
|
|
121
|
+
interface SandboxFiles {
|
|
122
|
+
/** Read file (auto-detects binary by extension) */
|
|
123
|
+
read(path: string): Promise<string | Uint8Array>;
|
|
124
|
+
/** Write single file */
|
|
125
|
+
write(path: string, content: string | Buffer | ArrayBuffer | Uint8Array): Promise<void>;
|
|
126
|
+
/** Write multiple files in batch */
|
|
127
|
+
writeBatch(files: Array<{
|
|
128
|
+
path: string;
|
|
129
|
+
data: string | Buffer | ArrayBuffer | Uint8Array;
|
|
130
|
+
}>): Promise<void>;
|
|
131
|
+
/** Read file as stream */
|
|
132
|
+
readStream(path: string): Promise<ReadableStream<Uint8Array>>;
|
|
133
|
+
/** Write from stream */
|
|
134
|
+
writeStream(path: string, stream: ReadableStream<Uint8Array>): Promise<void>;
|
|
135
|
+
/** Get pre-signed upload URL for large files (expiration in seconds) */
|
|
136
|
+
uploadUrl(path: string, expiresInSeconds?: number): Promise<string>;
|
|
137
|
+
/** Get pre-signed download URL for large files (expiration in seconds) */
|
|
138
|
+
downloadUrl(path: string, expiresInSeconds?: number): Promise<string>;
|
|
139
|
+
/** Create directory (recursive) */
|
|
140
|
+
makeDir(path: string): Promise<void>;
|
|
141
|
+
/** Check if file or directory exists */
|
|
142
|
+
exists(path: string): Promise<boolean>;
|
|
143
|
+
/** List directory contents */
|
|
144
|
+
list(path: string): Promise<FileInfo[]>;
|
|
145
|
+
/** Delete file or directory */
|
|
146
|
+
remove(path: string): Promise<void>;
|
|
147
|
+
/** Rename or move file/directory */
|
|
148
|
+
rename(oldPath: string, newPath: string): Promise<void>;
|
|
149
|
+
/** Watch directory for changes */
|
|
150
|
+
watchDir(path: string, onEvent: (event: FilesystemEvent) => void | Promise<void>, options?: WatchOptions): Promise<WatchHandle>;
|
|
151
|
+
}
|
|
152
|
+
/** Sandbox instance with full capabilities */
|
|
153
|
+
interface SandboxInstance {
|
|
154
|
+
readonly sandboxId: string;
|
|
155
|
+
readonly commands: SandboxCommands;
|
|
156
|
+
readonly files: SandboxFiles;
|
|
157
|
+
/** Get public URL for port */
|
|
158
|
+
getHost(port: number): Promise<string>;
|
|
159
|
+
/** Check if sandbox is running */
|
|
160
|
+
isRunning(): Promise<boolean>;
|
|
161
|
+
/** Get sandbox metadata and timing */
|
|
162
|
+
getInfo(): Promise<SandboxInfo>;
|
|
163
|
+
/** Terminate sandbox */
|
|
164
|
+
kill(): Promise<void>;
|
|
165
|
+
/** Pause sandbox (preserves state) */
|
|
166
|
+
pause(): Promise<void>;
|
|
167
|
+
}
|
|
168
|
+
/** Sandbox lifecycle management */
|
|
169
|
+
interface SandboxProvider {
|
|
170
|
+
/** Provider type identifier */
|
|
171
|
+
readonly providerType: string;
|
|
172
|
+
/** Create new sandbox */
|
|
173
|
+
create(options: SandboxCreateOptions): Promise<SandboxInstance>;
|
|
174
|
+
/** Connect to existing sandbox */
|
|
175
|
+
connect(sandboxId: string, timeoutMs?: number): Promise<SandboxInstance>;
|
|
176
|
+
/** List sandboxes (first page only, up to limit) */
|
|
177
|
+
list(options?: SandboxListOptions): Promise<SandboxInfo[]>;
|
|
178
|
+
}
|
|
179
|
+
interface ModalConfig {
|
|
180
|
+
/** Modal app name. Default: "evolve-sandbox" */
|
|
181
|
+
appName?: string;
|
|
182
|
+
/** Default timeout in ms. Default: 3600000 (1 hour) */
|
|
183
|
+
defaultTimeoutMs?: number;
|
|
184
|
+
}
|
|
185
|
+
declare class ModalProvider implements SandboxProvider {
|
|
186
|
+
readonly providerType: "modal";
|
|
187
|
+
private readonly client;
|
|
188
|
+
private readonly appName;
|
|
189
|
+
private readonly defaultTimeoutMs;
|
|
190
|
+
private _app;
|
|
191
|
+
constructor(config?: ModalConfig);
|
|
192
|
+
private getApp;
|
|
193
|
+
create(options: SandboxCreateOptions): Promise<SandboxInstance>;
|
|
194
|
+
connect(sandboxId: string, _timeoutMs?: number): Promise<SandboxInstance>;
|
|
195
|
+
list(_options?: SandboxListOptions): Promise<SandboxInfo[]>;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Create Modal sandbox provider.
|
|
199
|
+
*
|
|
200
|
+
* Requires MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables,
|
|
201
|
+
* or a .modal.toml configuration file.
|
|
202
|
+
*
|
|
203
|
+
* @param config - Optional configuration
|
|
204
|
+
*/
|
|
205
|
+
declare function createModalProvider(config?: ModalConfig): SandboxProvider;
|
|
206
|
+
|
|
207
|
+
export { type FileInfo, type FilesystemEvent, type ModalConfig, ModalProvider, type ProcessInfo, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxConnectOptions, type SandboxCreateOptions, type SandboxFiles, type SandboxInfo, type SandboxInstance, type SandboxListOptions, type SandboxProvider, type SandboxRunOptions, type SandboxSpawnOptions, type WatchHandle, type WatchOptions, createModalProvider };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modal Sandbox Provider - Clean Architecture
|
|
3
|
+
*
|
|
4
|
+
* @requires modal >= 0.3.0
|
|
5
|
+
* @requires Node.js >= 18 (for ReadableStream support)
|
|
6
|
+
*
|
|
7
|
+
* Design principles:
|
|
8
|
+
* - Single way to do things (no dual methods)
|
|
9
|
+
* - Options objects only (no positional args)
|
|
10
|
+
* - All interface methods required (no optional ?)
|
|
11
|
+
* - Configuration externalized (no hardcoded mappings)
|
|
12
|
+
* - Clear naming (run = blocking, spawn = background)
|
|
13
|
+
*
|
|
14
|
+
* Modal-specific notes:
|
|
15
|
+
* - No native file APIs - uses exec() with stdin/stdout
|
|
16
|
+
* - pause() not supported - throws error
|
|
17
|
+
* - Requires app context for sandbox creation
|
|
18
|
+
*/
|
|
19
|
+
/** Result of a completed sandbox command */
|
|
20
|
+
interface SandboxCommandResult {
|
|
21
|
+
exitCode: number;
|
|
22
|
+
stdout: string;
|
|
23
|
+
stderr: string;
|
|
24
|
+
}
|
|
25
|
+
/** Handle to a running background process in sandbox */
|
|
26
|
+
interface SandboxCommandHandle {
|
|
27
|
+
readonly processId: string;
|
|
28
|
+
wait(): Promise<SandboxCommandResult>;
|
|
29
|
+
kill(): Promise<boolean>;
|
|
30
|
+
}
|
|
31
|
+
/** Information about a running process */
|
|
32
|
+
interface ProcessInfo {
|
|
33
|
+
processId: string;
|
|
34
|
+
cmd: string;
|
|
35
|
+
args: string[];
|
|
36
|
+
envs: Record<string, string>;
|
|
37
|
+
cwd?: string;
|
|
38
|
+
tag?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Sandbox metadata and lifecycle info */
|
|
41
|
+
interface SandboxInfo {
|
|
42
|
+
sandboxId: string;
|
|
43
|
+
image: string;
|
|
44
|
+
name?: string;
|
|
45
|
+
metadata: Record<string, string>;
|
|
46
|
+
startedAt: string;
|
|
47
|
+
/** End time (undefined for running sandboxes) */
|
|
48
|
+
endAt?: string;
|
|
49
|
+
}
|
|
50
|
+
/** File or directory entry info */
|
|
51
|
+
interface FileInfo {
|
|
52
|
+
name: string;
|
|
53
|
+
path: string;
|
|
54
|
+
type: "file" | "dir";
|
|
55
|
+
}
|
|
56
|
+
/** Filesystem event from watchDir */
|
|
57
|
+
interface FilesystemEvent {
|
|
58
|
+
/** Relative path to the changed file/directory */
|
|
59
|
+
name: string;
|
|
60
|
+
/** Type of filesystem operation */
|
|
61
|
+
type: "create" | "remove" | "rename" | "chmod" | "write";
|
|
62
|
+
}
|
|
63
|
+
/** Handle to stop watching a directory */
|
|
64
|
+
interface WatchHandle {
|
|
65
|
+
stop(): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
/** Options for watching a directory */
|
|
68
|
+
interface WatchOptions {
|
|
69
|
+
recursive?: boolean;
|
|
70
|
+
timeoutMs?: number;
|
|
71
|
+
onExit?: (err?: Error) => void | Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
/** Options for blocking sandbox command execution */
|
|
74
|
+
interface SandboxRunOptions {
|
|
75
|
+
timeoutMs?: number;
|
|
76
|
+
envs?: Record<string, string>;
|
|
77
|
+
cwd?: string;
|
|
78
|
+
onStdout?: (data: string) => void;
|
|
79
|
+
onStderr?: (data: string) => void;
|
|
80
|
+
}
|
|
81
|
+
/** Options for spawning background sandbox processes */
|
|
82
|
+
interface SandboxSpawnOptions extends SandboxRunOptions {
|
|
83
|
+
stdin?: boolean;
|
|
84
|
+
}
|
|
85
|
+
/** Options for connecting to a running process */
|
|
86
|
+
interface SandboxConnectOptions {
|
|
87
|
+
onStdout?: (data: string) => void;
|
|
88
|
+
onStderr?: (data: string) => void;
|
|
89
|
+
timeoutMs?: number;
|
|
90
|
+
}
|
|
91
|
+
/** Options for creating a sandbox */
|
|
92
|
+
interface SandboxCreateOptions {
|
|
93
|
+
image: string;
|
|
94
|
+
envs?: Record<string, string>;
|
|
95
|
+
metadata?: Record<string, string>;
|
|
96
|
+
timeoutMs?: number;
|
|
97
|
+
workingDirectory?: string;
|
|
98
|
+
}
|
|
99
|
+
/** Options for listing sandboxes */
|
|
100
|
+
interface SandboxListOptions {
|
|
101
|
+
state?: ("running" | "paused")[];
|
|
102
|
+
metadata?: Record<string, string>;
|
|
103
|
+
limit?: number;
|
|
104
|
+
}
|
|
105
|
+
/** Command execution capabilities */
|
|
106
|
+
interface SandboxCommands {
|
|
107
|
+
/** Run command and wait for completion */
|
|
108
|
+
run(command: string, options?: SandboxRunOptions): Promise<SandboxCommandResult>;
|
|
109
|
+
/** Spawn background process, returns handle for control */
|
|
110
|
+
spawn(command: string, options?: SandboxSpawnOptions): Promise<SandboxCommandHandle>;
|
|
111
|
+
/** List running processes */
|
|
112
|
+
list(): Promise<ProcessInfo[]>;
|
|
113
|
+
/** Connect to existing process by ID */
|
|
114
|
+
connect(processId: string, options?: SandboxConnectOptions): Promise<SandboxCommandHandle>;
|
|
115
|
+
/** Send data to process stdin */
|
|
116
|
+
sendStdin(processId: string, data: string): Promise<void>;
|
|
117
|
+
/** Kill process by ID */
|
|
118
|
+
kill(processId: string): Promise<boolean>;
|
|
119
|
+
}
|
|
120
|
+
/** File system operations */
|
|
121
|
+
interface SandboxFiles {
|
|
122
|
+
/** Read file (auto-detects binary by extension) */
|
|
123
|
+
read(path: string): Promise<string | Uint8Array>;
|
|
124
|
+
/** Write single file */
|
|
125
|
+
write(path: string, content: string | Buffer | ArrayBuffer | Uint8Array): Promise<void>;
|
|
126
|
+
/** Write multiple files in batch */
|
|
127
|
+
writeBatch(files: Array<{
|
|
128
|
+
path: string;
|
|
129
|
+
data: string | Buffer | ArrayBuffer | Uint8Array;
|
|
130
|
+
}>): Promise<void>;
|
|
131
|
+
/** Read file as stream */
|
|
132
|
+
readStream(path: string): Promise<ReadableStream<Uint8Array>>;
|
|
133
|
+
/** Write from stream */
|
|
134
|
+
writeStream(path: string, stream: ReadableStream<Uint8Array>): Promise<void>;
|
|
135
|
+
/** Get pre-signed upload URL for large files (expiration in seconds) */
|
|
136
|
+
uploadUrl(path: string, expiresInSeconds?: number): Promise<string>;
|
|
137
|
+
/** Get pre-signed download URL for large files (expiration in seconds) */
|
|
138
|
+
downloadUrl(path: string, expiresInSeconds?: number): Promise<string>;
|
|
139
|
+
/** Create directory (recursive) */
|
|
140
|
+
makeDir(path: string): Promise<void>;
|
|
141
|
+
/** Check if file or directory exists */
|
|
142
|
+
exists(path: string): Promise<boolean>;
|
|
143
|
+
/** List directory contents */
|
|
144
|
+
list(path: string): Promise<FileInfo[]>;
|
|
145
|
+
/** Delete file or directory */
|
|
146
|
+
remove(path: string): Promise<void>;
|
|
147
|
+
/** Rename or move file/directory */
|
|
148
|
+
rename(oldPath: string, newPath: string): Promise<void>;
|
|
149
|
+
/** Watch directory for changes */
|
|
150
|
+
watchDir(path: string, onEvent: (event: FilesystemEvent) => void | Promise<void>, options?: WatchOptions): Promise<WatchHandle>;
|
|
151
|
+
}
|
|
152
|
+
/** Sandbox instance with full capabilities */
|
|
153
|
+
interface SandboxInstance {
|
|
154
|
+
readonly sandboxId: string;
|
|
155
|
+
readonly commands: SandboxCommands;
|
|
156
|
+
readonly files: SandboxFiles;
|
|
157
|
+
/** Get public URL for port */
|
|
158
|
+
getHost(port: number): Promise<string>;
|
|
159
|
+
/** Check if sandbox is running */
|
|
160
|
+
isRunning(): Promise<boolean>;
|
|
161
|
+
/** Get sandbox metadata and timing */
|
|
162
|
+
getInfo(): Promise<SandboxInfo>;
|
|
163
|
+
/** Terminate sandbox */
|
|
164
|
+
kill(): Promise<void>;
|
|
165
|
+
/** Pause sandbox (preserves state) */
|
|
166
|
+
pause(): Promise<void>;
|
|
167
|
+
}
|
|
168
|
+
/** Sandbox lifecycle management */
|
|
169
|
+
interface SandboxProvider {
|
|
170
|
+
/** Provider type identifier */
|
|
171
|
+
readonly providerType: string;
|
|
172
|
+
/** Create new sandbox */
|
|
173
|
+
create(options: SandboxCreateOptions): Promise<SandboxInstance>;
|
|
174
|
+
/** Connect to existing sandbox */
|
|
175
|
+
connect(sandboxId: string, timeoutMs?: number): Promise<SandboxInstance>;
|
|
176
|
+
/** List sandboxes (first page only, up to limit) */
|
|
177
|
+
list(options?: SandboxListOptions): Promise<SandboxInfo[]>;
|
|
178
|
+
}
|
|
179
|
+
interface ModalConfig {
|
|
180
|
+
/** Modal app name. Default: "evolve-sandbox" */
|
|
181
|
+
appName?: string;
|
|
182
|
+
/** Default timeout in ms. Default: 3600000 (1 hour) */
|
|
183
|
+
defaultTimeoutMs?: number;
|
|
184
|
+
}
|
|
185
|
+
declare class ModalProvider implements SandboxProvider {
|
|
186
|
+
readonly providerType: "modal";
|
|
187
|
+
private readonly client;
|
|
188
|
+
private readonly appName;
|
|
189
|
+
private readonly defaultTimeoutMs;
|
|
190
|
+
private _app;
|
|
191
|
+
constructor(config?: ModalConfig);
|
|
192
|
+
private getApp;
|
|
193
|
+
create(options: SandboxCreateOptions): Promise<SandboxInstance>;
|
|
194
|
+
connect(sandboxId: string, _timeoutMs?: number): Promise<SandboxInstance>;
|
|
195
|
+
list(_options?: SandboxListOptions): Promise<SandboxInfo[]>;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Create Modal sandbox provider.
|
|
199
|
+
*
|
|
200
|
+
* Requires MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables,
|
|
201
|
+
* or a .modal.toml configuration file.
|
|
202
|
+
*
|
|
203
|
+
* @param config - Optional configuration
|
|
204
|
+
*/
|
|
205
|
+
declare function createModalProvider(config?: ModalConfig): SandboxProvider;
|
|
206
|
+
|
|
207
|
+
export { type FileInfo, type FilesystemEvent, type ModalConfig, ModalProvider, type ProcessInfo, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxConnectOptions, type SandboxCreateOptions, type SandboxFiles, type SandboxInfo, type SandboxInstance, type SandboxListOptions, type SandboxProvider, type SandboxRunOptions, type SandboxSpawnOptions, type WatchHandle, type WatchOptions, createModalProvider };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {ModalClient}from'modal';import {pack}from'tar-stream';var b={"evolve-all":"evolvingmachines/evolve-all:latest"},h=new Set([".xlsx",".xls",".docx",".doc",".pptx",".ppt",".pdf",".zip",".tar",".gz",".7z",".rar",".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".mp3",".wav",".ogg",".flac",".aac",".mp4",".avi",".mov",".mkv",".webm",".woff",".woff2",".ttf",".otf",".eot",".exe",".dll",".so",".dylib",".sqlite",".db",".pickle",".pkl",".parquet"]);function y(c){let t=c.substring(c.lastIndexOf(".")).toLowerCase();return h.has(t)}var l=class{constructor(t){this.sandbox=t;}wrapAsUser(t,e,n){let r="";n&&Object.keys(n).length>0&&(r=Object.entries(n).filter(([,o])=>o!=null).map(([o,a])=>`export ${o}='${String(a).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let s=e?`cd '${e.replace(/'/g,"'\\''")}' && ${r}${t}`:`${r}${t}`;return ["su","user","-c",`echo ${Buffer.from(s).toString("base64")} | base64 -d | bash`]}async run(t,e){let n=this.wrapAsUser(t,e?.cwd,e?.envs),r=await this.sandbox.exec(n,{timeoutMs:e?.timeoutMs}),{stdout:s,stderr:i}=await this.accumulateStreams(r,e?.onStdout,e?.onStderr);return {exitCode:await r.wait(),stdout:s,stderr:i}}async spawn(t,e){let n=this.wrapAsUser(t,e?.cwd,e?.envs),r=await this.sandbox.exec(n,{timeoutMs:e?.timeoutMs}),s="",i="",o=this.accumulateStreams(r,e?.onStdout?d=>{e.onStdout(d);}:void 0,e?.onStderr?d=>{e.onStderr(d);}:void 0).then(({stdout:d,stderr:m})=>{s=d,i=m;}).catch(()=>{});return {processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await o,{exitCode:await r.wait(),stdout:s,stderr:i}),kill:async()=>false}}async list(){let t=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await t.wait(),(await t.stdout.readText()).trim().split(`
|
|
2
|
+
`).slice(1).map(r=>{let s=r.trim().split(/\s+/);return {processId:s[0],cmd:s[1]||"",args:s.slice(2),envs:{}}})}async connect(t,e){throw new Error("Modal does not support connecting to existing processes")}async sendStdin(t,e){throw new Error("Modal does not support sendStdin by process ID")}async kill(t){return await(await this.sandbox.exec(["kill","-9",t],{timeoutMs:1e4})).wait()===0}async accumulateStreams(t,e,n){let r="",s="",i=[];return i.push((async()=>{try{for await(let o of t.stdout){let a=typeof o=="string"?o:new TextDecoder().decode(o);r+=a,e?.(a);}}catch{}})()),i.push((async()=>{try{for await(let o of t.stderr){let a=typeof o=="string"?o:new TextDecoder().decode(o);s+=a,n?.(a);}}catch{}})()),await Promise.all(i),{stdout:r,stderr:s}}},f=class{constructor(t){this.sandbox=t;}async read(t){if(y(t)){let r=await this.sandbox.exec(["cat",t],{timeoutMs:3e5,mode:"binary"}),s=await r.wait();if(s!==0){let i=await r.stderr.readText();throw new Error(`Failed to read file ${t}: ${i||`exit code ${s}`}`)}return await r.stdout.readBytes()}let e=await this.sandbox.exec(["cat",t],{timeoutMs:3e5}),n=await e.wait();if(n!==0){let r=await e.stderr.readText();throw new Error(`Failed to read file ${t}: ${r||`exit code ${n}`}`)}return await e.stdout.readText()}async write(t,e){let n=this.toBuffer(e),r=t.substring(0,t.lastIndexOf("/"));r&&await this.makeDir(r);let s=t.replace(/'/g,"'\\''"),i=await this.sandbox.exec(["bash","-c",`cat > '${s}'`],{mode:"binary"});await i.stdin.writeBytes(new Uint8Array(n)),await i.stdin.getWriter().close(),await i.wait(),await(await this.sandbox.exec(["chown","user:user",t],{timeoutMs:1e4})).wait();}async writeBatch(t){let e=pack(),n=[],r=new Set;for(let a of t){let d=this.toBuffer(a.data),m=a.path.startsWith("/")?a.path.slice(1):a.path;e.entry({name:m},d);let u=a.path.substring(0,a.path.lastIndexOf("/"));u&&r.add(u);}e.finalize();for await(let a of e)n.push(Buffer.from(a));let s=Buffer.concat(n),i=await this.sandbox.exec(["tar","-xf","-","-C","/"],{mode:"binary"});if(await i.stdin.writeBytes(new Uint8Array(s)),await i.stdin.getWriter().close(),await i.wait(),r.size>0){let a=Array.from(r),d=new Set(a.map(m=>m.split("/").slice(0,4).join("/")));for(let m of d)await(await this.sandbox.exec(["chown","-R","user:user",m],{timeoutMs:3e4})).wait();}}async makeDir(t){await(await this.sandbox.exec(["mkdir","-p",t],{timeoutMs:1e4})).wait(),await(await this.sandbox.exec(["chown","-R","user:user",t],{timeoutMs:1e4})).wait();}async exists(t){return await(await this.sandbox.exec(["test","-e",t],{timeoutMs:1e4})).wait()===0}async list(t){let e=t.replace(/'/g,"'\\''"),n=await this.sandbox.exec(["bash","-c",`ls -la '${e}' | tail -n +2`],{timeoutMs:3e4});await n.wait();let r=await n.stdout.readText(),s=[];for(let i of r.trim().split(`
|
|
3
|
+
`)){if(!i)continue;let o=i.split(/\s+/);if(o.length<9)continue;let a=o[0],d=o.slice(8).join(" ");d==="."||d===".."||s.push({name:d,path:t.endsWith("/")?`${t}${d}`:`${t}/${d}`,type:a.startsWith("d")?"dir":"file"});}return s}async remove(t){await(await this.sandbox.exec(["rm","-rf",t],{timeoutMs:3e4})).wait();}async rename(t,e){await(await this.sandbox.exec(["mv",t,e],{timeoutMs:3e4})).wait();}async readStream(t){return (await this.sandbox.exec(["cat",t],{timeoutMs:3e5,mode:"binary"})).stdout}async writeStream(t,e){let n=t.substring(0,t.lastIndexOf("/"));n&&await this.makeDir(n);let r=t.replace(/'/g,"'\\''"),s=await this.sandbox.exec(["bash","-c",`cat > '${r}'`],{mode:"binary"}),i=e.getReader();try{for(;;){let{done:a,value:d}=await i.read();if(a)break;await s.stdin.writeBytes(d);}}finally{i.releaseLock();}await s.stdin.getWriter().close(),await s.wait();}async uploadUrl(t,e){throw new Error("Modal does not support pre-signed upload URLs")}async downloadUrl(t,e){throw new Error("Modal does not support pre-signed download URLs")}async watchDir(t,e,n){throw new Error("Modal does not support watchDir")}toBuffer(t){if(typeof t=="string")return Buffer.from(t,"utf-8");if(t instanceof Buffer)return t;if(t instanceof ArrayBuffer||t instanceof Uint8Array)return Buffer.from(t);throw new Error(`Unsupported data type: ${typeof t}`)}},p=class{constructor(t,e){this.sandbox=t;this.commands=new l(t),this.files=new f(t),this.image=e,this.startTime=new Date;}commands;files;image;startTime;get sandboxId(){return this.sandbox.sandboxId}async getHost(t){let n=(await this.sandbox.tunnels())[t];if(!n)throw new Error(`No tunnel found for port ${t}`);return n.url}async isRunning(){try{return await(await this.sandbox.exec(["echo","ping"],{timeoutMs:5e3})).wait(),!0}catch{return false}}async getInfo(){return {sandboxId:this.sandbox.sandboxId,image:this.image,metadata:{},startedAt:this.startTime.toISOString()}}async kill(){try{await this.sandbox.terminate();}catch{await new Promise(t=>setTimeout(t,500)),await this.sandbox.terminate();}}async pause(){throw new Error("Modal does not support pause. Use kill() instead.")}},g=class{providerType="modal";client;appName;defaultTimeoutMs;_app;constructor(t={}){this.client=new ModalClient,this.appName=t.appName??"evolve-sandbox",this.defaultTimeoutMs=t.defaultTimeoutMs??36e5;}async getApp(){return this._app||(this._app=await this.client.apps.fromName(this.appName,{createIfMissing:true})),this._app}async create(t){let e=await this.getApp(),n=t.timeoutMs??this.defaultTimeoutMs,r=b[t.image]??t.image,s=this.client.images.fromRegistry(r),i=t.envs?Object.fromEntries(Object.entries(t.envs).filter(([,d])=>d!=null)):void 0,o=i&&Object.keys(i).length>0?i:void 0,a=await this.client.sandboxes.create(e,s,{timeoutMs:n,workdir:t.workingDirectory,env:o});return new p(a,r)}async connect(t,e){let n=await this.client.sandboxes.fromId(t);return new p(n,"unknown")}async list(t){let e=[],n=t?.limit??100;try{for await(let r of this.client.sandboxes.list())if(e.push({sandboxId:r.sandboxId,image:"unknown",metadata:{},startedAt:new Date().toISOString()}),e.length>=n)break}catch{}return e}};function M(c={}){return new g(c)}export{g as ModalProvider,M as createModalProvider};
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@evolvingmachines/modal",
|
|
3
|
+
"version": "0.0.7",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"ai",
|
|
6
|
+
"agents",
|
|
7
|
+
"sandbox",
|
|
8
|
+
"modal",
|
|
9
|
+
"gpu",
|
|
10
|
+
"evolve-sdk",
|
|
11
|
+
"orchestration"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/evolving-machines-lab/evolve",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/evolving-machines-lab/evolve.git"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "dist/index.cjs",
|
|
20
|
+
"types": "dist/index.d.ts",
|
|
21
|
+
"license": "Apache-2.0",
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"import": "./dist/index.js",
|
|
30
|
+
"require": "./dist/index.cjs"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "tsup --minify",
|
|
35
|
+
"dev": "tsup --watch",
|
|
36
|
+
"type-check": "tsc --noEmit"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"modal": "^0.6.0",
|
|
40
|
+
"tar-stream": "^3.1.7"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/node": "^22.15.18",
|
|
44
|
+
"@types/tar-stream": "^3.1.4",
|
|
45
|
+
"tsup": "^8.4.0",
|
|
46
|
+
"typescript": "^5.8.3"
|
|
47
|
+
}
|
|
48
|
+
}
|