pravah 0.2.0

Typed, stepwise agentic information flows for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::future::Future;
use std::marker::PhantomData;
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;

use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde_json::Value;
use thiserror::Error;

use crate::clients::ToolCall;
use crate::context::Context;
use crate::deps::DepsError;

/// Error produced when a tool invocation fails.
#[derive(Debug, Error)]
pub enum ToolError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("failed to serialize output: {0}")]
    Serialize(serde_json::Error),
    #[error("failed to deserialize input: {0}")]
    Deserialize(serde_json::Error),
    #[error("unknown tool '{0}")]
    UnknownTool(String),
    #[error("path '{0}' escapes the working directory")]
    PathEscape(String),
    #[error("command '{0}' is not in the allowed list")]
    ForbiddenCommand(String),
    #[error("http error: {0}")]
    Http(String),
    #[error("{0}")]
    Missing(#[from] DepsError),
    #[error("{0}")]
    Other(#[from] Box<dyn std::error::Error + Send + Sync>),
    /// Auto-generated `submit` sentinel signalling a flow state transition.
    /// Caught by the orchestrator before reaching history; never propagates to user code.
    #[doc(hidden)]
    #[error("exit signal from tool")]
    Exit(serde_json::Value),
    /// A tool requesting user input before the flow can continue.
    /// Produced by [`ToolError::suspend`]; caught by the orchestrator, which transitions
    /// to the matching resume variant and returns [`crate::flows::FlowError::Suspended`].
    #[error("suspend signal from tool")]
    Suspend(serde_json::Value),
}

impl ToolError {
    /// Serializes `val` and wraps it as a suspend signal.
    ///
    /// On serialization failure, returns [`ToolError::Serialize`] instead of panicking.
    pub fn suspend<T: serde::Serialize + 'static>(val: T) -> Self {
        match serde_json::to_value(&val) {
            Ok(value) => ToolError::Suspend(value),
            Err(e) => ToolError::Serialize(e),
        }
    }
}

impl Context {
    /// Returns `Ok(())` if `cmd` appears in the `commands` allowlist.
    pub fn check_command(&self, cmd: &str) -> Result<(), ToolError> {
        if self.commands().iter().any(|c| c == cmd) {
            Ok(())
        } else {
            Err(ToolError::ForbiddenCommand(cmd.to_owned()))
        }
    }

    /// Resolves `raw` to an absolute path and verifies it stays within `working_dir`.
    ///
    /// Relative paths are resolved against `working_dir`. `..` components are
    /// collapsed without hitting the filesystem, so this check is safe for
    /// paths that do not yet exist (e.g. write targets).
    pub fn resolve(&self, raw: &str) -> Result<PathBuf, ToolError> {
        let working_dir = normalize_path(self.working_dir());
        let path = Path::new(raw);
        let requested = if path.is_absolute() {
            normalize_path(path)
        } else {
            normalize_path(&working_dir.join(path))
        };
        if !requested.starts_with(&working_dir) {
            return Err(ToolError::PathEscape(raw.to_owned()));
        }
        let canonical_root = canonical_working_dir(&working_dir)?;
        let relative = requested
            .strip_prefix(&working_dir)
            .map_err(|_| ToolError::PathEscape(raw.to_owned()))?;
        resolve_within_root(raw, &canonical_root, relative)
    }
}

fn canonical_working_dir(path: &Path) -> Result<PathBuf, ToolError> {
    match std::fs::canonicalize(path) {
        Ok(canonical) => Ok(canonical),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(path.to_path_buf()),
        Err(error) => Err(ToolError::Io(error)),
    }
}

fn resolve_within_root(raw: &str, root: &Path, relative: &Path) -> Result<PathBuf, ToolError> {
    let mut resolved = root.to_path_buf();

    for component in relative.components() {
        match component {
            Component::CurDir => continue,
            Component::ParentDir => {
                resolved.pop();
            }
            Component::Normal(part) => {
                resolved.push(part);
                match std::fs::symlink_metadata(&resolved) {
                    Ok(meta) if meta.file_type().is_symlink() => {
                        let canonical = std::fs::canonicalize(&resolved)?;
                        if !canonical.starts_with(root) {
                            return Err(ToolError::PathEscape(raw.to_owned()));
                        }
                        resolved = canonical;
                    }
                    Ok(_) => {}
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(error) => return Err(ToolError::Io(error)),
                }
            }
            Component::RootDir => {
                resolved = root.to_path_buf();
            }
            Component::Prefix(_) => {
                return Err(ToolError::PathEscape(raw.to_owned()));
            }
        }

        if !resolved.starts_with(root) {
            return Err(ToolError::PathEscape(raw.to_owned()));
        }
    }

    Ok(resolved)
}

/// Collapses `.` and `..` components without touching the filesystem.
fn normalize_path(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            c => out.push(c),
        }
    }
    out
}

/// The output of a single tool invocation.
#[derive(Debug)]
pub struct ToolOutput {
    pub call: ToolCall,
    pub value: serde_json::Value,
}

/// Metadata the orchestrator sends to the LLM to advertise a tool.
#[derive(Debug, Clone)]
pub struct ToolDefinition {
    pub name: String,
    pub description: String,
    /// JSON Schema `object` describing the tool's input shape.
    pub parameters: Value,
}

/// Typed tool trait where `Self` is both the tool and its deserialized input.
///
/// Implement this trait on a struct that derives [`serde::Deserialize`] and
/// [`JsonSchema`]. The struct's fields become the LLM-callable arguments.
/// [`ToolDefinition`] is derived automatically via [`Tool::definition`].
pub trait Tool: DeserializeOwned + JsonSchema + Sized + Send {
    /// Typed output this tool produces. Must be `Serialize` so `ErasedTool` can
    /// convert it to `serde_json::Value` after dispatch without the caller
    /// building raw JSON.
    type Output: serde::Serialize + Send;

    fn name() -> &'static str;

    fn description() -> &'static str;

    /// Execute the tool, consuming `self` (the parsed input).
    fn call(self, ctx: Context) -> impl Future<Output = Result<Self::Output, ToolError>> + Send;

    /// Derives a [`ToolDefinition`] from this tool's metadata and input schema.
    fn definition() -> ToolDefinition {
        let parameters = serde_json::to_value(schemars::schema_for!(Self))
            .unwrap_or_else(|e| {
                tracing::error!(tool = Self::name(), error = %e, "tool schema serialization failed; parameters will be empty");
                Value::Object(Default::default())
            });
        ToolDefinition {
            name: Self::name().to_owned(),
            description: Self::description().to_owned(),
            parameters,
        }
    }
}

/// Creates a heap-allocated type-erased dispatcher for tool type `T`.
/// Crate-internal; used by [`ToolBoxBuilder::tool`] and `commons`.
pub(crate) fn make_dispatcher<T: Tool + 'static>() -> Box<dyn ErasedTool> {
    Box::new(ToolDispatcher::<T>(PhantomData))
}

/// Object-safe wrapper around [`Tool`] for use in heterogeneous collections.
///
/// Do not implement this directly — use the blanket impl via [`Tool`].
pub(crate) trait ErasedTool: Send + Sync {
    fn name(&self) -> &str;
    fn definition(&self) -> ToolDefinition;
    /// Deserializes `args` into the concrete tool type, calls it, returns the output.
    fn call_raw<'a>(
        &'a self,
        ctx: Context,
        args: Value,
    ) -> Pin<Box<dyn Future<Output = Result<serde_json::Value, ToolError>> + Send + 'a>>;
}

/// Zero-sized adapter that makes any [`Tool`] object-safe as [`ErasedTool`].
struct ToolDispatcher<T>(PhantomData<fn() -> T>);

impl<T: Tool + 'static> ErasedTool for ToolDispatcher<T> {
    fn name(&self) -> &str {
        T::name()
    }

    fn definition(&self) -> ToolDefinition {
        T::definition()
    }

    fn call_raw<'a>(
        &'a self,
        ctx: Context,
        args: Value,
    ) -> Pin<Box<dyn Future<Output = Result<serde_json::Value, ToolError>> + Send + 'a>> {
        Box::pin(async move {
            let input: T = serde_json::from_value(args).map_err(ToolError::Deserialize)?;
            let output = input.call(ctx).await?;
            serde_json::to_value(output).map_err(ToolError::Serialize)
        })
    }
}

/// Stateless registry of tools. Shareable across agents via `Arc<ToolBox>`.
///
/// Build with [`ToolBox::builder`]; dispatch with [`ToolBox::call`].
pub struct ToolBox {
    tools: Vec<Box<dyn ErasedTool>>,
    exit_name: String,
}

impl ToolBox {
    /// Starts building a new [`ToolBox`].
    pub fn builder() -> ToolBoxBuilder {
        ToolBoxBuilder {
            tools: Vec::new(),
            exit_name: "submit".to_owned(),
        }
    }

    /// Returns the name used for the auto-generated exit sentinel tool.
    pub fn exit_name(&self) -> &str {
        &self.exit_name
    }

    /// Returns the [`ToolDefinition`] for every registered tool.
    pub fn definitions(&self) -> Vec<ToolDefinition> {
        self.tools.iter().map(|t| t.definition()).collect()
    }

    /// Returns `true` if no tools have been registered.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Appends a pre-boxed tool. `pub(crate)` so only `commons` can inject the sentinel.
    pub(crate) fn push_erased(&mut self, tool: Box<dyn ErasedTool>) {
        self.tools.push(tool);
    }

    /// Dispatches `tool_call` to the matching tool, using `ctx` for execution.
    pub async fn call(&self, tool_call: &ToolCall, ctx: Context) -> Result<ToolOutput, ToolError> {
        let tool = self
            .tools
            .iter()
            .find(|t| t.name() == tool_call.name)
            .ok_or_else(|| ToolError::UnknownTool(tool_call.name.clone()))?;
        let call = tool_call.clone();
        tool.call_raw(ctx, tool_call.args.clone())
            .await
            .map(|o| ToolOutput { call, value: o })
    }
}

/// Builder for [`ToolBox`].
pub struct ToolBoxBuilder {
    tools: Vec<Box<dyn ErasedTool>>,
    exit_name: String,
}

impl ToolBoxBuilder {
    /// Overrides the name of the auto-generated exit sentinel tool (default: `"submit"`).
    pub fn with_exit_name(mut self, name: impl Into<String>) -> Self {
        self.exit_name = name.into();
        self
    }

    /// Returns the current exit sentinel tool name.
    pub fn exit_name(&self) -> &str {
        &self.exit_name
    }

    /// Registers a tool type `T`. Call multiple times to add more tools.
    pub fn tool<T: Tool + 'static>(mut self) -> Self {
        self.tools.push(make_dispatcher::<T>());
        self
    }

    /// Finishes the builder and returns the registered toolbox.
    pub fn build(self) -> ToolBox {
        ToolBox {
            tools: self.tools,
            exit_name: self.exit_name,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use serde_json::json;
    use tempfile::NamedTempFile;

    use super::*;
    use crate::context::FlowConf;
    use crate::tools::fs::{ReadFile, WriteFile};

    fn ctx(dir: &std::path::Path) -> Context {
        Context::new(FlowConf {
            working_dir: Some(dir.to_path_buf()),
            ..Default::default()
        })
    }

    /// Verifies that all registered tool definitions are collected with correct names.
    #[test]
    fn toolbox_collects_definitions() {
        let tb = ToolBox::builder()
            .tool::<ReadFile>()
            .tool::<WriteFile>()
            .build();
        let defs = tb.definitions();
        assert_eq!(defs.len(), 2);
        assert_eq!(defs[0].name, "read_file");
        assert_eq!(defs[1].name, "write_file");
    }

    /// Verifies that `call` dispatches to the correct tool and returns its output.
    #[tokio::test]
    async fn toolbox_dispatches_read_file() {
        let mut tmp = NamedTempFile::new().unwrap();
        write!(tmp, "hello toolbox").unwrap();
        let path = tmp.path().to_string_lossy().into_owned();

        let tb = ToolBox::builder().tool::<ReadFile>().build();
        let tc = ToolCall {
            id: "1".into(),
            name: "read_file".into(),
            args: json!({ "path": path }),
            thought_signatures: None,
        };
        let output = tb
            .call(&tc, ctx(tmp.path().parent().unwrap()))
            .await
            .unwrap();
        let result = output.value;
        assert_eq!(result["content"], "hello toolbox");
    }

    /// Verifies that calling an unregistered tool name returns `ToolError::UnknownTool`.
    #[tokio::test]
    async fn toolbox_unknown_tool_returns_error() {
        let tb = ToolBox::builder().tool::<ReadFile>().build();
        let tc = ToolCall {
            id: "x".into(),
            name: "no_such_tool".into(),
            args: json!({}),
            thought_signatures: None,
        };
        let err = tb
            .call(&tc, ctx(std::path::Path::new("/tmp")))
            .await
            .unwrap_err();
        assert!(matches!(err, ToolError::UnknownTool(n) if n == "no_such_tool"));
    }
}