1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use super::image;
7pub use crate::terminal_text::clean_output;
8
9const TEXT_LIMIT: usize = 64 * 1024;
11const JSON_LIMIT: usize = 512 * 1024;
13const RESULT_LIMIT: usize = 8 * 1024 * 1024;
15const MAX_CONTENT_BLOCKS: usize = 32;
17
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
22pub enum Content {
23 Text {
24 text: String,
25 },
26 Json {
27 data: Value,
28 },
29 Image {
31 data: String,
32 #[serde(rename = "mimeType")]
33 mime_type: image::Mime,
34 },
35}
36
37#[derive(Debug, Clone, PartialEq)]
40pub struct ContentBlocks<T>(Vec<T>);
41
42impl<T> ContentBlocks<T> {
43 pub fn new(content: Vec<T>) -> Result<Self, InvalidResult> {
44 if !(1..=MAX_CONTENT_BLOCKS).contains(&content.len()) {
45 return Err(InvalidResult(
46 "tool result must contain 1..=32 content blocks",
47 ));
48 }
49 Ok(Self(content))
50 }
51
52 pub fn as_slice(&self) -> &[T] {
53 &self.0
54 }
55
56 pub fn into_vec(self) -> Vec<T> {
57 self.0
58 }
59
60 fn try_map<U, E>(self, map: impl FnMut(T) -> Result<U, E>) -> Result<ContentBlocks<U>, E> {
62 self.0
63 .into_iter()
64 .map(map)
65 .collect::<Result<_, _>>()
66 .map(ContentBlocks)
67 }
68}
69
70#[derive(Debug, Clone, PartialEq)]
73pub struct ErrorMessage(Content);
74
75impl ErrorMessage {
76 pub fn new(message: impl Into<String>) -> Result<Self, InvalidResult> {
77 let text = message.into();
78 if text.trim().is_empty() {
79 return Err(InvalidResult("tool error message must not be blank"));
80 }
81 Ok(Self(Content::Text { text }))
82 }
83
84 pub fn diagnostic(message: impl Into<String>) -> Self {
86 Self::new(message)
87 .unwrap_or_else(|_| Self::new("Tool failed.").expect("fallback is nonblank"))
88 }
89
90 pub fn as_str(&self) -> &str {
91 let Content::Text { text } = &self.0 else {
92 unreachable!("error messages are constructed only from text")
93 };
94 text
95 }
96}
97
98#[derive(Debug, thiserror::Error)]
100#[error("{0}")]
101pub struct InvalidResult(&'static str);
102
103#[derive(Debug, Clone, PartialEq)]
105pub enum ToolResult {
106 Success(ContentBlocks<Content>),
107 Error(ErrorMessage),
108}
109
110impl ToolResult {
111 pub fn success(content: Content) -> Self {
113 Self::Success(ContentBlocks(vec![content]))
114 }
115
116 pub fn try_success(content: Vec<Content>) -> Result<Self, InvalidResult> {
117 ContentBlocks::new(content).map(Self::Success)
118 }
119
120 pub fn error(message: impl Into<String>) -> Self {
123 Self::Error(ErrorMessage::diagnostic(message))
124 }
125
126 pub fn is_error(&self) -> bool {
127 matches!(self, Self::Error(_))
128 }
129
130 pub fn content(&self) -> &[Content] {
131 match self {
132 Self::Success(content) => content.as_slice(),
133 Self::Error(message) => std::slice::from_ref(&message.0),
134 }
135 }
136
137 pub fn into_content(self) -> Vec<Content> {
138 match self {
139 Self::Success(content) => content.into_vec(),
140 Self::Error(message) => vec![message.0],
141 }
142 }
143
144 fn from_wire(content: Vec<Content>, is_error: bool) -> Result<Self, InvalidResult> {
145 if !is_error {
146 return Self::try_success(content);
147 }
148 let [Content::Text { text }] = content.as_slice() else {
149 return Err(InvalidResult(
150 "tool error must contain exactly one text block",
151 ));
152 };
153 ErrorMessage::new(text.clone()).map(Self::Error)
154 }
155}
156
157impl Serialize for ToolResult {
158 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
159 use serde::ser::SerializeStruct;
160 let mut result =
161 serializer.serialize_struct("ToolResult", if self.is_error() { 2 } else { 1 })?;
162 result.serialize_field("content", self.content())?;
163 if self.is_error() {
164 result.serialize_field("isError", &true)?;
165 }
166 result.end()
167 }
168}
169
170impl<'de> Deserialize<'de> for ToolResult {
171 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
172 #[derive(Deserialize)]
175 #[serde(rename_all = "camelCase", deny_unknown_fields)]
176 struct SavedResult {
177 content: Vec<Content>,
178 #[serde(default)]
179 is_error: bool,
180 }
181 let saved = SavedResult::deserialize(deserializer)?;
182 Self::from_wire(saved.content, saved.is_error).map_err(serde::de::Error::custom)
183 }
184}
185
186#[derive(Deserialize)]
187#[serde(rename_all = "camelCase", deny_unknown_fields)]
188struct WireResult {
189 content: Vec<WireContent<WireImage>>,
190 #[serde(default)]
191 is_error: bool,
192}
193
194#[derive(Deserialize)]
195#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)]
196enum WireContent<I> {
197 Text { text: String },
198 Json { data: Value },
199 Image(I),
200}
201
202#[derive(Deserialize)]
205#[serde(untagged)]
206enum WireImage {
207 Data(InlineImage),
208 Path(ImageFile),
209}
210
211#[derive(Deserialize)]
212#[serde(rename_all = "camelCase", deny_unknown_fields)]
213struct InlineImage {
214 mime_type: image::Mime,
215 data: String,
216}
217
218#[derive(Deserialize)]
219#[serde(rename_all = "camelCase", deny_unknown_fields)]
220struct ImageFile {
221 mime_type: image::Mime,
222 #[serde(deserialize_with = "image_path")]
223 path: PathBuf,
224}
225
226fn image_path<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<PathBuf, D::Error> {
227 let path = String::deserialize(deserializer)?;
228 crate::files::path_from_text(&path).map_err(serde::de::Error::custom)
229}
230
231#[derive(Debug, thiserror::Error)]
233#[error("Agent tool returned invalid output.")]
234pub struct InvalidOutput;
235
236pub fn parse(stdout: &[u8], output_dir: &Path) -> Result<ToolResult, InvalidOutput> {
237 let result = match parse_wire(stdout)? {
238 CommandOutput::Error(message) => {
239 if message.as_str().len() > TEXT_LIMIT {
240 return Err(InvalidOutput);
241 }
242 ToolResult::Error(message)
243 }
244 CommandOutput::Success(blocks) => {
245 let mut size = 0;
246 let normalized = blocks.try_map(|block| {
247 let block = normalize(load(block, output_dir)?)?;
248 size += serde_json::to_vec(&block).map_err(|_| InvalidOutput)?.len();
249 (size <= RESULT_LIMIT).then_some(block).ok_or(InvalidOutput)
250 })?;
251 ToolResult::Success(normalized)
252 }
253 };
254 if serde_json::to_vec(&result)
255 .map_err(|_| InvalidOutput)?
256 .len()
257 > RESULT_LIMIT
258 {
259 return Err(InvalidOutput);
260 }
261 Ok(result)
262}
263
264enum CommandOutput {
265 Success(ContentBlocks<WireContent<WireImage>>),
266 Error(ErrorMessage),
267}
268
269fn parse_wire(stdout: &[u8]) -> Result<CommandOutput, InvalidOutput> {
270 let wire: WireResult =
272 serde_json::from_str(&crate::platform::text::output(stdout)).map_err(|_| InvalidOutput)?;
273 if !wire.is_error {
274 return ContentBlocks::new(wire.content)
275 .map(CommandOutput::Success)
276 .map_err(|_| InvalidOutput);
277 }
278 let [WireContent::Text { text }] =
279 <[_; 1]>::try_from(wire.content).map_err(|_| InvalidOutput)?
280 else {
281 return Err(InvalidOutput);
282 };
283 ErrorMessage::new(text)
284 .map(CommandOutput::Error)
285 .map_err(|_| InvalidOutput)
286}
287
288enum LoadedImage {
289 Data(InlineImage),
290 FileBytes {
291 mime_type: image::Mime,
292 bytes: Vec<u8>,
293 },
294}
295
296fn load(
297 block: WireContent<WireImage>,
298 output_dir: &Path,
299) -> Result<WireContent<LoadedImage>, InvalidOutput> {
300 Ok(match block {
301 WireContent::Text { text } => WireContent::Text { text },
302 WireContent::Json { data } => WireContent::Json { data },
303 WireContent::Image(WireImage::Data(data)) => WireContent::Image(LoadedImage::Data(data)),
304 WireContent::Image(WireImage::Path(ImageFile { mime_type, path })) => {
305 let bytes = image::read_output(output_dir, &path).map_err(|_| InvalidOutput)?;
306 WireContent::Image(LoadedImage::FileBytes { mime_type, bytes })
307 }
308 })
309}
310
311fn normalize(block: WireContent<LoadedImage>) -> Result<Content, InvalidOutput> {
313 match block {
314 WireContent::Text { text } if text.len() <= TEXT_LIMIT => Ok(Content::Text { text }),
315 WireContent::Json { data }
316 if serde_json::to_vec(&data).map_err(|_| InvalidOutput)?.len() <= JSON_LIMIT =>
317 {
318 Ok(Content::Json { data })
319 }
320 WireContent::Image(LoadedImage::Data(InlineImage { mime_type, data })) => {
321 image::normalize_base64(&data, mime_type).map_err(|_| InvalidOutput)
322 }
323 WireContent::Image(LoadedImage::FileBytes { mime_type, bytes }) => {
324 image::normalize(&bytes, Some(mime_type)).map_err(|_| InvalidOutput)
325 }
326 _ => Err(InvalidOutput),
327 }
328}
329
330pub fn plain(stdout: &[u8], successful: bool, truncated: bool) -> ToolResult {
331 let clean = clean_output(stdout);
332 let text = String::from_utf8(clean).expect("clean output is UTF-8");
333 let failed = !successful;
334 let mut text = if failed {
335 format!("Agent tool exited unsuccessfully.\n{text}")
336 } else {
337 text
338 };
339 if text.len() > TEXT_LIMIT || truncated {
340 let suffix = "\n[output truncated]";
341 let end = text.floor_char_boundary(TEXT_LIMIT - suffix.len());
342 text.truncate(end);
343 text.push_str(suffix);
344 }
345 if failed {
346 ToolResult::error(text)
347 } else {
348 ToolResult::success(Content::Text { text })
349 }
350}