Embedded Kotlin Scripts and Classloaders, Idea Support

I have some code based on Simplified main-kts.
I made some changes so that an application can get the result of the script by calling evalFile() (based on the test code for that example).

At first I tried adding ivy @dependsOn annotations to the scripts, so that the dependencies would also be recognized by Idea, however it seems that those classes are loaded in a different Classloader, so it was not possible to cast the result of the script to the correct class and call the methods.

So I changed the script definition code to inherit the classpath and classloader from the calling thread. This seems to work better, however now Idea does not recognize the dependencies (unless the scripts are placed in a source directory with the correct classpath).

I also would like to use the @import annotation to share code between scripts, however this does not play well with having the scripts in a source directory.
Besides that, Idea does not yet support the @import annotation (but should in a future version, according to this issue).

We would like to use Kotlin *.kts scripts for controlling a large system (implemented in Scala, with a DSL implemented in Kotlin).
The scripts need to be modified by staff on site, while the software is only updated when a new release is ready.

Question: Is there any way in the script definition code to recognize when the script is being viewed in Intellij Idea, so that the classpath can be set correctly for editing, while still inheriting the classpath when run in the application?

Or is there a way to overcome the issue with the different classloaders when getting the dependencies via ivy @dependsOn annotations?
I think what happens is that the script is getting different copies of the same classes (that are already in the application’s classpath), so when the application tries to call a method in the DSL class returned from the script, the compiler complains that the types are not compatible (probably because they are from a different classloader).