Skip to main content

subspace_agent_tools/
read.rs

1//! A read tool: one typed request, one blocking service call, no approval.
2
3use super::{AgentTool, CallMonitor, Invocation, ToolSpec, blocking, decoded};
4use async_trait::async_trait;
5use serde::de::DeserializeOwned;
6use serde_json::Value;
7use std::sync::Arc;
8
9/// A board's read actions. `Request` is a strict, `action`-tagged enum, so an
10/// unknown action or field is refused before any service call.
11pub trait ReadService: Send + Sync + 'static {
12    type Request: DeserializeOwned + Send + 'static;
13    fn read(&self, request: Self::Request) -> Result<Value, String>;
14
15    /// Boards with cancellable clients override this without changing older tools.
16    fn read_monitored(
17        &self,
18        request: Self::Request,
19        monitor: &dyn CallMonitor,
20    ) -> Result<Value, String> {
21        if monitor.cancelled() {
22            return Err("The read was cancelled before it started.".into());
23        }
24        self.read(request)
25    }
26}
27
28pub struct ReadTool<S: ReadService> {
29    spec: ToolSpec,
30    service: Arc<S>,
31}
32
33impl<S: ReadService> ReadTool<S> {
34    pub fn new(spec: ToolSpec, service: Arc<S>) -> Self {
35        Self { spec, service }
36    }
37}
38
39#[async_trait]
40impl<S: ReadService> AgentTool for ReadTool<S> {
41    fn spec(&self) -> &ToolSpec {
42        &self.spec
43    }
44
45    async fn call(&self, invocation: Invocation) -> Result<Value, String> {
46        let request = decoded::<S::Request>(invocation.arguments)?;
47        let service = self.service.clone();
48        blocking(move || service.read_monitored(request, invocation.monitor.as_ref())).await
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::{ReadService, ReadTool};
55    use crate::{Access, AgentTool, ApprovalPolicy, Arguments, ToolSpec, test_support};
56    use serde::Deserialize;
57    use serde_json::{Value, json};
58    use std::sync::Arc;
59
60    struct Cancelled;
61
62    impl crate::CallMonitor for Cancelled {
63        fn cancelled(&self) -> bool {
64            true
65        }
66    }
67
68    #[derive(Deserialize)]
69    #[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
70    enum Request {
71        Echo { text: String },
72    }
73
74    struct Echo;
75
76    impl ReadService for Echo {
77        type Request = Request;
78        fn read(&self, request: Request) -> Result<Value, String> {
79            let Request::Echo { text } = request;
80            Ok(json!({ "text": text }))
81        }
82    }
83
84    #[tokio::test]
85    async fn a_read_decodes_strictly_and_never_asks_for_approval() {
86        let tool = ReadTool::new(
87            ToolSpec {
88                name: "echo_read",
89                title: "Echo",
90                description: "Echo",
91                access: Access::Read,
92                arguments: Arguments::Single { fields: Vec::new() },
93                approval: ApprovalPolicy::None,
94            },
95            Arc::new(Echo),
96        );
97        let (approval, invocation) =
98            test_support::invocation(json!({"action":"echo","text":"hi"}), true);
99        assert_eq!(tool.call(invocation).await.unwrap()["text"], "hi");
100        let (_, unknown) = test_support::invocation(json!({"action":"raw_http"}), true);
101        assert!(tool.call(unknown).await.is_err());
102        let (_, extra) =
103            test_support::invocation(json!({"action":"echo","text":"hi","token":"x"}), true);
104        assert!(tool.call(extra).await.is_err());
105        assert!(approval.summaries().is_empty());
106    }
107
108    #[tokio::test]
109    async fn a_cancelled_read_does_not_start_a_service_call() {
110        let tool = ReadTool::new(
111            ToolSpec {
112                name: "echo_read",
113                title: "Echo",
114                description: "Echo",
115                access: Access::Read,
116                arguments: Arguments::Single { fields: Vec::new() },
117                approval: ApprovalPolicy::None,
118            },
119            Arc::new(Echo),
120        );
121        let (_, mut invocation) =
122            test_support::invocation(json!({"action":"echo","text":"hi"}), true);
123        invocation.monitor = Arc::new(Cancelled);
124        assert!(tool.call(invocation).await.is_err());
125    }
126}