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