Skip to main content

base/interface/
tool_result.rs

1//! `ToolResultTransformer` — the last hands on a tool's output before the
2//! model reads it.
3//!
4//! Truncation, redaction, moving something large out of the conversation and
5//! leaving a reference: these are policies about what a result may look like,
6//! not about what a tool does. A tool that enforces its own cap enforces it
7//! for everyone, in units it chose; a deployment that must never let a
8//! credential reach a provider has nowhere to say so at all.
9//!
10//! # Last, and why that is the whole point
11//!
12//! The chain runs after every hook, immediately before the outcome is
13//! returned. That ordering is what makes a redacting transformer a guarantee
14//! rather than a suggestion: nothing downstream can put back what it took
15//! out. Run it earlier and a `PostToolUse` hook rewriting the result would
16//! quietly undo it.
17//!
18//! The cost of that choice is that hook payloads see the untransformed text.
19//! That is the right trade here — a hook is a local command the operator
20//! configured, at the same trust level as the engine itself, while the model
21//! is a remote party.
22//!
23//! # Errors go through too
24//!
25//! A failure message is as capable of carrying a path, a token or a hostname
26//! as a success is. A transformer that only saw successful results would be a
27//! redaction policy with a hole in it.
28
29use crate::interface::tool_middleware::ToolCall;
30
31/// A large piece of binary content a tool returned, on its way to becoming an
32/// image block beside the tool result.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ResultImage {
35    pub media_type: String,
36    /// Base64, without a data-URI prefix.
37    pub data: String,
38}
39
40/// A tool's output, mid-flight.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ToolResultDraft {
43    /// What the model will read.
44    pub text: String,
45    /// Images that will ride alongside the result. A transformer may drop or
46    /// replace these — that is what "move the large thing out of the
47    /// conversation" looks like from here.
48    pub images: Vec<ResultImage>,
49    /// Whether this is a failure. Transformers see failures too; see the
50    /// module docs.
51    pub is_error: bool,
52}
53
54/// A policy about what a tool result may look like.
55pub trait ToolResultTransformer: Send + Sync {
56    fn transform(&self, call: &ToolCall, draft: &mut ToolResultDraft);
57}
58
59/// Run every transformer, in order.
60pub 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
70/// Cap a result's length, saying so where it was cut.
71///
72/// Not registered by default: the engine imposes no cap of its own here, and
73/// silently shortening a result is exactly the kind of thing that should be a
74/// deployment's decision rather than a default nobody was told about.
75pub 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        // The note says what was lost. A silently shortened result reads to
87        // the model as a complete one, and it will reason from the missing
88        // half as though it were not there.
89        draft.text = format!("{kept}\n… [{dropped} bytes truncated]");
90    }
91}
92
93/// Replace known secrets wherever they appear.
94///
95/// Literal matching, not patterns: a deployment knows its own credentials —
96/// it just handed them to a
97/// [`CredentialSource`](crate::interface::credentials::CredentialSource) —
98/// and matching what it knows cannot misfire the way a heuristic pattern can.
99/// A regex that redacts something that merely looks like a token turns a
100/// correct tool result into a confusing one.
101pub 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            // Empty strings would match everywhere and replace nothing
110            // usefully; dropping them here beats every call site checking.
111            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    /// A failure message carries the same things a success does. A policy that
188    /// only covered successes would be a policy with a hole in it.
189    #[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}