agent86-core 1.2.3

The agent behind agent86: a safe agent runtime you can embed
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
//! Execution backends for command and Python tools, ported from Python's
//! `tools/sandbox/policy.py`, `subprocess_exec.py`, `docker_exec.py`, and
//! `executor.py`.
//!
//! The default restricted subprocess runs with the workspace as its working
//! directory, an allowlisted environment (so API keys never reach tool
//! processes), a hard timeout that kills the whole process tree, and capped
//! output. It is not true isolation; the opt-in Docker backend runs each command
//! in a throwaway container with no network, capped memory and CPU, and a PID limit.

use super::SandboxPolicy;
use crate::config::SandboxConfig;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::io::{Read, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};

/// Seconds to wait for the pipes to drain after a kill before giving up on the output.
const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
/// Seconds allowed for the `docker kill` that cleans up after a timeout.
const DOCKER_KILL_TIMEOUT: Duration = Duration::from_secs(10);
const CONTAINER_WORKDIR: &str = "/workspace";

/// Environment variables forwarded on every platform.
const ENV_ALLOWLIST_COMMON: &[&str] = &["PATH", "LANG", "LC_ALL", "PYTHONIOENCODING", "PYTHONUTF8"];
const ENV_ALLOWLIST_WINDOWS: &[&str] = &[
    "PATHEXT",
    "SYSTEMROOT",
    "WINDIR",
    "COMSPEC",
    "TEMP",
    "TMP",
    "HOMEDRIVE",
    "HOMEPATH",
    "USERPROFILE",
    "APPDATA",
    "LOCALAPPDATA",
    "NUMBER_OF_PROCESSORS",
    "PROCESSOR_ARCHITECTURE",
    "OS",
];
/// Without these, git, pip, and npm break on macOS and Linux.
const ENV_ALLOWLIST_POSIX: &[&str] = &[
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "TMPDIR",
    "TERM",
    "TZ",
    "SSL_CERT_FILE",
    "SSL_CERT_DIR",
    "REQUESTS_CA_BUNDLE",
    "CURL_CA_BUNDLE",
    "NODE_EXTRA_CA_CERTS",
];
/// Whole families that are safe one by one (locale categories, XDG directories).
const ENV_ALLOWLIST_PREFIXES: &[&str] = &["LC_", "XDG_"];
/// Substrings that mark a variable as a credential, refused even when passed through.
const SECRET_MARKERS: &[&str] = &[
    "TOKEN",
    "SECRET",
    "PASSWORD",
    "PASSWD",
    "CREDENTIAL",
    "API_KEY",
];
const SECRET_SUFFIXES: &[&str] = &["_KEY"];

/// The exact-name allowlist for this platform.
pub fn env_allowlist() -> Vec<&'static str> {
    let platform = if cfg!(windows) {
        ENV_ALLOWLIST_WINDOWS
    } else {
        ENV_ALLOWLIST_POSIX
    };
    ENV_ALLOWLIST_COMMON
        .iter()
        .chain(platform)
        .copied()
        .collect()
}

/// True if `name` looks like it holds a credential.
pub fn is_secret_name(name: &str) -> bool {
    let upper = name.to_uppercase();
    SECRET_MARKERS.iter().any(|marker| upper.contains(marker))
        || SECRET_SUFFIXES.iter().any(|suffix| upper.ends_with(suffix))
}

/// The environment a tool subprocess gets: the allowlist plus opted-in names,
/// never anything credential-shaped.
///
/// Windows environment names are case-insensitive; Python sees them uppercased,
/// so names are matched (and passed on) uppercased there.
pub fn scrubbed_env(
    passthrough: &[String],
    environment: impl IntoIterator<Item = (OsString, OsString)>,
) -> BTreeMap<OsString, OsString> {
    let normalize = |name: &str| {
        if cfg!(windows) {
            name.to_uppercase()
        } else {
            name.to_owned()
        }
    };
    let current: BTreeMap<String, OsString> = environment
        .into_iter()
        .filter_map(|(name, value)| Some((normalize(name.to_str()?), value)))
        .collect();
    let allowed = env_allowlist();

    let mut env = BTreeMap::new();
    for (name, value) in &current {
        let listed = allowed.contains(&name.as_str());
        let family = ENV_ALLOWLIST_PREFIXES
            .iter()
            .any(|prefix| name.starts_with(prefix))
            && !is_secret_name(name);
        if listed || family {
            env.insert(OsString::from(name), value.clone());
        }
    }
    for name in passthrough {
        if is_secret_name(name) {
            // A passthrough entry must not become a way to hand tool processes a key.
            continue;
        }
        if let Some(value) = current.get(&normalize(name)) {
            env.insert(OsString::from(normalize(name)), value.clone());
        }
    }
    env.entry(OsString::from("PYTHONIOENCODING"))
        .or_insert_with(|| OsString::from("utf-8"));
    env
}

/// What a command produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecResult {
    pub returncode: i32,
    pub stdout: String,
    pub stderr: String,
    pub timed_out: bool,
}

impl ExecResult {
    pub fn ok(&self) -> bool {
        self.returncode == 0 && !self.timed_out
    }
}

/// What to run: a shell command line, or an argv list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecRequest {
    Shell(String),
    Argv(Vec<String>),
}

/// The configured execution backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Executor {
    Subprocess,
    Docker(DockerExecutor),
}

impl Executor {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Subprocess => "subprocess",
            Self::Docker(_) => "docker",
        }
    }

    /// Run `request`; `secrets` are the user's secrets (`crate::vault`), set in the
    /// process's environment after the scrub, because the user granted them.
    pub fn run(
        &self,
        policy: &SandboxPolicy,
        request: &ExecRequest,
        stdin: Option<&str>,
        secrets: &[(String, String)],
    ) -> std::io::Result<ExecResult> {
        match self {
            Self::Subprocess => run_subprocess(policy, request, stdin, secrets),
            Self::Docker(docker) => Ok(docker.run(policy, request, stdin, secrets)),
        }
    }

    /// The argv that runs a Python snippet read from stdin, isolated from site config.
    ///
    /// Python uses its own interpreter (`sys.executable`); here it is the `python`
    /// on PATH on Windows, where `python3` is often the Microsoft Store stub, and
    /// `python3` elsewhere.
    pub fn python_argv(&self) -> Vec<String> {
        let interpreter = match self {
            Self::Docker(_) => "python",
            Self::Subprocess if cfg!(windows) => "python",
            Self::Subprocess => "python3",
        };
        vec![interpreter.to_owned(), "-I".to_owned(), "-".to_owned()]
    }
}

/// Pick the backend for `config`, with a note when Docker was requested but is unusable.
pub fn build_executor(config: &SandboxConfig) -> (Executor, Option<String>) {
    if config.mode != crate::config::SandboxMode::Docker {
        return (Executor::Subprocess, None);
    }
    if docker_available() {
        return (Executor::Docker(DockerExecutor::new(config)), None);
    }
    (
        Executor::Subprocess,
        Some(
            "Docker requested but not available; falling back to the subprocess sandbox."
                .to_owned(),
        ),
    )
}

/// Whether `docker info` succeeds within ten seconds.
pub fn docker_available() -> bool {
    let Ok(mut child) = Command::new("docker")
        .arg("info")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        match child.try_wait() {
            Ok(Some(status)) => return status.success(),
            Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
            _ => {
                let _ = child.kill();
                let _ = child.wait();
                return false;
            }
        }
    }
}

/// Decode process output as Python's text-mode pipes do: UTF-8 with replacement
/// and universal newlines.
fn decode(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes)
        .replace("\r\n", "\n")
        .replace('\r', "\n")
}

/// Encode stdin as Python's text-mode pipe does (`\n` becomes `\r\n` on Windows).
fn encode(text: &str) -> Vec<u8> {
    if cfg!(windows) {
        text.replace('\n', "\r\n").into_bytes()
    } else {
        text.as_bytes().to_vec()
    }
}

/// Build the `Command` for a request: `cmd.exe /c "..."` or `/bin/sh -c ...`, as
/// Python's `shell=True` does, or the argv as given.
fn command_for(request: &ExecRequest) -> Command {
    match request {
        ExecRequest::Shell(line) => shell_command(line),
        ExecRequest::Argv(argv) => {
            let mut command = Command::new(&argv[0]);
            command.args(&argv[1..]);
            command
        }
    }
}

#[cfg(windows)]
fn shell_command(line: &str) -> Command {
    use std::os::windows::process::CommandExt;
    let comspec = std::env::var_os("COMSPEC").unwrap_or_else(|| OsString::from("cmd.exe"));
    let mut command = Command::new(comspec);
    // Exactly the command line Python builds: `<comspec> /c "<command>"`.
    command.raw_arg(format!("/c \"{line}\""));
    command
}

#[cfg(not(windows))]
fn shell_command(line: &str) -> Command {
    let mut command = Command::new("/bin/sh");
    command.arg("-c").arg(line);
    command
}

/// Start the child at the head of its own process group, so the whole tree can be killed.
#[cfg(windows)]
fn new_process_group(command: &mut Command) {
    use std::os::windows::process::CommandExt;
    const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
    command.creation_flags(CREATE_NEW_PROCESS_GROUP);
}

#[cfg(unix)]
fn new_process_group(command: &mut Command) {
    use std::os::unix::process::CommandExt;
    command.process_group(0);
}

#[cfg(not(any(windows, unix)))]
fn new_process_group(_command: &mut Command) {}

/// Kill `child` and everything it spawned. Best effort, never fails.
fn kill_process_tree(child: &mut Child) {
    if matches!(child.try_wait(), Ok(Some(_))) {
        return;
    }
    let pid = child.id().to_string();
    let tree_kill = if cfg!(windows) {
        // A new process group alone does not cascade; taskkill /T walks the tree.
        Command::new("taskkill")
            .args(["/T", "/F", "/PID", &pid])
            .output()
    } else {
        // The child leads its own group, whose id is its pid.
        Command::new("kill")
            .args(["-KILL", "--", &format!("-{pid}")])
            .output()
    };
    drop(tree_kill);
    // Make sure the direct child is reaped even if the tree kill missed.
    let _ = child.kill();
}

/// How much of one pipe is kept (beyond Python, which keeps all of it). The
/// output is cut to `max_output_chars` afterwards anyway; this bounds what `yes`
/// or `cat /dev/zero` can pile up in memory before the timeout ends them.
pub const MAX_CAPTURE_BYTES: u64 = 8 * 1024 * 1024;

/// Read `pipe` to the end on a thread, reporting the bytes on `sender`.
fn reader<R: Read + Send + 'static>(pipe: R, sender: mpsc::Sender<(usize, Vec<u8>)>, index: usize) {
    std::thread::spawn(move || {
        let _ = sender.send((index, capture(pipe)));
    });
}

/// After a timed-out child was killed, wait up to `wait` ([`DRAIN_TIMEOUT`]) for its pipes to
/// close. A pipe a surviving grandchild still holds is given up on (left empty);
/// one that already closed keeps what it carried.
fn drain(
    receiver: &mpsc::Receiver<(usize, Vec<u8>)>,
    outputs: &mut [Option<Vec<u8>>; 2],
    wait: Duration,
) {
    let deadline = Instant::now() + wait;
    while outputs.iter().any(Option::is_none) {
        match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
            Ok((index, bytes)) => outputs[index] = Some(bytes),
            Err(_) => break,
        }
    }
}

/// The first [`MAX_CAPTURE_BYTES`] of `pipe`; the rest is read and dropped, so
/// the child never blocks on a full pipe and EOF still means it is done.
fn capture(mut pipe: impl Read) -> Vec<u8> {
    let mut bytes = Vec::new();
    let _ = (&mut pipe).take(MAX_CAPTURE_BYTES).read_to_end(&mut bytes);
    let _ = std::io::copy(&mut pipe, &mut std::io::sink());
    bytes
}

fn exit_code(status: std::process::ExitStatus) -> i32 {
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return -signal;
        }
    }
    status.code().unwrap_or(-1)
}

/// Run `request` in a restricted subprocess under `policy`.
///
/// Like Python's `communicate(timeout=...)`, the deadline covers both the process
/// exiting and its pipes closing: a backgrounded grandchild still holding stdout
/// counts as still running.
///
/// `secrets` join the environment after the scrub: the scrub keeps out keys the
/// process inherited, while these the user entered for the agent to use.
pub fn run_subprocess(
    policy: &SandboxPolicy,
    request: &ExecRequest,
    stdin: Option<&str>,
    secrets: &[(String, String)],
) -> std::io::Result<ExecResult> {
    let mut command = command_for(request);
    let mut env = scrubbed_env(&policy.env_passthrough, std::env::vars_os());
    for (name, value) in secrets {
        // Upper-cased on Windows, as `scrubbed_env` passes names, so a secret
        // replaces a variable of the same name rather than sitting beside it.
        let name = if cfg!(windows) {
            name.to_uppercase()
        } else {
            name.clone()
        };
        env.insert(OsString::from(name), OsString::from(value));
    }
    command
        .current_dir(super::plain_path(policy.workspace()))
        .env_clear()
        .envs(env)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    new_process_group(&mut command);
    let mut child = command.spawn()?;

    let input = stdin.map(encode).unwrap_or_default();
    if let Some(mut pipe) = child.stdin.take() {
        std::thread::spawn(move || {
            let _ = pipe.write_all(&input);
            // Dropping the pipe closes it, so the child sees end of input.
        });
    }
    let (sender, receiver) = mpsc::channel();
    if let Some(pipe) = child.stdout.take() {
        reader(pipe, sender.clone(), 0);
    }
    if let Some(pipe) = child.stderr.take() {
        reader(pipe, sender, 1);
    }

    let deadline = Instant::now() + policy.timeout;
    let mut outputs: [Option<Vec<u8>>; 2] = [None, None];
    let mut status = None;
    loop {
        while let Ok((index, bytes)) = receiver.try_recv() {
            outputs[index] = Some(bytes);
        }
        if status.is_none() {
            status = child.try_wait()?;
        }
        if let (Some(status), [Some(_), Some(_)]) = (status, &outputs) {
            let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
            return Ok(ExecResult {
                returncode: exit_code(status),
                stdout: policy.truncate(decode(&stdout)),
                stderr: policy.truncate(decode(&stderr)),
                timed_out: false,
            });
        }
        if Instant::now() >= deadline {
            break;
        }
        std::thread::sleep(Duration::from_millis(10));
    }

    // Timed out: kill the tree, then collect whatever it already wrote.
    kill_process_tree(&mut child);
    drain(&receiver, &mut outputs, DRAIN_TIMEOUT);
    let _ = child.wait();
    let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
    let seconds = policy.timeout.as_secs();
    Ok(ExecResult {
        returncode: 124,
        stdout: policy.truncate(decode(&stdout)),
        stderr: format!(
            "{}\n[timed out after {seconds}s]",
            policy.truncate(decode(&stderr))
        ),
        timed_out: true,
    })
}

/// Runs each command in a fresh, throwaway container via the `docker` CLI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DockerExecutor {
    pub image: String,
    pub memory: String,
    pub cpus: String,
    pub network: bool,
}

impl DockerExecutor {
    pub fn new(config: &SandboxConfig) -> Self {
        Self {
            image: config.docker_image.clone(),
            memory: config.docker_memory.clone(),
            cpus: config.docker_cpus.clone(),
            network: config.docker_network,
        }
    }

    /// The full `docker run ...` argv for `request`.
    pub fn build_command(
        &self,
        workspace: &Path,
        request: &ExecRequest,
        name: Option<&str>,
    ) -> Vec<String> {
        self.build_command_with_env(workspace, request, name, &[])
    }

    /// [`DockerExecutor::build_command`] passing the variables `env_names` into the
    /// container. Each is a bare `-e NAME`, so Docker reads the value from its own
    /// environment and it never appears in a process list.
    pub fn build_command_with_env(
        &self,
        workspace: &Path,
        request: &ExecRequest,
        name: Option<&str>,
        env_names: &[&str],
    ) -> Vec<String> {
        let mut command: Vec<String> = [
            "docker",
            "run",
            "--rm",
            "-i",
            "--memory",
            &self.memory,
            "--cpus",
            &self.cpus,
            "--pids-limit",
            "256",
            // Beyond Python: no capabilities but those writing the mounted workspace
            // (owned by the user, not the container's root) and installing packages
            // need, so no raw sockets, `mknod`, `chroot`, or capability games; and
            // setuid binaries gain nothing.
            "--cap-drop",
            "ALL",
            // One flag per capability: Docker refuses a comma-separated list.
            "--cap-add",
            "CHOWN",
            "--cap-add",
            "DAC_OVERRIDE",
            "--cap-add",
            "FOWNER",
            "--cap-add",
            "FSETID",
            "--cap-add",
            "SETUID",
            "--cap-add",
            "SETGID",
            "--security-opt",
            "no-new-privileges",
            "-w",
            CONTAINER_WORKDIR,
            "-v",
        ]
        .iter()
        .map(|part| (*part).to_owned())
        .collect();
        command.push(format!("{}:{CONTAINER_WORKDIR}", mount_source(workspace)));
        if !self.network {
            command.extend(["--network".to_owned(), "none".to_owned()]);
        }
        if let Some(name) = name {
            // The only handle on the container once `docker run` is killed.
            command.extend(["--name".to_owned(), name.to_owned()]);
        }
        for env_name in env_names {
            command.extend(["-e".to_owned(), (*env_name).to_owned()]);
        }
        command.push(self.image.clone());
        match request {
            ExecRequest::Shell(line) => {
                command.extend(["sh".to_owned(), "-c".to_owned(), line.clone()]);
            }
            ExecRequest::Argv(argv) => command.extend(argv.iter().cloned()),
        }
        command
    }

    fn run(
        &self,
        policy: &SandboxPolicy,
        request: &ExecRequest,
        stdin: Option<&str>,
        secrets: &[(String, String)],
    ) -> ExecResult {
        let name = format!("agent86-{}", crate::turn::new_session_id());
        let env_names: Vec<&str> = secrets.iter().map(|(name, _)| name.as_str()).collect();
        let argv =
            self.build_command_with_env(policy.workspace(), request, Some(&name), &env_names);
        let mut command = Command::new(&argv[0]);
        command
            .args(&argv[1..])
            .envs(secrets.iter().map(|(name, value)| (name, value)))
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let mut child = match command.spawn() {
            Ok(child) => child,
            Err(error) => {
                return ExecResult {
                    returncode: 127,
                    stdout: String::new(),
                    stderr: format!("docker not found: {error}"),
                    timed_out: false,
                };
            }
        };
        let input = stdin.map(encode).unwrap_or_default();
        if let Some(mut pipe) = child.stdin.take() {
            std::thread::spawn(move || {
                let _ = pipe.write_all(&input);
            });
        }
        let (sender, receiver) = mpsc::channel();
        if let Some(pipe) = child.stdout.take() {
            reader(pipe, sender.clone(), 0);
        }
        if let Some(pipe) = child.stderr.take() {
            reader(pipe, sender, 1);
        }

        let deadline = Instant::now() + policy.timeout;
        let mut outputs: [Option<Vec<u8>>; 2] = [None, None];
        loop {
            while let Ok((index, bytes)) = receiver.try_recv() {
                outputs[index] = Some(bytes);
            }
            if let (Ok(Some(status)), [Some(_), Some(_)]) = (child.try_wait(), &outputs) {
                let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
                return ExecResult {
                    returncode: exit_code(status),
                    stdout: policy.truncate(decode(&stdout)),
                    stderr: policy.truncate(decode(&stderr)),
                    timed_out: false,
                };
            }
            if Instant::now() >= deadline {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }

        // Killing the `docker run` client leaves the container running.
        let _ = child.kill();
        let _ = child.wait();
        let killed = kill_container(&name);
        let note = if killed {
            ""
        } else {
            " (container may still be running)"
        };
        // Beyond Python, which discards it: what the container printed before the
        // timeout is kept, as the subprocess executor keeps it.
        drain(&receiver, &mut outputs, DRAIN_TIMEOUT);
        let [stdout, stderr] = outputs.map(Option::unwrap_or_default);
        let stderr = policy.truncate(decode(&stderr));
        let timed_out = format!("[timed out after {}s]{note}", policy.timeout.as_secs());
        ExecResult {
            returncode: 124,
            stdout: policy.truncate(decode(&stdout)),
            stderr: if stderr.is_empty() {
                timed_out
            } else {
                format!("{stderr}\n{timed_out}")
            },
            timed_out: true,
        }
    }
}

/// Stop an orphaned container by name. Best effort.
fn kill_container(name: &str) -> bool {
    let Ok(mut child) = Command::new("docker")
        .args(["kill", name])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    let deadline = Instant::now() + DOCKER_KILL_TIMEOUT;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => return status.success(),
            Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(50)),
            _ => {
                let _ = child.kill();
                return false;
            }
        }
    }
}

/// A bind-mount source Docker accepts: `C:\Users\me\proj` becomes `/c/Users/me/proj`,
/// avoiding the drive colon that would confuse `-v src:dst`.
pub fn mount_source(workspace: &Path) -> String {
    let text = super::display_path(workspace).replace('\\', "/");
    let bytes = text.as_bytes();
    if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() {
        format!("/{}{}", (bytes[0] as char).to_ascii_lowercase(), &text[2..])
    } else {
        text
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A reader that counts what was taken from it.
    struct Counted<R> {
        inner: R,
        read: u64,
    }

    impl<R: Read> Read for Counted<R> {
        fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
            let count = self.inner.read(buffer)?;
            self.read += count as u64;
            Ok(count)
        }
    }

    #[test]
    fn a_flood_of_output_is_kept_to_the_cap_and_the_rest_drained() {
        let total = MAX_CAPTURE_BYTES * 3;
        let mut pipe = Counted {
            inner: std::io::repeat(b'y').take(total),
            read: 0,
        };
        let kept = capture(&mut pipe);
        assert_eq!(kept.len() as u64, MAX_CAPTURE_BYTES);
        assert_eq!(
            pipe.read, total,
            "everything was read, so the child never blocks"
        );
        assert_eq!(capture(&b"short"[..]), b"short");
    }

    #[test]
    fn a_pipe_still_held_after_a_timeout_does_not_wipe_the_one_that_finished() {
        let (sender, receiver) = mpsc::channel();
        // stdout finished; a grandchild keeps stderr open (its sender never sends).
        sender.send((0, b"partial output".to_vec())).unwrap();
        let _held = sender;
        let mut outputs = [None, None];
        drain(&receiver, &mut outputs, Duration::from_millis(50));
        assert_eq!(outputs[0].as_deref(), Some(&b"partial output"[..]));
        assert_eq!(outputs[1], None);
    }
}