1use crate::tool_input_validation::{
4 CompiledToolInputValidator, ToolInputValidationError, ToolInputValidatorError,
5};
6use merry_core::{CoreError, PendingToolCall, ToolCallId, ToolInputSchema, ToolName, ToolSpec};
7use serde::de::DeserializeOwned;
8use serde_json::Value;
9use std::{collections::BTreeSet, fmt, sync::Arc};
10use thiserror::Error;
11
12type OutputValidator = Arc<dyn Fn(&str) -> Result<(), String> + Send + Sync>;
13
14pub const FINAL_OUTPUT_TOOL_NAME: &str = "merry_final_output";
16
17#[derive(Clone)]
19pub struct FinalOutputContract {
20 tool_spec: ToolSpec,
21 input_validator: CompiledToolInputValidator,
22 output_validator: Option<OutputValidator>,
23}
24
25impl fmt::Debug for FinalOutputContract {
26 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27 formatter
28 .debug_struct("FinalOutputContract")
29 .field("tool_spec", &self.tool_spec)
30 .field("input_validator", &self.input_validator)
31 .field("output_validator", &self.output_validator.is_some())
32 .finish()
33 }
34}
35
36impl PartialEq for FinalOutputContract {
37 fn eq(&self, other: &Self) -> bool {
38 self.tool_spec == other.tool_spec
39 }
40}
41
42impl FinalOutputContract {
43 pub fn new(schema: ToolInputSchema) -> Result<Self, FinalOutputContractError> {
45 if !schema.is_object_schema() {
46 return Err(FinalOutputContractError::RootSchemaMustBeObject);
47 }
48 let schema = schema.require_object()?;
49 let value = serde_json::to_value(schema.as_schema()).map_err(|source| {
50 FinalOutputContractError::SchemaSerialization {
51 message: source.to_string(),
52 }
53 })?;
54 validate_schema_field_descriptions(&value)?;
55 let tool_spec = ToolSpec::new(
56 ToolName::new(FINAL_OUTPUT_TOOL_NAME)?,
57 "Submit the final structured output when the task is complete.",
58 schema,
59 )?;
60 let input_validator = CompiledToolInputValidator::compile(tool_spec.input_schema())?;
61
62 Ok(Self {
63 tool_spec,
64 input_validator,
65 output_validator: None,
66 })
67 }
68
69 #[must_use]
76 pub fn with_output_decoder<T>(mut self) -> Self
77 where
78 T: DeserializeOwned,
79 {
80 self.output_validator = Some(Arc::new(|json| {
81 serde_json::from_str::<T>(json)
82 .map(|_| ())
83 .map_err(|source| source.to_string())
84 }));
85 self
86 }
87
88 #[must_use]
90 pub fn tool_name(&self) -> &ToolName {
91 self.tool_spec.name()
92 }
93
94 #[must_use]
96 pub fn tool_spec(&self) -> &ToolSpec {
97 &self.tool_spec
98 }
99
100 pub(crate) fn validate_call(
101 &self,
102 call: &PendingToolCall,
103 ) -> Result<(), ToolInputValidationError> {
104 self.input_validator.validate_call(call)
105 }
106
107 pub(crate) fn validate_output(&self, json: &str) -> Result<(), String> {
108 self.output_validator
109 .as_ref()
110 .map_or(Ok(()), |validator| validator(json))
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct FinalOutput {
117 call_id: ToolCallId,
118 json: String,
119}
120
121impl FinalOutput {
122 pub(crate) fn new(call_id: ToolCallId, json: String) -> Self {
123 Self { call_id, json }
124 }
125
126 #[must_use]
128 pub fn call_id(&self) -> &ToolCallId {
129 &self.call_id
130 }
131
132 #[must_use]
134 pub fn json(&self) -> &str {
135 &self.json
136 }
137}
138
139#[derive(Debug, Error)]
141pub enum FinalOutputContractError {
142 #[error(transparent)]
144 Core(#[from] CoreError),
145 #[error("final output schema could not be serialized: {message}")]
147 SchemaSerialization { message: String },
148 #[error("final output schema could not be compiled: {message}")]
150 SchemaCompilation { message: String },
151 #[error("final output schema root must describe a JSON object")]
154 RootSchemaMustBeObject,
155 #[error("final output schema field {field} must include a description")]
157 MissingFieldDescription { field: String },
158}
159
160impl From<ToolInputValidatorError> for FinalOutputContractError {
161 fn from(source: ToolInputValidatorError) -> Self {
162 Self::SchemaCompilation {
163 message: source.to_string(),
164 }
165 }
166}
167
168fn validate_schema_field_descriptions(value: &Value) -> Result<(), FinalOutputContractError> {
169 fn walk(
170 root: &Value,
171 schema: &Value,
172 path: &str,
173 visited_refs: &mut BTreeSet<String>,
174 ) -> Result<(), FinalOutputContractError> {
175 if let Some(reference) = schema.get("$ref").and_then(Value::as_str)
176 && visited_refs.insert(reference.to_owned())
177 {
178 let target = reference
179 .strip_prefix('#')
180 .and_then(|pointer| root.pointer(pointer))
181 .ok_or_else(|| FinalOutputContractError::MissingFieldDescription {
182 field: format!("{path} ({reference})"),
183 })?;
184 walk(root, target, path, visited_refs)?;
185 }
186
187 if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
188 for (field, field_schema) in properties {
189 if field == "type" {
190 continue;
191 }
192 let field_path = format!("{path}.{field}");
193 let has_description = field_schema
194 .get("description")
195 .and_then(Value::as_str)
196 .is_some_and(|description| !description.trim().is_empty());
197 if !has_description {
198 return Err(FinalOutputContractError::MissingFieldDescription {
199 field: field_path
200 .strip_prefix("$.")
201 .unwrap_or(&field_path)
202 .to_owned(),
203 });
204 }
205 walk(root, field_schema, &field_path, visited_refs)?;
206 }
207 }
208
209 if let Some(items) = schema.get("items") {
210 walk(root, items, &format!("{path}[]"), visited_refs)?;
211 }
212
213 for keyword in ["oneOf", "anyOf", "allOf"] {
214 if let Some(branches) = schema.get(keyword).and_then(Value::as_array) {
215 for (index, branch) in branches.iter().enumerate() {
216 walk(
217 root,
218 branch,
219 &format!("{path}.{keyword}[{index}]"),
220 visited_refs,
221 )?;
222 }
223 }
224 }
225
226 if let Some(definitions) = schema.get("$defs").and_then(Value::as_object) {
227 for (name, definition) in definitions {
228 walk(
229 root,
230 definition,
231 &format!("{path}.$defs.{name}"),
232 visited_refs,
233 )?;
234 }
235 }
236
237 Ok(())
238 }
239
240 walk(value, value, "$", &mut BTreeSet::new())
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246 use merry_core::ToolInputSchema;
247 use schemars::Schema;
248 use serde_json::json;
249
250 fn schema(value: serde_json::Value) -> ToolInputSchema {
251 ToolInputSchema::new(Schema::try_from(value).expect("valid schema"))
252 .expect("valid tool input schema")
253 }
254
255 #[test]
256 fn final_output_contract_uses_reserved_provider_portable_tool_name() {
257 let contract = FinalOutputContract::new(schema(json!({
258 "type": "object",
259 "properties": {
260 "summary": {
261 "type": "string",
262 "description": "Short final summary."
263 }
264 },
265 "required": ["summary"],
266 "additionalProperties": false
267 })))
268 .expect("contract should build");
269
270 assert_eq!(contract.tool_name().as_str(), "merry_final_output");
271 assert_eq!(contract.tool_spec().name().as_str(), "merry_final_output");
272 assert!(
273 contract
274 .tool_spec()
275 .description()
276 .contains("final structured output")
277 );
278 }
279
280 #[test]
281 fn final_output_contract_rejects_schema_without_field_descriptions() {
282 let error = FinalOutputContract::new(schema(json!({
283 "type": "object",
284 "properties": {
285 "summary": { "type": "string" }
286 },
287 "required": ["summary"],
288 "additionalProperties": false
289 })))
290 .expect_err("schema field descriptions are required");
291
292 assert_eq!(
293 error.to_string(),
294 "final output schema field summary must include a description"
295 );
296 }
297
298 #[test]
299 fn final_output_contract_rejects_nested_field_without_description() {
300 let error = FinalOutputContract::new(schema(json!({
301 "type": "object",
302 "properties": {
303 "summary": {
304 "type": "object",
305 "description": "Structured final summary.",
306 "properties": {
307 "status": { "type": "string" }
308 }
309 }
310 },
311 "required": ["summary"],
312 "additionalProperties": false
313 })))
314 .expect_err("nested schema field descriptions are required");
315
316 assert_eq!(
317 error.to_string(),
318 "final output schema field summary.status must include a description"
319 );
320 }
321
322 #[test]
323 fn final_output_contract_rejects_scalar_root_schema_explicitly() {
324 let error = FinalOutputContract::new(schema(json!({"type": "string"})))
325 .expect_err("structured final output must use an object schema");
326
327 assert!(matches!(
328 error,
329 FinalOutputContractError::RootSchemaMustBeObject
330 ));
331 }
332}