1use std::borrow::Cow;
3
4use rig_core::message::ToolResultContent;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8const EXCERPT_BYTES: usize = 8 * 1024;
10const EXCERPT_LINES: usize = 80;
12const GAP: &str = "\n…\n";
13const SUMMARY_CHARS: usize = 120;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "camelCase")]
18pub enum ToolKind {
19 Read,
20 Edit,
21 Command,
22 Verify,
23 Other,
24}
25
26impl ToolKind {
27 pub(crate) fn for_name(name: &str) -> Self {
28 match name {
29 "read" | "list" | "glob" | "grep" => Self::Read,
30 "write" | "edit" => Self::Edit,
31 "run_command" => Self::Command,
32 name if crate::verify_tools::chat_tool(name) => Self::Verify,
33 _ => Self::Other,
34 }
35 }
36
37 pub(crate) fn as_str(self) -> &'static str {
38 match self {
39 Self::Read => "read",
40 Self::Edit => "edit",
41 Self::Command => "command",
42 Self::Verify => "verify",
43 Self::Other => "other",
44 }
45 }
46
47 pub(crate) fn from_db(value: &str) -> Self {
48 match value {
49 "read" => Self::Read,
50 "edit" => Self::Edit,
51 "command" => Self::Command,
52 "verify" => Self::Verify,
53 _ => Self::Other,
54 }
55 }
56}
57
58#[derive(Default, Deserialize)]
59#[serde(default)]
60struct Arguments<'a> {
61 path: Option<&'a str>,
62 pattern: Option<&'a str>,
63 old_text: Option<&'a str>,
64 new_text: Option<&'a str>,
65 program: Option<&'a str>,
66 #[serde(borrow)]
67 args: Vec<&'a str>,
68}
69
70pub(super) fn read_summary(
71 name: &str,
72 path: Option<&std::path::Path>,
73 pattern: Option<&str>,
74) -> String {
75 let path = path.map(crate::platform::path_text);
76 let argument = match name {
77 "list" => path.as_deref().unwrap_or("."),
78 "glob" | "grep" => pattern.unwrap_or(""),
79 _ => path.as_deref().unwrap_or(""),
80 };
81 short([name, argument].into_iter().flat_map(str::split_whitespace))
82}
83
84pub(super) fn summary(name: &str, arguments: &Value) -> String {
85 let args = Arguments::deserialize(arguments).unwrap_or_default();
86 let words = match name {
87 "read" | "write" => vec![name, args.path.unwrap_or("")],
88 "edit" => {
89 let target = short(
90 [name, args.path.unwrap_or("")]
91 .into_iter()
92 .flat_map(str::split_whitespace),
93 );
94 return match (args.old_text, args.new_text) {
95 (Some(old), Some(new)) => {
96 format!("{target} +{} −{}", new.lines().count(), old.lines().count())
97 }
98 _ => target,
99 };
100 }
101 "list" => vec![name, args.path.unwrap_or(".")],
102 "glob" | "grep" => vec![name, args.pattern.unwrap_or("")],
103 "run_command" => {
104 let mut words = vec!["ran", args.program.unwrap_or("")];
105 words.extend(args.args);
106 words
107 }
108 _ => return short(name.split('_')),
109 };
110 short(words.into_iter().flat_map(str::split_whitespace))
111}
112
113fn short<'a>(words: impl IntoIterator<Item = &'a str>) -> String {
114 let mut chars = words.into_iter().flat_map(|word| word.chars().chain([' ']));
115 let label: String = chars.by_ref().take(SUMMARY_CHARS).collect();
116 if chars.next().is_some() {
117 format!("{}…", label.trim_end())
118 } else {
119 label.trim_end().to_owned()
120 }
121}
122
123pub(super) struct ResultView {
124 pub output: String,
125 pub exit_code: Option<i32>,
126 pub omitted_lines: usize,
127 pub truncated: bool,
128}
129
130#[derive(Deserialize, Serialize)]
131#[serde(rename_all = "camelCase")]
132pub(super) struct CommandOutput<'a> {
133 pub exit_code: i32,
134 #[serde(borrow)]
135 pub stdout: Cow<'a, str>,
136 #[serde(borrow)]
137 pub stderr: Cow<'a, str>,
138 #[serde(default)]
139 pub truncated: bool,
140}
141
142impl<'a> CommandOutput<'a> {
143 fn from_part(part: &'a ToolResultContent) -> Option<Self> {
144 match part {
145 ToolResultContent::Json { value } => Self::deserialize(value).ok(),
146 ToolResultContent::Text(text) => serde_json::from_str(&text.text).ok(),
148 _ => None,
149 }
150 }
151}
152
153fn legacy_exit(text: &str) -> Option<i32> {
154 text.lines()
155 .next()?
156 .strip_prefix("Command did not succeed: Exited(")?
157 .strip_suffix(')')?
158 .parse()
159 .ok()
160}
161
162impl ResultView {
163 pub(super) fn new<'a>(
164 kind: ToolKind,
165 content: impl IntoIterator<Item = &'a ToolResultContent>,
166 ) -> Self {
167 let mut exit_code = None;
168 let mut capture_truncated = false;
169 let text = content
170 .into_iter()
171 .map(|part| {
172 if kind == ToolKind::Command
173 && let Some(command) = CommandOutput::from_part(part)
174 {
175 exit_code = Some(command.exit_code);
176 capture_truncated = command.truncated;
177 return [command.stdout.as_ref(), command.stderr.as_ref()]
178 .into_iter()
179 .filter(|text| !text.is_empty())
180 .collect::<Vec<_>>()
181 .join("\n");
182 }
183 match part {
184 ToolResultContent::Text(text) => {
185 if kind == ToolKind::Command {
186 exit_code = legacy_exit(&text.text);
187 }
188 text.text.clone()
189 }
190 ToolResultContent::Json { value } => value.to_string(),
191 _ => "[non-text output]".into(),
192 }
193 })
194 .collect::<Vec<_>>()
195 .join("\n");
196 let (output, omitted_lines, clipped) = excerpt(text);
197 Self {
198 output,
199 exit_code,
200 omitted_lines,
201 truncated: clipped || capture_truncated,
202 }
203 }
204}
205
206fn excerpt(text: String) -> (String, usize, bool) {
207 let lines = text.lines().count();
208 if text.len() <= EXCERPT_BYTES && lines <= EXCERPT_LINES {
209 return (text, 0, false);
210 }
211 let bytes_per_end = (EXCERPT_BYTES - GAP.len()) / 2;
212 let lines_per_end = (EXCERPT_LINES - 1) / 2;
213 let head_end = text
214 .split_inclusive('\n')
215 .take(lines_per_end)
216 .map(str::len)
217 .sum::<usize>();
218 let tail_len = text
219 .split_inclusive('\n')
220 .rev()
221 .take(lines_per_end)
222 .map(str::len)
223 .sum::<usize>();
224 let head = &text[..text.floor_char_boundary(head_end.min(bytes_per_end))];
225 let tail = &text[text.ceil_char_boundary(text.len() - tail_len.min(bytes_per_end))..];
226 let omitted = lines.saturating_sub(head.lines().count() + tail.lines().count());
227 let head = head.strip_suffix('\n').unwrap_or(head);
228 (format!("{head}{GAP}{tail}"), omitted, true)
229}