trusty_code/llm/tool_call_extractor/error.rs
1//! Error type for [`super::ToolCallExtractor`] (#1023).
2//!
3//! Why: Extraction and validation can fail in several distinct, actionable
4//! ways (nothing found, malformed JSON, schema mismatch, unknown tool) plus
5//! one terminal way (the bounded repair loop in `super::repair` ran out of
6//! attempts). Callers — the agent loop's dispatch path today, and any future
7//! caller — need to branch on which happened without string-matching, and the
8//! repair loop needs a structured value to build its corrective message from.
9//! What: Defines `ToolCallExtractError` deriving `thiserror::Error`. No
10//! variant panics or unwraps on construction; this is purely a data carrier.
11//! Test: `error::tests::*` — display strings for each variant.
12
13use thiserror::Error;
14
15use super::ExtractionStrategy;
16use super::schema::SchemaViolation;
17use crate::llm::InferenceError;
18
19/// Failure modes of tool-call extraction and validation.
20///
21/// Why: Distinguishes "no candidate call found at all" from "found a call but
22/// its arguments are broken" from "found valid JSON but it fails the tool's
23/// schema" — each warrants a different corrective message from
24/// `repair::build_corrective_message`. `Unrepairable` is the terminal variant
25/// the bounded repair loop returns once `max_attempts` is exhausted.
26/// Test: Constructed and matched throughout `mod.rs`, `repair.rs` tests.
27#[derive(Debug, Error)]
28pub enum ToolCallExtractError {
29 /// No strategy in the configured order recovered a tool call.
30 ///
31 /// Why: The model may have answered in plain prose with no embedded call
32 /// at all, or used a convention none of the four strategies recognise.
33 /// What: Carries the strategies that were attempted, in order, for
34 /// diagnostics and for the corrective message.
35 #[error("no tool call found in response (tried strategies: {tried:?})")]
36 NoCallFound {
37 /// Strategies attempted, in the order they were tried.
38 tried: Vec<ExtractionStrategy>,
39 },
40
41 /// A candidate call's argument text failed to parse as JSON.
42 ///
43 /// Why: The native wire format carries `arguments` as a JSON-encoded
44 /// string (see `llm::FunctionCall::arguments`); a model can emit
45 /// syntactically broken JSON there even when the surrounding envelope is
46 /// well-formed.
47 /// What: Carries the tool `name` (best-effort — the name itself parses
48 /// independently of the arguments) and the underlying `serde_json` error.
49 #[error("tool call '{name}' arguments are not valid JSON: {source}")]
50 MalformedArguments {
51 /// The tool name the (unparseable) arguments were destined for.
52 name: String,
53 /// The underlying JSON parse error.
54 source: serde_json::Error,
55 },
56
57 /// The extracted call names a tool with no registered schema.
58 ///
59 /// Why: Validation needs a schema to check against; a hallucinated tool
60 /// name has none. This is distinct from `SchemaInvalid` because there is
61 /// nothing to validate the arguments AGAINST, not merely a mismatch.
62 /// What: Carries the unrecognised tool name.
63 #[error("no schema registered for tool '{name}'")]
64 UnknownTool {
65 /// The hallucinated or misspelled tool name.
66 name: String,
67 },
68
69 /// The extracted call's arguments failed schema validation.
70 ///
71 /// Why: The most common repairable failure — the model called a real
72 /// tool but got the argument shape wrong (missing required field, wrong
73 /// type, disallowed extra key).
74 /// What: Carries the tool `name` and every [`SchemaViolation`] found (not
75 /// just the first) so a single corrective message can address them all.
76 #[error("tool call '{name}' failed schema validation: {violations:?}")]
77 SchemaInvalid {
78 /// The tool the arguments were destined for.
79 name: String,
80 /// All violations found; see `schema::validate_args`.
81 violations: Vec<SchemaViolation>,
82 },
83
84 /// The retry callback's chat call failed (transport/API error).
85 ///
86 /// Why: `repair::extract_with_repair`'s retry closure typically wraps a
87 /// real `InferenceAdapter::chat` call; that call can fail independently of
88 /// extraction. Wrapping it here lets the repair loop propagate it with
89 /// `?` instead of requiring every caller to define its own error type.
90 /// What: Wraps the underlying `InferenceError`.
91 #[error("retry chat call failed: {0}")]
92 Retry(#[from] InferenceError),
93
94 /// The bounded repair loop exhausted its attempts without success.
95 ///
96 /// Why: The terminal, structured (never-panicking) error the repair loop
97 /// returns once `max_attempts` corrective round-trips have all failed —
98 /// this is the "Unrepairable → structured error" acceptance criterion.
99 /// What: Carries how many attempts were made and the last failure seen.
100 #[error("unrepairable after {attempts} attempt(s): {last_error}")]
101 Unrepairable {
102 /// Number of repair attempts made (corrective round-trips), not
103 /// counting the initial extraction attempt.
104 attempts: u32,
105 /// The failure from the final attempt.
106 last_error: Box<ToolCallExtractError>,
107 },
108}
109
110// ── Tests ─────────────────────────────────────────────────────────────────────
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115
116 /// `NoCallFound` lists the attempted strategies in its display string.
117 ///
118 /// Why: Diagnostics/logs should show what was tried without needing to
119 /// inspect the struct fields.
120 /// What: Construct with two strategies, assert both appear.
121 /// Test: this test.
122 #[test]
123 fn no_call_found_display_lists_strategies() {
124 let err = ToolCallExtractError::NoCallFound {
125 tried: vec![
126 ExtractionStrategy::FencedJson,
127 ExtractionStrategy::AngleBracket,
128 ],
129 };
130 let s = err.to_string();
131 assert!(s.contains("FencedJson"));
132 assert!(s.contains("AngleBracket"));
133 }
134
135 /// `SchemaInvalid` display includes the tool name.
136 ///
137 /// Why: Operators scanning logs need the tool name without expanding the
138 /// full violation list.
139 /// What: Construct with a name and one violation; assert name appears.
140 /// Test: this test.
141 #[test]
142 fn schema_invalid_display_includes_name() {
143 let err = ToolCallExtractError::SchemaInvalid {
144 name: "bash".into(),
145 violations: vec![SchemaViolation {
146 path: "$.command".into(),
147 message: "missing required property 'command'".into(),
148 }],
149 };
150 assert!(err.to_string().contains("bash"));
151 }
152
153 /// `Unrepairable` display includes the attempt count and nests the source.
154 ///
155 /// Why: This is the terminal error surfaced to callers; both pieces of
156 /// information must be visible without downcasting.
157 /// What: Wrap an `UnknownTool` inside `Unrepairable`; assert both appear.
158 /// Test: this test.
159 #[test]
160 fn unrepairable_display_includes_attempts_and_source() {
161 let err = ToolCallExtractError::Unrepairable {
162 attempts: 2,
163 last_error: Box::new(ToolCallExtractError::UnknownTool {
164 name: "frobnicate".into(),
165 }),
166 };
167 let s = err.to_string();
168 assert!(s.contains('2'));
169 assert!(s.contains("frobnicate"));
170 }
171}