1use super::{Access, AgentTool, ReadService, ReadTool, ToolSpec, encoded, schema};
6use crate::help_image::{HelpImage, validate_images};
7use serde::Deserialize;
8use serde_json::Value;
9use std::sync::Arc;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct BoardDoc {
14 pub id: &'static str,
15 pub title: &'static str,
16 pub markdown: &'static str,
18 pub images: &'static [HelpImage],
20}
21
22pub const HELP_TOOL: &str = "board_help";
24
25#[derive(Debug, Deserialize)]
26#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
27enum Request {
28 List,
29 Get { board_id: String },
30 Image { board_id: String, image_id: String },
31}
32
33struct BoardHelpService {
34 docs: Vec<BoardDoc>,
35}
36
37impl BoardHelpService {
38 fn list(&self) -> Result<Value, String> {
39 let boards: Vec<Value> = self
40 .docs
41 .iter()
42 .map(|doc| serde_json::json!({"board_id": doc.id, "title": doc.title}))
43 .collect();
44 encoded(serde_json::json!({ "boards": boards }))
45 }
46
47 fn get(&self, board_id: &str) -> Result<Value, String> {
48 let doc = self.doc(board_id)?;
49 validate_images(doc.images)?;
50 let images: Vec<Value> = doc
51 .images
52 .iter()
53 .map(|image| {
54 serde_json::json!({
55 "image_id": image.id,
56 "caption": image.caption,
57 "media_type": image.media_type,
58 "byte_length": image.bytes.len(),
59 })
60 })
61 .collect();
62 encoded(serde_json::json!({
63 "board_id": doc.id,
64 "title": doc.title,
65 "markdown": doc.markdown,
66 "images": images,
67 }))
68 }
69
70 fn image(&self, board_id: &str, image_id: &str) -> Result<Value, String> {
71 let doc = self.doc(board_id)?;
72 validate_images(doc.images)?;
73 let image = doc
74 .images
75 .iter()
76 .find(|image| image.id == image_id)
77 .ok_or_else(|| {
78 format!("No bundled help image {image_id} in active board {board_id}.")
79 })?;
80 image.reply(doc.id)
81 }
82
83 fn doc(&self, board_id: &str) -> Result<&BoardDoc, String> {
84 self.docs
85 .iter()
86 .find(|doc| doc.id == board_id)
87 .ok_or_else(|| {
88 format!(
89 "No active board {board_id} documents itself. Choose from: {}.",
90 self.ids().join(", ")
91 )
92 })
93 }
94
95 fn ids(&self) -> Vec<&'static str> {
96 self.docs.iter().map(|doc| doc.id).collect()
97 }
98}
99
100impl ReadService for BoardHelpService {
101 type Request = Request;
102
103 fn read(&self, request: Request) -> Result<Value, String> {
104 match request {
105 Request::List => self.list(),
106 Request::Get { board_id } => self.get(board_id.trim()),
107 Request::Image { board_id, image_id } => self.image(board_id.trim(), &image_id),
108 }
109 }
110}
111
112fn spec() -> ToolSpec {
113 ToolSpec {
114 name: HELP_TOOL,
115 title: "Board help",
116 description: "Read the bundled help of an active board: what it shows, how to set \
117 it up, which actions it supports and where its limits are. Call it \
118 when a question is about a board rather than about a service item.",
119 access: Access::Read,
120 arguments: schema::flat(&[
121 schema::action("list", "The active boards that have help.", vec![]),
122 schema::action(
123 "get",
124 "The board's help as Markdown and an image metadata catalog, without image bytes.",
125 vec![("board_id", schema::text(), true)],
126 ),
127 schema::action(
128 "image",
129 "Read one bundled help illustration from the active board. Use an image_id from get.",
130 vec![
131 ("board_id", schema::text(), true),
132 ("image_id", schema::text(), true),
133 ],
134 ),
135 ]),
136 approval: super::ApprovalPolicy::None,
137 }
138}
139
140pub fn help_tool(docs: Vec<BoardDoc>) -> Option<Arc<dyn AgentTool>> {
143 let service = service(documented(docs))?;
144 Some(Arc::new(ReadTool::new(spec(), service)))
145}
146
147fn documented(docs: Vec<BoardDoc>) -> Vec<BoardDoc> {
149 docs.into_iter()
150 .filter(|doc| !doc.markdown.trim().is_empty())
151 .collect()
152}
153
154fn service(docs: Vec<BoardDoc>) -> Option<Arc<BoardHelpService>> {
155 (!docs.is_empty()).then(|| Arc::new(BoardHelpService { docs }))
156}
157
158#[cfg(test)]
159#[path = "help/tests.rs"]
160mod image_tests;
161
162#[cfg(test)]
163mod tests {
164 use super::{BoardDoc, HELP_TOOL, help_tool};
165 use crate::{Access, AgentTool, test_support};
166 use serde_json::{Value, json};
167 use std::sync::Arc;
168
169 const IRC: &str = "# IRC\n\nWhat the board shows.";
170
171 fn docs() -> Vec<BoardDoc> {
172 vec![
173 BoardDoc {
174 id: "irc",
175 title: "Board",
176 markdown: IRC,
177 images: &[],
178 },
179 BoardDoc {
180 id: "github",
181 title: "GitHub",
182 markdown: "# GitHub",
183 images: &[],
184 },
185 ]
186 }
187
188 async fn call(tool: &Arc<dyn AgentTool>, arguments: Value) -> Result<Value, String> {
189 let (_, invocation) = test_support::invocation(arguments, true);
190 tool.call(invocation).await
191 }
192
193 #[tokio::test]
194 async fn the_tool_lists_active_boards_and_returns_their_exact_markdown() {
195 let tool = help_tool(docs()).unwrap();
196 assert_eq!(tool.spec().name, HELP_TOOL);
197 assert_eq!(tool.spec().access, Access::Read);
198 let listed = call(&tool, json!({"action": "list"})).await.unwrap();
199 assert_eq!(
200 listed["boards"],
201 json!([
202 {"board_id": "irc", "title": "Board"},
203 {"board_id": "github", "title": "GitHub"},
204 ])
205 );
206 let found = call(&tool, json!({"action": "get", "board_id": " irc "}))
207 .await
208 .unwrap();
209 assert_eq!(found["markdown"], json!(IRC));
210 assert_eq!(found["title"], json!("Board"));
211 }
212
213 #[tokio::test]
214 async fn a_board_outside_the_active_documents_is_refused() {
215 let tool = help_tool(docs()).unwrap();
216 let error = call(&tool, json!({"action": "get", "board_id": "missing"}))
217 .await
218 .unwrap_err();
219 assert!(error.contains("No active board missing"), "{error}");
220 assert!(error.contains("irc, github"), "{error}");
221 }
222
223 #[tokio::test]
224 async fn unknown_actions_and_fields_are_refused_before_any_lookup() {
225 let tool = help_tool(docs()).unwrap();
226 for arguments in [
227 json!({"action": "write", "board_id": "irc"}),
228 json!({"action": "get"}),
229 json!({"action": "get", "board_id": "irc", "token": "x"}),
230 ] {
231 assert!(call(&tool, arguments.clone()).await.is_err(), "{arguments}");
232 }
233 }
234
235 #[test]
236 fn boards_without_a_document_publish_no_help_tool() {
237 assert!(help_tool(Vec::new()).is_none());
238 assert!(
239 help_tool(vec![BoardDoc {
240 id: "terminal",
241 title: "Terminal",
242 markdown: " \n",
243 images: &[],
244 }])
245 .is_none()
246 );
247 }
248}