Skip to main content

algocline_engine/
executor.rs

1//! Lua execution engine.
2//!
3//! Orchestrates StdLib injection and Lua execution for each session:
4//!
5//! 1. **Layer 0** — [`bridge::register`] injects Rust-backed `alc.*` primitives
6//! 2. **Layer 1** — [`PRELUDE`] adds Lua-based combinators (`alc.map`, etc.)
7//! 3. **Layer 2** — [`mlua_pkg::Registry`] makes `require("ucb")` etc.
8//!    resolve from `~/.algocline/packages/`
9//!
10//! ## Execution models
11//!
12//! - **`eval_simple`** — sync eval on a shared VM (no LLM bridge).
13//!   For lightweight ops like reading package metadata.
14//! - **`start_session`** — spawns a **dedicated VM per session**.
15//!   Each session gets an isolated Lua VM so concurrent sessions
16//!   cannot interfere with each other's globals (`alc`, `ctx`).
17//!   `alc.llm()` yields the coroutine, and the VM is cleaned up
18//!   when the session completes or is abandoned.
19
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use algocline_core::{Budget, ExecutionMetrics, ExecutionSpec};
24use mlua::LuaSerdeExt;
25use mlua_isle::{AsyncIsle, AsyncIsleDriver, IsleError};
26use mlua_pkg::Registry;
27
28use crate::bridge;
29use crate::card::FileCardStore;
30use crate::llm_bridge::LlmRequest;
31use crate::resolver_factory::make_resolver;
32use crate::session::Session;
33use crate::state::JsonFileStore;
34use crate::variant_pkg::{register_variant_pkgs, VariantPkg};
35
36/// Layer 1: Prelude combinators (map, reduce, vote, filter).
37/// Embedded at compile time and loaded into every session.
38const PRELUDE: &str = include_str!("prelude.lua");
39
40/// Lua execution engine.
41///
42/// Holds a **shared VM** for lightweight stateless operations (`eval_simple`)
43/// and spawns **per-session VMs** for coroutine-based execution (`start_session`).
44///
45/// Per-session VMs eliminate global namespace pollution between concurrent
46/// sessions — each session's `alc`, `ctx`, and `package.loaded` are fully
47/// isolated.
48pub struct Executor {
49    /// Shared VM for eval_simple (stateless, no session globals).
50    isle: AsyncIsle,
51    _driver: AsyncIsleDriver,
52    /// Package resolver paths, cloned into each per-session VM.
53    lib_paths: Vec<PathBuf>,
54}
55
56impl Executor {
57    pub async fn new(lib_paths: Vec<PathBuf>) -> anyhow::Result<Self> {
58        let paths_for_shared = lib_paths.clone();
59        let (isle, driver) = AsyncIsle::spawn(move |lua| {
60            let mut reg = Registry::new();
61            for path in &paths_for_shared {
62                if let Some(resolver) = make_resolver(path) {
63                    reg.add(resolver);
64                }
65            }
66            reg.install(lua)?;
67            Ok(())
68        })
69        .await?;
70
71        Ok(Self {
72            isle,
73            _driver: driver,
74            lib_paths,
75        })
76    }
77
78    /// Evaluate Lua code without LLM bridge. For lightweight operations
79    /// like reading package metadata.
80    ///
81    /// Uses the shared VM. `extra_lib_paths` must be empty — use
82    /// [`Self::eval_simple_with_paths`] when project-local paths are needed.
83    pub async fn eval_simple(&self, code: String) -> Result<serde_json::Value, String> {
84        self.eval_simple_with_paths(code, vec![], vec![]).await
85    }
86
87    /// Evaluate Lua code without LLM bridge, with optional extra package paths
88    /// and variant pkgs.
89    ///
90    /// When both `extra_lib_paths` and `variant_pkgs` are empty, reuses the
91    /// shared VM (cheap). When either is non-empty, spawns a dedicated VM so
92    /// the extra resolvers are active (slightly more expensive, but `pkg_list`
93    /// is the only caller and it is low-frequency).
94    ///
95    /// The fast path does not register `alc.*` bridge primitives, so the
96    /// `state_store` / `card_store` / `scenarios_dir` handles that
97    /// [`Self::start_session`] requires are not threaded through here —
98    /// callers that need them go through `start_session`.
99    pub async fn eval_simple_with_paths(
100        &self,
101        code: String,
102        extra_lib_paths: Vec<PathBuf>,
103        variant_pkgs: Vec<VariantPkg>,
104    ) -> Result<serde_json::Value, String> {
105        if extra_lib_paths.is_empty() && variant_pkgs.is_empty() {
106            // Fast path: reuse the long-lived shared VM.
107            let task = self.isle.spawn_exec(move |lua| {
108                let result: mlua::Value = lua
109                    .load(&code)
110                    .eval()
111                    .map_err(|e| IsleError::Lua(e.to_string()))?;
112                let json: serde_json::Value = lua
113                    .from_value(result)
114                    .map_err(|e| IsleError::Lua(e.to_string()))?;
115                serde_json::to_string(&json)
116                    .map_err(|e| IsleError::Lua(format!("JSON serialize: {e}")))
117            });
118            let json_str = task.await.map_err(|e| e.to_string())?;
119            return serde_json::from_str(&json_str).map_err(|e| format!("JSON parse: {e}"));
120        }
121
122        // Slow path: spawn a dedicated VM with extra resolvers prepended.
123        let mut effective = extra_lib_paths;
124        effective.extend(self.lib_paths.iter().cloned());
125
126        let (tmp_isle, _tmp_driver) = AsyncIsle::spawn(move |lua| {
127            let mut reg = Registry::new();
128            // Variant pkgs first so alc.local.toml overrides win over global.
129            register_variant_pkgs(&mut reg, &variant_pkgs);
130            for path in &effective {
131                if let Some(resolver) = make_resolver(path) {
132                    reg.add(resolver);
133                }
134            }
135            reg.install(lua)?;
136            Ok(())
137        })
138        .await
139        .map_err(|e| format!("eval_simple VM spawn failed: {e}"))?;
140
141        let task = tmp_isle.spawn_exec(move |lua| {
142            let result: mlua::Value = lua
143                .load(&code)
144                .eval()
145                .map_err(|e| IsleError::Lua(e.to_string()))?;
146            let json: serde_json::Value = lua
147                .from_value(result)
148                .map_err(|e| IsleError::Lua(e.to_string()))?;
149            serde_json::to_string(&json).map_err(|e| IsleError::Lua(format!("JSON serialize: {e}")))
150        });
151
152        let json_str = task.await.map_err(|e| e.to_string())?;
153        serde_json::from_str(&json_str).map_err(|e| format!("JSON parse: {e}"))
154    }
155
156    /// Start a new Lua execution session on a **dedicated VM**.
157    ///
158    /// Each session gets its own Lua VM (OS thread + mlua instance) so
159    /// concurrent sessions cannot interfere with each other's globals.
160    /// The VM is cleaned up automatically when the session completes or
161    /// is abandoned (all senders drop → channel closes → thread exits).
162    ///
163    /// `extra_lib_paths` are prepended to `self.lib_paths` so project-local
164    /// packages take precedence over the global package directory.
165    /// `variant_pkgs` come from `alc.local.toml` and override both layers
166    /// (registered at the highest priority).
167    ///
168    /// `state_store` / `card_store` / `scenarios_dir` are resolved by the
169    /// service layer (typically from `AppConfig.app_dir()`) so the engine
170    /// crate never touches HOME. They flow through [`bridge::BridgeConfig`]
171    /// to back `alc.state.*` / `alc.card.*` / `alc._dirs.scenarios`.
172    #[allow(clippy::too_many_arguments)]
173    pub async fn start_session(
174        &self,
175        code: String,
176        ctx: serde_json::Value,
177        extra_lib_paths: Vec<PathBuf>,
178        variant_pkgs: Vec<VariantPkg>,
179        state_store: Arc<JsonFileStore>,
180        card_store: Arc<FileCardStore>,
181        scenarios_dir: PathBuf,
182    ) -> Result<Session, String> {
183        let spec = ExecutionSpec::new(code, ctx);
184        let metrics = ExecutionMetrics::new();
185
186        // Extract and apply budget from ctx.budget
187        if let Some(budget) = Budget::from_ctx(&spec.ctx) {
188            metrics.set_budget(budget);
189        }
190
191        let (llm_tx, llm_rx) = tokio::sync::mpsc::channel::<LlmRequest>(16);
192
193        // Build effective lib_paths: extra (project-local) first, then defaults.
194        // Priority: variant_pkgs > extra_lib_paths > self.lib_paths
195        // (ALC_PACKAGES_PATH + global default).
196        let mut effective = extra_lib_paths;
197        effective.extend(self.lib_paths.iter().cloned());
198
199        // Obtain the log-capture sink before moving `metrics` into BridgeConfig.
200        // The same Arc is shared with Session so snapshot() can read recent_logs.
201        let log_sink = metrics.log_sink_handle();
202
203        let bridge_config = bridge::BridgeConfig {
204            llm_tx: Some(llm_tx),
205            ns: spec.namespace.clone(),
206            custom_metrics: metrics.custom_metrics_handle(),
207            budget: metrics.budget_handle(),
208            progress: metrics.progress_handle(),
209            lib_paths: effective.clone(), // fork child VMs inherit project paths
210            variant_pkgs: variant_pkgs.clone(), // fork child VMs inherit variant overrides
211            state_store,
212            card_store,
213            scenarios_dir,
214            log_sink: Some(log_sink.clone()),
215        };
216        let lua_ctx = spec.ctx.clone();
217        let lua_code = spec.code.clone();
218
219        // 1. Spawn a dedicated VM for this session.
220        let (session_isle, session_driver) = AsyncIsle::spawn(move |lua| {
221            let mut reg = Registry::new();
222            // Variant pkgs first so alc.local.toml overrides win over global.
223            register_variant_pkgs(&mut reg, &variant_pkgs);
224            for path in &effective {
225                if let Some(resolver) = make_resolver(path) {
226                    reg.add(resolver);
227                }
228            }
229            reg.install(lua)?;
230            Ok(())
231        })
232        .await
233        .map_err(|e| format!("Session VM spawn failed: {e}"))?;
234
235        // 2. Setup: register alc.* StdLib, set ctx, load prelude.
236        //    Safe to set globals — this VM is exclusively ours.
237        session_isle
238            .exec(move |lua| {
239                let alc_table = lua.create_table()?;
240                bridge::register(lua, &alc_table, bridge_config)?;
241                lua.globals().set("alc", alc_table)?;
242
243                let ctx_value = lua.to_value(&lua_ctx)?;
244                lua.globals().set("ctx", ctx_value)?;
245
246                lua.load(PRELUDE)
247                    .exec()
248                    .map_err(|e| IsleError::Lua(format!("Prelude load failed: {e}")))?;
249
250                // Note: `print()` redirect is handled by `bridge::register` via
251                // `data::register_print` when `BridgeConfig::log_sink` is Some.
252                // That implementation routes to both tracing (alc.lua.print) and
253                // the per-session LogSink ring buffer, keeping stdout clean for
254                // the rmcp JSON-RPC stdio transport.
255                //
256                // `io.write` is intentionally left unchanged — scripts that
257                // explicitly target stdout/stderr can still use it.
258
259                // No need to clear package.loaded — fresh VM.
260
261                Ok("ok".to_string())
262            })
263            .await
264            .map_err(|e| format!("Session setup failed: {e}"))?;
265
266        // 3. Execute user code as a coroutine on the session VM.
267        let wrapped_code = format!("return alc.json_encode((function()\n{lua_code}\nend)())");
268        let exec_task = session_isle.spawn_coroutine_eval(&wrapped_code);
269
270        // Handle no longer needed — all requests have been sent.
271        // The driver keeps the channel alive until the session completes.
272        drop(session_isle);
273
274        Ok(Session::new(llm_rx, exec_task, metrics, session_driver))
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use std::fs;
282
283    /// Create a temporary package directory with the given name and `init.lua` content.
284    fn make_pkg_dir(parent: &std::path::Path, pkg_name: &str, init_lua: &str) -> PathBuf {
285        let pkg_dir = parent.join(pkg_name);
286        fs::create_dir_all(&pkg_dir).unwrap();
287        fs::write(pkg_dir.join("init.lua"), init_lua).unwrap();
288        parent.to_path_buf()
289    }
290
291    /// `extra_lib_paths=vec![]` — eval_simple must work as before.
292    #[tokio::test]
293    async fn no_extra_lib_paths_eval_simple() {
294        let executor = Executor::new(vec![]).await.unwrap();
295        let result = executor.eval_simple("return 42".to_string()).await.unwrap();
296        assert_eq!(result, serde_json::json!(42));
297    }
298
299    /// `eval_simple_with_paths` with a project-local package.
300    ///
301    /// Creates a temp dir with `test_pkg/init.lua` returning `{value = 99}`,
302    /// then verifies `require("test_pkg").value` == 99 via the extra resolver.
303    #[tokio::test]
304    async fn extra_lib_paths_reachable_via_eval_simple_with_paths() {
305        let tmp = tempfile::tempdir().unwrap();
306        let pkg_root = make_pkg_dir(tmp.path(), "test_pkg", "return { value = 99 }");
307
308        let executor = Executor::new(vec![]).await.unwrap();
309        let code = r#"
310            local pkg = require("test_pkg")
311            return pkg.value
312        "#
313        .to_string();
314
315        let result = executor
316            .eval_simple_with_paths(code, vec![pkg_root], vec![])
317            .await
318            .unwrap();
319
320        assert_eq!(result, serde_json::json!(99));
321    }
322
323    /// Variant pkg with a non-matching directory name resolves via
324    /// `VariantRootResolver` + `PrefixResolver`.
325    #[tokio::test]
326    async fn variant_pkg_resolves_root_and_submodule() {
327        let tmp = tempfile::tempdir().unwrap();
328        // pkg dir name (`physical-dir`) intentionally differs from the
329        // require name (`logical_name`) — variant scope must support this.
330        let pkg_dir = tmp.path().join("physical-dir");
331        fs::create_dir_all(&pkg_dir).unwrap();
332        fs::write(
333            pkg_dir.join("init.lua"),
334            "return { greet = function(n) return 'hi-' .. n end, sub = require('logical_name.sub') }",
335        )
336        .unwrap();
337        fs::write(pkg_dir.join("sub.lua"), "return { value = 7 }").unwrap();
338
339        let executor = Executor::new(vec![]).await.unwrap();
340        let code = r#"
341            local pkg = require("logical_name")
342            return { msg = pkg.greet("there"), sub_value = pkg.sub.value }
343        "#
344        .to_string();
345
346        let result = executor
347            .eval_simple_with_paths(code, vec![], vec![VariantPkg::new("logical_name", pkg_dir)])
348            .await
349            .unwrap();
350
351        assert_eq!(result["msg"], serde_json::json!("hi-there"));
352        assert_eq!(result["sub_value"], serde_json::json!(7));
353    }
354
355    /// Variant pkg overrides a same-name global pkg (priority: variant > global).
356    #[tokio::test]
357    async fn variant_pkg_overrides_global_same_name() {
358        let global_tmp = tempfile::tempdir().unwrap();
359        let variant_tmp = tempfile::tempdir().unwrap();
360
361        // Global: my_pkg returns 1
362        make_pkg_dir(global_tmp.path(), "my_pkg", "return { value = 1 }");
363        // Variant: my_pkg returns 2 — must win
364        let variant_dir = variant_tmp.path().join("my_pkg");
365        fs::create_dir_all(&variant_dir).unwrap();
366        fs::write(variant_dir.join("init.lua"), "return { value = 2 }").unwrap();
367
368        let executor = Executor::new(vec![global_tmp.path().to_path_buf()])
369            .await
370            .unwrap();
371
372        let code = r#"
373            local pkg = require("my_pkg")
374            return pkg.value
375        "#
376        .to_string();
377
378        let result = executor
379            .eval_simple_with_paths(code, vec![], vec![VariantPkg::new("my_pkg", variant_dir)])
380            .await
381            .unwrap();
382
383        assert_eq!(result, serde_json::json!(2));
384    }
385
386    /// When `extra_lib_paths` has a pkg with the same name as one in global paths,
387    /// the extra one takes priority (it is prepended).
388    #[tokio::test]
389    async fn extra_lib_paths_priority_over_default() {
390        let global_tmp = tempfile::tempdir().unwrap();
391        let extra_tmp = tempfile::tempdir().unwrap();
392
393        // Global: test_pkg returns 1
394        make_pkg_dir(global_tmp.path(), "test_pkg", "return { value = 1 }");
395        // Extra (project-local): test_pkg returns 2
396        let extra_root = make_pkg_dir(extra_tmp.path(), "test_pkg", "return { value = 2 }");
397
398        // Executor has global as its lib_paths.
399        let executor = Executor::new(vec![global_tmp.path().to_path_buf()])
400            .await
401            .unwrap();
402
403        let code = r#"
404            local pkg = require("test_pkg")
405            return pkg.value
406        "#
407        .to_string();
408
409        let result = executor
410            .eval_simple_with_paths(code, vec![extra_root], vec![])
411            .await
412            .unwrap();
413
414        // extra (2) must win over global (1)
415        assert_eq!(result, serde_json::json!(2));
416    }
417}