1use 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
36pub const WIRE_VERSION: u32 = 1;
38pub const MAX_LINE: usize = 1024 * 1024;
40pub const STDERR_KEEP: usize = 16 * 1024;
42pub const MAX_FAULTS: usize = 8;
44const MAX_FAULT: usize = 2000;
46const MAX_QUEUED: usize = 256;
49const MAX_QUEUED_BYTES: usize = 16 * 1024 * 1024;
51const FAULT_EVERY: Duration = Duration::from_secs(1);
53const WAIT_POLL: Duration = Duration::from_millis(20);
55const DRAIN_GRACE: Duration = Duration::from_millis(500);
57pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
59pub const MAX_CRASHES: u32 = 5;
61pub const NATIVE_STACK: usize = 64 * 1024 * 1024;
66const FIRST_BACKOFF: Duration = Duration::from_millis(500);
67const MAX_BACKOFF: Duration = Duration::from_secs(30);
68const STABLE: Duration = Duration::from_secs(30);
70const STOP_GRACE: Duration = Duration::from_millis(500);
72pub const CAPS: [&str; 9] = ["event", "request", "reply", "view", "notify", "notice", "log", "fault", "web"];
74
75#[derive(Debug, Clone, Default)]
77pub struct Launch {
78 pub argv: Vec<OsString>,
80 pub cwd: PathBuf,
81 pub env: BTreeMap<String, String>,
83 pub remove_env: Vec<String>,
85}
86
87pub 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
99pub type Prepare = Box<dyn Fn(&dyn Fn() -> bool) -> Result<Start, String> + Send + Sync>;
102
103#[derive(Debug, Clone, PartialEq)]
105pub enum Out {
106 Msg(Value),
108 Started,
109 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 Idle,
119 Starting,
120 Running,
121 Crashed,
123 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#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Status {
144 pub phase: Phase,
145 pub pid: Option<u32>,
146 pub starts: u32,
147 pub crashes: u32,
149 pub stderr: String,
151 pub faults: Vec<String>,
152 pub error: Option<String>,
154 pub subscribed: Vec<String>,
155}
156
157type Reply = Result<Value, String>;
158
159struct Inner {
160 phase: Phase,
161 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 fault_posted: Option<Instant>,
179 fault_held: u32,
181 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
199pub struct Backend {
201 shared: Arc<Shared>,
202}
203
204impl Backend {
205 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 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 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 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 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 pub fn report_fault(&self, text: &str) {
334 fault(&self.shared, text.to_owned());
335 }
336
337 pub fn post(&self, msg: Value) {
340 (self.shared.sink)(Out::Msg(msg));
341 }
342
343 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
384fn 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 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
412fn 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
447fn 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
459enum 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 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 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
555fn 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; }
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 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 #[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
613fn 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; }
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; }
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
685fn 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
694fn 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
719fn 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
757fn 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
803fn 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
848fn 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#[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
888pub 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
901fn 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
945pub struct BackendTool {
947 name: String,
948 plugin: PluginRef,
949 decl: ManifestTool,
950 backend: Arc<Backend>,
951 timeout: Duration,
952 types: byob_tools::ArtifactTypes,
954 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 pub fn with_cards(mut self, cards: Vec<(String, bool)>) -> Self {
965 self.cards = cards;
966 self
967 }
968
969 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 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 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 if ctx.attach_view(shown) {
1076 self.backend.post(json!({"type": CARD_MSG, "view": view, "key": key, "tree": tree}));
1077 }
1078 }
1079}
1080
1081pub const CARD_MSG: &str = "_tool_card";
1084
1085const MAX_SAVED: usize = 12;
1087
1088fn 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 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
1142fn 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 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 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 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}