base/interface/
tool_result.rs1use crate::interface::tool_middleware::ToolCall;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ResultImage {
35 pub media_type: String,
36 pub data: String,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ToolResultDraft {
43 pub text: String,
45 pub images: Vec<ResultImage>,
49 pub is_error: bool,
52}
53
54pub trait ToolResultTransformer: Send + Sync {
56 fn transform(&self, call: &ToolCall, draft: &mut ToolResultDraft);
57}
58
59pub fn apply(
61 transformers: &[std::sync::Arc<dyn ToolResultTransformer>],
62 call: &ToolCall,
63 draft: &mut ToolResultDraft,
64) {
65 for t in transformers {
66 t.transform(call, draft);
67 }
68}
69
70pub struct TruncateText {
76 pub max_bytes: usize,
77}
78
79impl ToolResultTransformer for TruncateText {
80 fn transform(&self, _call: &ToolCall, draft: &mut ToolResultDraft) {
81 if draft.text.len() <= self.max_bytes {
82 return;
83 }
84 let kept = crate::text::truncate_at_char_boundary(&draft.text, self.max_bytes);
85 let dropped = draft.text.len() - kept.len();
86 draft.text = format!("{kept}\n… [{dropped} bytes truncated]");
90 }
91}
92
93pub struct RedactLiterals {
102 secrets: Vec<String>,
103 replacement: String,
104}
105
106impl RedactLiterals {
107 pub fn new(secrets: impl IntoIterator<Item = impl Into<String>>) -> Self {
108 Self {
109 secrets: secrets
112 .into_iter()
113 .map(Into::into)
114 .filter(|s: &String| !s.is_empty())
115 .collect(),
116 replacement: "<redacted>".to_string(),
117 }
118 }
119}
120
121impl ToolResultTransformer for RedactLiterals {
122 fn transform(&self, _call: &ToolCall, draft: &mut ToolResultDraft) {
123 for secret in &self.secrets {
124 if draft.text.contains(secret.as_str()) {
125 draft.text = draft.text.replace(secret.as_str(), &self.replacement);
126 }
127 }
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134 use std::sync::Arc;
135
136 fn call() -> ToolCall {
137 ToolCall::new("Bash", serde_json::json!({"command": "env"}))
138 }
139
140 fn draft(text: &str) -> ToolResultDraft {
141 ToolResultDraft {
142 text: text.to_string(),
143 images: Vec::new(),
144 is_error: false,
145 }
146 }
147
148 #[test]
149 fn truncation_says_where_it_cut() {
150 let t = TruncateText { max_bytes: 10 };
151 let mut d = draft("0123456789abcdef");
152 t.transform(&call(), &mut d);
153 assert!(d.text.starts_with("0123456789"));
154 assert!(d.text.contains("truncated"), "{}", d.text);
155 }
156
157 #[test]
158 fn truncation_leaves_a_short_result_exactly_as_it_was() {
159 let t = TruncateText { max_bytes: 100 };
160 let mut d = draft("short");
161 t.transform(&call(), &mut d);
162 assert_eq!(d.text, "short");
163 }
164
165 #[test]
166 fn truncation_never_splits_a_character() {
167 let t = TruncateText { max_bytes: 4 };
168 let mut d = draft("日本語のテキスト");
169 t.transform(&call(), &mut d);
170 assert!(d.text.starts_with("日"), "{}", d.text);
171 }
172
173 #[test]
174 fn a_known_secret_does_not_reach_the_model() {
175 let t = RedactLiterals::new(["sk-live-abc123"]);
176 let mut d = draft("ANTHROPIC_API_KEY=sk-live-abc123\nOTHER=fine");
177 t.transform(&call(), &mut d);
178 assert!(!d.text.contains("sk-live-abc123"), "{}", d.text);
179 assert!(d.text.contains("<redacted>"), "{}", d.text);
180 assert!(
181 d.text.contains("OTHER=fine"),
182 "the rest must survive: {}",
183 d.text
184 );
185 }
186
187 #[test]
190 fn a_failure_is_transformed_too() {
191 let t = RedactLiterals::new(["sk-live-abc123"]);
192 let mut d = ToolResultDraft {
193 text: "command failed: bad token sk-live-abc123".into(),
194 images: Vec::new(),
195 is_error: true,
196 };
197 t.transform(&call(), &mut d);
198 assert!(!d.text.contains("sk-live-abc123"));
199 }
200
201 #[test]
202 fn transformers_run_in_order() {
203 let chain: Vec<Arc<dyn ToolResultTransformer>> = vec![
204 Arc::new(RedactLiterals::new(["secret"])),
205 Arc::new(TruncateText { max_bytes: 12 }),
206 ];
207 let mut d = draft("a secret and a great deal more text");
208 apply(&chain, &call(), &mut d);
209 assert!(!d.text.contains("secret"));
210 assert!(d.text.contains("truncated"));
211 }
212
213 #[test]
214 fn an_empty_chain_changes_nothing() {
215 let mut d = draft("untouched");
216 apply(&[], &call(), &mut d);
217 assert_eq!(d, draft("untouched"));
218 }
219}