1mod batch;
6mod chat_server;
7pub mod envelope;
8pub mod help;
9mod read;
10pub mod refresh;
11pub mod schema;
12mod search;
13pub mod secrets;
14#[cfg(any(test, feature = "test-support"))]
15pub mod test_support;
16pub mod web;
17
18use async_trait::async_trait;
19use serde::Serialize;
20use serde::de::DeserializeOwned;
21use serde_json::Value;
22use std::collections::HashSet;
23use std::sync::Arc;
24use subspace_core::config::Config;
25use subspace_core::credentials::Credentials;
26
27pub use batch::{MAX_BATCH, NO_RETRY, WriteService, WriteTool, summary};
28pub use chat_server::{ChatToolEndpoint, ChatToolServer};
29pub use help::{BoardDoc, HELP_TOOL, help_tool};
30pub mod help_image;
31pub use help_image::{HelpImage, help_image_reply};
32pub use read::{ReadService, ReadTool};
33
34#[derive(Clone)]
37pub struct ToolEnvironment {
38 pub config: Arc<Config>,
39 pub credentials: Arc<Credentials>,
40 pub search: Option<subspace_search::Service>,
41 pub config_file: Option<std::path::PathBuf>,
44 pub host: ToolHost,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum ToolHost {
53 App,
55 Headless,
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub enum Access {
62 Read,
63 Write,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub enum ApprovalPolicy {
69 None,
70 PerCall,
71}
72
73#[derive(Clone, Debug)]
75pub enum Arguments {
76 Actions {
77 actions: Vec<schema::Action>,
78 batched: bool,
79 },
80 Single {
81 fields: Vec<schema::Field>,
82 },
83}
84
85impl Arguments {
86 pub fn input_schema(&self) -> Value {
88 match self {
89 Self::Actions { actions, batched } => schema::actions_schema(actions, *batched),
90 Self::Single { fields } => schema::single_schema(fields),
91 }
92 }
93
94 pub fn action_names(&self) -> Vec<&'static str> {
96 match self {
97 Self::Actions { actions, .. } => actions.iter().map(|action| action.name).collect(),
98 Self::Single { .. } => Vec::new(),
99 }
100 }
101}
102
103#[derive(Clone, Debug)]
105pub struct ToolSpec {
106 pub name: &'static str,
108 pub title: &'static str,
109 pub description: &'static str,
110 pub access: Access,
111 pub arguments: Arguments,
112 pub approval: ApprovalPolicy,
113}
114
115impl ToolSpec {
116 pub fn input_schema(&self) -> Value {
117 self.arguments.input_schema()
118 }
119}
120
121fn validate_spec(spec: &ToolSpec) -> Result<(), String> {
122 if spec.access == Access::Write && spec.approval != ApprovalPolicy::PerCall {
123 return Err(format!(
124 "Write tool {} must require per-call approval.",
125 spec.name
126 ));
127 }
128 Ok(())
129}
130
131#[async_trait]
134pub trait Approval: Send + Sync {
135 async fn approve(&self, summary: String) -> Result<bool, String>;
136
137 async fn approve_in_app(&self, _summary: String) -> Result<bool, String> {
140 Ok(false)
141 }
142}
143
144pub struct Unattended;
146
147#[async_trait]
148impl Approval for Unattended {
149 async fn approve(&self, _summary: String) -> Result<bool, String> {
150 Ok(true)
151 }
152}
153
154pub trait CallMonitor: Send + Sync {
157 fn progress(&self, _done: usize, _total: usize, _message: &str) {}
159 fn cancelled(&self) -> bool {
161 false
162 }
163}
164
165pub struct Unmonitored;
167
168impl CallMonitor for Unmonitored {}
169
170pub struct Invocation {
172 pub arguments: Value,
173 pub approval: Arc<dyn Approval>,
174 pub monitor: Arc<dyn CallMonitor>,
175}
176
177#[async_trait]
179pub trait AgentTool: Send + Sync {
180 fn spec(&self) -> &ToolSpec;
181 async fn call(&self, invocation: Invocation) -> Result<Value, String>;
183}
184
185pub type ToolProvider = fn(&ToolEnvironment) -> Vec<Arc<dyn AgentTool>>;
187
188#[derive(Clone, Default)]
190pub struct Catalog {
191 tools: Vec<Arc<dyn AgentTool>>,
192}
193
194impl Catalog {
195 pub fn new(tools: Vec<Arc<dyn AgentTool>>) -> Result<Self, String> {
197 for tool in &tools {
198 validate_spec(tool.spec())?;
199 }
200 match duplicate_name(&tools) {
201 Some(name) => Err(format!("Two boards advertise the agent tool {name}.")),
202 None => Ok(Self { tools }),
203 }
204 }
205
206 pub fn tools(&self) -> &[Arc<dyn AgentTool>] {
207 &self.tools
208 }
209
210 pub fn get(&self, name: &str) -> Option<&Arc<dyn AgentTool>> {
211 self.tools.iter().find(|tool| tool.spec().name == name)
212 }
213
214 pub fn is_empty(&self) -> bool {
215 self.tools.is_empty()
216 }
217}
218
219fn duplicate_name(tools: &[Arc<dyn AgentTool>]) -> Option<&'static str> {
220 let mut seen = HashSet::new();
221 tools
222 .iter()
223 .map(|tool| tool.spec().name)
224 .find(|name| !seen.insert(*name))
225}
226
227pub fn catalog(
229 providers: &[ToolProvider],
230 environment: &ToolEnvironment,
231) -> Result<Catalog, String> {
232 catalog_with_help(providers, Vec::new(), environment)
233}
234
235pub fn catalog_with_help(
238 providers: &[ToolProvider],
239 docs: Vec<BoardDoc>,
240 environment: &ToolEnvironment,
241) -> Result<Catalog, String> {
242 let mut tools: Vec<Arc<dyn AgentTool>> = providers
243 .iter()
244 .flat_map(|provider| provider(environment))
245 .collect();
246 let serves_board_tools = !tools.is_empty();
249 tools.extend(application_tools(docs, environment, serves_board_tools));
250 Catalog::new(tools)
251}
252
253pub fn application_tools(
255 docs: Vec<BoardDoc>,
256 environment: &ToolEnvironment,
257 serves_board_tools: bool,
258) -> Vec<Arc<dyn AgentTool>> {
259 let search_boards = docs.iter().map(|board| board.id.to_owned()).collect();
260 application_tools_for_boards(docs, environment, serves_board_tools, search_boards)
261}
262
263pub fn application_tools_for_boards(
265 docs: Vec<BoardDoc>,
266 environment: &ToolEnvironment,
267 serves_board_tools: bool,
268 search_boards: Vec<String>,
269) -> Vec<Arc<dyn AgentTool>> {
270 let has_boards = !docs.is_empty();
271 let mut tools: Vec<_> = help_tool(docs).into_iter().collect();
272 if has_boards {
273 tools.extend(search::tools(environment.search.clone(), search_boards));
274 }
275 if serves_board_tools {
276 tools.extend(web::tools(environment, None));
277 }
278 tools
279}
280
281pub fn encoded(value: impl Serialize) -> Result<Value, String> {
282 serde_json::to_value(value).map_err(|error| error.to_string())
283}
284
285pub fn decoded<T: DeserializeOwned>(value: Value) -> Result<T, String> {
286 serde_json::from_value(value).map_err(|error| error.to_string())
287}
288
289pub async fn blocking<T: Send + 'static>(
291 task: impl FnOnce() -> Result<T, String> + Send + 'static,
292) -> Result<T, String> {
293 tokio::task::spawn_blocking(task)
294 .await
295 .map_err(|error| format!("Service worker failed: {error}"))?
296}
297
298pub fn configured_repo(config: &Config, repo: &str) -> Result<(), String> {
302 if config
303 .repos
304 .iter()
305 .any(|known| known.eq_ignore_ascii_case(repo))
306 {
307 Ok(())
308 } else {
309 Err(format!("Repository is not configured: {repo}"))
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::{
316 Access, AgentTool, ApprovalPolicy, Catalog, Invocation, ToolEnvironment, ToolProvider,
317 ToolSpec, catalog, configured_repo, decoded, encoded,
318 };
319 use crate::test_support;
320 use async_trait::async_trait;
321 use serde_json::{Value, json};
322 use std::sync::Arc;
323 use subspace_core::config::Config;
324
325 struct Named(ToolSpec);
326
327 #[async_trait]
328 impl AgentTool for Named {
329 fn spec(&self) -> &ToolSpec {
330 &self.0
331 }
332 async fn call(&self, _invocation: Invocation) -> Result<Value, String> {
333 Ok(json!(self.0.name))
334 }
335 }
336
337 fn tool(name: &'static str) -> Arc<dyn AgentTool> {
338 Arc::new(Named(ToolSpec {
339 name,
340 title: name,
341 description: "test",
342 access: Access::Read,
343 arguments: crate::Arguments::Single { fields: Vec::new() },
344 approval: ApprovalPolicy::None,
345 }))
346 }
347
348 fn first(_: &ToolEnvironment) -> Vec<Arc<dyn AgentTool>> {
349 vec![tool("one_read"), tool("one_write")]
350 }
351
352 fn second(_: &ToolEnvironment) -> Vec<Arc<dyn AgentTool>> {
353 vec![tool("two_read")]
354 }
355
356 #[test]
357 fn the_catalog_keeps_provider_order_and_refuses_duplicate_names() {
358 let environment = test_support::environment(Config::default());
359 let providers: [ToolProvider; 2] = [first, second];
360 let tools = catalog(&providers, &environment).unwrap();
361 let names: Vec<&str> = tools.tools().iter().map(|tool| tool.spec().name).collect();
362 assert_eq!(names, ["one_read", "one_write", "two_read", "web_read"]);
363 assert!(tools.get("two_read").is_some());
364 assert!(tools.get("missing").is_none());
365 let error = catalog(&[first, first], &environment).err().unwrap();
366 assert!(error.contains("one_read"), "{error}");
367 assert!(Catalog::default().is_empty());
368 }
369
370 #[test]
371 fn the_help_tool_follows_the_board_tools_when_a_board_documents_itself() {
372 let environment = test_support::environment(Config::default());
373 let docs = vec![crate::BoardDoc {
374 id: "one",
375 title: "One",
376 markdown: "# One",
377 images: &[],
378 }];
379 let catalog = crate::catalog_with_help(&[first], docs, &environment).unwrap();
380 let names: Vec<&str> = catalog
381 .tools()
382 .iter()
383 .map(|tool| tool.spec().name)
384 .collect();
385 assert_eq!(
386 names,
387 ["one_read", "one_write", crate::HELP_TOOL, "web_read"]
388 );
389 let without = crate::catalog_with_help(&[first], Vec::new(), &environment).unwrap();
390 assert!(without.get(crate::HELP_TOOL).is_none());
391 }
392
393 #[test]
394 fn configured_boundaries_are_case_insensitive_but_not_prefixes() {
395 let config = Config {
396 repos: vec!["work/repo".into()],
397 ..Default::default()
398 };
399 assert!(configured_repo(&config, "WORK/REPO").is_ok());
400 for repo in ["work/repo-extra", "other/repo", "work"] {
401 assert!(configured_repo(&config, repo).is_err(), "{repo}");
402 }
403 }
404
405 #[test]
406 fn values_round_trip_and_decoding_errors_are_visible() {
407 assert_eq!(encoded(vec!["field"]).unwrap(), json!(["field"]));
408 assert_eq!(decoded::<Vec<u32>>(json!([1, 2])).unwrap(), [1, 2]);
409 assert!(decoded::<Vec<u32>>(json!("text")).is_err());
410 }
411
412 #[test]
413 fn a_write_tool_cannot_disable_approval() {
414 let invalid: Arc<dyn AgentTool> = Arc::new(Named(ToolSpec {
415 name: "invalid_write",
416 title: "Invalid",
417 description: "Invalid",
418 access: Access::Write,
419 arguments: crate::Arguments::Single { fields: Vec::new() },
420 approval: ApprovalPolicy::None,
421 }));
422 let error = Catalog::new(vec![invalid]).err().unwrap();
423 assert!(error.contains("per-call approval"), "{error}");
424 }
425}