Skip to main content

pixie_pi/agent/
tool.rs

1//! Tool abstraction (`AgentTool` trait) and the permission gate hook.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use tokio_util::sync::CancellationToken;
9
10use crate::ai::types::{ToolResultContent, ToolSchema};
11
12/// How tool calls within a single assistant message are executed.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub enum ExecutionMode {
15    /// Tool calls run one at a time.
16    Sequential,
17    /// Tool calls run concurrently (default).
18    #[default]
19    Parallel,
20}
21
22/// The structured result of executing a tool. `content` is what the model sees.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct ToolResult {
25    pub content: Vec<ToolResultContent>,
26    /// Auxiliary payload attached by some tools (the bash truncation marker,
27    /// the edit diff + first-changed line). Not consumed by the loop or sent to
28    /// the model — only `content` is — but serialized with the result for
29    /// debugging, so it is always emitted (never skipped).
30    #[serde(default)]
31    pub details: Value,
32    #[serde(default)]
33    pub terminate: bool,
34}
35
36impl ToolResult {
37    pub fn text(text: impl Into<String>) -> Self {
38        Self {
39            content: vec![ToolResultContent::text(text)],
40            details: Value::Null,
41            terminate: false,
42        }
43    }
44
45    pub fn error(message: impl Into<String>) -> Self {
46        Self::text(message)
47    }
48
49    pub fn with_details(mut self, details: Value) -> Self {
50        self.details = details;
51        self
52    }
53}
54
55/// A tool the agent can call. `prepare_arguments` lets a tool normalize raw
56/// model arguments before validation (e.g. the edit tool accepting a legacy
57/// `oldText`/`newText` shape).
58#[async_trait]
59pub trait AgentTool: Send + Sync {
60    fn name(&self) -> &str;
61    fn label(&self) -> &str {
62        self.name()
63    }
64    fn description(&self) -> &str;
65    /// JSON Schema (object) describing the tool's parameters.
66    fn input_schema(&self) -> Value;
67    fn execution_mode(&self) -> ExecutionMode {
68        ExecutionMode::Parallel
69    }
70    fn prepare_arguments(&self, args: Value) -> Value {
71        args
72    }
73    /// Execute the tool. Throw on failure — the loop converts the error into
74    /// an error tool result.
75    async fn execute(
76        &self,
77        args: Value,
78        cancel: CancellationToken,
79    ) -> anyhow::Result<ToolResult>;
80
81    /// The schema fragment sent to the model.
82    fn schema(&self) -> ToolSchema {
83        ToolSchema {
84            name: self.name().to_string(),
85            description: self.description().to_string(),
86            input_schema: self.input_schema(),
87        }
88    }
89}
90
91/// Lightweight required-field validation against a JSON schema. Ensures keys
92/// listed in `required` are present (non-null) before a tool runs.
93pub fn validate_required(schema: &Value, args: &Value) -> Result<(), String> {
94    let Some(required) = schema.get("required").and_then(|v| v.as_array()) else {
95        return Ok(());
96    };
97    let obj = args.as_object().ok_or_else(|| "tool arguments must be an object".to_string())?;
98    for r in required {
99        if let Some(key) = r.as_str() {
100            let present = obj
101                .get(key)
102                .map(|v| !v.is_null())
103                .unwrap_or(false);
104            if !present {
105                return Err(format!("missing required parameter: {key}"));
106            }
107        }
108    }
109    Ok(())
110}
111
112// ---------------------------------------------------------------------------
113// Permission gate
114// ---------------------------------------------------------------------------
115
116/// Context handed to a [`ToolGate`] before a tool runs.
117pub struct ToolCallContext<'a> {
118    pub tool_call_id: &'a str,
119    pub tool_name: &'a str,
120    pub args: &'a Value,
121}
122
123/// Result of a `beforeToolCall` check.
124pub struct BeforeToolCallResult {
125    pub block: bool,
126    pub reason: Option<String>,
127}
128
129impl BeforeToolCallResult {
130    pub fn allow() -> Self {
131        Self {
132            block: false,
133            reason: None,
134        }
135    }
136    pub fn block(reason: impl Into<String>) -> Self {
137        Self {
138            block: true,
139            reason: Some(reason.into()),
140        }
141    }
142}
143
144/// Hook that may block a tool call (e.g. ask the user for permission).
145#[async_trait]
146pub trait ToolGate: Send + Sync {
147    async fn before(&self, ctx: ToolCallContext<'_>) -> BeforeToolCallResult;
148}
149
150/// A gate that permits every call.
151pub struct AllowAllGate;
152
153#[async_trait]
154impl ToolGate for AllowAllGate {
155    async fn before(&self, _ctx: ToolCallContext<'_>) -> BeforeToolCallResult {
156        BeforeToolCallResult::allow()
157    }
158}
159
160pub fn allow_all_gate() -> Arc<dyn ToolGate> {
161    Arc::new(AllowAllGate)
162}