monty-runtime 1.1.0

A secure, snapshotable Python sandbox written in Rust.
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
//! The standard `monty` CLI: run a file, a `-c` program, or a REPL session.
//!
//! Everything here is the *standalone* path. `monty subprocess` shares only the
//! allocator and the argument definitions, and reaches none of it — which is
//! why telemetry lives here rather than in `main`.

// only the exporter reads the environment; see the `telemetry` feature
#[cfg(feature = "telemetry")]
use std::env;
use std::{
    fmt, fs, io,
    process::ExitCode,
    thread,
    time::{Duration, Instant},
};

// Shadows `std::eprintln!` on purpose: every diagnostic here goes to stderr
// through `anstream`, which strips styling when stderr is not a terminal (or
// `NO_COLOR` is set) and enables virtual-terminal mode on Windows. Sandbox
// output keeps using `std::println!` — it is program data, not our styling.
use anstream::{AutoStream, ColorChoice, eprintln};
use anstyle::{AnsiColor, Color, Style};
use monty::{
    MontyRepl, MontyRun, ReplContinuationMode, ReplProgress, RunProgress, detect_repl_continuation_mode,
    source_within_nesting_bound,
};
use monty_fs::{MountCallOutcome, MountMode, MountTable, OverlayState};
use monty_type_checking::{SourceFile, TypeChecker};
use monty_types::{
    CallArgs, CompileOptions, DEFAULT_MAX_SUSPENSIONS, ExcType, ExtFunctionResult, MontyException, MontyObject,
    NameLookupResult, OsFunctionCall, OsPolicy, PrintWriter, ResourceLimits, ResourceTracker, SOURCE_SCAN_THRESHOLD,
    SleepMode, TypeCheckingConfig, memory_limit_with_headroom, validate_cwd,
};
use rustyline::{DefaultEditor, error::ReadlineError};
#[cfg(feature = "telemetry")]
use tracing::field::Empty;

use crate::Cli;

/// Dim/gray text (timings). `{DIM}` opens the style, `{DIM:#}` closes it.
const DIM: Style = Style::new().dimmed();
/// Bold red text (errors).
const BOLD_RED: Style = Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Red)));
/// Bold green text (success, headings).
const BOLD_GREEN: Style = Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Green)));
/// Bold cyan text (commands, prompts).
const BOLD_CYAN: Style = Style::new().bold().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));
const ARROW: &str = "❯";

const EXT_FUNCTIONS: bool = false;

/// Runs the CLI inside a `run monty` span, having configured the exporter.
/// Split from [`run_cli`] so the whole stack compiles away without the feature.
#[cfg(feature = "telemetry")]
pub(crate) fn run(cli: Cli) -> ExitCode {
    let logfire = match configure_logfire() {
        Ok(logfire) => logfire,
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}: failed to configure telemetry: {err}");
            return ExitCode::FAILURE;
        }
    };
    let run_span = logfire.as_ref().map(|_| logfire::span!("run monty", success = Empty,));
    let exit_code = run_cli(cli);
    if let Some(run_span) = run_span {
        run_span.record("success", exit_code == ExitCode::SUCCESS);
    }
    exit_code
}

/// Runs the CLI with no telemetry linked in — the default build, where
/// `LOGFIRE_TOKEN` is ignored rather than diagnosed.
#[cfg(not(feature = "telemetry"))]
pub(crate) fn run(cli: Cli) -> ExitCode {
    run_cli(cli)
}

/// Configures process-level telemetry for standalone CLI execution.
///
/// Worker subprocesses bypass this function so inherited credentials never
/// create an exporter in each sandbox process.
#[cfg(feature = "telemetry")]
fn configure_logfire() -> Result<Option<logfire::ShutdownGuard>, logfire::ConfigureError> {
    if env::var_os("LOGFIRE_TOKEN").is_some() {
        logfire::configure()
            .with_service_name("monty")
            .with_service_version(env!("CARGO_PKG_VERSION"))
            .finish()
            .map(logfire::Logfire::shutdown_guard)
            .map(Some)
    } else {
        Ok(None)
    }
}

/// Dispatches a parsed standalone CLI invocation.
fn run_cli(cli: Cli) -> ExitCode {
    // `Some` enables the check and carries how its diagnostics are rendered.
    let type_check = cli.type_check.then(|| TypeCheckingConfig {
        format: cli.type_check_format.unwrap_or_default(),
        color: stderr_styled(),
    });

    let limits = match cli.resource_limits() {
        Ok(limits) => limits,
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
            return ExitCode::FAILURE;
        }
    };
    let hard_memory_limit = memory_limit_with_headroom(limits.max_memory, type_check.is_some());
    monty_alloc::set_hard_limit(hard_memory_limit).expect("monty-runtime must install LimitedAllocator globally");

    // Build mount table early to fail fast on bad -m args.
    let (mounts, first_mount) = match build_mount_table(&cli.mounts) {
        Ok(Some((mt, first_mount))) => (Some(mt), Some(first_mount)),
        Ok(None) => (None, None),
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
            return ExitCode::FAILURE;
        }
    };
    let max_sleep = match cli.max_sleep() {
        Ok(max_sleep) => max_sleep,
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
            return ExitCode::FAILURE;
        }
    };
    let host = HostOs {
        mounts,
        max_sleep,
        sleep_budget: limits.max_total_sleep.map(SleepBudget::new),
    };
    let cwd = match sandbox_cwd(cli.cwd.as_deref(), first_mount) {
        Ok(cwd) => cwd,
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
            return ExitCode::FAILURE;
        }
    };

    if let Some(cmd) = cli.command {
        if cli.file.is_some() {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}: cannot specify both -c and a file");
            return ExitCode::FAILURE;
        }
        return if cli.interactive {
            dispatch_repl("<string>", &cmd, limits, host, &cwd)
        } else {
            dispatch_script("<string>", cmd, type_check, limits, host, &cwd)
        };
    }

    if let Some(file_path) = cli.file.as_deref() {
        let code = match read_file(file_path) {
            Ok(code) => code,
            Err(err) => {
                eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
                return ExitCode::FAILURE;
            }
        };
        return if cli.interactive {
            dispatch_repl(file_path, &code, limits, host, &cwd)
        } else {
            dispatch_script(file_path, code, type_check, limits, host, &cwd)
        };
    }

    dispatch_repl("repl.py", "", limits, host, &cwd)
}

/// Resolves the sandbox working directory: `--cwd`, else the first `--mount`
/// virtual path, else `/`. An explicit value goes through the shared [`validate_cwd`].
fn sandbox_cwd(cwd: Option<&str>, first_mount: Option<String>) -> Result<String, String> {
    match cwd {
        Some(cwd) => validate_cwd(cwd).map_err(|message| format!("--{message}")),
        None => Ok(first_mount.unwrap_or_else(|| "/".to_owned())),
    }
}

/// Builds the tracker from the CLI resource limits and runs the script.
fn dispatch_script(
    file_path: &str,
    code: String,
    type_check: Option<TypeCheckingConfig>,
    limits: ResourceLimits,
    host: HostOs,
    cwd: &str,
) -> ExitCode {
    run_script(file_path, code, type_check, ResourceTracker::new(limits), host, cwd)
}

/// REPL analog of [`dispatch_script`].
fn dispatch_repl(file_path: &str, code: &str, limits: ResourceLimits, host: HostOs, cwd: &str) -> ExitCode {
    run_repl(file_path, code, ResourceTracker::new(limits), host, cwd)
}

/// Executes a Python file in one-shot CLI mode.
///
/// This path keeps the existing CLI behavior: run type-checking for visibility,
/// compile the file as a full module, and execute it either through direct
/// execution or through the suspendable progress loop when mounts or external
/// functions are enabled.
///
/// Returns `ExitCode::SUCCESS` for successful execution and
/// `ExitCode::FAILURE` for parse/type/runtime failures.
fn run_script(
    file_path: &str,
    code: String,
    type_check: Option<TypeCheckingConfig>,
    tracker: ResourceTracker,
    mut host: HostOs,
    cwd: &str,
) -> ExitCode {
    // A source the compiler will reject as too deeply nested skips the (unguarded) type checker.
    if let Some(config) = type_check
        && source_within_nesting_bound(&code, SOURCE_SCAN_THRESHOLD)
    {
        let start = Instant::now();
        let mut checker = TypeChecker::default();
        if let Some(failure) = checker.run(&SourceFile::new(&code, file_path), None, config).unwrap() {
            let elapsed = start.elapsed();
            eprintln!(
                "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {BOLD_RED}type check failed{BOLD_RED:#}:\n{failure}",
                FormattedDuration(elapsed)
            );
        } else {
            let elapsed = start.elapsed();
            eprintln!(
                "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {BOLD_GREEN}type check passed{BOLD_GREEN:#}",
                FormattedDuration(elapsed)
            );
        }
    }

    let input_names = vec![];
    let inputs = vec![];

    let mut runner = match MontyRun::new(code, file_path, input_names, CompileOptions::default()) {
        Ok(ex) => ex.with_os_policy(host.os_policy()),
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#}:\n{err}");
            return ExitCode::FAILURE;
        }
    };
    runner.set_cwd(cwd);

    // Use the start() + loop path when mounts are configured or external functions
    // are enabled, since we need to intercept OsCalls.
    if EXT_FUNCTIONS || host.suspends() {
        let start = Instant::now();
        let progress = match runner.start(inputs, tracker, PrintWriter::Stdout) {
            Ok(p) => p,
            Err(err) => {
                let elapsed = start.elapsed();
                eprintln!(
                    "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {BOLD_RED}error{BOLD_RED:#}: {err}",
                    FormattedDuration(elapsed)
                );
                return ExitCode::FAILURE;
            }
        };

        let mut suspensions = SuspensionBudget::from_progress(&progress);
        match run_until_complete(progress, &mut host, &mut suspensions) {
            Ok(value) => {
                let elapsed = start.elapsed();
                eprintln!(
                    "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {value}",
                    FormattedDuration(elapsed)
                );
                ExitCode::SUCCESS
            }
            Err(err) => {
                let elapsed = start.elapsed();
                eprintln!(
                    "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {BOLD_RED}error{BOLD_RED:#}: {err}",
                    FormattedDuration(elapsed)
                );
                ExitCode::FAILURE
            }
        }
    } else {
        let start = Instant::now();
        let value = match runner.run(inputs, tracker, PrintWriter::Stdout) {
            Ok(p) => p,
            Err(err) => {
                let elapsed = start.elapsed();
                eprintln!(
                    "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {BOLD_RED}error{BOLD_RED:#}: {err}",
                    FormattedDuration(elapsed)
                );
                return ExitCode::FAILURE;
            }
        };
        let elapsed = start.elapsed();
        eprintln!(
            "{DIM}{}{DIM:#} {BOLD_CYAN}{ARROW}{BOLD_CYAN:#} {value}",
            FormattedDuration(elapsed)
        );
        ExitCode::SUCCESS
    }
}

/// Starts an interactive line-by-line REPL session.
///
/// Initializes `MontyRepl` once and incrementally feeds entered snippets without
/// replaying previous snippets, which matches the intended stateful REPL model.
/// Multiline input follows CPython-style prompts:
/// - `❯ ` for a new statement
/// - `… ` for continuation lines
///
/// Returns `ExitCode::SUCCESS` on EOF or `exit`, and `ExitCode::FAILURE` on
/// initialization or I/O errors.
fn run_repl(file_path: &str, code: &str, tracker: ResourceTracker, mut host: HostOs, cwd: &str) -> ExitCode {
    let mut suspensions = SuspensionBudget::new(&tracker);
    let mut repl = MontyRepl::new(file_path, tracker, CompileOptions::default()).with_os_policy(host.os_policy());
    repl.set_cwd(cwd);
    let mut repl = Some(repl);

    if !code.is_empty() {
        execute_repl_snippet(&mut repl, code, &mut host, &mut suspensions);
    }

    eprintln!("Monty v{} REPL. Type `exit` to exit.", env!("CARGO_PKG_VERSION"));

    let mut rl = match DefaultEditor::new() {
        Ok(rl) => rl,
        Err(err) => {
            eprintln!("{BOLD_RED}error{BOLD_RED:#} initializing editor: {err}");
            return ExitCode::FAILURE;
        }
    };

    let mut pending_snippet = String::new();
    let mut continuation_mode = ReplContinuationMode::Complete;

    // rustyline writes the prompt to stdout itself, so `anstream` never sees
    // it — style it up front, against stdout, or not at all.
    let statement_prompt = if stdout_styled() {
        format!("{BOLD_CYAN}{ARROW}{BOLD_CYAN:#} ")
    } else {
        format!("{ARROW} ")
    };

    loop {
        let prompt = if continuation_mode == ReplContinuationMode::Complete {
            statement_prompt.as_str()
        } else {
            "… "
        };

        let line = match rl.readline(prompt) {
            Ok(line) => line,
            Err(ReadlineError::Eof) => return ExitCode::SUCCESS,
            Err(ReadlineError::Interrupted) => {
                // Ctrl-C: discard pending input and start fresh
                pending_snippet.clear();
                continuation_mode = ReplContinuationMode::Complete;
                continue;
            }
            Err(err) => {
                eprintln!("{BOLD_RED}error{BOLD_RED:#} reading input: {err}");
                return ExitCode::FAILURE;
            }
        };

        let snippet = line.trim_end();
        if continuation_mode == ReplContinuationMode::Complete && snippet.is_empty() {
            continue;
        }
        if continuation_mode == ReplContinuationMode::Complete && snippet == "exit" {
            return ExitCode::SUCCESS;
        }

        pending_snippet.push_str(snippet);
        pending_snippet.push('\n');

        if continuation_mode == ReplContinuationMode::IncompleteBlock && snippet.is_empty() {
            let _ = rl.add_history_entry(pending_snippet.trim_end());
            execute_repl_snippet(&mut repl, &pending_snippet, &mut host, &mut suspensions);
            pending_snippet.clear();
            continuation_mode = ReplContinuationMode::Complete;
            continue;
        }

        let detected_mode = detect_repl_continuation_mode(&pending_snippet);
        match detected_mode {
            ReplContinuationMode::Complete => {
                if continuation_mode == ReplContinuationMode::IncompleteBlock {
                    continue;
                }
                let _ = rl.add_history_entry(pending_snippet.trim_end());
                execute_repl_snippet(&mut repl, &pending_snippet, &mut host, &mut suspensions);
                pending_snippet.clear();
                continuation_mode = ReplContinuationMode::Complete;
            }
            ReplContinuationMode::IncompleteBlock => continuation_mode = ReplContinuationMode::IncompleteBlock,
            ReplContinuationMode::IncompleteImplicit => {
                if continuation_mode != ReplContinuationMode::IncompleteBlock {
                    continuation_mode = ReplContinuationMode::IncompleteImplicit;
                }
            }
        }
    }
}

/// Executes one collected REPL snippet, printing the result or error.
///
/// When mounts are configured, uses `feed_start()` + a progress loop to intercept
/// `OsCall`s. Otherwise uses the simpler `feed_run()` path.
///
/// Takes `&mut Option<MontyRepl>` because `feed_start` consumes the repl —
/// we `take()` it out, run to completion, then put it back.
fn execute_repl_snippet(
    repl: &mut Option<MontyRepl>,
    snippet: &str,
    host: &mut HostOs,
    suspensions: &mut SuspensionBudget,
) {
    let r = repl.take().expect("repl must be present");

    if host.suspends() {
        match execute_repl_with_mounts(r, snippet, host, suspensions) {
            Ok((returned_repl, output)) => {
                if output != MontyObject::none() {
                    println!("{output}");
                }
                *repl = Some(returned_repl);
            }
            Err((returned_repl, err)) => {
                eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
                *repl = Some(returned_repl);
            }
        }
    } else {
        // No mounts — use the simple feed_run path (takes &mut self).
        let mut r = r;
        match r.feed_run(snippet, vec![], PrintWriter::Stdout) {
            Ok(output) => {
                if output != MontyObject::none() {
                    println!("{output}");
                }
            }
            Err(err) => {
                eprintln!("{BOLD_RED}error{BOLD_RED:#}: {err}");
            }
        }
        *repl = Some(r);
    }
}

/// Runs a REPL snippet with mount support via the `feed_start` + progress loop path.
///
/// Returns `Ok((repl, value))` on success, or `Err((repl, message))` on failure.
/// The repl is always returned so the caller can continue the session.
#[expect(clippy::result_large_err)]
fn execute_repl_with_mounts(
    r: MontyRepl,
    snippet: &str,
    host: &mut HostOs,
    suspensions: &mut SuspensionBudget,
) -> Result<(MontyRepl, MontyObject), (MontyRepl, String)> {
    let mut progress = match r.feed_start(snippet, vec![], PrintWriter::Stdout) {
        Ok(p) => p,
        Err(err) => return Err((err.repl, format!("{}", err.error))),
    };

    loop {
        // The CLI, as host, enforces `--max-suspensions`.
        if !matches!(progress, ReplProgress::Complete { .. })
            && let Some(exc) = suspensions.record_suspension()
        {
            let outcome = match progress {
                ReplProgress::OsCall(call) => call.abort(exc, PrintWriter::Stdout),
                ReplProgress::FunctionCall(call) => call.abort(exc, PrintWriter::Stdout),
                ReplProgress::NameLookup(lookup) => lookup.abort(exc, PrintWriter::Stdout),
                ReplProgress::ResolveFutures(state) => state.abort(exc, PrintWriter::Stdout),
                ReplProgress::Complete { .. } => unreachable!("only suspensions are counted"),
            };
            match outcome {
                Ok(p) => progress = p,
                Err(err) => return Err((err.repl, format!("{}", err.error))),
            }
            continue;
        }
        match progress {
            ReplProgress::Complete { repl, value } => return Ok((repl, value)),
            ReplProgress::OsCall(call) => {
                let outcome = match host.refuse_sleep(&call.function_call) {
                    Some(exc) => call.abort(exc, PrintWriter::Stdout),
                    None => call.resume_with(PrintWriter::Stdout, |fc| host.handle_os_call(fc)),
                };
                match outcome {
                    Ok(p) => progress = p,
                    Err(err) => return Err((err.repl, format!("{}", err.error))),
                }
            }
            ReplProgress::FunctionCall(call) => {
                return Err((
                    call.into_repl(),
                    "external function calls not supported in CLI".to_owned(),
                ));
            }
            ReplProgress::NameLookup(lookup) => match lookup.resume(NameLookupResult::Undefined, PrintWriter::Stdout) {
                Ok(p) => progress = p,
                Err(err) => return Err((err.repl, format!("{}", err.error))),
            },
            ReplProgress::ResolveFutures(state) => {
                return Err((state.into_repl(), "async futures not supported in CLI".to_owned()));
            }
        }
    }
}

/// Drives suspendable execution until completion.
///
/// This repeatedly resumes `RunProgress` values by resolving supported
/// external calls and returns the final value when execution reaches
/// `RunProgress::Complete`.
///
/// When a mount table is provided, filesystem `OsCall`s are handled via the
/// mount table. Non-filesystem `OsCall`s and `OsCall`s without a mount table
/// produce an error.
fn run_until_complete(
    mut progress: RunProgress,
    host: &mut HostOs,
    suspensions: &mut SuspensionBudget,
) -> Result<MontyObject, String> {
    loop {
        // The CLI, as host, enforces `--max-suspensions`.
        if !matches!(progress, RunProgress::Complete(_))
            && let Some(exc) = suspensions.record_suspension()
        {
            progress = match progress {
                RunProgress::OsCall(call) => call.abort(exc, PrintWriter::Stdout),
                RunProgress::FunctionCall(call) => call.abort(exc, PrintWriter::Stdout),
                RunProgress::NameLookup(lookup) => lookup.abort(exc, PrintWriter::Stdout),
                RunProgress::ResolveFutures(state) => state.abort(exc, PrintWriter::Stdout),
                RunProgress::Complete(_) => unreachable!("only suspensions are counted"),
            }
            .map_err(|err| format!("{err}"))?;
            continue;
        }
        match progress {
            RunProgress::Complete(value) => return Ok(value),
            RunProgress::FunctionCall(call) => {
                let return_value = resolve_external_call(&call.function_name, &call.args)?;
                progress = call
                    .resume(return_value, PrintWriter::Stdout)
                    .map_err(|err| format!("{err}"))?;
            }
            RunProgress::ResolveFutures(state) => {
                return Err(format!(
                    "async futures not supported in CLI: {:?}",
                    state.pending_call_ids()
                ));
            }
            RunProgress::NameLookup(lookup) => {
                let result = if lookup.name == "add_ints" {
                    NameLookupResult::from(MontyObject::function("add_ints".to_string(), None))
                } else {
                    NameLookupResult::Undefined
                };
                progress = lookup
                    .resume(result, PrintWriter::Stdout)
                    .map_err(|err| format!("{err}"))?;
            }
            RunProgress::OsCall(call) => {
                let outcome = match host.refuse_sleep(&call.function_call) {
                    Some(exc) => call.abort(exc, PrintWriter::Stdout),
                    None => call.resume_with(PrintWriter::Stdout, |fc| host.handle_os_call(fc)),
                };
                progress = outcome.map_err(|err| format!("{err}"))?;
            }
        }
    }
}

/// Charges requested delays before waiting, so `--max-total-sleep` refusal is deterministic.
struct SleepBudget {
    limit: Duration,
    /// Capped delays accepted so far, checked against `limit`.
    used: Duration,
}

impl SleepBudget {
    fn new(limit: Duration) -> Self {
        Self {
            limit,
            used: Duration::ZERO,
        }
    }

    /// Charges `delay` or returns an uncatchable error with the same message as the pools.
    fn charge(&mut self, delay: Duration) -> Option<MontyException> {
        let total = self.used.saturating_add(delay);
        if total > self.limit {
            Some(MontyException::new(
                ExcType::TimeoutError,
                Some(format!("sleep limit exceeded: {total:?} > {:?}", self.limit)),
            ))
        } else {
            self.used = total;
            None
        }
    }
}

/// Tracks the CLI-enforced suspension limit across an entire REPL session.
struct SuspensionBudget {
    limit: usize,
    seen: usize,
}

impl SuspensionBudget {
    /// Initializes a budget from the tracker's limits.
    fn new(tracker: &ResourceTracker) -> Self {
        Self {
            limit: tracker.max_suspensions(),
            seen: 0,
        }
    }

    /// Reads a one-shot run's limit from its initial progress.
    fn from_progress(progress: &RunProgress) -> Self {
        let limit = match progress {
            RunProgress::FunctionCall(call) => call.tracker().max_suspensions(),
            RunProgress::OsCall(call) => call.tracker().max_suspensions(),
            RunProgress::NameLookup(lookup) => lookup.tracker().max_suspensions(),
            RunProgress::ResolveFutures(state) => state.tracker().max_suspensions(),
            // never counted, so the value is immaterial
            RunProgress::Complete(_) => DEFAULT_MAX_SUSPENSIONS,
        };
        Self { limit, seen: 0 }
    }

    /// Counts one suspension and returns the exception to abort it with once
    /// the count is over budget.
    fn record_suspension(&mut self) -> Option<MontyException> {
        self.seen += 1;
        let limit = self.limit;
        (self.seen > limit).then(|| {
            MontyException::new(
                ExcType::RuntimeError,
                Some(format!("suspension limit {limit} exceeded")),
            )
        })
    }
}

/// Handles CLI mounts and sleeps, enforcing per-sleep and total sleep limits.
struct HostOs {
    mounts: Option<MountTable>,
    /// Longest wait a sleep performs; longer ones are cut short.
    max_sleep: Duration,
    sleep_budget: Option<SleepBudget>,
}

impl HostOs {
    /// Mount dispatch and total sleep accounting require OS calls to reach the host.
    fn suspends(&self) -> bool {
        self.mounts.is_some() || self.sleep_budget.is_some()
    }

    /// Uses the system clock and entropy, with `--max-sleep` capping each sleep.
    /// Without mounts or a sleep budget, the interpreter waits instead of the CLI.
    fn os_policy(&self) -> OsPolicy {
        OsPolicy {
            sleep: SleepMode::System(self.max_sleep),
            ..OsPolicy::default()
        }
    }

    /// Charges system sleeps after capping them at `--max-sleep`, or returns an error to abort the feed.
    /// Other calls are free.
    fn refuse_sleep(&mut self, call: &OsFunctionCall) -> Option<MontyException> {
        match (call, self.sleep_budget.as_mut()) {
            (OsFunctionCall::SystemSleep(delay) | OsFunctionCall::AsyncSystemSleep(delay), Some(budget)) => {
                budget.charge((*delay).min(self.max_sleep))
            }
            _ => None,
        }
    }

    /// Waits for system sleeps, enforcing `--max-sleep` again in case the sandbox did not.
    /// Other calls go to the mounts, transferring write payloads without copying.
    fn handle_os_call(&mut self, call: OsFunctionCall) -> ExtFunctionResult {
        if let OsFunctionCall::SystemSleep(delay) | OsFunctionCall::AsyncSystemSleep(delay) = call {
            thread::sleep(delay.min(self.max_sleep));
            return MontyObject::none().into();
        }
        match self.mounts.as_mut() {
            Some(mounts) => match mounts.handle_os_call(call) {
                MountCallOutcome::Handled(Ok(obj)) => obj.into(),
                MountCallOutcome::Handled(Err(err)) => err.into_exception().into(),
                MountCallOutcome::NotHandled(call) => call.on_no_handler().into(),
            },
            None => call.on_no_handler().into(),
        }
    }
}

/// Resolves supported CLI external function calls.
///
/// The CLI currently supports only `add_ints(int, int)`, which makes it
/// possible to exercise the suspend/resume path in a deterministic way.
///
/// Returns a runtime-like error string for unknown function names, wrong arity,
/// or incorrect argument types.
fn resolve_external_call(function_name: &str, args: &CallArgs) -> Result<MontyObject, String> {
    let rendered = || args.args().map(|arg| arg.py_repr()).collect::<Vec<_>>().join(", ");
    if function_name != "add_ints" {
        return Err(format!("unknown external function: {function_name}({})", rendered()));
    }

    if args.args().len() != 2 {
        return Err(format!(
            "add_ints requires exactly 2 arguments, got {}",
            args.args().len()
        ));
    }

    match (
        args.arg(0).and_then(|a| a.as_int()),
        args.arg(1).and_then(|b| b.as_int()),
    ) {
        (Some(a), Some(b)) => a
            .checked_add(b)
            .map(MontyObject::int)
            .ok_or_else(|| format!("add_ints result is out of i64 range, got {}", rendered())),
        _ => Err(format!("add_ints requires integer arguments, got {}", rendered())),
    }
}

// =============================================================================
// Mount parsing
// =============================================================================

/// Builds a [`MountTable`] from CLI `-m` arguments, returning it with the
/// first mount's virtual path (the default sandbox working directory).
///
/// Returns `None` if no mounts were specified. Fails early with a descriptive
/// error if any mount spec is malformed or the host path doesn't exist.
fn build_mount_table(mount_args: &[String]) -> Result<Option<(MountTable, String)>, String> {
    if mount_args.is_empty() {
        return Ok(None);
    }

    let mut table = MountTable::new();
    let mut first_virtual_path = None;
    for arg in mount_args {
        let (host_path, virtual_path, mode, write_bytes_limit) = parse_mount(arg)?;
        table
            .mount(&virtual_path, &host_path, mode, write_bytes_limit)
            .map_err(|e| format!("mount {arg}: {e}"))?;
        first_virtual_path.get_or_insert(virtual_path);
    }
    Ok(first_virtual_path.map(|first| (table, first)))
}

/// Parses a single mount specification string.
///
/// Format: `host_path::virtual_path[::mode[::write_limit_bytes]]`
///
/// Uses `::` as the separator to avoid ambiguity with Windows drive letters
/// (e.g., `C:\data::/mnt::rw::1000000`).
///
/// Mode defaults to `ro` (read-only) when omitted. Valid modes:
/// - `ro` — read-only
/// - `rw` — read-write
/// - `overlay` — in-memory copy-on-write overlay
fn parse_mount(spec: &str) -> Result<(String, String, MountMode, Option<u64>), String> {
    let parts: Vec<&str> = spec.split("::").collect();

    let (host_path, virtual_path, mode_str, limit_str) = match parts.len() {
        2 => (parts[0], parts[1], "ro", None),
        3 => (parts[0], parts[1], parts[2], None),
        4 => (parts[0], parts[1], parts[2], Some(parts[3])),
        _ => {
            return Err(format!(
                "invalid mount spec '{spec}': expected host_path::virtual_path[::mode[::write_limit_bytes]]"
            ));
        }
    };

    if host_path.is_empty() || virtual_path.is_empty() {
        return Err(format!(
            "invalid mount spec '{spec}': host and virtual paths must not be empty"
        ));
    }

    let mode = match mode_str {
        "ro" => MountMode::ReadOnly,
        "rw" => MountMode::ReadWrite,
        "overlay" => MountMode::OverlayMemory(OverlayState::new()),
        other => {
            return Err(format!(
                "invalid mount mode '{other}' in '{spec}': expected 'ro', 'rw', or 'overlay'"
            ));
        }
    };

    let write_bytes_limit = match limit_str {
        Some("") => {
            return Err(format!("invalid write limit in '{spec}': value must not be empty"));
        }
        Some(limit) => Some(
            limit
                .parse::<u64>()
                .map_err(|_| format!("invalid write limit '{limit}' in '{spec}': expected a non-negative integer"))?,
        ),
        None => None,
    };

    Ok((host_path.to_owned(), virtual_path.to_owned(), mode, write_bytes_limit))
}

// =============================================================================
// File I/O and formatting utilities
// =============================================================================

/// Reads a Python source file from disk, returning its contents as a string.
///
/// Returns an error message if the path doesn't exist, isn't a file, or can't be read.
fn read_file(file_path: &str) -> Result<String, String> {
    match fs::metadata(file_path) {
        Ok(metadata) => {
            if !metadata.is_file() {
                return Err(format!("{file_path} is not a file"));
            }
        }
        Err(err) => {
            return Err(format!("reading {file_path}: {err}"));
        }
    }
    match fs::read_to_string(file_path) {
        Ok(contents) => Ok(contents),
        Err(err) => Err(format!("reading file: {err}")),
    }
}

/// Wrapper around `Duration` that formats with 5 significant digits and an auto-selected unit.
///
/// - `< 1ms` → microseconds, e.g. `123.45μs`
/// - `1ms..1s` → milliseconds, e.g. `12.345ms`
/// - `≥ 1s` → seconds, e.g. `1.2345s`
///
/// The goal is a compact, human-readable duration string that stays consistent in width
/// regardless of whether execution took microseconds or seconds.
struct FormattedDuration(Duration);

impl fmt::Display for FormattedDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let duration = self.0;
        let total_secs = duration.as_secs_f64();

        if total_secs < 1e-3 {
            // Microseconds
            let us = total_secs * 1e6;
            let decimals = sig_digits_after_decimal(us);
            write!(f, "{us:.decimals$}μs")
        } else if total_secs < 1.0 {
            // Milliseconds
            let ms = total_secs * 1e3;
            let decimals = sig_digits_after_decimal(ms);
            write!(f, "{ms:.decimals$}ms")
        } else {
            // Seconds
            let decimals = sig_digits_after_decimal(total_secs);
            write!(f, "{total_secs:.decimals$}s")
        }
    }
}

/// Calculates how many decimal places to show for 5 significant digits.
///
/// Counts the number of digits before the decimal point, then returns `5 - that count`
/// (clamped to 0). For example, `12.345` has 2 digits before the decimal → 3 after = 5 total.
fn sig_digits_after_decimal(value: f64) -> usize {
    let before = if value < 1.0 {
        1
    } else {
        // value is always positive and < 1e6 in practice, so log10 fits in a u32
        #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let digits = (value.log10().floor() as u32) + 1;
        digits as usize
    };
    5usize.saturating_sub(before)
}

// =============================================================================
// Terminal output
// =============================================================================

/// Whether stderr should carry ANSI styling.
///
/// Resolved by `anstream` from the signals its macros use — is stderr a
/// terminal, `NO_COLOR`, `CLICOLOR{,_FORCE}`, `TERM` — so that what we render
/// ourselves (the type checker's diagnostics) agrees with the styling
/// `eprintln!` puts around it.
fn stderr_styled() -> bool {
    AutoStream::choice(&io::stderr()) != ColorChoice::Never
}

/// The same question for stdout, which is where rustyline writes the REPL
/// prompt. Asking about stderr instead would put escapes in `monty -i > out`.
fn stdout_styled() -> bool {
    AutoStream::choice(&io::stdout()) != ColorChoice::Never
}