ferridriver-script 0.4.0

Sandboxed QuickJS scripting engine for ferridriver. Runs JS scripts against Page/Browser/Context with bound args, per-call isolation, scoped fs, and structured errors.
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
//! `ScriptEngine` + `Session`: a sandboxed `QuickJS` runtime/context.
//!
//! [`ScriptEngine::run`] is the one-shot path (fresh VM, library/test
//! convenience). [`Session`] is the persistent path: one `QuickJS`
//! runtime + context reused across many [`Session::execute`] calls so
//! user `globalThis` state survives between executions REPL-style while
//! framework bindings refresh each call. The production MCP server keeps
//! a set of [`Session`]s with a retention policy in
//! [`crate::session_table::SessionTable`].

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use rquickjs::function::{Async, Func};
use rquickjs::{AsyncContext, AsyncRuntime, CatchResultExt, Ctx, Module, Object, Value, async_with};

use crate::console::{ConsoleCapture, strip_ansi};
use crate::error::{ScriptError, ScriptErrorKind};
use crate::fs::PathSandbox;
use crate::result::{ConsoleLevel, ScriptResult};
use crate::vars::VarsStore;

/// Default console-capture limits.
pub const DEFAULT_MAX_CONSOLE_ENTRIES: usize = 1_000;
pub const DEFAULT_MAX_CONSOLE_BYTES: usize = 1_048_576;
pub const DEFAULT_MAX_CONSOLE_ENTRY_BYTES: usize = 8_192;

/// Default per-script wall-clock timeout (5 minutes).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(300);

/// Default per-script memory quota (256 MiB).
pub const DEFAULT_MEMORY_LIMIT: usize = 256 * 1024 * 1024;

/// Default per-script JS stack size (1 MiB).
pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;

/// Default GC trigger threshold (64 MiB). QuickJS is reference-counted;
/// the cycle GC otherwise fires adaptively at ~1.5x live size, so an
/// object-churny automation script (big `evaluate` results, repeated
/// `ariaSnapshot`/snapshot trees, locator chains) pays recurring
/// mark-sweep stalls mid-run. Raising the floor lets a typical
/// short-lived script finish with few/zero cycle-GC passes — the same
/// lever Amazon LLRT exposes (`LLRT_GC_THRESHOLD_MB`, 20 MiB default).
/// `default_memory_limit` (256 MiB) remains the hard backstop, and
/// acyclic garbage is still freed immediately by refcounting, so this
/// only defers *cycle* collection, not normal frees.
pub const DEFAULT_GC_THRESHOLD: usize = 64 * 1024 * 1024;

/// Default cap on concurrently-retained persistent session VMs. When a
/// new session would exceed this, the least-recently-used idle VM is
/// evicted (its `globalThis` state is discarded; a later call rebuilds).
pub const DEFAULT_MAX_SESSION_VMS: usize = 64;

/// Default idle TTL: a session VM untouched this long is reaped on the
/// next `SessionTable::acquire`, independent of cap pressure, so a
/// long-running server does not pin dead sessions' memory indefinitely.
pub const DEFAULT_SESSION_IDLE_TTL: Duration = Duration::from_secs(30 * 60);

/// Configuration for the script engine.
#[derive(Debug, Clone)]
pub struct ScriptEngineConfig {
  pub default_timeout: Duration,
  pub default_memory_limit: usize,
  pub default_stack_size: usize,
  /// Cycle-GC trigger threshold in bytes. See [`DEFAULT_GC_THRESHOLD`].
  pub default_gc_threshold: usize,
  pub max_console_entries: usize,
  pub max_console_bytes: usize,
  pub max_console_entry_bytes: usize,
  /// Upper bound on persistent session VMs kept warm at once.
  pub max_session_vms: usize,
  /// Idle TTL for a session VM. `None` disables time-based reaping (only
  /// the `max_session_vms` LRU cap applies).
  pub session_idle_ttl: Option<Duration>,
}

impl Default for ScriptEngineConfig {
  fn default() -> Self {
    Self {
      default_timeout: DEFAULT_TIMEOUT,
      default_memory_limit: DEFAULT_MEMORY_LIMIT,
      default_stack_size: DEFAULT_STACK_SIZE,
      default_gc_threshold: DEFAULT_GC_THRESHOLD,
      max_console_entries: DEFAULT_MAX_CONSOLE_ENTRIES,
      max_console_bytes: DEFAULT_MAX_CONSOLE_BYTES,
      max_console_entry_bytes: DEFAULT_MAX_CONSOLE_ENTRY_BYTES,
      max_session_vms: DEFAULT_MAX_SESSION_VMS,
      session_idle_ttl: Some(DEFAULT_SESSION_IDLE_TTL),
    }
  }
}

/// Per-call overrides for a single `run` invocation.
#[derive(Debug, Clone, Default)]
pub struct RunOptions {
  pub timeout: Option<Duration>,
  pub memory_limit: Option<usize>,
  pub stack_size: Option<usize>,
  pub gc_threshold: Option<usize>,
}

/// Which host is running the extension/registry. Exposed to JS as the
/// native global `ferridriver.host` ("mcp" | "bdd" | "script") so one
/// extension file can branch its contributions — e.g. only `defineTool`
/// under MCP, only `Given/When/Then` under the test runner — without any
/// runtime cost (a single string set once per session).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExtensionHost {
  /// MCP server (`ferridriver mcp`) — consumes `defineTool` tools.
  Mcp,
  /// BDD test runner (`ferridriver bdd`) — consumes step/hook defs.
  Bdd,
  /// Ad-hoc script (`ferridriver run` / `run_script`).
  #[default]
  Script,
}

impl ExtensionHost {
  #[must_use]
  pub fn as_str(self) -> &'static str {
    match self {
      Self::Mcp => "mcp",
      Self::Bdd => "bdd",
      Self::Script => "script",
    }
  }
}

/// Per-call execution context holding session-level state the script reaches
/// via globals (`vars`, `fs`, `artifacts`, and the optional browser bindings
/// `page` / `context` / `request`). A `None` entry skips installation of
/// the matching global so pure-compute scripts don't need the extra
/// infrastructure.
#[derive(Clone)]
pub struct RunContext {
  pub vars: Arc<dyn VarsStore>,
  pub sandbox: Arc<PathSandbox>,
  /// Optional dedicated output directory, exposed to scripts as `artifacts`.
  /// Typically `.ferridriver/artifacts/` alongside `script_root`.
  pub artifacts: Option<Arc<PathSandbox>>,
  pub page: Option<Arc<ferridriver::Page>>,
  pub browser_context: Option<Arc<ferridriver::context::ContextRef>>,
  pub request: Option<Arc<ferridriver::http_client::HttpClient>>,
  /// Optional root `Browser` handle exposed as the `browser` global.
  /// Scripts use it for
  /// `browser.newContext(BrowserContextOptions)` — the natural
  /// Playwright entry point that §4.1's options bag attaches to.
  pub browser: Option<Arc<ferridriver::Browser>>,
  /// Plugin bindings to install on the `plugins` global. Empty means no
  /// `plugins` global is exposed beyond the singleton commands runner.
  pub plugins: Vec<crate::bindings::PluginBinding>,
  /// When true, ES module imports use normal filesystem resolution
  /// instead of the `PathSandbox`-rooted loader. Intended for trusted
  /// first-party code (BDD step files run from the user's own CLI), so
  /// step files can `import './helpers.js'` from anywhere on disk. The
  /// MCP / `run_script` path leaves this `false` and stays sandboxed.
  pub trusted_modules: bool,
  /// Which host is driving this session — surfaced to JS as
  /// `ferridriver.host`. Defaults to [`ExtensionHost::Script`].
  pub host: ExtensionHost,
  /// Opt-in sandbox relaxations resolved from config (the env
  /// allow-list). Default = fully locked down.
  pub caps: ScriptCaps,
}

/// Resolved, ready-to-install sandbox relaxations. Built by the host
/// (MCP/CLI/BDD) from `ferridriver_config::ScriptingConfig`; the engine
/// only consumes it. Default is the locked-down posture: no env.
#[derive(Debug, Clone, Default)]
pub struct ScriptCaps {
  /// `process.env` contents — already filtered to the operator's
  /// allow-list intersected with the real environment. Empty ⇒
  /// `process.env` is an empty object.
  pub env: std::collections::BTreeMap<String, String>,
}

impl ScriptCaps {
  /// Resolve from an operator allow-list: only the named variables, and
  /// only those actually present in the process environment, are
  /// captured. A name not in the environment is silently absent (same
  /// as Node) — it is never invented.
  #[must_use]
  pub fn resolve(allow_env: &[String]) -> Self {
    let env = allow_env
      .iter()
      .filter_map(|k| std::env::var(k).ok().map(|v| (k.clone(), v)))
      .collect();
    Self { env }
  }
}

/// The session's owning [`AsyncContext`], stashed as rquickjs userdata
/// at [`Session::create`] so bindings that mint a `Page` from script
/// (`browser.newContext().newPage()`, `locator.page()`, `frame.page()`)
/// can thread it into `PageJs` — without it, `page.route` /
/// `page.exposeFunction` cross-task dispatch has no context to re-enter.
pub(crate) struct SessionAsyncCtx(pub(crate) AsyncContext);

// SAFETY: holds only an owned `AsyncContext` (`'static`; no borrowed
// JS values), so re-stating the unused `'js` lifetime is sound.
#[allow(unsafe_code)]
unsafe impl rquickjs::JsLifetime<'_> for SessionAsyncCtx {
  type Changed<'to> = SessionAsyncCtx;
}

/// The session's durable persistent-process registry, stashed as
/// userdata so `plugins.<name>` dispatch can hand a tool's `commands`
/// binding the registry without threading it through `RunContext`.
/// Re-installed (same `Arc`) on every VM (re)build by
/// [`crate::session_table::BrowserSession::run`], so a persistent
/// process outlives a VM rebuild but dies with the session record.
pub(crate) struct SessionProcsUd(pub(crate) std::sync::Arc<crate::session_procs::SessionProcs>);

// SAFETY: holds only an owned `Arc` (`'static`; no borrowed JS values).
#[allow(unsafe_code)]
unsafe impl rquickjs::JsLifetime<'_> for SessionProcsUd {
  type Changed<'to> = SessionProcsUd;
}

/// Sandboxed `QuickJS` scripting engine.
pub struct ScriptEngine {
  config: ScriptEngineConfig,
}

impl ScriptEngine {
  #[must_use]
  pub fn new(config: ScriptEngineConfig) -> Self {
    Self { config }
  }

  #[must_use]
  pub fn config(&self) -> &ScriptEngineConfig {
    &self.config
  }

  /// Run a script once in a throwaway VM with bound args. A one-shot
  /// convenience for library consumers and tests that need no
  /// continuity; the persistent MCP path uses
  /// [`crate::session_table::SessionTable`] instead.
  ///
  /// `args` is bound as the `args` global (positional) and never
  /// interpolated into `source` — preventing prompt injection. No state
  /// survives the call.
  pub async fn run(
    &self,
    source: &str,
    args: &[serde_json::Value],
    options: RunOptions,
    context: RunContext,
  ) -> ScriptResult {
    match Session::create(self.config.clone(), &context).await {
      Ok(session) => session.execute(source, args, options, &context).await.result,
      Err(e) => ScriptResult::err(e, 0, Vec::new()),
    }
  }
}

/// Outcome of one [`Session::execute`]: the script result plus whether
/// the VM was left in a state the caller must discard before the next
/// execution. Poisoning means the interpreter was force-halted mid-run
/// (timeout interrupt) or hit an allocation fault — a plain JS `throw`
/// is NOT poisoning and leaves session state intact.
#[derive(Debug)]
pub struct SessionRun {
  pub result: ScriptResult,
  pub poisoned: bool,
}

/// A persistent `QuickJS` runtime + context reused across many script
/// executions for one logical session.
///
/// User state on `globalThis` (and `var` / `function` declarations,
/// which hoist to the global object) survives across [`execute`] calls
/// REPL-style. Top-level `let` / `const` inside a script are scoped to
/// the async wrapper of that single call and do NOT persist — assign to
/// `globalThis` for continuity. Framework bindings (`page`, `context`,
/// `request`, `browser`, `vars`, `fs`, `artifacts`, `console`, `args`)
/// are reinstalled every call so they always reflect current session
/// state. Plugin bindings are installed once at creation.
///
/// [`execute`]: Session::execute
pub struct Session {
  runtime: AsyncRuntime,
  ctx: AsyncContext,
  config: ScriptEngineConfig,
  default_request: Arc<ferridriver::http_client::HttpClient>,
  /// Last resource limits pushed to `runtime`. `set_memory_limit` /
  /// `set_max_stack_size` / `set_gc_threshold` each take the runtime's
  /// async lock; re-pushing identical values every `execute` is pure
  /// overhead on a warm persistent session that runs many small
  /// scripts (the MCP path). Skip the setter when the value is
  /// unchanged.
  applied: AppliedLimits,
}

/// Currently-applied runtime limits, so `execute` can skip redundant
/// `AsyncRuntime` setter calls.
struct AppliedLimits {
  memory: AtomicUsize,
  stack: AtomicUsize,
  gc: AtomicUsize,
}

impl Session {
  /// Build the persistent VM: runtime, resource limits, sandbox-rooted
  /// module loader, context, and one-time plugin install. The module
  /// loader is bound to `context.sandbox` for the VM's lifetime, so a
  /// session must always be driven with the same `script_root`.
  pub async fn create(config: ScriptEngineConfig, context: &RunContext) -> Result<Self, ScriptError> {
    let runtime = AsyncRuntime::new().map_err(|e| ScriptError::internal(format!("rquickjs runtime init: {e}")))?;

    runtime.set_memory_limit(config.default_memory_limit).await;
    runtime.set_max_stack_size(config.default_stack_size).await;
    // Defer cycle-GC so short automation scripts don't mark-sweep
    // mid-run (LLRT-style). Refcounting still frees acyclic garbage
    // immediately; memory_limit is the hard cap.
    runtime.set_gc_threshold(config.default_gc_threshold).await;

    // Module loader rooted at the sandbox — lets scripts `import './x.js'`.
    // Resolver and loader both check containment; rquickjs's built-in
    // ScriptLoader is replaced with our sandboxed pair so a rogue import
    // can't escape `script_root`. Bound once: the sandbox is stable for
    // the session's lifetime.
    if context.trusted_modules {
      // Trusted first-party code (BDD step files): normal filesystem
      // ESM resolution so shared `import './helpers.js'` works from
      // anywhere, not only under the sandbox root.
      let mut resolver = rquickjs::loader::FileResolver::default();
      resolver.add_path(".");
      resolver.add_path(context.sandbox.root().to_string_lossy().as_ref());
      runtime
        .set_loader(resolver, rquickjs::loader::ScriptLoader::default())
        .await;
    } else {
      runtime
        .set_loader(
          crate::modules::SandboxResolver::new(context.sandbox.clone()),
          crate::modules::SandboxLoader::new(context.sandbox.clone()),
        )
        .await;
    }

    let ctx = AsyncContext::full(&runtime)
      .await
      .map_err(|e| ScriptError::internal(format!("rquickjs context init: {e}")))?;

    // Plugin bindings are server-global and immutable post-load, so they
    // install exactly once. The per-tool wrappers dereference
    // `globalThis.page` / `context` / `request` lazily at invocation,
    // by which point `execute` has refreshed those bindings.
    let plugins = context.plugins.clone();
    // Cloned out of `context` (a `&RunContext`) so the async_with future
    // owns them rather than borrowing across the await.
    let vars = context.vars.clone();
    let sandbox = context.sandbox.clone();
    let sandbox_root = context.sandbox.root().to_string_lossy().into_owned();
    let artifacts = context.artifacts.clone();
    let host = context.host;
    let caps = context.caps.clone();
    let ud_ctx = ctx.clone();
    let install: Result<(), ScriptError> = async_with!(ctx => |ctx| {
      // Stash the session's AsyncContext so script-minted pages can
      // thread it into PageJs (route/exposeFunction cross-task
      // dispatch). A failure here only degrades those to "no async
      // ctx" (same as before this fix) — never a correctness break.
      let _ = ctx.store_userdata(SessionAsyncCtx(ud_ctx));
      // The active-tool net allow-list cell `fetch` reads (resting state
      // = unrestricted). Stored once per VM so it survives rebuilds and
      // is present even when no plugin runs; `plugins::dispatch_tool`
      // swaps it around each net-restricted handler's poll.
      let _ = ctx.store_userdata(crate::bindings::fetch::NetPolicyUd(
        crate::bindings::fetch::NetPolicy::default(),
      ));
      // Native route-handler registry (context userdata): session-once
      // so `page.route` works on ANY page (script-launched
      // `context.newPage()`, not just the MCP-prebound one whose
      // `install_page` also creates it).
      crate::bindings::page::ensure_page_callbacks(&ctx);
      install_runtime_shims(&ctx).map_err(|e| ScriptError::internal(format!("failed to install runtime shims: {e}")))?;

      // Session-stable bindings: install ONCE, not per `execute`. Class
      // prototypes are idempotent; `vars`/`fs`/`artifacts`/`browser_type`
      // back onto Arcs that never change for a session's lifetime (the
      // `SessionTable` slot owns the durable `vars`; the sandbox is
      // fixed per session). Only per-call-variant handles
      // (page/context/request/browser/console/args) refresh in `execute`.
      crate::bindings::define_classes(&ctx)
        .map_err(|e| ScriptError::internal(format!("failed to define classes: {e}")))?;
      install_vars(&ctx, vars).map_err(|e| ScriptError::internal(format!("failed to install vars: {e}")))?;
      install_fs(&ctx, sandbox).map_err(|e| ScriptError::internal(format!("failed to install fs: {e}")))?;
      crate::bindings::process::install(&ctx, &caps, &sandbox_root)
        .map_err(|e| ScriptError::internal(format!("failed to install process: {e}")))?;
      if let Some(artifacts) = artifacts {
        crate::bindings::install_artifacts(&ctx, artifacts)
          .map_err(|e| ScriptError::internal(format!("failed to install artifacts: {e}")))?;
      }
      crate::bindings::install_browser_type(&ctx)
        .map_err(|e| ScriptError::internal(format!("failed to install browser_type: {e}")))?;

      // expect() global (Jest value matchers, Playwright web-first
      // matchers, asymmetric matchers, expect.poll). Session-stable —
      // class prototypes + factory function are installed once and
      // survive across `execute` calls.
      crate::bindings::expect::install_expect(&ctx)
        .map_err(|e| ScriptError::internal(format!("failed to install expect: {e}")))?;

      // The unified extension registry (userdata) + native contribution
      // points (`Given`/`When`/`Then`/`defineTool`/...). Must precede
      // `install_plugins`: evaluating an extension's bytecode registers
      // its tools/steps through this native surface (`defineTool` /
      // `Given`...), so the registry must already exist.
      crate::bindings::install_bdd(&ctx)
        .map_err(|e| ScriptError::internal(format!("failed to install extension registry: {e}")))?;

      // `ferridriver.host` — the native context flag an extension reads
      // to branch between MCP and the test runner. One string, set once.
      let fd = Object::new(ctx.clone()).map_err(|e| ScriptError::internal(format!("ferridriver global: {e}")))?;
      fd.set("host", host.as_str())
        .map_err(|e| ScriptError::internal(format!("ferridriver.host: {e}")))?;
      ctx
        .globals()
        .set("ferridriver", fd)
        .map_err(|e| ScriptError::internal(format!("install ferridriver global: {e}")))?;

      crate::bindings::install_plugins(&ctx, &plugins)
        .map_err(|e| ScriptError::internal(format!("failed to install plugins: {e}")))
    })
    .await;
    install?;

    let applied = AppliedLimits {
      memory: AtomicUsize::new(config.default_memory_limit),
      stack: AtomicUsize::new(config.default_stack_size),
      gc: AtomicUsize::new(config.default_gc_threshold),
    };
    Ok(Self {
      runtime,
      ctx,
      config,
      default_request: Arc::new(ferridriver::http_client::HttpClient::new(
        ferridriver::http_client::HttpClientOptions::default(),
      )),
      applied,
    })
  }

  /// The session's owning [`AsyncContext`]. The BDD core clones this to
  /// drive registered JS step functions back over the async bridge
  /// (same mechanism as `page.route` cross-task dispatch).
  #[must_use]
  pub fn async_context(&self) -> AsyncContext {
    self.ctx.clone()
  }

  /// Stash the session's persistent-process registry into VM userdata
  /// so plugin `commands` start/status/stop reach it. Idempotent; the
  /// same `Arc` is re-installed on each VM rebuild (the registry is
  /// durable session state, the VM is not).
  pub async fn install_session_procs(&self, procs: std::sync::Arc<crate::session_procs::SessionProcs>) {
    async_with!(self.ctx => |ctx| {
      let _ = ctx.store_userdata(SessionProcsUd(procs));
    })
    .await;
  }

  /// Push resource limits to the runtime, skipping any setter whose
  /// value is unchanged since the last call (avoids the runtime's async
  /// lock on the warm-session hot path).
  async fn apply_limits(&self, memory: usize, stack: usize, gc: usize) {
    if self.applied.memory.swap(memory, Ordering::Relaxed) != memory {
      self.runtime.set_memory_limit(memory).await;
    }
    if self.applied.stack.swap(stack, Ordering::Relaxed) != stack {
      self.runtime.set_max_stack_size(stack).await;
    }
    if self.applied.gc.swap(gc, Ordering::Relaxed) != gc {
      self.runtime.set_gc_threshold(gc).await;
    }
  }

  /// Fresh console capture sized by the session config.
  fn new_console(&self) -> Arc<ConsoleCapture> {
    Arc::new(ConsoleCapture::new(
      self.config.max_console_entries,
      self.config.max_console_bytes,
      self.config.max_console_entry_bytes,
    ))
  }

  /// Arm the interrupt handler for this call's deadline. The handler fires
  /// regularly during interpretation; once the deadline passes it halts
  /// the interpreter. Returns the flag set when a force-halt occurred.
  async fn arm_timeout(&self, deadline: Instant) -> Arc<AtomicBool> {
    let timed_out = Arc::new(AtomicBool::new(false));
    let flag = timed_out.clone();
    self
      .runtime
      .set_interrupt_handler(Some(Box::new(move || {
        if Instant::now() >= deadline {
          flag.store(true, Ordering::Relaxed);
          true
        } else {
          false
        }
      })))
      .await;
    timed_out
  }

  /// Per-call framework globals (`console`, `page`, `context`, ...).
  fn globals_install(&self, context: &RunContext, console: &Arc<ConsoleCapture>) -> GlobalsInstall {
    GlobalsInstall {
      console: console.clone(),
      page: context.page.clone(),
      browser_context: context.browser_context.clone(),
      request: context.request.clone(),
      default_request: self.default_request.clone(),
      browser: context.browser.clone(),
      async_ctx: self.ctx.clone(),
    }
  }

  /// Build the `SessionRun` from an eval result, applying the poison rule:
  /// a timeout force-halt or an OOM leaves the heap untrustworthy and must
  /// rebuild the VM; a plain throw / recoverable stack overflow does not.
  fn finish(
    &self,
    eval_result: Result<serde_json::Value, ScriptError>,
    started: Instant,
    console: &Arc<ConsoleCapture>,
    timed_out: &Arc<AtomicBool>,
    timeout: Duration,
  ) -> SessionRun {
    let duration = elapsed_ms(started);
    let drained = console.drain();
    match eval_result {
      Ok(value) => SessionRun {
        result: ScriptResult::ok(value, duration, drained),
        poisoned: false,
      },
      Err(mut err) => {
        let timed_out = timed_out.load(Ordering::Relaxed);
        let oom = is_oom(&err);
        let poisoned = timed_out || oom;
        if timed_out {
          err = ScriptError::timeout(duration, timeout.as_millis() as u64);
        }
        SessionRun {
          result: ScriptResult::err(err, duration, drained),
          poisoned,
        }
      },
    }
  }

  /// Apply this call's resource overrides (falling back to session
  /// defaults), and return the resolved wall-clock timeout.
  async fn apply_call_limits(&self, options: &RunOptions) -> Duration {
    self
      .apply_limits(
        options.memory_limit.unwrap_or(self.config.default_memory_limit),
        options.stack_size.unwrap_or(self.config.default_stack_size),
        options.gc_threshold.unwrap_or(self.config.default_gc_threshold),
      )
      .await;
    options.timeout.unwrap_or(self.config.default_timeout)
  }

  /// Execute one script against the persistent VM. Framework globals are
  /// refreshed from `context` first; user `globalThis` state from prior
  /// executions is preserved.
  ///
  /// The source is wrapped in an async IIFE, so top-level `return <value>`
  /// surfaces as the run result. For ES-module sources (TypeScript,
  /// `import`/`export`) bundle them first and use [`Self::execute_module`].
  pub async fn execute(
    &self,
    source: &str,
    args: &[serde_json::Value],
    options: RunOptions,
    context: &RunContext,
  ) -> SessionRun {
    let started = Instant::now();
    let console = self.new_console();
    let timeout = self.apply_call_limits(&options).await;
    let timed_out = self.arm_timeout(started + timeout).await;
    let install = self.globals_install(context, &console);
    let source_owned = source.to_string();

    let eval_result: Result<serde_json::Value, ScriptError> = async_with!(self.ctx => |ctx| {
      if let Err(e) = install_call_globals(&ctx, args, install) {
        return Err(ScriptError::internal(format!("failed to install globals: {e}")));
      }

      let wrapped = wrap_source(&source_owned);

      let promise: rquickjs::Promise<'_> = match ctx.eval(wrapped.as_bytes()) {
        Ok(v) => v,
        Err(e) => return Err(caught_to_script_error(rquickjs::CaughtError::from_error(&ctx, e), &source_owned)),
      };

      let result: Value<'_> = match promise.into_future::<Value<'_>>().await {
        Ok(v) => v,
        Err(e) => return Err(caught_to_script_error(rquickjs::CaughtError::from_error(&ctx, e), &source_owned)),
      };

      Ok(value_to_json(&ctx, result).unwrap_or(serde_json::Value::Null))
    })
    .await;

    self.finish(eval_result, started, &console, &timed_out, timeout)
  }

  /// Execute a precompiled bundled ES module against the persistent VM —
  /// the TypeScript / `import` / `export` path. Framework globals
  /// (`args`, `page`, `console`, ...) are installed exactly as for
  /// [`Self::execute`]; top-level `await` is native to the module.
  ///
  /// A module cannot use top-level `return`, so the run's result value is
  /// the module's `default` export (`null` when it has none). Error
  /// locations are remapped through the bundle's source map back to the
  /// original `.ts`/`.js` position.
  pub async fn execute_module(
    &self,
    bundle: &crate::bundle::CompiledBundle,
    args: &[serde_json::Value],
    options: RunOptions,
    context: &RunContext,
  ) -> SessionRun {
    let started = Instant::now();
    let console = self.new_console();
    let timeout = self.apply_call_limits(&options).await;
    let timed_out = self.arm_timeout(started + timeout).await;
    let install = self.globals_install(context, &console);
    let bytecode = Arc::clone(&bundle.bytecode);
    let label = bundle.module_name.clone();

    let eval_result: Result<serde_json::Value, ScriptError> = async_with!(self.ctx => |ctx| {
      if let Err(e) = install_call_globals(&ctx, args, install) {
        return Err(ScriptError::internal(format!("failed to install globals: {e}")));
      }

      // SAFETY: `bytecode` was produced by `Module::write` in THIS process
      // with native endianness and is never persisted across an
      // interpreter boundary in a form this load trusts — same contract
      // `eval_bundle` / `install_plugins` rely on. (The disk cache only
      // ever loads bytecode written by an ABI-identical toolchain.)
      #[allow(unsafe_code)]
      let module = match (unsafe { Module::load(ctx.clone(), &bytecode) }).catch(&ctx) {
        Ok(m) => m,
        Err(e) => return Err(caught_to_script_error(e, &label)),
      };
      let (evaluated, promise) = match module.eval().catch(&ctx) {
        Ok(v) => v,
        Err(e) => return Err(caught_to_script_error(e, &label)),
      };
      if let Err(e) = promise.into_future::<()>().await.catch(&ctx) {
        return Err(caught_to_script_error(e, &label));
      }

      // Result = the module's `default` export, if any.
      let default = evaluated
        .namespace()
        .and_then(|ns| ns.get::<_, Value<'_>>("default"))
        .unwrap_or_else(|_| Value::new_undefined(ctx.clone()));
      Ok(value_to_json(&ctx, default).unwrap_or(serde_json::Value::Null))
    })
    .await;

    // Remap the failure location back to the original source.
    let eval_result = eval_result.map_err(|mut e| {
      if let Some(line) = e.line {
        if let Some((src, sl, sc)) = bundle.remap(line, e.column.unwrap_or(1)) {
          e.message = format!("{} (at {src}:{sl}:{sc})", e.message);
        }
      }
      e
    });

    self.finish(eval_result, started, &console, &timed_out, timeout)
  }
}

/// Wrap user source in an async IIFE so `await` works at the top level and
/// the expression evaluates to a `Promise<value>` the engine can await.
fn wrap_source(source: &str) -> String {
  format!("(async () => {{\n{source}\n}})()")
}

/// QuickJS raises an `out of memory` error when an allocation fails
/// after the runtime memory limit is hit. The allocation site is
/// arbitrary, so the heap cannot be trusted afterwards — treat it as
/// poisoning (rebuild the VM), exactly like a timeout force-halt.
fn is_oom(err: &ScriptError) -> bool {
  err.message.to_ascii_lowercase().contains("out of memory")
}

/// Everything `install_globals` needs beyond `ctx` + args JSON. Bundled into
/// a struct so the helper stays under the clippy arity limit as the binding
/// surface grows.
struct GlobalsInstall {
  console: Arc<ConsoleCapture>,
  page: Option<Arc<ferridriver::Page>>,
  browser_context: Option<Arc<ferridriver::context::ContextRef>>,
  request: Option<Arc<ferridriver::http_client::HttpClient>>,
  default_request: Arc<ferridriver::http_client::HttpClient>,
  browser: Option<Arc<ferridriver::Browser>>,
  /// `AsyncContext` driving the script — passed to `install_page` so
  /// `page.route` callbacks can dispatch back into JS from a separate
  /// tokio task. Always present (cloned from the session's context).
  async_ctx: AsyncContext,
}

/// Reinstall ONLY the per-call-variant globals: `args`, `console`, and
/// whichever of `page` / `context` / `request` / `browser` the run
/// context carries (their backend handles are re-resolved every call).
/// `vars` / `fs` / `artifacts` / `browser_type` / class prototypes are
/// session-stable and installed once at [`Session::create`]; plugin
/// bindings likewise.
fn install_call_globals(ctx: &Ctx<'_>, args: &[serde_json::Value], inst: GlobalsInstall) -> rquickjs::Result<()> {
  let globals = ctx.globals();

  // args: build the JS array directly from the serde values — no JSON
  // string, no JS-side `JSON.parse`, and immune to a script reassigning
  // `globalThis.JSON` in a persistent VM.
  let args_arr = rquickjs::Array::new(ctx.clone())?;
  for (i, a) in args.iter().enumerate() {
    args_arr.set(i, crate::bindings::convert::json_to_js(ctx, a)?)?;
  }
  globals.set("args", args_arr)?;

  install_console(ctx, inst.console)?;

  if let Some(page) = inst.page {
    crate::bindings::install_page(ctx, page, inst.async_ctx.clone())?;
  }
  if let Some(bcx) = inst.browser_context {
    crate::bindings::install_browser_context(ctx, bcx)?;
  }
  if let Some(browser) = inst.browser {
    crate::bindings::install_browser(ctx, browser)?;
  }
  if let Some(req) = inst.request {
    crate::bindings::fetch::install(ctx, req.clone())?;
    crate::bindings::install_request(ctx, req)?;
  } else {
    // `fetch` is always present; with no session HTTP context it uses
    // a session-stable default one (no shared cookies). Same net posture as the
    // `request` binding when absent.
    crate::bindings::fetch::install(ctx, inst.default_request)?;
  }

  Ok(())
}

fn install_console(ctx: &Ctx<'_>, capture: Arc<ConsoleCapture>) -> rquickjs::Result<()> {
  use std::fmt::Write as _;

  use rquickjs::function::Rest;

  // Reuse rquickjs-extra-console's Node-style value renderer (handles
  // `%s`/`%d` substitution, arrays, objects, `[Function: name]`, Symbol,
  // bounded depth) — but route the rendered line into our
  // `ConsoleCapture` sink instead of the `log` crate, so it still
  // surfaces in `ScriptResult.console[]` for the MCP caller. The
  // formatter is stateless (`max_depth` only), cheap to clone per level.
  let formatter = rquickjs_extra_console::Formatter::builder().max_depth(3).build();
  let console = Object::new(ctx.clone())?;

  for (name, level) in [
    ("log", ConsoleLevel::Log),
    ("info", ConsoleLevel::Info),
    ("warn", ConsoleLevel::Warn),
    ("error", ConsoleLevel::Error),
    ("debug", ConsoleLevel::Debug),
  ] {
    let cap = capture.clone();
    let fmt = formatter.clone();
    console.set(
      name,
      Func::from(move |args: Rest<Value<'_>>| -> rquickjs::Result<()> {
        let mut msg = String::new();
        for (i, v) in args.0.into_iter().enumerate() {
          if i > 0 {
            let _ = msg.write_char(' ');
          }
          fmt.format(&mut msg, v)?;
        }
        cap.push(level, strip_ansi(&msg));
        Ok(())
      }),
    )?;
  }

  ctx.globals().set("console", console)?;
  Ok(())
}

/// Install the session-lifetime runtime shims: timers, URL, and a few
/// hand-rolled web globals. Called once at [`Session::create`]; these
/// PERSIST across executions (browser/REPL-like) and are cancelled only
/// when the session VM is dropped (poison / eviction / session end) —
/// dropping the `AsyncRuntime` aborts every `setInterval`/`setTimeout`
/// task `ctx.spawn`ed by the timers module, so no per-call teardown is
/// needed. Sandbox-safe surface only — `os` / `sqlite` are deliberately
/// excluded so scripts cannot escape the filesystem/db sandbox.
fn install_runtime_shims(ctx: &Ctx<'_>) -> rquickjs::Result<()> {
  // Native timers (setTimeout/Interval, ctx.spawn-backed) and the
  // URLSearchParams class.
  rquickjs_extra_timers::init(ctx)?;
  rquickjs_extra_url::init(ctx)?;
  // Native TextEncoder/TextDecoder/URL classes + queueMicrotask/btoa/
  // atob — all real #[rquickjs::class]/Func bindings, no JS glue.
  crate::bindings::webapi::install(ctx)?;
  Ok(())
}

fn install_vars(ctx: &Ctx<'_>, vars: Arc<dyn VarsStore>) -> rquickjs::Result<()> {
  let obj = Object::new(ctx.clone())?;

  {
    let v = vars.clone();
    obj.set("get", Func::from(move |name: String| v.get(&name)))?;
  }
  {
    let v = vars.clone();
    obj.set(
      "set",
      Func::from(move |name: String, value: String| {
        v.set(&name, value);
      }),
    )?;
  }
  {
    let v = vars.clone();
    obj.set("has", Func::from(move |name: String| v.has(&name)))?;
  }
  {
    let v = vars.clone();
    obj.set(
      "delete",
      Func::from(move |name: String| {
        v.delete(&name);
      }),
    )?;
  }
  {
    let v = vars.clone();
    obj.set("keys", Func::from(move || v.keys()))?;
  }

  ctx.globals().set("vars", obj)?;
  Ok(())
}

fn install_fs(ctx: &Ctx<'_>, sandbox: Arc<PathSandbox>) -> rquickjs::Result<()> {
  let obj = Object::new(ctx.clone())?;

  {
    let sb = sandbox.clone();
    obj.set(
      "readFile",
      Func::from(Async(move |path: String| {
        let sb = sb.clone();
        async move {
          let resolved = sb.resolve_read(&path).map_err(|e| to_rq_error(&e))?;
          tokio::fs::read_to_string(&resolved)
            .await
            .map_err(|e| rquickjs::Error::new_from_js_message("fs", "readFile", e.to_string()))
        }
      })),
    )?;
  }
  {
    let sb = sandbox.clone();
    obj.set(
      "readFileBytes",
      Func::from(Async(move |path: String| {
        let sb = sb.clone();
        async move {
          let resolved = sb.resolve_read(&path).map_err(|e| to_rq_error(&e))?;
          tokio::fs::read(&resolved)
            .await
            .map_err(|e| rquickjs::Error::new_from_js_message("fs", "readFileBytes", e.to_string()))
        }
      })),
    )?;
  }
  {
    let sb = sandbox.clone();
    obj.set(
      "writeFile",
      Func::from(Async(move |path: String, contents: String| {
        let sb = sb.clone();
        async move {
          let resolved = sb.resolve_write(&path).map_err(|e| to_rq_error(&e))?;
          tokio::fs::write(&resolved, contents)
            .await
            .map_err(|e| rquickjs::Error::new_from_js_message("fs", "writeFile", e.to_string()))
        }
      })),
    )?;
  }
  {
    let sb = sandbox.clone();
    obj.set(
      "readdir",
      Func::from(Async(move |path: String| {
        let sb = sb.clone();
        async move {
          let resolved = sb.resolve_read(&path).map_err(|e| to_rq_error(&e))?;
          let mut entries = tokio::fs::read_dir(&resolved)
            .await
            .map_err(|e| rquickjs::Error::new_from_js_message("fs", "readdir", e.to_string()))?;
          let mut names: Vec<String> = Vec::new();
          while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| rquickjs::Error::new_from_js_message("fs", "readdir", e.to_string()))?
          {
            names.push(entry.file_name().to_string_lossy().into_owned());
          }
          Ok::<_, rquickjs::Error>(names)
        }
      })),
    )?;
  }
  {
    let sb = sandbox.clone();
    obj.set(
      "exists",
      Func::from(Async(move |path: String| {
        let sb = sb.clone();
        async move {
          // Syntactic checks still apply; absence or sandbox-escape returns false.
          match sb.resolve_read(&path) {
            Ok(resolved) => Ok::<bool, rquickjs::Error>(tokio::fs::try_exists(&resolved).await.unwrap_or(false)),
            Err(_) => Ok(false),
          }
        }
      })),
    )?;
  }

  // Expose the sandbox root so scripts can build relative paths confidently.
  obj.set("root", sandbox.root().to_string_lossy().into_owned())?;

  ctx.globals().set("fs", obj)?;
  Ok(())
}

fn to_rq_error(err: &ScriptError) -> rquickjs::Error {
  // The `from`/`to` static labels are used only in rquickjs's Display impl.
  // We route sandbox-rejection errors through the FromJs variant so the
  // message propagates to JS as a thrown exception with our reason string.
  rquickjs::Error::new_from_js_message("fs", "sandbox", err.message.clone())
}

/// Convert the script's return value to `serde_json::Value`.
///
/// `rquickjs-serde` (`from_value`) drives the deserializer: it invokes
/// `toJSON()` / `valueOf()` (a returned `Date` still serialises as its
/// ISO string), coerces whole f64 in the safe-integer range to `i64`,
/// drops `undefined` / function / symbol, and renders non-finite as
/// null. We deserialize into a small AP-immune intermediate rather than
/// straight into `serde_json::Value`: a transitive dep force-enables
/// `serde_json/arbitrary_precision` workspace-wide, and under that
/// feature `serde_json::Value`'s own `Deserialize` demands a private
/// number representation that a non-`serde_json` deserializer (here,
/// `rquickjs-serde`) cannot provide — every numeric/array result would
/// otherwise fail to convert and collapse to `null`. The intermediate's
/// `Deserialize` is plain serde; the `serde_json::Value` is then built
/// with explicit constructors, which are AP-correct.
fn value_to_json<'js>(_ctx: &Ctx<'js>, value: Value<'js>) -> Option<serde_json::Value> {
  rquickjs_serde::from_value::<JsonInter>(value)
    .ok()
    .map(JsonInter::into_json)
}

/// AP-immune mirror of a JSON value. Its `Deserialize` is plain serde
/// (no `serde_json` number coupling); `into_json` rebuilds a
/// `serde_json::Value` via explicit constructors.
enum JsonInter {
  Null,
  Bool(bool),
  I64(i64),
  U64(u64),
  F64(f64),
  Str(String),
  Arr(Vec<JsonInter>),
  Obj(Vec<(String, JsonInter)>),
}

impl JsonInter {
  fn into_json(self) -> serde_json::Value {
    use serde_json::Value;
    match self {
      Self::Null => Value::Null,
      Self::Bool(b) => Value::Bool(b),
      Self::I64(n) => Value::Number(n.into()),
      Self::U64(n) => Value::Number(n.into()),
      Self::F64(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
      Self::Str(s) => Value::String(s),
      Self::Arr(a) => Value::Array(a.into_iter().map(Self::into_json).collect()),
      Self::Obj(o) => Value::Object(o.into_iter().map(|(k, v)| (k, v.into_json())).collect()),
    }
  }
}

impl<'de> serde::Deserialize<'de> for JsonInter {
  fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
    struct V;
    impl<'de> serde::de::Visitor<'de> for V {
      type Value = JsonInter;
      fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("any JSON value")
      }
      fn visit_unit<E>(self) -> Result<JsonInter, E> {
        Ok(JsonInter::Null)
      }
      fn visit_none<E>(self) -> Result<JsonInter, E> {
        Ok(JsonInter::Null)
      }
      fn visit_bool<E>(self, v: bool) -> Result<JsonInter, E> {
        Ok(JsonInter::Bool(v))
      }
      fn visit_i64<E>(self, v: i64) -> Result<JsonInter, E> {
        Ok(JsonInter::I64(v))
      }
      fn visit_u64<E>(self, v: u64) -> Result<JsonInter, E> {
        Ok(JsonInter::U64(v))
      }
      fn visit_f64<E>(self, v: f64) -> Result<JsonInter, E> {
        Ok(JsonInter::F64(v))
      }
      fn visit_str<E>(self, v: &str) -> Result<JsonInter, E> {
        Ok(JsonInter::Str(v.to_owned()))
      }
      fn visit_string<E>(self, v: String) -> Result<JsonInter, E> {
        Ok(JsonInter::Str(v))
      }
      fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<JsonInter, A::Error> {
        let mut out = Vec::new();
        while let Some(e) = a.next_element()? {
          out.push(e);
        }
        Ok(JsonInter::Arr(out))
      }
      fn visit_map<A: serde::de::MapAccess<'de>>(self, mut m: A) -> Result<JsonInter, A::Error> {
        let mut out = Vec::new();
        while let Some((k, v)) = m.next_entry()? {
          out.push((k, v));
        }
        Ok(JsonInter::Obj(out))
      }
    }
    d.deserialize_any(V)
  }
}

pub(crate) fn caught_to_script_error(caught: rquickjs::CaughtError<'_>, source: &str) -> ScriptError {
  let (message, stack, line, column) = match caught {
    rquickjs::CaughtError::Exception(ex) => {
      let message = ex.message().unwrap_or_else(|| "exception".to_string());
      let stack = ex.stack();
      // Playwright-style: lineNumber/columnNumber are present on most QuickJS
      // exceptions; read them directly off the exception object.
      let obj = ex.as_object();
      let line = obj.get::<_, u32>("lineNumber").ok();
      let column = obj.get::<_, u32>("columnNumber").ok();
      (message, stack, line, column)
    },
    rquickjs::CaughtError::Value(v) => (format!("{v:?}"), None, None, None),
    rquickjs::CaughtError::Error(e) => (format!("{e}"), None, None, None),
  };

  ScriptError {
    kind: ScriptErrorKind::Runtime,
    message,
    stack,
    line,
    column,
    source_snippet: line.and_then(|l| snippet_around_line(source, l, 2)),
  }
}

/// Build a 1-indexed source snippet with `context_lines` around the target
/// line, used in error reporting so the LLM can see where the script failed.
fn snippet_around_line(source: &str, line_1based: u32, context_lines: u32) -> Option<String> {
  use std::fmt::Write as _;
  let lines: Vec<&str> = source.lines().collect();
  if lines.is_empty() {
    return None;
  }
  let target = line_1based.saturating_sub(1) as usize;
  let start = target.saturating_sub(context_lines as usize);
  let end = (target + context_lines as usize + 1).min(lines.len());
  let mut out = String::new();
  for (i, text) in lines[start..end].iter().enumerate() {
    let ln = start + i + 1;
    let marker = if ln == line_1based as usize { ">>>" } else { "   " };
    let _ = writeln!(out, "{marker} {ln:>4}: {text}");
  }
  Some(out)
}

fn elapsed_ms(started: Instant) -> u64 {
  started.elapsed().as_millis() as u64
}