-
Notifications
You must be signed in to change notification settings - Fork 0
JVM Scripting Implementations
The io.github.solaceharmony.core.scripting package within the jvmMain source set provides concrete implementations for the scripting interfaces, tailored for the Java Virtual Machine environment.
This class implements the ScriptEngine interface for the JVM, providing capabilities to compile and execute Kotlin-based scripts (.kts). It leverages Kotlin's official kotlin.script.experimental.* APIs for robust script handling.
-
Core Scripting Infrastructure:
-
Scripting Host: Utilizes
kotlin.script.experimental.jvmhost.BasicJvmScriptingHostas the central component for orchestrating script compilation and evaluation. -
Compilation Configuration: A
compilationConfigurationis defined usingcreateJvmCompilationConfigurationFromTemplate<SimpleScript>. Key aspects of this configuration include:-
JVM Integration: Configures the JVM environment for scripting, notably attempting to update the classpath using
JvmScriptEngine::class.java.classLoader.getResources("").toList()to allow scripts to access project classes and dependencies. -
Implicit Receivers: Sets
Any::classas an implicit receiver, allowing scripts to call methods on a general context object if provided. -
Compiler Options: Appends specific compiler options, such as setting the
-jvm-targetto "17".
-
JVM Integration: Configures the JVM environment for scripting, notably attempting to update the classpath using
-
Base Script Definition: Scripts are expected to implicitly or explicitly extend a base class, in this case,
SimpleScript(an abstract class defined withinJvmScriptEngine.kt).
-
Scripting Host: Utilizes
-
Compilation Process (
compilemethod):-
Caching: Implements a
scriptCache(amutableMapOf<String, KotlinCompiledScript>) to store and retrieve already compiled scripts by name, avoiding redundant recompilation. -
Asynchronous Execution: Compilation is performed asynchronously using
withContext(Dispatchers.IO). -
Compilation Invocation: Calls
scriptingHost.compiler.invoke()with the script source (converted viatoScriptSource()) and the predefinedcompilationConfiguration. -
Result Handling:
- On
ResultWithDiagnostics.Success, it wraps the resultingkotlin.script.experimental.api.CompiledScriptin an internalKotlinCompiledScriptdata class (which also stores the script name and compilation timestamp), caches it, and returns it. - On
ResultWithDiagnostics.Failure, it extracts error messages from the diagnostics and throws aScriptCompilationException.
- On
- General exceptions during compilation are also caught and wrapped in
ScriptCompilationException.
-
Caching: Implements a
-
Execution Process (
executeandevalmethods):-
execute(compiledScript, parameters):- Expects an instance of the internal
KotlinCompiledScript. -
Asynchronous Execution: Performed using
withContext(Dispatchers.IO). -
Evaluation Configuration: Creates a
ScriptEvaluationConfigurationwhere:- Input
parametersare made available to the script viaprovidedProperties. - The JVM classpath is configured similarly to the compilation phase.
- Input
-
Evaluation Invocation: Calls
scriptingHost.evaluator.invoke()with thekotlinCompiledScriptfrom theKotlinCompiledScriptwrapper and the evaluation configuration. -
Result Handling:
- On
ResultWithDiagnostics.Success, it returns thescriptInstancefrom thereturnValue. - On
ResultWithDiagnostics.Failure, it throws aScriptExecutionExceptionwith extracted error messages.
- On
- Expects an instance of the internal
-
eval(scriptSource, scriptName, parameters):- Provides a convenience method to compile and execute in one step.
- Internally, it uses
scriptingHost.eval()which handles both compilation (using the sharedcompilationConfiguration) and evaluation (with a dynamically createdevaluationConfigurationfor parameters). - Error handling distinguishes between compilation and execution phases to throw
ScriptCompilationExceptionorScriptExecutionExceptionaccordingly.
-
-
Internal
KotlinCompiledScriptClass:- A private data class implementing the public
io.github.solaceharmony.core.scripting.CompiledScriptinterface. - It holds the
name,compilationTimestamp, and the actualkotlin.script.experimental.api.CompiledScriptobject obtained from the Kotlin scripting host.
- A private data class implementing the public
-
Custom Exceptions:
-
ScriptCompilationException(message: String): Thrown when script compilation fails. -
ScriptExecutionException(message: String): Thrown when script execution fails.
-
This implementation represents a significant advancement from a simulated engine, providing a functional foundation for dynamic Kotlin scripting within SolaceCore, complete with compilation, execution, parameter passing, and basic caching.
Implements the ScriptStorage interface using the local file system.
- Purpose: To provide persistent storage for script source code and their metadata on the JVM.
-
Constructor:
FileScriptStorage(private val baseDirectory: String) -
Storage Mechanism:
- Scripts are stored as
.ktsfiles within ascriptssubdirectory of thebaseDirectory. - Associated metadata for each script is stored in a corresponding
.jsonfile (e.g.,scriptName.ktsandscriptName.json). - Uses
kotlinx.serialization.json.Jsonfor serializing/deserializing metadata maps.
- Scripts are stored as
-
Operations: Implements
saveScript,loadScript,listScripts, anddeleteScriptby performing standard file I/O operations (create, read, write, list, delete) within the designated directory structure. All operations useDispatchers.IO.
Implements the ScriptVersionManager interface, also using a file-based approach for the JVM.
- Purpose: To manage and track different versions of scripts, enabling retrieval of specific versions and rollback capabilities.
-
Constructor:
FileScriptVersionManager(private val baseDirectory: String, private val scriptStorage: ScriptStorage) -
Storage Mechanism:
- Script versions are stored as individual
.ktsfiles within aversionssubdirectory ofbaseDirectory, further organized into subdirectories named after thescriptName(e.g.,baseDirectory/versions/scriptName/1.kts,baseDirectory/versions/scriptName/2.kts).
- Script versions are stored as individual
-
Operations:
-
addVersion(): Determines the next version number, saves the new script version into its version-specific file path, and then updates the main script entry in the providedscriptStoragewith metadata reflecting the new current version and timestamp. -
getVersion(): Reads the content of the specified version file. -
getLatestVersion(): Determines the highest version number (by checking metadata inscriptStorageand actual version files) and returns its source fromscriptStorage. -
rollback(): Retrieves the source of the target rollback version, then saves this source back into the mainscriptStorageas the current version, updating metadata to indicate the rollback. - All operations use
Dispatchers.IO.
-
A basic, non-compiler-based implementation of the ScriptValidator interface for the JVM.
- Purpose: To perform rudimentary checks on script source code.
-
Validation Logic:
- Checks for unbalanced parentheses, brackets, and braces.
- Flags multiple statements on a single line not separated by semicolons (though semicolons are largely optional in Kotlin).
- Checks for empty import statements or imports ending with a semicolon.
- Flags an empty script.
- Limitations: This validator does not perform full syntactic or semantic analysis that a Kotlin compiler would. It's a lightweight, preliminary checker.
A JVM-specific orchestrator class that integrates the various scripting components.
- Purpose: To provide a unified, high-level API for managing the entire script lifecycle, from validation and compilation to storage, versioning, execution, and hot-reloading.
-
Constructor:
ScriptManager(scriptEngine, scriptStorage, scriptVersionManager, scriptValidator) -
Key Functionalities:
- Maintains an in-memory cache (
compiledScriptCache) forCompiledScriptobjects. -
compileAndSave(): Orchestrates validation (ScriptValidator), compilation (ScriptEngine), saving (ScriptStorage), versioning (ScriptVersionManager), and caching. -
loadAndCompile(): Retrieves a script fromScriptStorage(if not cached), compiles it, and caches the result. -
execute(): Ensures a script is loaded/compiled, then executes it viaScriptEngine. -
reloadScript(): Clears a script from the cache and forces aloadAndCompileto pick up changes fromScriptStorage. -
rollback(): UsesScriptVersionManagerto perform a rollback and then reloads the script. - Delegates
listScripts()anddeleteScript()toScriptStorage(managing cache for delete).
- Maintains an in-memory cache (
-
Exception Defined:
ScriptValidationException.
classDiagram
direction LR
package "io.github.solaceharmony.core.scripting (commonMain)" {
interface ScriptEngine { <<Interface>> }
interface CompiledScript { <<Interface>> }
interface ScriptValidator { <<Interface>> }
class ValidationResult { }
interface ScriptVersionManager { <<Interface>> }
interface ScriptStorage { <<Interface>> }
}
package "io.github.solaceharmony.core.scripting (jvmMain)" {
class JvmScriptEngine {
+compile(): CompiledScript
+execute(): Any?
+eval(): Any?
}
ScriptEngine <|-- JvmScriptEngine
JvmScriptEngine ..> "SimpleCompiledScript" : (inner class) creates & uses
class "SimpleCompiledScript" {
+name: String
+compilationTimestamp: Long
+source: String
}
CompiledScript <|-- "SimpleCompiledScript"
class FileScriptStorage {
+saveScript()
+loadScript()
}
ScriptStorage <|-- FileScriptStorage
class FileScriptVersionManager {
+addVersion(): Int
+getVersion(): String?
+rollback(): Boolean
}
ScriptVersionManager <|-- FileScriptVersionManager
FileScriptVersionManager o-- ScriptStorage : uses
class SimpleScriptValidator {
+validate(): ValidationResult
}
ScriptValidator <|-- SimpleScriptValidator
class ScriptManager {
-scriptEngine: ScriptEngine
-scriptStorage: ScriptStorage
-scriptVersionManager: ScriptVersionManager
-scriptValidator: ScriptValidator
+compileAndSave(): CompiledScript
+loadAndCompile(): CompiledScript?
+execute(): Any?
+reloadScript(): CompiledScript?
+rollback(): CompiledScript?
}
ScriptManager o-- ScriptEngine
ScriptManager o-- ScriptStorage
ScriptManager o-- ScriptVersionManager
ScriptManager o-- ScriptValidator
ScriptManager ..> CompiledScript : caches
}
note for JvmScriptEngine "Uses Kotlin scripting APIs for compilation and execution."
note for SimpleScriptValidator "Performs basic, non-compiler checks."
These JVM implementations provide a functional, albeit with some current simplifications (like JvmScriptEngine and SimpleScriptValidator), scripting subsystem for SolaceCore, enabling dynamic code execution with support for file-based persistence and versioning.
← §5 Workflow Module (io.github.solaceharmony.core.workflow) · Architecture Overview · §7 Build System and Dependencies →
SolaceCore SSOT wiki · published from wiki/ by .github/workflows/publish-wiki.yml · edit the source in the repo, not the wiki.
Orientation
- Architectural Deep Dive
- Architecture Overview
- Design vs Implementation
- Framework Actor System
- Framework Architectural Vision
- Framework Concurrency and Communication
- Framework Data Storage and Management
- Framework Deployment and Containerization
- Framework Development Roadmap
- Framework Hot-Pluggable System
- Framework Implementation Status
- Framework Observability and Monitoring
- Framework Port System
- Framework System Architecture
- Framework Workflow Management
- Project Status
- Project Status Report
- Quick Status
- Solace Core Framework Architecture
- SolaceCore Architecture Overview
- Vision & Solace AI
Runtime
- Actor Builder
- Actor Communication Sequence Diagram
- Actor Core Definitions
- Actor Graph View
- Actor Metrics
- Actor Module Architecture
- Actor Queue Hibernation and Correlation
- Actor Roadmap
- Actor State Recovery Subsystem
- Actor State Serialization Subsystem
- Actor Supervision Module
- Actor System Architecture
- Actor System Class Diagram
- Actor Usage Examples
- Compose App Features
- JVM Scripting Implementations
- Kernel & Ports
- Kernel Channel System
- Kernel Future Enhancements
- Kernel Module Architecture
- Kernel Port Implementations and Exceptions
- Kernel Port Usage Example
- Kernel Testing Strategy
- Lifecycle Class Diagram
- Lifecycle Management Architecture
- Pipeline DSL
- Real-Time UI Implementation
- Scripting Module Architecture
- Scripting Module Design
- Scripting Supporting Components
- Shared Memory
- Storage & Persistence
- Storage Abstractions Architecture
- Storage Caching Subsystem
- Storage Checklist
- Storage Compression Subsystem
- Storage Core Interfaces
- Storage Encryption Subsystem
- Storage File-Based Architecture
- Storage File-Based Implementations
- Storage In-Memory Architecture
- Storage In-Memory Implementations
- Storage JVM Serialization Utilities
- Storage Module Architecture
- Storage Serialization Compression Encryption
- Storage Specialized Interfaces Architecture
- Storage Status and Future Plans
- Storage Testing
- Storage Thread Safety Guide
- Storage Thread Safety and Deadlock Prevention
- Storage Transactions
- Storage Usage Examples
- Supervisor and Hot Swap
- SupervisorActor
- System Architecture Diagram
- Workflow Management Architecture
- Workflow Management Design Concept
- Workflow Orchestration
Solace AI
- Confusion Corrector
- Inference Cube
- Inference Cube Technical Architecture
- Long-Term Memory
- MCP and Tool Format
- Memory & Reflection
- Memory Compression
- Memory Feature Overview
- Memory Retrieval
- Mood & Emotional Model
- Mood Module Implementation
- Mouth Tool Technical Spec
- Multimodal Nudging
- Perception Actors
- Provider Specs
- Reflection Memory
- Solace AI Overview
- Supervisor AI
- Supervisor Emotional Model Integration
- Time Actor
- Voice & Mouth Tool
- Working Memory
- Zoom Level Technical Spec
- Zoom Levels
Reference
- Advanced Workflow Example
- Basic Actor Usage
- Build System and Dependencies
- Development Tooling and Practices
- Documentation Catalog
- Documentation Index
- Feature Index
- Glossary
- How the Wiki Publishes
- JVM Utilities
- Kotlin Implementation Details
- Kotlin-Aligned Architecture Overview
- Kotlin-Aligned Contributing
- Kotlin-Aligned Core Architectural Principles
- Kotlin-Aligned Daily Development Workflow
- Kotlin-Aligned Development Examples
- Kotlin-Aligned Development Workflow
- Kotlin-Aligned Documentation
- Kotlin-Aligned Implementation Status
- Kotlin-Aligned Key Concepts
- Kotlin-Aligned Known Issues
- Kotlin-Aligned Quick Start
- Kotlin-Aligned Running the System
- Kotlin-Aligned System Architecture
- LangChain Actor Code Changes
- LangChain Actor Usage Improvements
- LangChain ActorInterface Code Changes
- LangChain Best Practices
- LangChain Bugs
- LangChain Chain Implementation
- LangChain Code Changes
- LangChain Code Changes Rollout and Impact
- LangChain Configuration Management Improvements
- LangChain Configuration Recommendations
- LangChain Core Architecture Recommendations
- LangChain Directory Structure Changes
- LangChain Documentation Improvements
- LangChain Dynamic Wiring Rollout Notes
- LangChain Fix Proposal
- LangChain Implementation Priorities
- LangChain Lifecycle Management Improvements
- LangChain Memory Integration Recommendations
- LangChain Metrics and Observability Recommendations
- LangChain Migration Strategy
- LangChain New Files Needed
- LangChain New Packages to Add
- LangChain Package-by-Package Improvements
- LangChain Patterns
- LangChain Port Code Changes
- LangChain Port System Recommendations
- LangChain Port Usability Improvements
- LangChain Prompt Management Recommendations
- LangChain Recommendations
- LangChain Recommendations Rollout Plan
- LangChain Required Interface Changes
- LangChain Testing Changes
- LangChain Testing Improvements
- LangChain Testing Recommendations
- LangChain Tool Integration Recommendations
- LangChain Type-Safe Dynamic Wiring
- LangChain Type-Safe Dynamic Wiring System
- LangChain Usage Design Improvements
- Master Checklist
- Roadmap
- Roadmap Issues
- Roadmap Phase 1 Stability and Testing
- Roadmap Phase 2 Production Infrastructure
- Roadmap Phase 3 Documentation and Developer Experience
- Roadmap Phase 4 Graph Database Integration
- Roadmap Phase 5 Security Framework
- Roadmap Phase 6 Distributed System
- Roadmap Phase 7 Advanced Features
- Roadmap Phase 8 Ecosystem Development
- Roadmap Timeline and Success Metrics
- Setup Instructions
- Sketch Architecture
- Status Documentation
- Task 1 Core Tests
- Task 2 Connection Wiring
- Task 3 Concurrency Issues
- Task 4 Dynamic Registration
- Task 5 Integration Tests
- Task 6 Deadlock Detection
- Task Documentation
- Test Coverage Checklist
- Testing Strategy