Skip to main content

brep_script_core/
worker.rs

1//! The code-mode worker: one restricted JavaScript execution in a process of
2//! its own, on Boa, unchanged. A host binary becomes this process when it is
3//! started with the hidden worker flag (`BREP_mcp_core` `cad::code::worker_entry`).
4//!
5//! The host that starts this process owns it: it watches the process's CPU
6//! time, memory and age, and KILLS it — on an agent's halt
7//! (`cad_code_cancel`) or a limit — which stops any running script, however
8//! it loops. Nothing in the host's address space is reachable from the
9//! script, and a killed worker leaves nothing behind but the CAD operations
10//! it had already handed to the service.
11//!
12//! Protocol, one JSON object per line:
13//!
14//! - stdin, first line: `{"source", "sdk", "manifest"}` — the program (an ES
15//!   module with `export default async function main()`), the `@brep/cad`
16//!   module source, and the manifest identity as JSON text;
17//! - stdin, then: `{"reply": id, "body": text}` — a host call's answer;
18//! - stdout: `{"call": id, "method": m, "body": text}` — a host call (the
19//!   global `__brep_host(method, body)` the SDK uses, answered by a Promise);
20//!   `{"log": line}`; and last `{"done": {"ok": json}}` or
21//!   `{"done": {"error": {"code", "message"}}}`.
22//!
23//! The only importable module is `@brep/cad`; there is no filesystem,
24//! network, process, timer or environment binding.
25//!
26//! The same protocol drives the browser's code worker (a Web Worker running
27//! this crate in the app's wasm, messages in place of lines): `Realm` is the
28//! event-driven core both share — `Realm::begin` runs the program until it
29//! waits on the host or ends, `Realm::answer` delivers one host reply and
30//! runs on. `main` is that core over stdin and stdout.
31use crate::{describe, install_console, Logs};
32use boa_engine::builtins::promise::PromiseState;
33use boa_engine::module::{ModuleLoader, Referrer};
34use boa_engine::object::builtins::{JsFunction, JsPromise};
35use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, Module, NativeFunction, Source};
36use serde_json::{json, Value};
37use std::cell::RefCell;
38use std::collections::HashMap;
39#[cfg(not(target_arch = "wasm32"))]
40use std::io::{BufRead, Write};
41use std::rc::Rc;
42
43struct OnlySdk {
44    sdk: String,
45    parsed: RefCell<Option<Module>>,
46}
47
48impl ModuleLoader for OnlySdk {
49    async fn load_imported_module(
50        self: Rc<Self>,
51        _referrer: Referrer,
52        request: boa_engine::module::ModuleRequest,
53        context: &RefCell<&mut Context>,
54    ) -> JsResult<Module> {
55        let spec = request.specifier().to_std_string_escaped();
56        if spec != "@brep/cad" {
57            return Err(JsNativeError::typ().with_message(format!("cannot import `{spec}`: the only importable module is @brep/cad")).into());
58        }
59        if let Some(m) = self.parsed.borrow().as_ref() {
60            return Ok(m.clone());
61        }
62        let mut cx = context.borrow_mut();
63        let module = Module::parse(Source::from_bytes(&self.sdk).with_path(std::path::Path::new("@brep/cad")), None, &mut cx)?;
64        *self.parsed.borrow_mut() = Some(module.clone());
65        Ok(module)
66    }
67}
68
69thread_local! {
70    static PENDING: RefCell<HashMap<u64, (JsFunction, JsFunction)>> = RefCell::new(HashMap::new());
71    static NEXT: RefCell<u64> = const { RefCell::new(0) };
72    /// Where this realm's protocol messages go: stdout natively, the Web
73    /// Worker's `postMessage` in the browser.
74    static SINK: RefCell<Option<Box<dyn Fn(&Value)>>> = RefCell::new(None);
75}
76
77fn emit(line: &Value) {
78    SINK.with(|s| {
79        if let Some(sink) = s.borrow().as_ref() {
80            sink(line);
81        }
82    });
83}
84
85fn done_error(code: &str, message: String) -> Value {
86    json!({ "done": { "error": { "code": code, "message": message } } })
87}
88
89/// `__brep_host(method, body)`: send the call to the host and answer a
90/// pending Promise, settled when the host's reply arrives.
91fn host_call(_: &JsValue, args: &[JsValue], cx: &mut Context) -> JsResult<JsValue> {
92    let text = |i: usize| args.get(i).and_then(JsValue::as_string).map(|s| s.to_std_string_escaped()).unwrap_or_default();
93    let (method, body) = (text(0), text(1));
94    let (promise, resolvers) = JsPromise::new_pending(cx);
95    let id = NEXT.with(|n| {
96        *n.borrow_mut() += 1;
97        *n.borrow()
98    });
99    PENDING.with(|p| p.borrow_mut().insert(id, (resolvers.resolve, resolvers.reject)));
100    emit(&json!({ "call": id, "method": method, "body": body }));
101    Ok(promise.into())
102}
103
104/// Boa's own runtime limits (loop iterations per frame, recursion, stack)
105/// are uncatchable in JavaScript; reported as the resource limit they are.
106fn fail(code: &str, e: JsError, cx: &mut Context) -> Value {
107    let limit = e.as_engine().is_some();
108    let message = describe(e, cx);
109    done_error(if limit || message.contains("RuntimeLimitError") { "resource_limit" } else { code }, message)
110}
111
112/// A parse error made actionable: the parser's message, the source lines
113/// it points at with a caret, and the fix for the mistakes that produce it
114/// when a program travels inside JSON (a `\n` escape decoded to a real line
115/// break inside a quoted string; a whole program escaped twice).
116pub fn syntax_help(source: &str, message: &str) -> String {
117    let mut out = message.to_string();
118    let unterminated = message.to_ascii_lowercase().contains("unterminated string literal");
119    // Boa names no position for an unterminated string: find the quote
120    // that opens a string the line ends inside.
121    let (row, col) = position(message).or_else(|| if unterminated { open_quote(source) } else { None }).unwrap_or((0, 0));
122    let lines: Vec<&str> = source.lines().collect();
123    if (1..=lines.len()).contains(&row) {
124        out.push_str("\n");
125        for n in row.saturating_sub(1).max(1)..=(row + 1).min(lines.len()) {
126            let text: String = lines[n - 1].chars().take(160).collect();
127            out.push_str(&format!("\n{n:>4} | {text}"));
128            if n == row && col > 0 && col <= 161 {
129                out.push_str(&format!("\n     | {}^", " ".repeat(col - 1)));
130            }
131        }
132    }
133    if !source.contains('\n') && source.contains("\\n") {
134        out.push_str("\n\nhint: the program arrived as ONE line holding literal \\n sequences: it was escaped twice. Send real line breaks (one JSON string escape, not two).");
135    } else if unterminated {
136        out.push_str("\n\nhint: a '...' or \"...\" string cannot span lines. A program sent inside JSON turns each \\n into a real line break: write \\\\n in the JSON for the two-character escape, or use a template literal `...` for multi-line text (an expressions_set script, say).");
137        if lines.iter().any(|l| l.contains("n't") || l.contains("'s ")) {
138            out.push_str(" An apostrophe also ends a '...' string early: use \"...\" or `...` for text containing one.");
139        }
140    }
141    out
142}
143
144/// Where the first '...' or "..." string still open at its line's end
145/// begins (1-based row and column), skipping comments and template literals
146/// (a `${...}` inside one is skipped with it; a regex literal can mislead the
147/// scan, which only places a hint).
148fn open_quote(source: &str) -> Option<(usize, usize)> {
149    let (mut row, mut col) = (1usize, 0usize);
150    let mut quote: Option<(char, usize, usize)> = None;
151    let (mut template, mut line_comment, mut block_comment, mut escaped) = (false, false, false, false);
152    let mut prev = '\0';
153    for ch in source.chars() {
154        col += 1;
155        if ch == '\n' {
156            if quote.is_some() && !escaped { return quote.map(|(_, r, c)| (r, c)); }
157            row += 1;
158            col = 0;
159            line_comment = false;
160            escaped = false;
161            prev = ch;
162            continue;
163        }
164        if line_comment {
165        } else if block_comment {
166            if prev == '*' && ch == '/' { block_comment = false; }
167        } else if let Some((q, _, _)) = quote {
168            if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == q { quote = None }
169        } else if template {
170            if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == '`' { template = false }
171        } else if prev == '/' && ch == '/' {
172            line_comment = true;
173        } else if prev == '/' && ch == '*' {
174            block_comment = true;
175        } else if ch == '\'' || ch == '"' {
176            quote = Some((ch, row, col));
177        } else if ch == '`' {
178            template = true;
179        }
180        prev = if block_comment && prev == '/' && ch == '*' { '\0' } else { ch };
181    }
182    quote.map(|(_, r, c)| (r, c))
183}
184
185/// The first source position a parser message names: Boa's `line N, col M`
186/// or the TypeScript checker's `(N,M)`.
187fn position(message: &str) -> Option<(usize, usize)> {
188    let digits = |s: &str| -> Option<(usize, usize)> {
189        let n: String = s.chars().take_while(char::is_ascii_digit).collect();
190        Some((n.parse().ok()?, n.len()))
191    };
192    for (at, _) in message.match_indices("line ") {
193        let rest = &message[at + 5..];
194        let Some((row, used)) = digits(rest) else { continue };
195        let col = rest[used..].find("col").and_then(|c| digits(rest[used + c..].trim_start_matches(|ch: char| !ch.is_ascii_digit()))).map_or(0, |(c, _)| c);
196        return Some((row, col));
197    }
198    for (at, _) in message.match_indices('(') {
199        let rest = &message[at + 1..];
200        let Some((row, used)) = digits(rest) else { continue };
201        if !rest[used..].starts_with(',') { continue }
202        let Some((col, used2)) = digits(&rest[used + 1..]) else { continue };
203        if rest[used + 1 + used2..].starts_with(')') { return Some((row, col)); }
204    }
205    None
206}
207
208/// One execution, driven by its host's messages.
209pub struct Realm {
210    cx: Context,
211    logs: Logs,
212    sent: usize,
213    main: JsPromise,
214}
215
216impl Realm {
217    /// Start an execution from its start message (`{source, sdk,
218    /// manifest}`), its protocol messages going to `sink`: run the program
219    /// until it waits on the host (`Some`) or ends (`None`; its `done` sent).
220    pub fn begin(start: &str, sink: Box<dyn Fn(&Value)>) -> Option<Realm> {
221        SINK.with(|s| *s.borrow_mut() = Some(sink));
222        let start: Value = match serde_json::from_str(start) {
223            Ok(v) => v,
224            Err(e) => {
225                emit(&done_error("internal_error", format!("bad start message: {e}")));
226                return None;
227            }
228        };
229        let field = |k: &str| start.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
230        let (source, sdk, manifest) = (field("source"), field("sdk"), field("manifest"));
231        let loader = Rc::new(OnlySdk { sdk, parsed: RefCell::new(None) });
232        let mut cx = match Context::builder().module_loader(loader).build() {
233            Ok(cx) => cx,
234            Err(e) => {
235                emit(&done_error("internal_error", e.to_string()));
236                return None;
237            }
238        };
239        cx.runtime_limits_mut().set_loop_iteration_limit(crate::LOOP_ITERATION_LIMIT);
240        cx.runtime_limits_mut().set_recursion_limit(crate::RECURSION_LIMIT);
241        let logs: Logs = Rc::new(RefCell::new(Vec::new()));
242        let setup = (|| -> JsResult<()> {
243            install_console(&mut cx, &logs)?;
244            cx.register_global_property(js_string!("__brep_manifest"), js_string!(manifest), boa_engine::property::Attribute::all())?;
245            cx.register_global_builtin_callable(js_string!("__brep_host"), 2, NativeFunction::from_fn_ptr(host_call))?;
246            Ok(())
247        })();
248        if let Err(e) = setup {
249            let line = done_error("internal_error", describe(e, &mut cx));
250            return Self::end(&logs, &mut 0, line);
251        }
252        let mut sent = 0;
253        match Self::start_main(&source, &mut cx) {
254            Ok(main) => {
255                let mut realm = Realm { cx, logs, sent, main };
256                if realm.progress() {
257                    None
258                } else {
259                    Some(realm)
260                }
261            }
262            Err(line) => Self::end(&logs, &mut sent, line),
263        }
264    }
265
266    /// Evaluate the module and call its `main`: its Promise, or the `done`
267    /// line when it cannot start.
268    fn start_main(source: &str, cx: &mut Context) -> Result<JsPromise, Value> {
269        let module = Module::parse(Source::from_bytes(source).with_path(std::path::Path::new("main.js")), None, cx).map_err(|e| {
270            let mut line = fail("compile_failed", e, cx);
271            if let Some(message) = line["done"]["error"]["message"].as_str() {
272                line["done"]["error"]["message"] = Value::String(syntax_help(source, message));
273            }
274            line
275        })?;
276        let evaluated = module.load_link_evaluate(cx);
277        cx.run_jobs().map_err(|e| fail("job_failed", e, cx))?;
278        match evaluated.state() {
279            PromiseState::Fulfilled(_) => {}
280            PromiseState::Rejected(v) => {
281                // A link failure (a refused import) or a top-level throw.
282                let message = describe(JsError::from_opaque(v), cx);
283                let code = if message.contains("cannot import") || message.contains("SyntaxError") { "compile_failed" } else { "script_failed" };
284                return Err(done_error(code, message));
285            }
286            PromiseState::Pending => {
287                return Err(done_error("invalid_arguments", "module evaluation is pending without progress: top-level code may not wait on the host".into()))
288            }
289        }
290        let main = module.namespace(cx).get(js_string!("default"), cx).map_err(|e| fail("script_failed", e, cx))?;
291        let Some(main) = main.as_callable() else {
292            return Err(done_error("invalid_arguments", "the program must `export default async function main()`".into()));
293        };
294        let returned = main.call(&JsValue::undefined(), &[], cx).map_err(|e| fail("script_failed", e, cx))?;
295        returned
296            .as_object()
297            .and_then(|o| JsPromise::from_object(o.clone()).ok())
298            .ok_or_else(|| done_error("invalid_arguments", "main() must be async (return a Promise)".into()))
299    }
300
301    /// Deliver one host message (`{reply, body}`) and run on: whether the
302    /// execution has ended (its `done` sent).
303    pub fn answer(&mut self, message: &str) -> bool {
304        let Ok(msg) = serde_json::from_str::<Value>(message) else { return false };
305        let (Some(id), Some(body)) = (msg.get("reply").and_then(Value::as_u64), msg.get("body").and_then(Value::as_str)) else { return false };
306        if let Some((resolve, _)) = PENDING.with(|p| p.borrow_mut().remove(&id)) {
307            if let Err(e) = resolve.call(&JsValue::undefined(), &[js_string!(body).into()], &mut self.cx) {
308                let line = fail("job_failed", e, &mut self.cx);
309                Self::end(&self.logs, &mut self.sent, line);
310                return true;
311            }
312        }
313        self.progress()
314    }
315
316    /// The host closed the bridge with the execution still waiting.
317    pub fn abandon(&mut self) {
318        Self::end(&self.logs, &mut self.sent, done_error("internal_error", "the host closed the bridge".into()));
319    }
320
321    /// Run every job, then end if `main` settled or nothing can progress:
322    /// whether it ended.
323    fn progress(&mut self) -> bool {
324        if let Err(e) = self.cx.run_jobs() {
325            let line = fail("job_failed", e, &mut self.cx);
326            Self::end(&self.logs, &mut self.sent, line);
327            return true;
328        }
329        flush_logs(&self.logs, &mut self.sent);
330        let line = match self.main.state() {
331            PromiseState::Fulfilled(v) => match v.to_json(&mut self.cx) {
332                Ok(json) => json!({ "done": { "ok": json.unwrap_or(Value::Null) } }),
333                Err(e) => done_error("invalid_arguments", format!("main's result is not JSON: {}", describe(e, &mut self.cx))),
334            },
335            PromiseState::Rejected(v) => {
336                let message = describe(JsError::from_opaque(v), &mut self.cx);
337                done_error(if message.contains("RuntimeLimitError") { "resource_limit" } else { "script_failed" }, message)
338            }
339            PromiseState::Pending if PENDING.with(|p| p.borrow().is_empty()) => {
340                done_error("invalid_arguments", "main is pending without progress: no host call is outstanding and no job can run".into())
341            }
342            // Park on the host: nothing can run until a reply arrives.
343            PromiseState::Pending => return false,
344        };
345        Self::end(&self.logs, &mut self.sent, line);
346        true
347    }
348
349    /// Send the remaining logs and the `done` line; drop unsettled host calls
350    /// (they hold this realm's functions).
351    fn end(logs: &Logs, sent: &mut usize, line: Value) -> Option<Realm> {
352        flush_logs(logs, sent);
353        emit(&line);
354        PENDING.with(|p| p.borrow_mut().clear());
355        None
356    }
357}
358
359fn flush_logs(logs: &Logs, sent: &mut usize) {
360    let lines = logs.borrow();
361    for line in &lines[*sent..] {
362        emit(&json!({ "log": line }));
363    }
364    *sent = lines.len();
365}
366
367/// Run one execution reading stdin and writing stdout; the process exits
368/// after the `done` line.
369#[cfg(not(target_arch = "wasm32"))]
370pub fn main() {
371    let stdin = std::io::stdin();
372    let mut lines = stdin.lock().lines();
373    let Some(Ok(first)) = lines.next() else { return };
374    let sink = Box::new(|line: &Value| {
375        let mut out = std::io::stdout().lock();
376        let _ = writeln!(out, "{line}");
377        let _ = out.flush();
378    });
379    let Some(mut realm) = Realm::begin(&first, sink) else { return };
380    loop {
381        let Some(Ok(line)) = lines.next() else {
382            realm.abandon();
383            return;
384        };
385        if realm.answer(&line) {
386            return;
387        }
388    }
389}
390