BREP_script_core 0.2.0

The next.BREP.io script interpreter core (Rust B-rep CAD): evaluate one JavaScript file on Boa, call one global function with one JSON argument, and return its JSON result or its refusal. Shared by the PLM server's hooks and the CAD app, native and wasm.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! The code-mode worker: one restricted JavaScript execution in a process of
//! its own, on Boa. A host binary becomes this process when it is started
//! with the hidden worker flag (`BREP_mcp_core` `cad::code::worker_entry`).
//!
//! The host that starts this process owns it: it watches the process's CPU
//! time, memory and age, and KILLS it — on an agent's halt or a limit — which
//! stops any running script, however it loops. Nothing in the host's address
//! space is reachable from the script, and a killed worker leaves nothing
//! behind but the CAD operations it had already handed to the service.
//!
//! A program is a plain script body with top-level `await` and `return`; the
//! returned value is its result. The worker blanks one leading
//! `import … from "@brep/cad"` line ([`strip_sdk_import`](crate::worker::strip_sdk_import)) and runs the body
//! as `export default async function main() { BODY }` ([`module_source`](crate::worker::module_source)).
//! `sdk` is a global built from the names the host granted: each
//! `sdk.<namespace>.<action>(body)` is one host call, and a name that is not
//! there throws saying which names are close.
//!
//! Protocol, one JSON object per line:
//!
//! - stdin, first line: `{"names", "limits", "source"}` — the granted
//!   `<namespace>.<action>` names, the execution's limits (the HOST enforces
//!   them: Boa has no CPU or heap quota of its own) and the program;
//! - stdin, then: `{"call": id, "ok": true, "value": json}` or
//!   `{"call": id, "ok": false, "error": record}` — a host call's answer;
//! - stdout: `{"call": id, "method": "<namespace>.<action>", "body": json}` —
//!   a host call, answered by a Promise that resolves with the value or
//!   rejects with an `ApiFailure` error carrying the record as `.error`;
//!   `{"log": line}`; and last `{"done": {"ok": json}}` or
//!   `{"done": {"error": {"code", "message"}}}`.
//!
//! Nothing is importable; there is no filesystem, network, process, timer or
//! environment binding.
//!
//! The same protocol drives the browser's code worker (a Web Worker running
//! this crate in the app's wasm, messages in place of lines): `Realm` is the
//! event-driven core both share — `Realm::begin` runs the program until it
//! waits on the host or ends, `Realm::answer` delivers one host reply and
//! runs on. `main` is that core over stdin and stdout.
use crate::{describe, install_console, Logs};
use boa_engine::builtins::promise::PromiseState;
use boa_engine::module::{ModuleLoader, Referrer};
use boa_engine::object::builtins::{JsFunction, JsPromise};
use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, Module, NativeFunction, Source};
use serde_json::{json, Value};
use std::cell::RefCell;
use std::collections::HashMap;
#[cfg(not(target_arch = "wasm32"))]
use std::io::{BufRead, Write};
use std::rc::Rc;

/// A program imports nothing: every dynamic `import()` is refused (a static
/// `import` cannot be written in a script body at all).
struct NoImports;

impl ModuleLoader for NoImports {
    async fn load_imported_module(
        self: Rc<Self>,
        _referrer: Referrer,
        request: boa_engine::module::ModuleRequest,
        _context: &RefCell<&mut Context>,
    ) -> JsResult<Module> {
        let spec = request.specifier().to_std_string_escaped();
        Err(JsNativeError::typ().with_message(format!("cannot import `{spec}`: a program imports nothing; `sdk` is a global")).into())
    }
}

/// What a program body is wrapped in. The opening shares the body's first
/// line, so the rows a parser names are the program's own rows.
pub const MAIN_OPEN: &str = "export default async function main() { ";

/// The ES module a program body runs as: its top-level `await` and `return`
/// are those of an async `main`. The closing brace has a line of its own, so
/// a body that ends in a `//` comment keeps it.
pub fn module_source(body: &str) -> String {
    format!("{MAIN_OPEN}{body}\n}}")
}

/// Blank one leading `import … from "@brep/cad"` statement (the first line
/// that is not empty or a `//` comment), for clients that write modules:
/// `sdk` is a global either way. The statement becomes spaces, so every row
/// and column after it is unchanged. Any other program is returned as it is.
pub fn strip_sdk_import(source: &str) -> String {
    let mut offset = 0;
    for line in source.split_inclusive('\n') {
        let trimmed = line.trim_start();
        if trimmed.trim_end().is_empty() || trimmed.starts_with("//") {
            offset += line.len();
            continue;
        }
        let start = offset + (line.len() - trimmed.len());
        let Some(rest) = trimmed.strip_prefix("import") else { break };
        if !rest.starts_with(|c: char| c.is_whitespace() || matches!(c, '{' | '*' | '"' | '\'')) {
            break;
        }
        let Some((at, quoted)) = ["\"@brep/cad\"", "'@brep/cad'"].iter().filter_map(|q| rest.find(q).map(|at| (at, *q))).min() else { break };
        // Between `import` and the specifier: a clause and `from`, or nothing.
        let clause = rest[..at].trim();
        if !(clause.is_empty() || (clause.ends_with("from") && !clause.contains(['"', '\'', ';', '(', '=']))) {
            break;
        }
        let mut end = "import".len() + at + quoted.len();
        let tail = &trimmed[end..];
        let spaces = tail.len() - tail.trim_start_matches([' ', '\t']).len();
        if tail[spaces..].starts_with(';') {
            end += spaces + 1;
        }
        let blank = " ".repeat(trimmed[..end].chars().count());
        return format!("{}{blank}{}", &source[..start], &source[start + end..]);
    }
    source.to_string()
}

/// Builds the global `sdk` from the granted names (`__brep_names`, JSON
/// text) over the host bridge (`__brep_host(method, json) -> Promise<json>`),
/// then removes both globals. `sdk` and each `sdk.<namespace>` are plain
/// objects behind a guard: their actions are enumerable and assignable (the
/// test-mcp prelude wraps them in place), and reading a name that is not
/// there throws a TypeError naming the closest names.
const BOOTSTRAP: &str = r#"(() => {
  const host = globalThis.__brep_host;
  const names = JSON.parse(globalThis.__brep_names);
  delete globalThis.__brep_host;
  delete globalThis.__brep_names;
  const failure = (error) => {
    const e = new Error(error && error.message ? error.message : "API failure");
    e.name = "ApiFailure";
    e.error = error === undefined ? null : error;
    return e;
  };
  const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
  const tree = {};
  for (const name of names) {
    const dot = name.indexOf(".");
    if (dot <= 0 || dot === name.length - 1) continue;
    const namespace = name.slice(0, dot);
    const action = name.slice(dot + 1);
    if (!own(tree, namespace)) tree[namespace] = {};
    tree[namespace][action] = async (body) => {
      const text = JSON.stringify(body === undefined ? {} : body);
      if (text === undefined) throw new TypeError("sdk." + name + " takes one JSON value (an object of arguments)");
      const reply = JSON.parse(await host(name, text));
      if (reply && reply.ok === true) return reply.value;
      throw failure(reply ? reply.error : null);
    };
  }
  const passThrough = new Set(["then", "toJSON", "constructor", "valueOf", "toString", "inspect", "prototype", "__proto__", "length", "name"]);
  const squash = (k) => k.toLowerCase().replace(/[^a-z0-9]/g, "");
  function distance(a, b) {
    const row = Array.from({ length: b.length + 1 }, (_, j) => j);
    for (let i = 1; i <= a.length; i++) {
      let prev = row[0];
      row[0] = i;
      for (let j = 1; j <= b.length; j++) {
        const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
        prev = row[j];
        row[j] = next;
      }
    }
    return row[b.length];
  }
  // The members of `target` closest to `key`: one spelled another way
  // (`massProperties`) first, then by edit distance.
  function near(target, key) {
    const wanted = squash(key);
    return Object.keys(target)
      .map((k) => [squash(k) === wanted ? -1 : distance(squash(k), wanted), k])
      .filter(([d]) => d <= Math.max(2, Math.floor(key.length / 3)))
      .sort((a, b) => a[0] - b[0])
      .slice(0, 3)
      .map(([, k]) => k);
  }
  function unknown(namespace, key) {
    const hints = [];
    const add = (path) => { if (hints.length < 4 && !hints.includes(path)) hints.push(path); };
    if (namespace === null) {
      for (const k of near(tree, key)) add("sdk." + k);
      // A bare action name: say which namespaces hold it.
      for (const g of Object.keys(tree)) if (own(tree[g], key)) add("sdk." + g + "." + key);
    } else {
      const members = tree[namespace];
      // The registry's own spelling (`scene_entities`) of `sdk.scene.entities`.
      const prefix = namespace + "_";
      if (key.startsWith(prefix) && own(members, key.slice(prefix.length))) add("sdk." + namespace + "." + key.slice(prefix.length));
      for (const g of Object.keys(tree)) {
        if (g !== namespace) for (const m of Object.keys(tree[g])) if (squash(m) === squash(key)) add("sdk." + g + "." + m);
      }
      for (const k of near(members, key)) add("sdk." + namespace + "." + k);
    }
    const path = namespace === null ? "sdk." + key : "sdk." + namespace + "." + key;
    const listing = namespace === null ? "the `sdk` tool lists the namespaces: sdk({})" : "the `sdk` tool lists this namespace: sdk({topic: \"" + namespace + "\"})";
    return path + " does not exist, or is not granted to this program" + (hints.length ? "; did you mean " + hints.join(" or ") + "?" : "") + " (" + listing + ")";
  }
  const guard = (target, namespace) => new Proxy(target, {
    get(t, key, receiver) {
      if (typeof key !== "string" || key in t || passThrough.has(key)) return Reflect.get(t, key, receiver);
      throw new TypeError(unknown(namespace, key));
    },
  });
  const guarded = {};
  for (const namespace of Object.keys(tree)) guarded[namespace] = guard(tree[namespace], namespace);
  Object.defineProperty(globalThis, "sdk", { value: guard(guarded, null), writable: false, enumerable: true, configurable: false });
})();
"#;

thread_local! {
    static PENDING: RefCell<HashMap<u64, (JsFunction, JsFunction)>> = RefCell::new(HashMap::new());
    static NEXT: RefCell<u64> = const { RefCell::new(0) };
    /// Where this realm's protocol messages go: stdout natively, the Web
    /// Worker's `postMessage` in the browser.
    static SINK: RefCell<Option<Box<dyn Fn(&Value)>>> = RefCell::new(None);
}

fn emit(line: &Value) {
    SINK.with(|s| {
        if let Some(sink) = s.borrow().as_ref() {
            sink(line);
        }
    });
}

fn done_error(code: &str, message: String) -> Value {
    json!({ "done": { "error": { "code": code, "message": message } } })
}

/// `__brep_host(method, body)`: send the call (its body as JSON, not text)
/// to the host and answer a pending Promise, settled with the reply's JSON
/// text when the host's reply arrives.
fn host_call(_: &JsValue, args: &[JsValue], cx: &mut Context) -> JsResult<JsValue> {
    let text = |i: usize| args.get(i).and_then(JsValue::as_string).map(|s| s.to_std_string_escaped()).unwrap_or_default();
    let method = text(0);
    let body: Value = serde_json::from_str(&text(1)).map_err(|e| JsNativeError::typ().with_message(format!("sdk.{method}: the argument is not JSON: {e}")))?;
    let (promise, resolvers) = JsPromise::new_pending(cx);
    let id = NEXT.with(|n| {
        *n.borrow_mut() += 1;
        *n.borrow()
    });
    PENDING.with(|p| p.borrow_mut().insert(id, (resolvers.resolve, resolvers.reject)));
    emit(&json!({ "call": id, "method": method, "body": body }));
    Ok(promise.into())
}

/// Boa's own runtime limits (loop iterations per frame, recursion, stack)
/// are uncatchable in JavaScript; reported as the resource limit they are.
fn fail(code: &str, e: JsError, cx: &mut Context) -> Value {
    let limit = e.as_engine().is_some();
    let message = describe(e, cx);
    done_error(if limit || message.contains("RuntimeLimitError") { "resource_limit" } else { code }, message)
}

/// A parse error made actionable: the parser's message, the source lines
/// it points at with a caret, and the fix for the mistakes that produce it
/// when a program travels inside JSON (a `\n` escape decoded to a real line
/// break inside a quoted string; a whole program escaped twice; a module
/// written where a script body is expected). `source` is the program body
/// and `first_row_shift` how far the parser's columns on its first row are
/// from the body's ([`MAIN_OPEN`] shares that row).
pub fn syntax_help(source: &str, message: &str, first_row_shift: usize) -> String {
    let mut out = message.to_string();
    let unterminated = message.to_ascii_lowercase().contains("unterminated string literal");
    // Boa names no position for an unterminated string: find the quote
    // that opens a string the line ends inside.
    let named = position(message).map(|(row, col)| (row, if row == 1 { col.saturating_sub(first_row_shift) } else { col }));
    let (row, col) = named.or_else(|| if unterminated { open_quote(source) } else { None }).unwrap_or((0, 0));
    let lines: Vec<&str> = source.lines().collect();
    if (1..=lines.len()).contains(&row) {
        out.push_str("\n");
        for n in row.saturating_sub(1).max(1)..=(row + 1).min(lines.len()) {
            let text: String = lines[n - 1].chars().take(160).collect();
            out.push_str(&format!("\n{n:>4} | {text}"));
            if n == row && col > 0 && col <= 161 {
                out.push_str(&format!("\n     | {}^", " ".repeat(col - 1)));
            }
        }
    }
    if !source.contains('\n') && source.contains("\\n") {
        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).");
    } else if unterminated {
        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).");
        if lines.iter().any(|l| l.contains("n't") || l.contains("'s ")) {
            out.push_str(" An apostrophe also ends a '...' string early: use \"...\" or `...` for text containing one.");
        }
    } else if lines.iter().any(|l| l.starts_with("export ") || l.starts_with("import ")) {
        out.push_str("\n\nhint: a program is a script body, not a module: write its statements at the top level with `await` and `return` (the returned value is the result). `sdk` is a global, nothing is imported, and `export` is not valid.");
    }
    out
}

/// Where the first '...' or "..." string still open at its line's end
/// begins (1-based row and column), skipping comments and template literals
/// (a `${...}` inside one is skipped with it; a regex literal can mislead the
/// scan, which only places a hint).
fn open_quote(source: &str) -> Option<(usize, usize)> {
    let (mut row, mut col) = (1usize, 0usize);
    let mut quote: Option<(char, usize, usize)> = None;
    let (mut template, mut line_comment, mut block_comment, mut escaped) = (false, false, false, false);
    let mut prev = '\0';
    for ch in source.chars() {
        col += 1;
        if ch == '\n' {
            if quote.is_some() && !escaped { return quote.map(|(_, r, c)| (r, c)); }
            row += 1;
            col = 0;
            line_comment = false;
            escaped = false;
            prev = ch;
            continue;
        }
        if line_comment {
        } else if block_comment {
            if prev == '*' && ch == '/' { block_comment = false; }
        } else if let Some((q, _, _)) = quote {
            if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == q { quote = None }
        } else if template {
            if escaped { escaped = false } else if ch == '\\' { escaped = true } else if ch == '`' { template = false }
        } else if prev == '/' && ch == '/' {
            line_comment = true;
        } else if prev == '/' && ch == '*' {
            block_comment = true;
        } else if ch == '\'' || ch == '"' {
            quote = Some((ch, row, col));
        } else if ch == '`' {
            template = true;
        }
        prev = if block_comment && prev == '/' && ch == '*' { '\0' } else { ch };
    }
    quote.map(|(_, r, c)| (r, c))
}

/// The first source position a parser message names (Boa's `line N, col M`).
fn position(message: &str) -> Option<(usize, usize)> {
    let digits = |s: &str| -> Option<(usize, usize)> {
        let n: String = s.chars().take_while(char::is_ascii_digit).collect();
        Some((n.parse().ok()?, n.len()))
    };
    for (at, _) in message.match_indices("line ") {
        let rest = &message[at + 5..];
        let Some((row, used)) = digits(rest) else { continue };
        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);
        return Some((row, col));
    }
    None
}

/// One execution, driven by its host's messages.
pub struct Realm {
    cx: Context,
    logs: Logs,
    sent: usize,
    main: JsPromise,
}

impl Realm {
    /// Start an execution from its start message (`{names, limits,
    /// source}`), its protocol messages going to `sink`: run the program
    /// until it waits on the host (`Some`) or ends (`None`; its `done` sent).
    pub fn begin(start: &str, sink: Box<dyn Fn(&Value)>) -> Option<Realm> {
        SINK.with(|s| *s.borrow_mut() = Some(sink));
        let start: Value = match serde_json::from_str(start) {
            Ok(v) => v,
            Err(e) => {
                emit(&done_error("internal_error", format!("bad start message: {e}")));
                return None;
            }
        };
        let source = strip_sdk_import(start.get("source").and_then(Value::as_str).unwrap_or_default());
        // The names become functions; the host is the boundary that decides
        // what a call by one of them may do.
        let names: Vec<&str> = start.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect();
        let names = Value::from(names).to_string();
        let mut cx = match Context::builder().module_loader(Rc::new(NoImports)).build() {
            Ok(cx) => cx,
            Err(e) => {
                emit(&done_error("internal_error", e.to_string()));
                return None;
            }
        };
        cx.runtime_limits_mut().set_loop_iteration_limit(crate::LOOP_ITERATION_LIMIT);
        cx.runtime_limits_mut().set_recursion_limit(crate::RECURSION_LIMIT);
        let logs: Logs = Rc::new(RefCell::new(Vec::new()));
        let setup = (|| -> JsResult<()> {
            install_console(&mut cx, &logs)?;
            cx.register_global_property(js_string!("__brep_names"), js_string!(names), boa_engine::property::Attribute::all())?;
            cx.register_global_builtin_callable(js_string!("__brep_host"), 2, NativeFunction::from_fn_ptr(host_call))?;
            cx.eval(Source::from_bytes(BOOTSTRAP).with_path(std::path::Path::new("sdk")))?;
            Ok(())
        })();
        if let Err(e) = setup {
            let line = done_error("internal_error", describe(e, &mut cx));
            return Self::end(&logs, &mut 0, line);
        }
        let mut sent = 0;
        match Self::start_main(&source, &mut cx) {
            Ok(main) => {
                let mut realm = Realm { cx, logs, sent, main };
                if realm.progress() {
                    None
                } else {
                    Some(realm)
                }
            }
            Err(line) => Self::end(&logs, &mut sent, line),
        }
    }

    /// Wrap the program body as a module, evaluate it and call its `main`:
    /// its Promise, or the `done` line when it cannot start.
    fn start_main(source: &str, cx: &mut Context) -> Result<JsPromise, Value> {
        let wrapped = module_source(source);
        let module = Module::parse(Source::from_bytes(&wrapped).with_path(std::path::Path::new("main.js")), None, cx).map_err(|e| {
            let mut line = fail("compile_failed", e, cx);
            if let Some(message) = line["done"]["error"]["message"].as_str() {
                line["done"]["error"]["message"] = Value::String(syntax_help(source, message, MAIN_OPEN.len()));
            }
            line
        })?;
        let evaluated = module.load_link_evaluate(cx);
        cx.run_jobs().map_err(|e| fail("job_failed", e, cx))?;
        match evaluated.state() {
            PromiseState::Fulfilled(_) => {}
            PromiseState::Rejected(v) => {
                // The wrapper only declares `main`: this is the engine's refusal.
                let message = describe(JsError::from_opaque(v), cx);
                let code = if message.contains("SyntaxError") { "compile_failed" } else { "script_failed" };
                return Err(done_error(code, message));
            }
            PromiseState::Pending => return Err(done_error("internal_error", "the program's module did not evaluate".into())),
        }
        let main = module.namespace(cx).get(js_string!("default"), cx).map_err(|e| fail("script_failed", e, cx))?;
        // A body that closes the wrapper early (an unbalanced `}`) can leave
        // something else here.
        let Some(main) = main.as_callable() else {
            return Err(done_error("compile_failed", "the program is not a script body (check for an unbalanced `}`)".into()));
        };
        let returned = main.call(&JsValue::undefined(), &[], cx).map_err(|e| fail("script_failed", e, cx))?;
        returned
            .as_object()
            .and_then(|o| JsPromise::from_object(o.clone()).ok())
            .ok_or_else(|| done_error("invalid_arguments", "main() must be async (return a Promise)".into()))
    }

    /// Deliver one host message (`{call, ok, value}` or `{call, ok: false,
    /// error}`) and run on: whether the execution has ended (its `done`
    /// sent). The `sdk` function that made the call resolves with the value
    /// or throws the error.
    pub fn answer(&mut self, message: &str) -> bool {
        let Ok(mut msg) = serde_json::from_str::<Value>(message) else { return false };
        let Some(id) = msg.get("call").and_then(Value::as_u64) else { return false };
        if !msg.get("ok").is_some_and(Value::is_boolean) { return false }
        if let Some(reply) = msg.as_object_mut() {
            reply.remove("call");
        }
        let body = msg.to_string();
        if let Some((resolve, _)) = PENDING.with(|p| p.borrow_mut().remove(&id)) {
            if let Err(e) = resolve.call(&JsValue::undefined(), &[js_string!(body).into()], &mut self.cx) {
                let line = fail("job_failed", e, &mut self.cx);
                Self::end(&self.logs, &mut self.sent, line);
                return true;
            }
        }
        self.progress()
    }

    /// The host closed the bridge with the execution still waiting.
    pub fn abandon(&mut self) {
        Self::end(&self.logs, &mut self.sent, done_error("internal_error", "the host closed the bridge".into()));
    }

    /// Run every job, then end if `main` settled or nothing can progress:
    /// whether it ended.
    fn progress(&mut self) -> bool {
        if let Err(e) = self.cx.run_jobs() {
            let line = fail("job_failed", e, &mut self.cx);
            Self::end(&self.logs, &mut self.sent, line);
            return true;
        }
        flush_logs(&self.logs, &mut self.sent);
        let line = match self.main.state() {
            PromiseState::Fulfilled(v) => match v.to_json(&mut self.cx) {
                Ok(json) => json!({ "done": { "ok": json.unwrap_or(Value::Null) } }),
                Err(e) => done_error("invalid_arguments", format!("the program's result is not JSON: {}", describe(e, &mut self.cx))),
            },
            PromiseState::Rejected(v) => {
                let message = describe(JsError::from_opaque(v), &mut self.cx);
                done_error(if message.contains("RuntimeLimitError") { "resource_limit" } else { "script_failed" }, message)
            }
            PromiseState::Pending if PENDING.with(|p| p.borrow().is_empty()) => {
                done_error("invalid_arguments", "the program is pending without progress: no host call is outstanding and no job can run".into())
            }
            // Park on the host: nothing can run until a reply arrives.
            PromiseState::Pending => return false,
        };
        Self::end(&self.logs, &mut self.sent, line);
        true
    }

    /// Send the remaining logs and the `done` line; drop unsettled host calls
    /// (they hold this realm's functions).
    fn end(logs: &Logs, sent: &mut usize, line: Value) -> Option<Realm> {
        flush_logs(logs, sent);
        emit(&line);
        PENDING.with(|p| p.borrow_mut().clear());
        None
    }
}

fn flush_logs(logs: &Logs, sent: &mut usize) {
    let lines = logs.borrow();
    for line in &lines[*sent..] {
        emit(&json!({ "log": line }));
    }
    *sent = lines.len();
}

/// Run one execution reading stdin and writing stdout; the process exits
/// after the `done` line.
#[cfg(not(target_arch = "wasm32"))]
pub fn main() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();
    let Some(Ok(first)) = lines.next() else { return };
    let sink = Box::new(|line: &Value| {
        let mut out = std::io::stdout().lock();
        let _ = writeln!(out, "{line}");
        let _ = out.flush();
    });
    let Some(mut realm) = Realm::begin(&first, sink) else { return };
    loop {
        let Some(Ok(line)) = lines.next() else {
            realm.abandon();
            return;
        };
        if realm.answer(&line) {
            return;
        }
    }
}