1#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
16
17use std::fmt::Write as _;
18use std::sync::Arc;
19
20use byob_plugins::native::{NativeBackend, NativeFactory, Outbox};
21use serde_json::Value;
22
23pub const ID: &str = "help";
25pub const TOOL: &str = "byob_help";
27pub const MAX_CHARS: usize = 8000;
29pub const MAX_HITS: usize = 3;
31const MAX_QUERY: usize = 300;
33
34pub struct Topic {
36 pub name: &'static str,
38 pub summary: &'static str,
40 pub aliases: &'static [&'static str],
42 pub text: &'static str,
44}
45
46pub static TOPICS: &[Topic] = &[
48 Topic {
49 name: "byob",
50 summary: "Installing byob, connecting a model (Connect a model, presets, API keys), the command line, the browser UI and Tailscale, workspaces, routines, running in the background, My phone (Telegram, ntfy), plugins.",
51 aliases: &["readme", "install", "setup", "use", "usage", "start", "getting-started"],
52 text: include_str!("../docs/byob.md"),
53 },
54 Topic {
55 name: "mail",
56 summary: "The Mail plugin (IMAP/SMTP, one account): settings, Gmail (app password), Fastmail, iCloud, what each tool does, what always asks first.",
57 aliases: &["email", "e-mail", "gmail", "imap", "smtp"],
58 text: include_str!("../docs/mail.md"),
59 },
60 Topic {
61 name: "calendar",
62 summary: "The Calendar plugin (CalDAV, one account): settings for Fastmail, iCloud, Nextcloud, Radicale; tools, time zones, recurrence; why Google Calendar isn't supported.",
63 aliases: &["calendars", "caldav", "events"],
64 text: include_str!("../docs/calendar.md"),
65 },
66 Topic {
67 name: "environments",
68 summary: "Where commands run and how tools get installed: install_packages (Nix, pixi), project environments (flake.nix, pixi, mise, .venv, devcontainer), Docker/Podman containers.",
69 aliases: &["environment", "containers", "docker", "podman", "nix", "pixi", "packages"],
70 text: include_str!("../docs/environments.md"),
71 },
72 Topic {
73 name: "views",
74 summary: "For plugin authors: view trees, the UI plugins draw (panes, header chips, cards, tables, grids, charts), events and patches.",
75 aliases: &["view", "view-trees", "ui", "panes"],
76 text: include_str!("../docs/views.md"),
77 },
78 Topic {
79 name: "plugin-backends",
80 summary: "For plugin authors: long-lived plugin backends (Python or Rust), their lifecycle and wire format, hooks, artifacts and web views, the Python helper.",
81 aliases: &["plugins", "plugin", "backends", "backend", "hooks", "plugins-backend", "writing-plugins"],
82 text: include_str!("../docs/plugin-backends.md"),
83 },
84];
85
86pub fn factory() -> NativeFactory {
87 Arc::new(|| Box::new(Help) as Box<dyn NativeBackend>)
88}
89
90pub struct Help;
92
93impl NativeBackend for Help {
94 fn request(&mut self, method: &str, params: &Value, _out: &Outbox) -> Result<Value, String> {
95 match method {
96 "tool" => {
97 let name = params.get("name").and_then(Value::as_str).unwrap_or_default();
98 if name != TOOL {
99 return Err(format!("the help backend has no tool {name:?}"));
100 }
101 help(params.get("args").unwrap_or(&Value::Null)).map(Value::String)
102 }
103 "hook" => Ok(serde_json::json!({"action": "continue"})),
104 other => Err(format!("the help backend doesn't answer {other:?} requests")),
105 }
106 }
107}
108
109fn arg<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
111 args.get(key)?.as_str().map(str::trim).filter(|s| !s.is_empty())
112}
113
114fn uint(args: &Value, key: &str) -> Option<usize> {
116 let v = args.get(key)?;
117 let n = v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f as u64)).or_else(|| v.as_str()?.trim().parse().ok())?;
118 usize::try_from(n).ok()
119}
120
121pub fn help(args: &Value) -> Result<String, String> {
123 let start = uint(args, "start").unwrap_or(0);
124 let section = args.get("section").and_then(|v| match v {
126 Value::String(s) => Some(s.trim().to_owned()).filter(|s| !s.is_empty()),
127 Value::Number(n) => Some(n.to_string()),
128 _ => None,
129 });
130 match (arg(args, "topic"), arg(args, "query")) {
131 (Some(t), _) => read(find_topic(t)?, section.as_deref(), start),
132 (None, Some(q)) => Ok(search(q)),
133 (None, None) if section.is_some() => Err(format!("Say which topic the section is in (topic). {}", topic_list())),
134 (None, None) => Ok(topic_list()),
135 }
136}
137
138pub fn topic_list() -> String {
140 let mut out = String::from("byob's help topics (read one with byob_help {\"topic\": \"<name>\"}, or search them all with {\"query\": \"<words>\"}):\n");
141 for t in TOPICS {
142 let _ = writeln!(out, "- {}: {}", t.name, t.summary);
143 }
144 out
145}
146
147fn find_topic(name: &str) -> Result<&'static Topic, String> {
148 let n = name.trim().trim_end_matches(".md").to_lowercase().replace([' ', '_'], "-");
149 let n = n.rsplit('/').next().unwrap_or(&n);
150 TOPICS
151 .iter()
152 .find(|t| t.name == n)
153 .or_else(|| TOPICS.iter().find(|t| t.aliases.contains(&n)))
154 .ok_or_else(|| format!("There is no help topic {name:?}. {}", topic_list()))
155}
156
157fn body(t: &Topic) -> &'static str {
159 let text = t.text;
160 match text.strip_prefix("<!--").and_then(|r| r.find("-->\n").map(|i| &r[i + 4..])) {
161 Some(rest) => rest,
162 None => text,
163 }
164}
165
166#[derive(Debug)]
169pub struct Section {
170 pub level: u8,
171 pub heading: String,
172 pub text: &'static str,
173 pub own: &'static str,
175}
176
177pub fn sections(text: &'static str) -> Vec<Section> {
180 let mut heads: Vec<(usize, u8, String)> = Vec::new();
182 let mut fence = false;
183 let mut at = 0;
184 for line in text.split_inclusive('\n') {
185 let t = line.trim_end();
186 if t.trim_start().starts_with("```") {
187 fence = !fence;
188 } else if !fence {
189 if let Some(h) = t.strip_prefix("### ") {
190 heads.push((at, 3, h.trim().to_owned()));
191 } else if let Some(h) = t.strip_prefix("## ") {
192 heads.push((at, 2, h.trim().to_owned()));
193 } else if let Some(h) = t.strip_prefix("# ")
194 && heads.is_empty()
195 {
196 heads.push((at, 1, h.trim().to_owned()));
197 }
198 }
199 at += line.len();
200 }
201 if heads.first().is_none_or(|h| h.0 != 0) {
202 heads.insert(0, (0, 1, String::new()));
203 }
204 let mut out = Vec::with_capacity(heads.len());
205 for (i, (from, level, heading)) in heads.iter().enumerate() {
206 let next = heads.get(i + 1).map_or(text.len(), |h| h.0);
207 let end = heads.iter().skip(i + 1).find(|h| h.1 <= *level || *level == 1).map_or(text.len(), |h| h.0);
209 let (Some(t), Some(own)) = (text.get(*from..end), text.get(*from..next)) else { continue };
210 out.push(Section { level: *level, heading: heading.clone(), text: t, own });
211 }
212 out
213}
214
215fn read(topic: &Topic, section: Option<&str>, start: usize) -> Result<String, String> {
217 let all = sections(body(topic));
218 let (text, label) = match section {
219 None => (body(topic), None),
220 Some(s) => {
221 let tops: Vec<&Section> = all.iter().filter(|x| x.level == 2).collect();
222 let want = s.trim_start_matches('#').trim().to_lowercase();
223 let by_number = want.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).and_then(|i| tops.get(i).copied());
224 let by_name = || {
225 all.iter()
226 .filter(|x| x.level > 1)
227 .find(|x| x.heading.to_lowercase() == want)
228 .or_else(|| all.iter().filter(|x| x.level > 1).find(|x| x.heading.to_lowercase().contains(&want)))
229 };
230 match by_number.or_else(by_name) {
231 Some(x) => (x.text, Some(x.heading.clone())),
232 None => return Err(format!("{:?} has no section {s:?}. Its sections: {}.", topic.name, contents(&all))),
233 }
234 }
235 };
236 let total = text.chars().count();
237 if start >= total && start > 0 {
238 return Err(format!("start {start} is past the end ({total} characters)."));
239 }
240 let (window, end) = window(text, start, MAX_CHARS);
241 let mut out = String::new();
242 if section.is_none() && start == 0 && end < total {
243 let _ = writeln!(out, "[{:?} is long ({total} characters); its sections: {}.]\n", topic.name, contents(&all));
244 }
245 out.push_str(window.trim_end());
246 if end < total {
247 let sec = label.map(|l| format!(", \"section\": {}", Value::String(l))).unwrap_or_default();
248 let _ = write!(out, "\n\n[Shown: characters {start}-{end} of {total}. Read on with byob_help {{\"topic\": {:?}{sec}, \"start\": {end}}}", topic.name);
249 if section.is_none() {
250 out.push_str(", or read one section with \"section\" (a name or number)");
251 }
252 out.push_str(".]");
253 }
254 Ok(out)
255}
256
257fn contents(all: &[Section]) -> String {
259 all.iter().filter(|x| x.level == 2).enumerate().map(|(i, x)| format!("{}. {}", i + 1, x.heading)).collect::<Vec<_>>().join(", ")
260}
261
262fn window(text: &str, start: usize, max: usize) -> (&str, usize) {
265 let mut idx = text.char_indices().map(|(i, _)| i).skip(start);
266 let Some(from) = idx.next() else { return ("", start) };
267 let total = text.chars().count();
268 if total.saturating_sub(start) <= max {
269 return (text.get(from..).unwrap_or_default(), total);
270 }
271 let to = text.char_indices().nth(start.saturating_add(max)).map_or(text.len(), |(i, _)| i);
272 let mut slice = text.get(from..to).unwrap_or_default();
273 if let Some(nl) = slice.rfind('\n').filter(|&nl| nl > slice.len() / 2) {
275 slice = slice.get(..=nl).unwrap_or(slice);
276 }
277 let end = start + slice.chars().count();
278 (slice, end)
279}
280
281const STOP: &[&str] = &[
282 "a", "about", "an", "and", "any", "are", "as", "at", "be", "byob", "byob's", "can", "could", "do", "does", "for", "from", "get", "have", "how", "i", "if",
283 "in", "into", "is", "it", "its", "me", "my", "of", "on", "or", "please", "should", "so", "that", "the", "there", "this", "to", "up", "use", "using",
284 "want", "way", "what", "when", "where", "which", "why", "will", "with", "would", "you", "your",
285];
286
287fn terms(q: &str) -> Vec<String> {
289 let q: String = q.chars().take(MAX_QUERY).collect::<String>().to_lowercase();
290 let mut out: Vec<String> = Vec::new();
291 for w in q.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '\'')) {
292 let w = w.trim_matches('\'').trim_end_matches("'s");
293 if w.chars().count() < 2 || STOP.contains(&w) || out.iter().any(|o| o == w) {
294 continue;
295 }
296 out.push(w.to_owned());
297 if out.len() >= 12 {
298 break;
299 }
300 }
301 out
302}
303
304struct Hit<'a> {
306 topic: &'static Topic,
307 section: &'a Section,
308 score: f64,
309}
310
311fn search(query: &str) -> String {
313 let q: String = query.chars().take(80).collect();
314 let q = q.as_str();
315 let words = terms(query);
316 if words.is_empty() {
317 return format!("Nothing to search for in {q:?}: give a few keywords, e.g. \"gmail app password\".\n\n{}", topic_list());
318 }
319 let docs: Vec<(&'static Topic, Vec<Section>)> = TOPICS.iter().map(|t| (t, sections(body(t)))).collect();
320 let units: Vec<(&'static Topic, &Section, String)> =
322 docs.iter().flat_map(|(t, ss)| ss.iter().filter(|s| !s.own.trim().is_empty()).map(move |s| (*t, s, s.own.to_lowercase()))).collect();
323 let n = units.len().max(1) as f64;
324 let idf: Vec<f64> = words
325 .iter()
326 .map(|w| {
327 let df = units.iter().filter(|u| u.2.contains(w.as_str())).count();
328 if df == 0 { 0.0 } else { (1.0 + n / df as f64).ln() }
329 })
330 .collect();
331 let pairs: Vec<String> = words.windows(2).map(|p| format!("{} {}", p[0], p[1])).collect();
332 let mut hits: Vec<Hit> = Vec::new();
333 for (topic, section, lower) in &units {
334 let heading = section.heading.to_lowercase();
335 let mut score = 0.0;
336 let mut matched = 0;
338 for (w, idf) in words.iter().zip(&idf) {
339 let count = lower.matches(w.as_str()).count().min(10);
340 let named = topic.name.contains(w.as_str()) || topic.aliases.iter().any(|a| a == w);
341 if named {
342 score += idf;
343 }
344 if count == 0 {
345 continue;
346 }
347 matched += 1;
348 score += idf * (1.0 + (count as f64).ln_1p());
349 if heading.contains(w.as_str()) {
350 score += 3.0 * idf;
351 }
352 }
353 score += 2.0 * pairs.iter().filter(|p| lower.contains(p.as_str())).count() as f64;
354 score *= 0.5 + 0.5 * matched as f64 / words.len() as f64;
356 if matched > 0 && score > 0.0 {
357 hits.push(Hit { topic, section, score });
358 }
359 }
360 hits.sort_by(|a, b| b.score.total_cmp(&a.score));
361 hits.truncate(MAX_HITS);
362 if hits.is_empty() {
363 return format!("Nothing in byob's docs matches {q:?}.\n\n{}", topic_list());
364 }
365 let per = MAX_CHARS / hits.len();
366 let mut out = format!("byob's docs, best matches for {:?}:\n", words.join(" "));
367 for h in &hits {
368 let heading = if h.section.heading.is_empty() { h.topic.name.to_owned() } else { h.section.heading.clone() };
369 let _ = writeln!(out, "\n--- topic {:?}, section {:?} ---", h.topic.name, heading);
370 let (text, end) = window(h.section.text, 0, per);
371 out.push_str(text.trim_end());
372 out.push('\n');
373 if end < h.section.text.chars().count() {
374 let section = if h.section.level == 1 { String::new() } else { format!(", \"section\": {}", Value::String(heading)) };
375 let _ = writeln!(out, "[cut; read it all with byob_help {{\"topic\": {:?}{section}}}]", h.topic.name);
376 }
377 }
378 out
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384 use serde_json::json;
385
386 fn call(args: Value) -> Result<String, String> {
387 help(&args)
388 }
389
390 #[test]
391 fn no_arguments_list_the_topics() {
392 let out = call(json!({})).unwrap();
393 for t in TOPICS {
394 assert!(out.contains(&format!("- {}: {}\n", t.name, t.summary)), "{out}");
395 }
396 assert_eq!(call(Value::Null).unwrap(), out);
397 assert_eq!(call(json!({"topic": " ", "query": ""})).unwrap(), out, "blank is unset");
398 }
399
400 #[test]
401 fn every_doc_is_embedded_and_listed() {
402 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs");
403 let mut files: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
404 files.sort();
405 let mut names: Vec<String> = TOPICS.iter().map(|t| format!("{}.md", t.name)).collect();
406 names.sort();
407 assert_eq!(files, names);
408 for t in TOPICS {
409 assert!(t.text.starts_with("<!-- Generated from "), "{}", t.name);
410 assert!(body(t).starts_with("# "), "{}: {:?}", t.name, &body(t)[..40]);
411 }
412 }
413
414 #[test]
415 fn reads_a_topic_and_pages_a_long_one() {
416 let mail = call(json!({"topic": "mail"})).unwrap();
418 assert!(mail.starts_with("# Mail\n") && mail.contains("## Gmail") && !mail.contains("<!--"), "{mail}");
419 assert!(!mail.contains("## Tests") && !mail.contains("## Crates"), "developer sections are left out");
420 assert_eq!(call(json!({"topic": "Gmail"})).unwrap(), mail, "aliases pick a topic");
421 assert_eq!(call(json!({"topic": "docs/mail.md"})).unwrap(), mail);
422 let first = call(json!({"topic": "plugin-backends"})).unwrap();
424 assert!(first.starts_with("[\"plugin-backends\" is long"), "{}", &first[..200]);
425 assert!(first.contains("1. Declaring one, 2. Lifecycle"), "{}", &first[..400]);
426 let end = first.rsplit_once("\"start\": ").unwrap().1.split('}').next().unwrap().parse::<usize>().unwrap();
427 assert!(end <= MAX_CHARS && end > MAX_CHARS / 2, "{end}");
428 let next = call(json!({"topic": "plugin-backends", "start": end})).unwrap();
429 assert!(!next.starts_with('['), "no contents after the first window");
430 assert!(body(&TOPICS[5]).chars().skip(end).take(200).collect::<String>().starts_with(&next.chars().take(200).collect::<String>()));
431 assert!(call(json!({"topic": "mail", "start": 1_000_000})).unwrap_err().contains("past the end"));
432 }
433
434 #[test]
435 fn reads_one_section_by_name_or_number() {
436 let gmail = call(json!({"topic": "mail", "section": "gmail"})).unwrap();
437 assert!(gmail.starts_with("## Gmail\n") && gmail.contains("app password") && !gmail.contains("## Not supported yet"), "{gmail}");
438 let first = call(json!({"topic": "mail", "section": 1})).unwrap();
439 assert!(first.starts_with("## Settings\n"), "{first}");
440 assert_eq!(call(json!({"topic": "mail", "section": "1"})).unwrap(), first);
441 let tools = call(json!({"topic": "mail", "section": "Tools"})).unwrap();
443 assert!(tools.contains("### Sending always asks"), "{tools}");
444 let asks = call(json!({"topic": "mail", "section": "sending always"})).unwrap();
445 assert!(asks.starts_with("### Sending always asks") && !asks.contains("## Hostile input"), "{asks}");
446 let err = call(json!({"topic": "mail", "section": "nope"})).unwrap_err();
447 assert!(err.contains("has no section \"nope\"") && err.contains("1. Settings"), "{err}");
448 assert!(call(json!({"section": "Gmail"})).unwrap_err().contains("which topic"));
449 }
450
451 #[test]
452 fn unknown_topics_list_the_real_ones() {
453 let err = call(json!({"topic": "telepathy"})).unwrap_err();
454 assert!(err.starts_with("There is no help topic \"telepathy\"."), "{err}");
455 for t in TOPICS {
456 assert!(err.contains(&format!("- {}:", t.name)), "{err}");
457 }
458 }
459
460 #[test]
461 fn a_query_finds_the_gmail_app_password() {
462 let out = call(json!({"query": "how do I connect my Gmail to byob?"})).unwrap();
463 let first = out.split("\n--- ").nth(1).unwrap();
464 assert!(first.starts_with("topic \"mail\", section \"Gmail\""), "{out}");
465 assert!(first.contains("app password") && first.contains("2-Step Verification"), "{out}");
466 let out = call(json!({"query": "app password"})).unwrap();
467 assert!(out.contains("topic \"mail\""), "{out}");
468 assert!(out.matches("\n--- topic ").count() <= MAX_HITS);
469 assert!(call(json!({"query": "how do I"})).unwrap().starts_with("Nothing to search for"));
471 assert!(call(json!({"query": "zzyzx quuxplumber"})).unwrap().starts_with("Nothing in byob's docs matches"));
472 }
473
474 #[test]
475 fn outputs_stay_under_the_cap() {
476 let cap = MAX_CHARS + 600; for t in TOPICS {
478 let out = call(json!({"topic": t.name})).unwrap();
479 assert!(out.chars().count() <= cap, "{}: {}", t.name, out.chars().count());
480 for (i, _) in sections(body(t)).iter().filter(|s| s.level == 2).enumerate() {
481 let out = call(json!({"topic": t.name, "section": i + 1})).unwrap();
482 assert!(out.chars().count() <= cap, "{} section {}: {}", t.name, i + 1, out.chars().count());
483 }
484 }
485 for q in ["plugin", "settings tools hooks views events", "a b c d e f g h i j k l m n o p", &"password ".repeat(500)] {
486 let out = call(json!({"query": q})).unwrap();
487 assert!(out.chars().count() <= cap + MAX_QUERY, "{q}: {}", out.chars().count());
488 }
489 for args in [
491 json!({"topic": "mail", "start": -5}),
492 json!({"topic": "mail", "start": 1e300}),
493 json!({"topic": 7}),
494 json!({"topic": "mail", "section": []}),
495 json!([1, 2]),
496 ] {
497 let _ = call(args);
498 }
499 assert_eq!(window("héllo wörld", 3, 4), ("lo w", 7));
500 assert_eq!(window("abc", 5, 4), ("", 5));
501 }
502
503 #[test]
504 fn headings_in_code_fences_are_not_sections() {
505 let ss = sections("# T\n\nintro\n\n## A\n\n```sh\n## not one\n# nor this\n```\n\n### B\n\nb\n\n## C\n\nc\n");
506 let heads: Vec<(u8, &str)> = ss.iter().map(|s| (s.level, s.heading.as_str())).collect();
507 assert_eq!(heads, [(1, "T"), (2, "A"), (3, "B"), (2, "C")]);
508 assert!(ss[1].text.contains("### B") && !ss[1].text.contains("## C") && !ss[1].own.contains("### B"));
509 assert_eq!(ss[0].text, "# T\n\nintro\n\n", "the intro stops at the first section");
510 }
511
512 #[test]
513 fn served_through_the_wire_dispatch() {
514 let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
515 let s = Arc::clone(&seen);
516 let out = Outbox::new(move |m| s.lock().unwrap().push(m));
517 let mut h = Help;
518 byob_plugins::native::dispatch(&mut h, &json!({"type": "init", "settings": {}, "secrets": {}}), &out);
519 byob_plugins::native::dispatch(
520 &mut h,
521 &json!({"type": "request", "id": 1, "method": "tool", "params": {"name": "byob_help", "args": {"topic": "calendar", "section": "Settings"}}}),
522 &out,
523 );
524 byob_plugins::native::dispatch(&mut h, &json!({"type": "request", "id": 2, "method": "tool", "params": {"name": "nope", "args": {}}}), &out);
525 let seen = seen.lock().unwrap();
526 assert_eq!(seen[0]["type"], "reply");
527 assert!(seen[0]["result"].as_str().unwrap().starts_with("## Settings"), "{:?}", seen[0]);
528 assert!(seen[1]["error"].as_str().unwrap().contains("no tool"), "{:?}", seen[1]);
529 }
530}