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