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