Skip to main content

base/interface/tool/
result.rs

1//! What a running tool call reports and returns: progress, validation, result blocks.
2
3use super::*;
4
5/// One progress report of a running tool call. `progress` and `total` are in
6/// whatever unit the tool counts (lines, bytes, steps); either may be absent.
7#[derive(Debug, Clone, Default, PartialEq)]
8#[non_exhaustive]
9pub struct ProgressUpdate {
10    pub message: String,
11    pub progress: Option<f64>,
12    pub total: Option<f64>,
13}
14
15impl ProgressUpdate {
16    pub fn text(message: impl Into<String>) -> Self {
17        Self {
18            message: message.into(),
19            ..Self::default()
20        }
21    }
22    pub fn with_progress(mut self, progress: f64) -> Self {
23        self.progress = Some(progress);
24        self
25    }
26    pub fn with_total(mut self, total: f64) -> Self {
27        self.total = Some(total);
28        self
29    }
30}
31
32/// What a tool call reports progress through. The engine hands every call
33/// one that reaches the session's event stream as `AgentEvent::ToolProgress`,
34/// rate-limited per call; reports after the call returns are dropped.
35#[derive(Clone)]
36pub struct ProgressSender {
37    tool_use_id: String,
38    callback: Option<Arc<dyn ProgressCallback>>,
39}
40impl std::fmt::Debug for ProgressSender {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("ProgressSender")
43            .field("tool_use_id", &self.tool_use_id)
44            .finish_non_exhaustive()
45    }
46}
47pub trait ProgressCallback: Send + Sync {
48    fn on_progress(&self, tool_use_id: &str, data: &str);
49    fn on_update(&self, tool_use_id: &str, update: ProgressUpdate) {
50        self.on_progress(tool_use_id, &update.message);
51    }
52}
53impl ProgressSender {
54    pub fn noop(id: impl Into<String>) -> Self {
55        Self {
56            tool_use_id: id.into(),
57            callback: None,
58        }
59    }
60    pub fn new(id: impl Into<String>) -> Self {
61        Self {
62            tool_use_id: id.into(),
63            callback: None,
64        }
65    }
66    pub fn with_callback(id: impl Into<String>, cb: Arc<dyn ProgressCallback>) -> Self {
67        Self {
68            tool_use_id: id.into(),
69            callback: Some(cb),
70        }
71    }
72    pub fn send(&self, data: &str) {
73        if let Some(ref cb) = self.callback {
74            cb.on_progress(&self.tool_use_id, data);
75        }
76    }
77    pub fn update(&self, update: ProgressUpdate) {
78        if let Some(ref cb) = self.callback {
79            cb.on_update(&self.tool_use_id, update);
80        }
81    }
82    pub fn tool_use_id(&self) -> &str {
83        &self.tool_use_id
84    }
85}
86
87#[derive(Debug, Clone)]
88pub enum ValidationResult {
89    Ok,
90    Err(String, i32),
91}
92impl ValidationResult {
93    pub fn is_ok(&self) -> bool {
94        matches!(self, Self::Ok)
95    }
96    pub fn is_err(&self) -> bool {
97        matches!(self, Self::Err(..))
98    }
99    pub fn err(m: impl Into<String>, c: i32) -> Self {
100        Self::Err(m.into(), c)
101    }
102}
103
104#[derive(Debug, Clone, Serialize, Deserialize, Default)]
105#[non_exhaustive]
106pub struct ToolResult {
107    pub content: ToolResultContent,
108    pub is_error: bool,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub structured_content: Option<Value>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub mcp_meta: Option<McpMeta>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub new_messages: Option<Vec<Value>>,
115    /// The files this call wrote, for the host; the model never sees it.
116    #[serde(default, skip_serializing_if = "Vec::is_empty")]
117    pub file_changes: Vec<FileChange>,
118}
119
120/// One file a tool call wrote, as `tool_result` reports it to the host.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
122#[non_exhaustive]
123pub struct FileChange {
124    /// The resolved write target, absolute.
125    pub path: String,
126    pub op: FileOp,
127    /// `sha256:<hex>` of the content before; `None` when there was none or
128    /// it was too large to hash.
129    pub before_hash: Option<String>,
130    pub after_hash: Option<String>,
131    pub before_bytes: Option<u64>,
132    pub after_bytes: u64,
133    pub added: u64,
134    pub removed: u64,
135    /// `--- a/<path>` / `+++ b/<path>`, three lines of context.
136    pub unified_diff: Option<String>,
137    /// The diff stops at a hunk boundary short of the whole change.
138    pub truncated: bool,
139    /// Why there is no diff, when there is none.
140    pub omitted: Option<DiffOmitted>,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
144#[serde(rename_all = "snake_case")]
145#[non_exhaustive]
146pub enum FileOp {
147    Create,
148    Modify,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
152#[serde(rename_all = "snake_case")]
153#[non_exhaustive]
154pub enum DiffOmitted {
155    TooLarge,
156    Binary,
157    /// A result transformer rewrote the call's text, and the diff would
158    /// carry the file content it may have removed.
159    Redacted,
160}
161
162impl FileChange {
163    pub fn new(path: impl Into<String>, op: FileOp, after_bytes: u64) -> Self {
164        Self {
165            path: path.into(),
166            op,
167            before_hash: None,
168            after_hash: None,
169            before_bytes: None,
170            after_bytes,
171            added: 0,
172            removed: 0,
173            unified_diff: None,
174            truncated: false,
175            omitted: None,
176        }
177    }
178
179    /// What may go to a host that must not see the file's content.
180    pub fn without_content(mut self) -> Self {
181        if self.unified_diff.take().is_some() || self.omitted.is_none() {
182            self.omitted = Some(DiffOmitted::Redacted);
183        }
184        self.truncated = false;
185        self
186    }
187}
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct McpMeta {
190    #[serde(default)]
191    pub server_name: String,
192}
193#[derive(Debug, Clone, Serialize, Deserialize)]
194#[serde(untagged)]
195pub enum ToolResultContent {
196    Text(String),
197    Blocks(Vec<ToolResultBlock>),
198}
199impl Default for ToolResultContent {
200    fn default() -> Self {
201        Self::Text(String::new())
202    }
203}
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ToolResultBlock {
206    #[serde(rename = "type")]
207    pub block_type: String,
208    pub text: Option<String>,
209    pub source: Option<Value>,
210}
211
212/// Largest image, decoded, that goes to the model as one image block. The API
213/// refuses an image over 5 MB of base64 — 3.75 MB decoded — and the refused
214/// request would carry it again on every later turn; rounded down to leave
215/// room for the rest of the request.
216pub const MAX_IMAGE_BYTES: u64 = 3_500_000;
217
218/// Constructors/accessors for the two block shapes the model layer understands.
219///
220/// The `source` object of an image block is the Anthropic `image.source` shape
221/// (`{type: "base64", media_type, data}`) verbatim — MCP servers already hand us
222/// that shape, and the runtime's tool-result renderer reads it back out with
223/// [`ToolResultBlock::as_image`]. Building it through these two functions keeps
224/// the producer (`Read`, the MCP adapter) and the consumer from drifting apart.
225impl ToolResultBlock {
226    pub fn text(s: impl Into<String>) -> Self {
227        Self {
228            block_type: "text".into(),
229            text: Some(s.into()),
230            source: None,
231        }
232    }
233    pub fn image(media_type: impl Into<String>, data: impl Into<String>) -> Self {
234        Self {
235            block_type: "image".into(),
236            text: None,
237            source: Some(serde_json::json!({
238                "type": "base64",
239                "media_type": media_type.into(),
240                "data": data.into(),
241            })),
242        }
243    }
244    /// `(media_type, base64_data)` when this is a well-formed image block.
245    pub fn as_image(&self) -> Option<(&str, &str)> {
246        if self.block_type != "image" {
247            return None;
248        }
249        let source = self.source.as_ref()?;
250        Some((
251            source.get("media_type")?.as_str()?,
252            source.get("data")?.as_str()?,
253        ))
254    }
255}
256
257impl ToolResult {
258    pub fn text(s: impl Into<String>) -> Self {
259        Self {
260            content: ToolResultContent::Text(s.into()),
261            is_error: false,
262            structured_content: None,
263            mcp_meta: None,
264            new_messages: None,
265            file_changes: Vec::new(),
266        }
267    }
268    pub fn error_text(s: impl Into<String>) -> Self {
269        Self {
270            content: ToolResultContent::Text(s.into()),
271            is_error: true,
272            structured_content: None,
273            mcp_meta: None,
274            new_messages: None,
275            file_changes: Vec::new(),
276        }
277    }
278    pub fn blocks(blocks: Vec<ToolResultBlock>) -> Self {
279        Self {
280            content: ToolResultContent::Blocks(blocks),
281            ..Self::default()
282        }
283    }
284    pub fn with_error(mut self, is_error: bool) -> Self {
285        self.is_error = is_error;
286        self
287    }
288    pub fn with_structured(mut self, v: Value) -> Self {
289        self.structured_content = Some(v);
290        self
291    }
292    pub fn with_mcp_meta(mut self, m: McpMeta) -> Self {
293        self.mcp_meta = Some(m);
294        self
295    }
296    pub fn with_new_messages(mut self, m: Vec<Value>) -> Self {
297        self.new_messages = Some(m);
298        self
299    }
300    pub fn with_file_change(mut self, change: FileChange) -> Self {
301        self.file_changes.push(change);
302        self
303    }
304}