Skip to main content

sim_web_shell/
cli.rs

1//! Loadable CLI claims for the web shell surfaces.
2
3use std::sync::Arc;
4
5use sim_codec_lisp::LispCodecLib;
6use sim_kernel::{
7    AbiVersion, Args, CORE_FUNCTION_CLASS_ID, Callable, ClassRef, CodecId, Cx, Error, Export, Expr,
8    Lib, LibManifest, LibTarget, Linker, LoadCx, Object, ObjectCompat, Result, Symbol, Value,
9    Version, read_eval_capability,
10};
11use sim_run_core::{Bootloader, cli_main_entrypoint_symbol};
12
13use crate::serve::{ServeConfig, serve_with_cx};
14
15/// Loadable lib that claims the `atelier` command-line verb.
16pub struct AtelierCliLib;
17
18/// Loadable lib that claims the `browse` command-line verb.
19pub struct BrowseCliLib;
20
21impl Lib for AtelierCliLib {
22    fn manifest(&self) -> LibManifest {
23        cli_manifest("atelier", "cli/main/atelier")
24    }
25
26    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
27        register_cli_entrypoint(cx, linker, "atelier")
28    }
29}
30
31impl Lib for BrowseCliLib {
32    fn manifest(&self) -> LibManifest {
33        cli_manifest("browse", "cli/main/browse")
34    }
35
36    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
37        register_cli_entrypoint(cx, linker, "browse")
38    }
39}
40
41fn cli_manifest(id: &str, entrypoint: &str) -> LibManifest {
42    LibManifest {
43        id: Symbol::new(id),
44        version: Version(env!("CARGO_PKG_VERSION").to_owned()),
45        abi: AbiVersion { major: 0, minor: 1 },
46        target: LibTarget::HostRegistered,
47        requires: Vec::new(),
48        capabilities: Vec::new(),
49        exports: vec![Export::Function {
50            symbol: symbol_from_slash(entrypoint),
51            function_id: None,
52        }],
53    }
54}
55
56fn register_cli_entrypoint(
57    cx: &mut LoadCx,
58    linker: &mut Linker<'_>,
59    verb: &'static str,
60) -> Result<()> {
61    linker.function_value(
62        Symbol::qualified("cli", format!("main/{verb}")),
63        cx.factory()
64            .opaque(Arc::new(WebShellCliEntrypoint { verb }))?,
65    )?;
66    Ok(())
67}
68
69#[derive(Clone)]
70struct WebShellCliEntrypoint {
71    verb: &'static str,
72}
73
74impl Object for WebShellCliEntrypoint {
75    fn display(&self, _cx: &mut Cx) -> Result<String> {
76        Ok(format!("#<function cli/main/{}>", self.verb))
77    }
78
79    fn as_any(&self) -> &dyn std::any::Any {
80        self
81    }
82}
83
84impl ObjectCompat for WebShellCliEntrypoint {
85    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
86        if let Some(value) = cx
87            .registry()
88            .class_by_symbol(&Symbol::qualified("core", "Function"))
89        {
90            return Ok(value.clone());
91        }
92        cx.factory().class_stub(
93            CORE_FUNCTION_CLASS_ID,
94            Symbol::qualified("core", "Function"),
95        )
96    }
97
98    fn as_callable(&self) -> Option<&dyn Callable> {
99        Some(self)
100    }
101}
102
103impl Callable for WebShellCliEntrypoint {
104    fn call(&self, cx: &mut Cx, args: Args) -> Result<Value> {
105        verify_cli_envelope(cx, &args, self.verb)?;
106        cx.factory().bool(true)
107    }
108}
109
110fn verify_cli_envelope(cx: &mut Cx, args: &Args, verb: &str) -> Result<()> {
111    let envelope = args
112        .values()
113        .first()
114        .ok_or_else(|| Error::Eval(format!("cli/main/{verb} expects a CLI envelope")))?;
115    let envelope_verb = envelope_string_field(cx, envelope, "verb")?;
116    if envelope_verb != verb {
117        return Err(Error::Eval(format!(
118            "cli/main/{verb} received verb {envelope_verb}"
119        )));
120    }
121    let payload_args = envelope_args(cx, envelope)?;
122    if payload_args.first().map(String::as_str) != Some(verb) {
123        return Err(Error::Eval(format!(
124            "cli/main/{verb} expects the first payload argument to be {verb}"
125        )));
126    }
127    Ok(())
128}
129
130fn envelope_string_field(cx: &mut Cx, envelope: &Value, field: &str) -> Result<String> {
131    let Some(table) = envelope.object().as_table_impl() else {
132        return Err(Error::Eval("CLI envelope is not a table".to_owned()));
133    };
134    match table.get(cx, Symbol::new(field))?.object().as_expr(cx)? {
135        Expr::String(text) => Ok(text),
136        Expr::Nil => Err(Error::Eval(format!("CLI envelope field {field} is nil"))),
137        other => Err(Error::Eval(format!(
138            "CLI envelope field {field} is not a string: {other:?}"
139        ))),
140    }
141}
142
143fn envelope_args(cx: &mut Cx, envelope: &Value) -> Result<Vec<String>> {
144    let Some(table) = envelope.object().as_table_impl() else {
145        return Err(Error::Eval("CLI envelope is not a table".to_owned()));
146    };
147    let value = table.get(cx, Symbol::new("args"))?;
148    let Some(list) = value.object().as_list() else {
149        return Err(Error::Eval(
150            "CLI envelope field args is not a list".to_owned(),
151        ));
152    };
153    list.to_vec(cx, Some(64))?
154        .into_iter()
155        .map(|value| match value.object().as_expr(cx)? {
156            Expr::String(text) => Ok(text),
157            other => Err(Error::Eval(format!(
158                "CLI payload argument is not a string: {other:?}"
159            ))),
160        })
161        .collect()
162}
163
164fn symbol_from_slash(text: &str) -> Symbol {
165    match text.split_once('/') {
166        Some((head, tail)) => Symbol::qualified(head, tail),
167        None => Symbol::new(text),
168    }
169}
170
171// ---------------------------------------------------------------------------
172// The loadable `serve` verb: boots the web shell through the sim-run bootloader.
173// ---------------------------------------------------------------------------
174
175/// The verb the bootloader dispatches to serve the web shell (`sim serve ...`).
176pub const WEB_SERVE_VERB: &str = "serve";
177
178/// Returns the function symbol exported for the bootloader handoff.
179pub fn web_serve_entrypoint_symbol() -> Symbol {
180    cli_main_entrypoint_symbol(WEB_SERVE_VERB)
181}
182
183/// Registers the `codec/lisp` boot codec and the web-shell `serve` verb onto an
184/// existing [`Bootloader`], returning it for further composition. A downstream binary
185/// can stack this with other serve libraries (e.g. MCP) onto one bootloader.
186pub fn configure_web_bootloader(loader: Bootloader) -> Bootloader {
187    loader
188        // The web shell evaluates cookbook recipes, which needs read-eval. Grant it
189        // here at the trusted host boundary (the bootloader holds the boot session's
190        // GrantSeat); the serve lib no longer self-grants it. run_recipe still gates
191        // each run on read-eval, so the capability is required, not ambient behavior.
192        .with_capability(read_eval_capability())
193        .host_lib("codec/lisp", || {
194            Box::new(LispCodecLib::new(CodecId(1)).expect("lisp boot codec"))
195        })
196        .host_verb(WEB_SERVE_VERB, "lib/web-serve", || Box::new(WebServeLib))
197}
198
199/// A standalone [`Bootloader`] pre-configured to serve the web shell: the `codec/lisp`
200/// boot codec plus the `serve` verb. The thin `sim-web-shell` binary is just
201/// `web_bootloader().run(..)`.
202pub fn web_bootloader() -> Bootloader {
203    configure_web_bootloader(Bootloader::standard())
204}
205
206/// Loadable library exporting the web-shell `serve` entrypoint.
207pub struct WebServeLib;
208
209impl Lib for WebServeLib {
210    fn manifest(&self) -> LibManifest {
211        LibManifest {
212            id: Symbol::qualified("lib", "web-serve"),
213            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
214            abi: AbiVersion { major: 0, minor: 1 },
215            target: LibTarget::HostRegistered,
216            requires: Vec::new(),
217            capabilities: vec![read_eval_capability()],
218            exports: vec![Export::Function {
219                symbol: web_serve_entrypoint_symbol(),
220                function_id: None,
221            }],
222        }
223    }
224
225    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
226        linker.function_value(
227            web_serve_entrypoint_symbol(),
228            cx.factory().opaque(Arc::new(WebServeEntrypoint))?,
229        )?;
230        Ok(())
231    }
232}
233
234#[derive(Clone)]
235struct WebServeEntrypoint;
236
237impl Object for WebServeEntrypoint {
238    fn display(&self, _cx: &mut Cx) -> Result<String> {
239        Ok("cli/main/serve".to_owned())
240    }
241
242    fn as_any(&self) -> &dyn std::any::Any {
243        self
244    }
245}
246
247impl ObjectCompat for WebServeEntrypoint {
248    fn as_callable(&self) -> Option<&dyn Callable> {
249        Some(self)
250    }
251}
252
253impl Callable for WebServeEntrypoint {
254    fn call(&self, cx: &mut Cx, args: Args) -> Result<Value> {
255        // Parse `--addr` / `--atelier-root` from the boot envelope (skipping the
256        // `serve` verb), then run the blocking HTTP loop in the bootloader cx.
257        let config = match args.values().first() {
258            Some(envelope) => {
259                let payload = envelope_args(cx, envelope)?;
260                parse_serve_config(payload.into_iter().skip(1))?
261            }
262            None => ServeConfig::default(),
263        };
264        serve_with_cx(cx, &config)
265            .map_err(|err| Error::Eval(format!("web serve failed: {err}")))?;
266        cx.factory().bool(true)
267    }
268}
269
270/// Parse the serve envelope arguments, failing closed on malformed input: a
271/// bare `--addr`/`--atelier-root` with no value, or any unknown flag/positional,
272/// is an error rather than a silently-ignored argument (so `--add 0.0.0.0:80`
273/// cannot quietly leave the shell bound to loopback).
274fn parse_serve_config(args: impl Iterator<Item = String>) -> Result<ServeConfig> {
275    let mut config = ServeConfig::default();
276    let mut iter = args;
277    while let Some(arg) = iter.next() {
278        match arg.as_str() {
279            "--addr" => {
280                config.addr = iter
281                    .next()
282                    .ok_or_else(|| Error::Eval("--addr requires a value".to_owned()))?;
283            }
284            other if other.starts_with("--addr=") => {
285                config.addr = other["--addr=".len()..].to_owned();
286            }
287            "--atelier-root" => {
288                config.atelier_root = iter
289                    .next()
290                    .ok_or_else(|| Error::Eval("--atelier-root requires a value".to_owned()))?
291                    .into();
292            }
293            other if other.starts_with("--atelier-root=") => {
294                config.atelier_root = other["--atelier-root=".len()..].into();
295            }
296            "--dry-run" => {
297                config.dry_run = true;
298            }
299            other => {
300                return Err(Error::Eval(format!("unknown serve argument: {other}")));
301            }
302        }
303    }
304    Ok(config)
305}
306
307#[cfg(test)]
308mod tests {
309    use super::parse_serve_config;
310
311    fn parse(args: &[&str]) -> super::Result<super::ServeConfig> {
312        parse_serve_config(args.iter().map(|a| (*a).to_owned()))
313    }
314
315    #[test]
316    fn missing_addr_value_errors() {
317        let err = parse(&["--addr"]).expect_err("bare --addr must error");
318        assert!(err.to_string().contains("--addr requires a value"));
319    }
320
321    #[test]
322    fn missing_atelier_root_value_errors() {
323        let err = parse(&["--atelier-root"]).expect_err("bare --atelier-root must error");
324        assert!(err.to_string().contains("--atelier-root requires a value"));
325    }
326
327    #[test]
328    fn unknown_flag_errors() {
329        // A typo such as `--add` must fail visibly, not silently bind loopback.
330        let err = parse(&["--add", "0.0.0.0:80"]).expect_err("unknown flag must error");
331        assert!(err.to_string().contains("unknown serve argument: --add"));
332    }
333
334    #[test]
335    fn unknown_positional_errors() {
336        let err = parse(&["serve-extra"]).expect_err("stray positional must error");
337        assert!(
338            err.to_string()
339                .contains("unknown serve argument: serve-extra")
340        );
341    }
342
343    #[test]
344    fn dry_run_still_succeeds() {
345        let config = parse(&["--dry-run"]).expect("--dry-run must parse");
346        assert!(config.dry_run);
347    }
348
349    #[test]
350    fn addr_and_atelier_root_parse() {
351        let config = parse(&["--addr", "127.0.0.1:9000", "--atelier-root", "/tmp/atelier"])
352            .expect("valid args must parse");
353        assert_eq!(config.addr, "127.0.0.1:9000");
354        assert_eq!(config.atelier_root.to_str(), Some("/tmp/atelier"));
355        assert!(!config.dry_run);
356    }
357
358    #[test]
359    fn inline_addr_value_parses() {
360        let config = parse(&["--addr=127.0.0.1:9100"]).expect("inline addr must parse");
361        assert_eq!(config.addr, "127.0.0.1:9100");
362    }
363}