Skip to main content

byob_plugins/
backend.rs

1//! A plugin's backend: one long-lived process the engine talks to in JSON lines (the wire
2//! format is in `docs/plugins-backend.md`).
3//!
4//! [`Backend`] owns the process. It starts lazily on first use (an event or a request) on a
5//! thread of its own, so nothing here blocks the caller: messages queue until it runs. A
6//! writer thread feeds stdin, a reader thread reads stdout (lines over [`MAX_LINE`] are
7//! dropped with a fault), a third keeps the last [`STDERR_KEEP`] bytes of stderr. Replies
8//! go straight to the waiting [`Backend::request`]; everything else goes to the [`Sink`]
9//! (the engine's inbox). A backend that exits is started again after a backoff (0.5 s,
10//! doubling to 30 s), at once when someone uses it, and given up on after [`MAX_CRASHES`]
11//! crashes in a row. [`Backend::stop`] (reload, switched off, removed, dropped) closes stdin
12//! and kills it if it doesn't exit within half a second. A waiter thread notices the process
13//! exiting even when something it started still holds its stdout; on Unix it runs in a
14//! process group of its own, killed with it. Faults reach the sink at most once a second
15//! (the rest are counted). Every thread runs under `catch_unwind`.
16
17use byob_types::process::NoWindow as _;
18use std::collections::{BTreeMap, BTreeSet, VecDeque};
19use std::ffi::OsString;
20use std::io::{self, BufRead, BufReader, Read, Write};
21use std::panic::{AssertUnwindSafe, catch_unwind};
22use std::path::{Path, PathBuf};
23use std::process::{Child, ChildStdin, Command, Stdio};
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, SyncSender, TrySendError, channel, sync_channel};
26use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
27use std::thread;
28use std::time::{Duration, Instant};
29
30use byob_tools::{Access, FileChange, Tool, ToolContext, ToolOutput, ToolSpec};
31use serde_json::{Value, json};
32
33use crate::PluginRef;
34use crate::manifest::{ManifestTool, path_inside};
35use crate::native::{NativeBackend, Outbox, dispatch, panic_text};
36
37/// The wire format's version (`init.v`).
38pub const WIRE_VERSION: u32 = 1;
39/// Longest line either way (one message).
40pub const MAX_LINE: usize = 1024 * 1024;
41/// Bytes of stderr kept.
42pub const STDERR_KEEP: usize = 16 * 1024;
43/// Faults kept (the newest).
44pub const MAX_FAULTS: usize = 8;
45/// Characters kept of one fault.
46const MAX_FAULT: usize = 2000;
47/// Messages kept while it starts, and waiting for a running one to read them; older
48/// ones are dropped while it starts, newer ones once it runs.
49const MAX_QUEUED: usize = 256;
50/// Bytes kept while it starts.
51const MAX_QUEUED_BYTES: usize = 16 * 1024 * 1024;
52/// Faults passed to the sink at most this often (the rest are counted in the next one).
53const FAULT_EVERY: Duration = Duration::from_secs(1);
54/// How often the waiter checks whether the process exited.
55const WAIT_POLL: Duration = Duration::from_millis(20);
56/// How long its output gets to be read after it exited.
57const DRAIN_GRACE: Duration = Duration::from_millis(500);
58/// How long a tool call waits for its reply.
59pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
60/// Crashes in a row after which it isn't started again (until its plugin reloads).
61pub const MAX_CRASHES: u32 = 5;
62/// Stack of a native backend's thread. Native backends may recurse on untrusted input in
63/// libraries byob doesn't control (IronCalc parses and evaluates formulas recursively), and
64/// running out of stack aborts the whole process rather than panicking; only the pages
65/// actually touched are committed.
66pub const NATIVE_STACK: usize = 64 * 1024 * 1024;
67const FIRST_BACKOFF: Duration = Duration::from_millis(500);
68const MAX_BACKOFF: Duration = Duration::from_secs(30);
69/// Running this long resets the crash count.
70const STABLE: Duration = Duration::from_secs(30);
71/// How long a stopped backend gets to exit before it is killed.
72const STOP_GRACE: Duration = Duration::from_millis(500);
73/// What the engine supports, sent in `init.caps`.
74pub const CAPS: [&str; 9] = ["event", "request", "reply", "view", "notify", "notice", "log", "fault", "web"];
75
76/// How to start the process (worked out on the start thread: it may build a venv).
77#[derive(Debug, Clone, Default)]
78pub struct Launch {
79    /// Program and arguments.
80    pub argv: Vec<OsString>,
81    pub cwd: PathBuf,
82    /// Added to the inherited environment.
83    pub env: BTreeMap<String, String>,
84    /// Removed from it.
85    pub remove_env: Vec<String>,
86}
87
88/// What a backend runs as: a process, or in-tree code on a thread ([`crate::native`]).
89pub enum Start {
90    Process(Launch),
91    Native(Box<dyn NativeBackend>),
92}
93
94impl From<Launch> for Start {
95    fn from(l: Launch) -> Self {
96        Self::Process(l)
97    }
98}
99
100/// Works out how to start it; its argument says the start was called off (the backend
101/// stopped), so a long preparation (a venv build) can give up.
102pub type Prepare = Box<dyn Fn(&dyn Fn() -> bool) -> Result<Start, String> + Send + Sync>;
103
104/// What a backend says that isn't a reply, and its lifecycle.
105#[derive(Debug, Clone, PartialEq)]
106pub enum Out {
107    /// A message (`view`, `notify`, `notice`, `log`, `fault`, or a newer type).
108    Msg(Value),
109    Started,
110    /// It exited or couldn't start: why.
111    Exited(String),
112}
113
114pub type Sink = Arc<dyn Fn(Out) + Send + Sync>;
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum Phase {
118    /// Not started yet.
119    Idle,
120    Starting,
121    Running,
122    /// Exited; starts again after a backoff or on the next use.
123    Crashed,
124    /// Couldn't start, or crashed too often: stays down until its plugin reloads.
125    Failed,
126    Stopped,
127}
128
129impl Phase {
130    pub fn label(self) -> &'static str {
131        match self {
132            Self::Idle => "idle",
133            Self::Starting => "starting",
134            Self::Running => "running",
135            Self::Crashed => "crashed",
136            Self::Failed => "failed",
137            Self::Stopped => "stopped",
138        }
139    }
140}
141
142/// A snapshot for status displays.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct Status {
145    pub phase: Phase,
146    pub pid: Option<u32>,
147    pub starts: u32,
148    /// Crashes in a row.
149    pub crashes: u32,
150    /// The kept stderr (and `log` lines).
151    pub stderr: String,
152    pub faults: Vec<String>,
153    /// Why it isn't running (exit, start failure).
154    pub error: Option<String>,
155    pub subscribed: Vec<String>,
156}
157
158type Reply = Result<Value, String>;
159
160struct Inner {
161    phase: Phase,
162    /// Bumped for every process started.
163    generation: u64,
164    writer: Option<SyncSender<Vec<u8>>>,
165    queued: VecDeque<Vec<u8>>,
166    queued_bytes: usize,
167    child: Option<Child>,
168    pid: Option<u32>,
169    pending: BTreeMap<u64, Sender<Reply>>,
170    next_id: u64,
171    stderr: Ring,
172    faults: VecDeque<String>,
173    subscribed: BTreeSet<String>,
174    starts: u32,
175    crashes: u32,
176    started_at: Option<Instant>,
177    error: Option<String>,
178    /// When a fault last went to the sink.
179    fault_posted: Option<Instant>,
180    /// Faults recorded since, not passed on yet.
181    fault_held: u32,
182    /// A thread will pass them on.
183    fault_flush: bool,
184}
185
186struct Shared {
187    plugin: String,
188    init: Value,
189    prepare: Prepare,
190    sink: Sink,
191    inner: Mutex<Inner>,
192}
193
194impl Shared {
195    fn lock(&self) -> MutexGuard<'_, Inner> {
196        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
197    }
198}
199
200/// One plugin backend (see the module docs). Stops its process when dropped.
201pub struct Backend {
202    shared: Arc<Shared>,
203}
204
205impl Backend {
206    /// `init` is the init message (sent first to every process, with `restart` added);
207    /// `events` the engine events it gets from the start.
208    pub fn new(plugin: &str, init: Value, events: &[String], prepare: Prepare, sink: Sink) -> Self {
209        let inner = Inner {
210            phase: Phase::Idle,
211            generation: 0,
212            writer: None,
213            queued: VecDeque::new(),
214            queued_bytes: 0,
215            child: None,
216            pid: None,
217            pending: BTreeMap::new(),
218            next_id: 1,
219            stderr: Ring::default(),
220            faults: VecDeque::new(),
221            subscribed: events.iter().cloned().collect(),
222            starts: 0,
223            crashes: 0,
224            started_at: None,
225            error: None,
226            fault_posted: None,
227            fault_held: 0,
228            fault_flush: false,
229        };
230        Self { shared: Arc::new(Shared { plugin: plugin.to_owned(), init, prepare, sink, inner: Mutex::new(inner) }) }
231    }
232
233    pub fn plugin(&self) -> &str {
234        &self.shared.plugin
235    }
236
237    /// It asked for engine event `event`.
238    pub fn wants(&self, event: &str) -> bool {
239        self.shared.lock().subscribed.contains(event)
240    }
241
242    pub fn status(&self) -> Status {
243        let g = self.shared.lock();
244        Status {
245            phase: g.phase,
246            pid: g.pid,
247            starts: g.starts,
248            crashes: g.crashes,
249            stderr: g.stderr.text(),
250            faults: g.faults.iter().cloned().collect(),
251            error: g.error.clone(),
252            subscribed: g.subscribed.iter().cloned().collect(),
253        }
254    }
255
256    /// Start it now if it isn't running (normally it starts on first use).
257    pub fn start(&self) {
258        let mut g = self.shared.lock();
259        if matches!(g.phase, Phase::Idle | Phase::Crashed) {
260            begin_start(&self.shared, &mut g);
261        }
262    }
263
264    /// Send an `event` message (`{"type": "event", "event": …, …}`), starting the backend if
265    /// needed. `false` if it can't take it (stopped, failed, too big).
266    pub fn event(&self, msg: Value) -> bool {
267        let Ok(line) = serde_json::to_vec(&msg) else { return false };
268        if line.len() > MAX_LINE {
269            log::warn!("plugin {}: an event over {MAX_LINE} bytes wasn't sent", self.shared.plugin);
270            return false;
271        }
272        let mut g = self.shared.lock();
273        if matches!(g.phase, Phase::Idle | Phase::Crashed) {
274            begin_start(&self.shared, &mut g);
275        }
276        push_line(&self.shared, &mut g, line).is_ok()
277    }
278
279    /// Ask it something and wait for the `reply` (or `timeout`, or `cancelled()`).
280    pub fn request(&self, method: &str, params: Value, timeout: Duration, cancelled: &dyn Fn() -> bool) -> Result<Value, String> {
281        let (tx, rx) = channel();
282        let id = {
283            let mut g = self.shared.lock();
284            match g.phase {
285                Phase::Stopped => return Err("the backend was stopped (its plugin changed, or was switched off or removed); try again".into()),
286                Phase::Failed => return Err(g.error.clone().unwrap_or_else(|| "the backend couldn't start".into())),
287                Phase::Idle | Phase::Crashed => begin_start(&self.shared, &mut g),
288                Phase::Starting | Phase::Running => {}
289            }
290            let id = g.next_id;
291            g.next_id = g.next_id.wrapping_add(1);
292            let line = serde_json::to_vec(&json!({"type": "request", "id": id, "method": method, "params": params})).map_err(|e| e.to_string())?;
293            if line.len() > MAX_LINE {
294                return Err(format!("the request is over {MAX_LINE} bytes"));
295            }
296            g.pending.insert(id, tx);
297            if let Err(why) = push_line(&self.shared, &mut g, line) {
298                g.pending.remove(&id);
299                return Err(why.into());
300            }
301            id
302        };
303        let started = Instant::now();
304        loop {
305            match rx.recv_timeout(Duration::from_millis(20)) {
306                Ok(r) => return r,
307                Err(RecvTimeoutError::Disconnected) => return Err("the backend went away".into()),
308                Err(RecvTimeoutError::Timeout) => {}
309            }
310            let gave_up = if cancelled() {
311                Some("Stopped by the user.".to_owned())
312            } else if started.elapsed() >= timeout {
313                Some(if timeout < Duration::from_secs(1) {
314                    format!("the backend didn't answer within {} ms", timeout.as_millis())
315                } else {
316                    format!("the backend didn't answer within {} seconds", timeout.as_secs())
317                })
318            } else {
319                None
320            };
321            if let Some(why) = gave_up {
322                let mut g = self.shared.lock();
323                g.pending.remove(&id);
324                if let Ok(line) = serde_json::to_vec(&json!({"type": "cancel", "id": id})) {
325                    let _ = push_line(&self.shared, &mut g, line);
326                }
327                return Err(why);
328            }
329        }
330    }
331
332    /// A problem byob found in what it sent (e.g. a view tree it had to fix): kept in its
333    /// status (`faults`) for the model and the user, and passed to the sink as a `fault`.
334    pub fn report_fault(&self, text: &str) {
335        fault(&self.shared, text.to_owned());
336    }
337
338    /// Hand `msg` to the sink as if the backend had sent it (the tool host uses this to pass
339    /// a tool's card on to the engine).
340    pub fn post(&self, msg: Value) {
341        (self.shared.sink)(Out::Msg(msg));
342    }
343
344    /// Stop the process for good (this object won't start it again).
345    pub fn stop(&self, why: &str) {
346        stop(&self.shared, why);
347    }
348}
349
350impl Drop for Backend {
351    fn drop(&mut self) {
352        stop(&self.shared, "the backend was stopped");
353    }
354}
355
356fn stop(shared: &Arc<Shared>, why: &str) {
357    let mut g = shared.lock();
358    if g.phase == Phase::Stopped {
359        return;
360    }
361    let was = g.phase;
362    g.phase = Phase::Stopped;
363    if let Some(tx) = g.writer.take()
364        && let Ok(line) = serde_json::to_vec(&json!({"type": "shutdown"}))
365    {
366        let _ = tx.try_send(line);
367    }
368    take_queued(&mut g);
369    g.pid = None;
370    let child = g.child.take();
371    for (_, tx) in std::mem::take(&mut g.pending) {
372        let _ = tx.send(Err(why.to_owned()));
373    }
374    drop(g);
375    if let Some(child) = child {
376        log::info!("plugin {}: stopping its backend ({why})", shared.plugin);
377        guarded("byob-backend-stop", move || {
378            reap(child, STOP_GRACE);
379        });
380    } else if was != Phase::Idle {
381        log::info!("plugin {}: backend stopped ({why})", shared.plugin);
382    }
383}
384
385/// Wait up to `grace` for `child` to exit, then kill it; either way kill what is left of
386/// its process group. Returns how it ended.
387fn reap(mut child: Child, grace: Duration) -> String {
388    let pid = child.id();
389    let deadline = Instant::now() + grace;
390    let how = loop {
391        match child.try_wait() {
392            Ok(Some(status)) => break exit_text(status),
393            Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
394            _ => {
395                // the group before the leader is reaped, so its id can't be reused yet
396                byob_sandbox::kill_group(pid);
397                let _ = child.kill();
398                break child.wait().map_or_else(|e| e.to_string(), exit_text);
399            }
400        }
401    };
402    byob_sandbox::kill_group(pid);
403    how
404}
405
406fn exit_text(status: std::process::ExitStatus) -> String {
407    match status.code() {
408        Some(c) => format!("exit code {c}"),
409        None => "killed by a signal".into(),
410    }
411}
412
413/// Queue one line: to the writer when running (dropped, with a fault, when it isn't
414/// reading), kept while starting (the oldest dropped past [`MAX_QUEUED`] or
415/// [`MAX_QUEUED_BYTES`]).
416fn push_line(shared: &Arc<Shared>, g: &mut Inner, line: Vec<u8>) -> Result<(), &'static str> {
417    const NOT_RUNNING: &str = "the backend isn't running";
418    match g.phase {
419        Phase::Running => match &g.writer {
420            Some(tx) => match tx.try_send(line) {
421                Ok(()) => Ok(()),
422                Err(TrySendError::Full(_)) => {
423                    record_fault(shared, g, format!("it isn't reading its input: {MAX_QUEUED} messages wait, so one was dropped"), false);
424                    Err("the backend isn't reading its input (too many messages wait); the message was dropped")
425                }
426                Err(TrySendError::Disconnected(_)) => Err(NOT_RUNNING),
427            },
428            None => Err(NOT_RUNNING),
429        },
430        Phase::Starting => {
431            let mut dropped = false;
432            while g.queued.len() >= MAX_QUEUED || (!g.queued.is_empty() && g.queued_bytes.saturating_add(line.len()) > MAX_QUEUED_BYTES) {
433                let Some(old) = g.queued.pop_front() else { break };
434                g.queued_bytes = g.queued_bytes.saturating_sub(old.len());
435                dropped = true;
436            }
437            if dropped {
438                log::warn!("plugin {}: its backend is slow to start; an old message was dropped", shared.plugin);
439            }
440            g.queued_bytes = g.queued_bytes.saturating_add(line.len());
441            g.queued.push_back(line);
442            Ok(())
443        }
444        Phase::Idle | Phase::Crashed | Phase::Failed | Phase::Stopped => Err(NOT_RUNNING),
445    }
446}
447
448/// Empty the start queue.
449fn take_queued(g: &mut Inner) -> VecDeque<Vec<u8>> {
450    g.queued_bytes = 0;
451    std::mem::take(&mut g.queued)
452}
453
454fn begin_start(shared: &Arc<Shared>, g: &mut Inner) {
455    g.phase = Phase::Starting;
456    let shared = Arc::clone(shared);
457    guarded("byob-backend-start", move || start_now(&shared));
458}
459
460/// What [`start_now`] got going.
461enum Running {
462    Process(Spawned),
463    Native(Box<dyn NativeBackend>),
464}
465
466fn start_now(shared: &Arc<Shared>) {
467    let called_off = || shared.lock().phase != Phase::Starting;
468    let prepared = catch_unwind(AssertUnwindSafe(|| (shared.prepare)(&called_off)));
469    let spawned = prepared.unwrap_or_else(|_| Err("preparing the backend crashed".into())).and_then(|s| match s {
470        Start::Process(l) => spawn(&l).map(Running::Process),
471        Start::Native(n) => Ok(Running::Native(n)),
472    });
473    let mut g = shared.lock();
474    if g.phase != Phase::Starting {
475        // stopped while it started
476        if let Ok(Running::Process((child, ..))) = spawned {
477            drop(g);
478            reap(child, Duration::ZERO);
479        }
480        return;
481    }
482    let running = match spawned {
483        Ok(parts) => parts,
484        Err(e) => {
485            g.phase = Phase::Failed;
486            g.error = Some(e.clone());
487            take_queued(&mut g);
488            for (_, tx) in std::mem::take(&mut g.pending) {
489                let _ = tx.send(Err(e.clone()));
490            }
491            drop(g);
492            log::warn!("plugin {}: its backend couldn't start: {e}", shared.plugin);
493            (shared.sink)(Out::Exited(e));
494            return;
495        }
496    };
497    g.generation = g.generation.wrapping_add(1);
498    let generation = g.generation;
499    // room for init, the start queue and a shutdown
500    let (tx, rx) = sync_channel::<Vec<u8>>(MAX_QUEUED + 2);
501    let mut init = shared.init.clone();
502    if let Some(o) = init.as_object_mut() {
503        o.insert("restart".into(), json!(g.starts));
504    }
505    if let Ok(line) = serde_json::to_vec(&init) {
506        let _ = tx.try_send(line);
507    }
508    for line in take_queued(&mut g) {
509        let _ = tx.try_send(line);
510    }
511    g.writer = Some(tx);
512    g.phase = Phase::Running;
513    g.starts = g.starts.saturating_add(1);
514    g.started_at = Some(Instant::now());
515    g.error = None;
516    let (child, stdin, stdout, stderr) = match running {
517        Running::Process(parts) => parts,
518        Running::Native(backend) => {
519            drop(g);
520            log::info!("plugin {}: native backend started", shared.plugin);
521            let s = Arc::clone(shared);
522            guarded_with_stack("byob-backend-native", NATIVE_STACK, move || {
523                let how = native_loop(&s, backend, &rx);
524                exited(&s, generation, &how);
525            });
526            (shared.sink)(Out::Started);
527            return;
528        }
529    };
530    let pid = child.id();
531    g.pid = Some(pid);
532    g.child = Some(child);
533    drop(g);
534    log::info!("plugin {}: backend started", shared.plugin);
535    let out_done = Arc::new(AtomicBool::new(false));
536    let err_done = Arc::new(AtomicBool::new(false));
537    guarded("byob-backend-in", move || write_loop(stdin, &rx));
538    let (s, done) = (Arc::clone(shared), Arc::clone(&err_done));
539    guarded("byob-backend-err", move || {
540        let _ = catch_unwind(AssertUnwindSafe(|| stderr_loop(stderr, &s, generation)));
541        done.store(true, Ordering::SeqCst);
542    });
543    let (s, done) = (Arc::clone(shared), Arc::clone(&out_done));
544    guarded("byob-backend-out", move || {
545        let read = catch_unwind(AssertUnwindSafe(|| read_loop(stdout, &s, generation)));
546        if read.is_err() {
547            log::error!("plugin {}: the backend reader crashed", s.plugin);
548        }
549        done.store(true, Ordering::SeqCst);
550    });
551    let s = Arc::clone(shared);
552    guarded("byob-backend-wait", move || wait_loop(&s, generation, pid, &out_done, &err_done));
553    (shared.sink)(Out::Started);
554}
555
556/// Watch the process of `generation` until it exits (or closes its stdout, or is stopped),
557/// then let the readers finish its output and report it [`exited`]. Its process group goes
558/// too, so nothing it started keeps the pipes (and the reader threads) alive.
559fn wait_loop(shared: &Arc<Shared>, generation: u64, pid: u32, out_done: &AtomicBool, err_done: &AtomicBool) {
560    let ended = loop {
561        thread::sleep(WAIT_POLL);
562        let mut g = shared.lock();
563        if g.generation != generation || g.phase != Phase::Running {
564            return; // stopped: stop() reaps it
565        }
566        let Some(child) = g.child.as_mut() else { return };
567        match child.try_wait() {
568            Ok(Some(status)) => {
569                g.child = None;
570                break Ok(exit_text(status));
571            }
572            Ok(None) if !out_done.load(Ordering::SeqCst) => {}
573            // it closed stdout (or can't be waited for): a moment to exit, then killed
574            Ok(None) | Err(_) => break Err(g.child.take()),
575        }
576    };
577    let how = match ended {
578        Ok(how) => {
579            byob_sandbox::kill_group(pid);
580            how
581        }
582        Err(Some(child)) => reap(child, Duration::from_secs(2)),
583        Err(None) => "it ended".to_owned(),
584    };
585    let deadline = Instant::now() + DRAIN_GRACE;
586    while !(out_done.load(Ordering::SeqCst) && err_done.load(Ordering::SeqCst)) && Instant::now() < deadline {
587        thread::sleep(Duration::from_millis(5));
588    }
589    exited(shared, generation, &how);
590}
591
592type Spawned = (Child, ChildStdin, std::process::ChildStdout, std::process::ChildStderr);
593
594fn spawn(l: &Launch) -> Result<Spawned, String> {
595    let Some((program, args)) = l.argv.split_first() else { return Err("no command to start".into()) };
596    let mut cmd = Command::new(program);
597    cmd.no_window();
598    cmd.args(args).current_dir(&l.cwd).envs(&l.env).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
599    // a group of its own, so what it starts is stopped with it
600    #[cfg(unix)]
601    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
602    for k in &l.remove_env {
603        cmd.env_remove(k);
604    }
605    let mut child = cmd.spawn().map_err(|e| format!("couldn't start {}: {e}", Path::new(program).display()))?;
606    match (child.stdin.take(), child.stdout.take(), child.stderr.take()) {
607        (Some(i), Some(o), Some(e)) => Ok((child, i, o, e)),
608        _ => {
609            reap(child, Duration::ZERO);
610            Err("no pipes to the backend".into())
611        }
612    }
613}
614
615/// Run a native backend on the lines byob sends until `shutdown` (or the channel closes on
616/// a stop), each call under `catch_unwind`; returns how it ended. Its messages go through
617/// the same handling as a process's stdout lines.
618fn native_loop(shared: &Arc<Shared>, mut backend: Box<dyn NativeBackend>, rx: &Receiver<Vec<u8>>) -> String {
619    let s = Arc::clone(shared);
620    let out = Outbox::new(move |msg: Value| {
621        let size = serde_json::to_vec(&msg).map_or(0, |v| v.len());
622        if size > MAX_LINE {
623            fault(&s, format!("a message over {MAX_LINE} bytes was dropped"));
624        } else if msg.is_object() {
625            handle_msg(&s, msg);
626        }
627    });
628    for line in rx {
629        let Ok(msg) = serde_json::from_slice::<Value>(&line) else { continue };
630        match catch_unwind(AssertUnwindSafe(|| dispatch(backend.as_mut(), &msg, &out))) {
631            Ok(true) => {}
632            Ok(false) => return "it shut down".into(),
633            Err(p) => {
634                let text = panic_text(p.as_ref());
635                shared.lock().stderr.push(format!("(panic) {text}\n").as_bytes());
636                fault(shared, format!("the native backend panicked: {text}"));
637                return format!("it panicked: {text}");
638            }
639        }
640    }
641    "it ended".into()
642}
643
644fn write_loop(mut stdin: ChildStdin, rx: &Receiver<Vec<u8>>) {
645    for mut line in rx {
646        line.push(b'\n');
647        if stdin.write_all(&line).and_then(|()| stdin.flush()).is_err() {
648            return;
649        }
650    }
651}
652
653fn stderr_loop(mut stderr: impl Read, shared: &Shared, generation: u64) {
654    let mut buf = [0u8; 4096];
655    loop {
656        match stderr.read(&mut buf) {
657            Ok(0) => return,
658            Ok(n) => {
659                let mut g = shared.lock();
660                if g.generation != generation {
661                    return; // a newer process runs
662                }
663                g.stderr.push(buf.get(..n).unwrap_or_default());
664            }
665            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
666            Err(_) => return,
667        }
668    }
669}
670
671fn read_loop(stdout: impl Read, shared: &Arc<Shared>, generation: u64) {
672    let mut r = BufReader::new(stdout);
673    let mut buf = Vec::new();
674    loop {
675        let line = read_line(&mut r, &mut buf, MAX_LINE);
676        if shared.lock().generation != generation {
677            return; // a newer process runs: this one's leftovers are stale
678        }
679        match line {
680            Ok(LineRead::Line) => handle_line(shared, &buf),
681            Ok(LineRead::TooLong) => fault(shared, format!("a message over {MAX_LINE} bytes was dropped")),
682            Ok(LineRead::Eof) | Err(_) => return,
683        }
684    }
685}
686
687/// Keep a fault in the status and pass it to the sink, at most once per [`FAULT_EVERY`]:
688/// faults in between are passed on together after it (the newest, with how many more).
689fn fault(shared: &Arc<Shared>, text: String) {
690    let post = record_fault(shared, &mut shared.lock(), text, true);
691    if let Some(text) = post {
692        post_fault(shared, &text);
693    }
694}
695
696/// [`fault`] for a caller holding the lock: returns the text to post now (only if
697/// `may_post`; else a thread posts it).
698fn record_fault(shared: &Arc<Shared>, g: &mut Inner, text: String, may_post: bool) -> Option<String> {
699    let text: String = text.chars().take(MAX_FAULT).collect();
700    if g.faults.len() >= MAX_FAULTS {
701        g.faults.pop_front();
702    }
703    g.faults.push_back(text.clone());
704    let wait = g.fault_posted.map_or(Duration::ZERO, |t| FAULT_EVERY.saturating_sub(t.elapsed()));
705    if may_post && wait.is_zero() && !g.fault_flush {
706        g.fault_posted = Some(Instant::now());
707        return Some(text);
708    }
709    g.fault_held = g.fault_held.saturating_add(1);
710    if !g.fault_flush {
711        g.fault_flush = true;
712        let s = Arc::clone(shared);
713        guarded("byob-backend-faults", move || {
714            thread::sleep(wait);
715            flush_faults(&s);
716        });
717    }
718    None
719}
720
721/// Pass on the faults held back: the newest, and how many more there were.
722fn flush_faults(shared: &Shared) {
723    let text = {
724        let mut g = shared.lock();
725        g.fault_flush = false;
726        let held = std::mem::take(&mut g.fault_held);
727        if held == 0 {
728            return;
729        }
730        g.fault_posted = Some(Instant::now());
731        let last = g.faults.back().cloned().unwrap_or_default();
732        if held > 1 { format!("{last} ({} more)", held - 1) } else { last }
733    };
734    post_fault(shared, &text);
735}
736
737fn post_fault(shared: &Shared, text: &str) {
738    log::warn!("plugin {}: {text}", shared.plugin);
739    (shared.sink)(Out::Msg(json!({"type": "fault", "text": text})));
740}
741
742fn handle_line(shared: &Arc<Shared>, line: &[u8]) {
743    if line.iter().all(u8::is_ascii_whitespace) {
744        return;
745    }
746    let msg = match serde_json::from_slice::<Value>(line) {
747        Ok(v @ Value::Object(_)) => v,
748        _ => {
749            let text = String::from_utf8_lossy(line);
750            shared.lock().stderr.push(format!("(stdout) {text}\n").as_bytes());
751            let short: String = text.chars().take(200).collect();
752            fault(shared, format!("stdout is for protocol messages (JSON objects, one per line); this isn't one: {short}"));
753            return;
754        }
755    };
756    handle_msg(shared, msg);
757}
758
759/// One message from the backend (a process's line, or a native backend's [`Outbox`]).
760fn handle_msg(shared: &Arc<Shared>, msg: Value) {
761    let kind = msg.get("type").and_then(Value::as_str).unwrap_or_default();
762    match kind {
763        "reply" => {
764            let Some(id) = msg.get("id").and_then(Value::as_u64) else {
765                fault(shared, "a reply without a numeric id".into());
766                return;
767            };
768            let tx = shared.lock().pending.remove(&id);
769            let Some(tx) = tx else { return };
770            let result = match msg.get("error").filter(|e| !e.is_null()) {
771                Some(Value::String(e)) => Err(e.clone()),
772                Some(e) => Err(e.to_string()),
773                None => Ok(msg.get("result").cloned().unwrap_or(Value::Null)),
774            };
775            let _ = tx.send(result);
776        }
777        "fault" => {
778            let text = msg.get("text").map(|t| t.as_str().map_or_else(|| t.to_string(), str::to_owned)).unwrap_or_default();
779            fault(shared, text);
780        }
781        "log" => {
782            let text = msg.get("text").and_then(Value::as_str).unwrap_or_default();
783            shared.lock().stderr.push(format!("(log) {text}\n").as_bytes());
784            log::info!("plugin {}: {}", shared.plugin, text.chars().take(500).collect::<String>());
785        }
786        "subscribe" | "unsubscribe" => {
787            let events: Vec<String> = msg.get("events").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
788            let unknown: Vec<&String> = events.iter().filter(|e| !crate::manifest::BACKEND_EVENTS.contains(&e.as_str())).collect();
789            if !unknown.is_empty() {
790                fault(shared, format!("no such engine events: {unknown:?} (there are {})", crate::manifest::BACKEND_EVENTS.join(", ")));
791            }
792            let mut g = shared.lock();
793            for e in events.iter().filter(|e| crate::manifest::BACKEND_EVENTS.contains(&e.as_str())) {
794                if kind == "subscribe" {
795                    g.subscribed.insert(e.clone());
796                } else {
797                    g.subscribed.remove(e);
798                }
799            }
800        }
801        _ => (shared.sink)(Out::Msg(msg)),
802    }
803}
804
805/// The backend of `generation` ended (`how`; its process, if any, is reaped).
806fn exited(shared: &Arc<Shared>, generation: u64, how: &str) {
807    let mut g = shared.lock();
808    if g.generation != generation || g.phase != Phase::Running {
809        return;
810    }
811    g.writer = None;
812    g.pid = None;
813    g.child = None;
814    let tail = g.stderr.last_lines(15);
815    let mut why = format!("the backend exited ({how})");
816    if !tail.is_empty() {
817        why.push_str(&format!("; its last output:\n{tail}"));
818    }
819    let stable = g.started_at.is_some_and(|t| t.elapsed() >= STABLE);
820    g.crashes = if stable { 1 } else { g.crashes.saturating_add(1) };
821    for (_, tx) in std::mem::take(&mut g.pending) {
822        let _ = tx.send(Err(why.clone()));
823    }
824    let crashes = g.crashes;
825    if crashes >= MAX_CRASHES {
826        g.phase = Phase::Failed;
827        why.push_str(&format!("\nIt exited {crashes} times in a row, so byob stopped starting it; fix it and reload the plugin."));
828    } else {
829        g.phase = Phase::Crashed;
830        let backoff = FIRST_BACKOFF.saturating_mul(1 << crashes.saturating_sub(1).min(8)).min(MAX_BACKOFF);
831        let s = Arc::clone(shared);
832        guarded("byob-backend-retry", move || {
833            thread::sleep(backoff);
834            let mut g = s.lock();
835            if g.phase == Phase::Crashed && g.generation == generation {
836                begin_start(&s, &mut g);
837            }
838        });
839    }
840    g.error = Some(why.clone());
841    drop(g);
842    log::warn!("plugin {}: {why}", shared.plugin);
843    (shared.sink)(Out::Exited(why));
844}
845
846fn guarded(name: &str, work: impl FnOnce() + Send + 'static) {
847    guarded_with_stack(name, 0, work);
848}
849
850/// [`guarded`] on a thread with a `stack`-byte stack (0: the default).
851fn guarded_with_stack(name: &str, stack: usize, work: impl FnOnce() + Send + 'static) {
852    let label = name.to_owned();
853    let builder = thread::Builder::new().name(name.into());
854    let builder = if stack > 0 { builder.stack_size(stack) } else { builder };
855    let spawned = builder.spawn(move || {
856        if catch_unwind(AssertUnwindSafe(work)).is_err() {
857            log::error!("{label} crashed");
858        }
859    });
860    if let Err(e) = spawned {
861        log::error!("could not start {name}: {e}");
862    }
863}
864
865/// The tail of a stream, bounded.
866#[derive(Default)]
867struct Ring(VecDeque<u8>);
868
869impl Ring {
870    fn push(&mut self, bytes: &[u8]) {
871        let bytes = bytes.get(bytes.len().saturating_sub(STDERR_KEEP)..).unwrap_or_default();
872        let overflow = (self.0.len() + bytes.len()).saturating_sub(STDERR_KEEP);
873        self.0.drain(..overflow.min(self.0.len()));
874        self.0.extend(bytes);
875    }
876
877    fn text(&self) -> String {
878        let (a, b) = self.0.as_slices();
879        let mut v = Vec::with_capacity(a.len() + b.len());
880        v.extend_from_slice(a);
881        v.extend_from_slice(b);
882        String::from_utf8_lossy(&v).into_owned()
883    }
884
885    fn last_lines(&self, n: usize) -> String {
886        last_lines(&self.text(), n)
887    }
888}
889
890/// The last `n` lines of `text`, trimmed.
891pub fn last_lines(text: &str, n: usize) -> String {
892    let lines: Vec<&str> = text.trim_end().lines().collect();
893    lines.get(lines.len().saturating_sub(n)..).unwrap_or_default().join("\n")
894}
895
896#[derive(Debug, PartialEq, Eq)]
897enum LineRead {
898    Line,
899    TooLong,
900    Eof,
901}
902
903/// Read one line into `buf` (cleared first), holding at most `max` bytes; longer lines are
904/// consumed and dropped.
905fn read_line(r: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> io::Result<LineRead> {
906    buf.clear();
907    let mut overflow = false;
908    let mut any = false;
909    loop {
910        let avail = match r.fill_buf() {
911            Ok(b) => b,
912            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
913            Err(e) => return Err(e),
914        };
915        if avail.is_empty() {
916            return Ok(match (overflow, any) {
917                (true, _) => LineRead::TooLong,
918                (false, true) => LineRead::Line,
919                (false, false) => LineRead::Eof,
920            });
921        }
922        any = true;
923        let newline = avail.iter().position(|&b| b == b'\n');
924        let (chunk, used) = match newline {
925            Some(i) => (avail.split_at(i).0, i.saturating_add(1)),
926            None => (avail, avail.len()),
927        };
928        if !overflow {
929            if buf.len().saturating_add(chunk.len()) > max {
930                overflow = true;
931                buf.clear();
932                buf.shrink_to(64 * 1024);
933            } else {
934                buf.extend_from_slice(chunk);
935            }
936        }
937        r.consume(used);
938        if newline.is_some() {
939            if buf.last() == Some(&b'\r') {
940                buf.pop();
941            }
942            return Ok(if overflow { LineRead::TooLong } else { LineRead::Line });
943        }
944    }
945}
946
947/// A tool a plugin's backend serves (`"run": "backend"`): each call is a `tool` request.
948pub struct BackendTool {
949    name: String,
950    plugin: PluginRef,
951    decl: ManifestTool,
952    backend: Arc<Backend>,
953    timeout: Duration,
954    /// The chat's artifact types, for the versions its results save.
955    types: byob_tools::ArtifactTypes,
956    /// The plugin's card views: (id, a web view).
957    cards: Vec<(String, bool)>,
958}
959
960impl BackendTool {
961    pub fn new(name: String, plugin: PluginRef, decl: ManifestTool, backend: Arc<Backend>) -> Self {
962        Self { name, plugin, decl, backend, timeout: REQUEST_TIMEOUT, types: byob_tools::ArtifactTypes::builtin(), cards: Vec::new() }
963    }
964
965    /// The card views its plugin declares (`views` with `"site": "card"`): (id, web view).
966    pub fn with_cards(mut self, cards: Vec<(String, bool)>) -> Self {
967        self.cards = cards;
968        self
969    }
970
971    /// Save the artifact versions its results carry with these types (the chat's).
972    pub fn with_types(mut self, types: byob_tools::ArtifactTypes) -> Self {
973        self.types = types;
974        self
975    }
976
977    pub fn with_timeout(mut self, timeout: Duration) -> Self {
978        self.timeout = timeout;
979        self
980    }
981
982    pub fn declared(&self) -> &ManifestTool {
983        &self.decl
984    }
985}
986
987impl Tool for BackendTool {
988    fn spec(&self) -> ToolSpec {
989        ToolSpec { name: self.name.clone(), description: self.decl.description.clone(), parameters: self.decl.params.clone() }
990    }
991
992    fn title(&self, args: &Value) -> String {
993        match &self.decl.title {
994            Some(t) => crate::python::fill_title(t, args),
995            None => format!("Used {}: {}", self.plugin.name, self.decl.name),
996        }
997    }
998
999    /// The declared title too while it runs, on approval cards and when it fails (not
1000    /// "Run describe_sheet").
1001    fn pending_title(&self, args: &Value) -> String {
1002        match &self.decl.title {
1003            Some(t) => crate::python::fill_title(t, args),
1004            None => format!("Use {}: {}", self.plugin.name, self.decl.name),
1005        }
1006    }
1007
1008    fn access(&self, _args: &Value) -> Access {
1009        self.decl.access.unwrap_or(Access::Execute)
1010    }
1011
1012    fn always_ask(&self, args: &Value) -> Option<String> {
1013        self.decl.confirm.as_ref()?.applies(args)
1014    }
1015
1016    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
1017        let args = if args.is_object() { args.clone() } else { Value::Object(serde_json::Map::new()) };
1018        let params = json!({
1019            "name": self.decl.name,
1020            "args": args,
1021            "workspace": ctx.workspace.display().to_string(),
1022            "chat": ctx.chat(),
1023        });
1024        match self.backend.request("tool", params, self.timeout, &|| ctx.cancelled()) {
1025            Ok(v) => {
1026                self.attach_card(&v, ctx);
1027                let mut out = tool_output(v.clone(), ctx.workspace);
1028                save_artifacts(&v, &self.types, ctx, &mut out);
1029                out
1030            }
1031            Err(e) if e.starts_with("Stopped by the user") => ToolOutput::err(e),
1032            Err(e) => ToolOutput::err(format!("{} (backend) ran into a problem:\n{e}", self.plugin.name)),
1033        }
1034    }
1035}
1036
1037impl BackendTool {
1038    /// A tool reply's card (`{"text": …, "card": <view tree>, "card_view"?: id, "card_key"?:
1039    /// k}`) goes onto the call's step (through `ctx`, so it lands on this call's step and
1040    /// nowhere else). A tree card is also posted to the engine (`CARD_MSG`) to be cached as
1041    /// the live view it owns; a web card's page gets the card's data.
1042    fn attach_card(&self, v: &Value, ctx: &ToolContext<'_>) {
1043        let Some(o) = v.as_object() else { return };
1044        let Some(tree) = o.get("card").filter(|c| c.is_object()) else { return };
1045        let card = match o.get("card_view").and_then(Value::as_str) {
1046            Some(want) => match self.cards.iter().find(|(id, _)| id == want) {
1047                Some(c) => c,
1048                None => {
1049                    let ids: Vec<&str> = self.cards.iter().map(|(id, _)| id.as_str()).collect();
1050                    self.backend.report_fault(&format!("card_view {want:?} isn't a card view in byob-plugin.json (card views: {})", ids.join(", ")));
1051                    return;
1052                }
1053            },
1054            None => match self.cards.first() {
1055                Some(c) => c,
1056                None => {
1057                    self.backend.report_fault("a tool returned a \"card\", but byob-plugin.json declares no view with \"site\": \"card\"");
1058                    return;
1059                }
1060            },
1061        };
1062        let (view, web) = (card.0.clone(), card.1);
1063        let key = match o.get("card_key").and_then(Value::as_str) {
1064            Some(k) if !k.is_empty() => k.chars().take(byob_protocol::sites::MAX_VIEW_KEY_CHARS).collect(),
1065            _ => format!("{}-{}", self.name, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos())),
1066        };
1067        if web {
1068            let text = o.get("text").and_then(Value::as_str).unwrap_or_default().to_owned();
1069            let card = byob_protocol::web::WebCard { plugin: self.plugin.id.clone(), view, key, data: tree.clone(), text };
1070            ctx.attach_view(byob_protocol::View::of(&card));
1071            return;
1072        }
1073        let (node, _faults) = byob_protocol::tree::decode(tree.clone());
1074        let mut shown = byob_protocol::View::of(&node);
1075        shown.owner = Some(byob_protocol::ViewRef::new(&self.plugin.id, &view, &key));
1076        // Only while a step takes it: a call from the plugin's own page shows no card.
1077        if ctx.attach_view(shown) {
1078            self.backend.post(json!({"type": CARD_MSG, "view": view, "key": key, "tree": tree}));
1079        }
1080    }
1081}
1082
1083/// The sink message type of a tree card a backend tool attached to its step (`{"type":
1084/// "_tool_card", "view", "key", "tree"}`): the engine caches it as a live view.
1085pub const CARD_MSG: &str = "_tool_card";
1086
1087/// Most artifact versions one tool result saves (a sheet and the charts drawn from it).
1088const MAX_SAVED: usize = 12;
1089
1090/// A tool reply's `artifact` (or `artifacts`, a list): `{"id"?, "title"?, "filename"?,
1091/// "file", "note"?}` — `file` is a path (absolute, or in the workspace) whose bytes become a
1092/// new version of artifact `id` (a new artifact without one). Each saved version is a file
1093/// change of the call (so the step shows the artifact and clients hear of it) and a line
1094/// for the model; a failure is a line too.
1095fn save_artifacts(v: &Value, types: &byob_tools::ArtifactTypes, ctx: &ToolContext<'_>, out: &mut ToolOutput) {
1096    let Some(o) = v.as_object() else { return };
1097    let items: Vec<&Value> = match (o.get("artifact"), o.get("artifacts")) {
1098        (Some(a), _) if a.is_object() => vec![a],
1099        (_, Some(Value::Array(list))) => list.iter().filter(|a| a.is_object()).take(MAX_SAVED).collect(),
1100        _ => return,
1101    };
1102    let chat = ctx.chat().unwrap_or_default();
1103    for a in items {
1104        let s = |k: &str| a.get(k).and_then(Value::as_str);
1105        let result = (|| {
1106            let file = s("file").filter(|f| !f.is_empty()).ok_or("the artifact has no \"file\" (the path of its bytes)")?;
1107            let path = if Path::new(file).is_absolute() { PathBuf::from(file) } else { ctx.workspace.join(file) };
1108            let bytes = std::fs::metadata(&path)
1109                .map_err(|e| format!("{file}: {e}"))
1110                .and_then(|m| if m.len() > byob_tools::artifact::MAX_FILE_BYTES { Err(format!("{file} is too big")) } else { Ok(()) })
1111                .and_then(|()| std::fs::read(&path).map_err(|e| format!("{file}: {e}")))?;
1112            let save = byob_tools::artifact::SaveBytes {
1113                chat,
1114                id: s("id"),
1115                title: s("title"),
1116                filename: s("filename"),
1117                bytes: &bytes,
1118                note: s("note").unwrap_or_default(),
1119                replace: None,
1120                // One request's saves of an artifact make one version.
1121                turn: ctx.turn(),
1122            };
1123            byob_tools::artifact::save_bytes(types, ctx.workspace, &save)
1124        })();
1125        match result {
1126            Ok(saved) => {
1127                out.text.push_str(&format!(
1128                    "\nSaved: artifact {}, version {} ({}){}.",
1129                    saved.artifact.id,
1130                    saved.version,
1131                    saved.artifact.filename,
1132                    if saved.created { "; a new artifact, use this id from now on" } else { "" }
1133                ));
1134                out.changes.push(FileChange::Created(saved.file));
1135            }
1136            Err(e) => {
1137                out.text.push_str(&format!("\nThe result couldn't be saved as an artifact: {e}"));
1138                out.failed = true;
1139            }
1140        }
1141    }
1142}
1143
1144/// A tool reply as tool output: text, `{"text": …, "files": […]}`, or any JSON.
1145fn tool_output(v: Value, workspace: &Path) -> ToolOutput {
1146    let (text, files) = match v {
1147        Value::String(s) => (s, Vec::new()),
1148        Value::Null => (String::new(), Vec::new()),
1149        Value::Object(o) if ["text", "files", "card", "artifact", "artifacts"].iter().any(|k| o.contains_key(*k)) => {
1150            let text = o.get("text").map(|t| t.as_str().map_or_else(|| t.to_string(), str::to_owned)).unwrap_or_default();
1151            let files = o.get("files").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
1152            (text, files)
1153        }
1154        other => (other.to_string(), Vec::new()),
1155    };
1156    let changes = files.iter().filter(|f| path_inside(f)).map(|f| workspace.join(f)).filter(|p| p.is_file()).map(FileChange::Modified).collect();
1157    let text = if text.trim().is_empty() { "(no result)".to_owned() } else { text };
1158    ToolOutput { text, failed: false, changes, images: Vec::new() }
1159}
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164
1165    fn lines(input: &[u8], max: usize) -> Vec<Result<String, LineRead>> {
1166        let mut r = io::BufReader::with_capacity(3, input);
1167        let mut buf = Vec::new();
1168        let mut out = Vec::new();
1169        loop {
1170            match read_line(&mut r, &mut buf, max).unwrap() {
1171                LineRead::Line => out.push(Ok(String::from_utf8(buf.clone()).unwrap())),
1172                LineRead::Eof => return out,
1173                other => out.push(Err(other)),
1174            }
1175        }
1176    }
1177
1178    #[test]
1179    fn long_lines_are_dropped_not_fatal() {
1180        assert_eq!(lines(b"ab\r\nwaaaaaaaaaaay too long\nok", 8), vec![Ok("ab".into()), Err(LineRead::TooLong), Ok("ok".into())]);
1181    }
1182
1183    #[test]
1184    fn ring_keeps_the_tail() {
1185        let mut r = Ring::default();
1186        r.push(&vec![b'a'; STDERR_KEEP]);
1187        r.push(b"\nlast line\n");
1188        assert_eq!(r.0.len(), STDERR_KEEP);
1189        assert_eq!(r.last_lines(1), "last line");
1190    }
1191
1192    #[test]
1193    fn tool_replies() {
1194        let ws = std::env::temp_dir();
1195        assert_eq!(tool_output(json!("hi"), &ws).text, "hi");
1196        assert_eq!(tool_output(json!({"text": "t", "files": ["../x"]}), &ws).text, "t");
1197        assert_eq!(tool_output(json!({"n": 1}), &ws).text, "{\"n\":1}");
1198        assert_eq!(tool_output(Value::Null, &ws).text, "(no result)");
1199    }
1200
1201    #[test]
1202    fn a_backend_that_cannot_start_fails_its_requests() {
1203        let sink: Sink = Arc::new(|_| {});
1204        let b = Backend::new("x", json!({"type": "init"}), &[], Box::new(|_: &dyn Fn() -> bool| Err("no python".into())), sink);
1205        let e = b.request("tool", json!({}), Duration::from_secs(5), &|| false).unwrap_err();
1206        assert_eq!(e, "no python");
1207        assert_eq!(b.status().phase, Phase::Failed);
1208        assert!(!b.event(json!({"type": "event"})));
1209    }
1210
1211    #[test]
1212    fn faults_reach_the_sink_at_most_once_a_second() {
1213        let posted = Arc::new(Mutex::new(Vec::new()));
1214        let p = Arc::clone(&posted);
1215        let sink: Sink = Arc::new(move |o| {
1216            if let Out::Msg(m) = o {
1217                p.lock().unwrap().push(m["text"].as_str().unwrap_or_default().to_owned());
1218            }
1219        });
1220        let b = Backend::new("x", json!({"type": "init"}), &[], Box::new(|_: &dyn Fn() -> bool| Err("-".into())), sink);
1221        for i in 0..100 {
1222            b.report_fault(&format!("not json {i}"));
1223        }
1224        // every one is in the status (the newest), the sink heard of the first only
1225        assert_eq!(b.status().faults.last().map(String::as_str), Some("not json 99"));
1226        assert_eq!(b.status().faults.len(), MAX_FAULTS);
1227        assert_eq!(*posted.lock().unwrap(), ["not json 0"]);
1228        // then of the rest, once
1229        let deadline = Instant::now() + Duration::from_secs(5);
1230        while posted.lock().unwrap().len() < 2 && Instant::now() < deadline {
1231            thread::sleep(Duration::from_millis(10));
1232        }
1233        thread::sleep(Duration::from_millis(200));
1234        assert_eq!(*posted.lock().unwrap(), ["not json 0", "not json 99 (98 more)"]);
1235    }
1236
1237    /// A backend that stays starting until stopped; `true` in the flag once its
1238    /// preparation saw that.
1239    fn never_starts() -> (Backend, Arc<std::sync::atomic::AtomicBool>) {
1240        let saw = Arc::new(AtomicBool::new(false));
1241        let s = Arc::clone(&saw);
1242        let prepare = Box::new(move |called_off: &dyn Fn() -> bool| {
1243            while !called_off() {
1244                thread::sleep(Duration::from_millis(5));
1245            }
1246            s.store(true, Ordering::SeqCst);
1247            Err("called off".to_owned())
1248        });
1249        (Backend::new("x", json!({"type": "init"}), &[], prepare, Arc::new(|_| {})), saw)
1250    }
1251
1252    #[test]
1253    fn a_stop_calls_off_a_long_preparation() {
1254        let (b, saw) = never_starts();
1255        b.start();
1256        thread::sleep(Duration::from_millis(50));
1257        assert_eq!(b.status().phase, Phase::Starting);
1258        b.stop("reloaded");
1259        let deadline = Instant::now() + Duration::from_secs(5);
1260        while !saw.load(Ordering::SeqCst) {
1261            assert!(Instant::now() < deadline, "the preparation went on");
1262            thread::sleep(Duration::from_millis(5));
1263        }
1264    }
1265
1266    #[test]
1267    fn a_slow_start_keeps_a_bounded_number_of_bytes() {
1268        let (b, _saw) = never_starts();
1269        let big = "x".repeat(MAX_LINE - 100);
1270        for _ in 0..40 {
1271            assert!(b.event(json!({"type": "event", "event": "client", "msg": big})));
1272        }
1273        let g = b.shared.lock();
1274        assert!(g.queued_bytes <= MAX_QUEUED_BYTES, "{}", g.queued_bytes);
1275        assert_eq!(g.queued_bytes, g.queued.iter().map(Vec::len).sum::<usize>());
1276        assert!(g.queued.len() < 40);
1277    }
1278}