agentmux_srv/drone/executor/blocks/
agent_output.rs1use serde_json::{json, Map, Value};
20
21pub const DEFAULT_MAX: usize = 200;
23pub const LIMIT_MAX: usize = 500;
25pub const MAX_FIELDS: usize = 12;
27
28#[derive(Debug, Clone, PartialEq)]
29enum Kind {
30 Text(usize),
31 Number,
32 Bool,
33 OneOf(Vec<String>),
34}
35
36#[derive(Debug, Clone, PartialEq)]
37struct Field {
38 name: String,
39 kind: Kind,
40}
41
42#[derive(Debug, Clone, PartialEq)]
44pub struct Schema {
45 fields: Vec<Field>,
46}
47
48fn valid_name(name: &str) -> bool {
49 let mut chars = name.chars();
50 matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c == '_')
51 && name.len() <= 32
52 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
53}
54
55fn parse_kind(name: &str, spec: &Value) -> Result<Kind, String> {
56 match spec {
57 Value::String(t) => match t.as_str() {
58 "string" => Ok(Kind::Text(DEFAULT_MAX)),
59 "number" => Ok(Kind::Number),
60 "boolean" => Ok(Kind::Bool),
61 other => Err(format!("field `{name}`: unknown type `{other}` (string, number or boolean)")),
62 },
63 Value::Object(o) => {
64 if let Some(values) = o.get("enum") {
65 let list = values.as_array().filter(|a| !a.is_empty() && a.len() <= 20);
66 let list = list.ok_or_else(|| format!("field `{name}`: `enum` is a list of 1 to 20 values"))?;
67 let strings: Option<Vec<String>> = list.iter().map(|v| v.as_str().filter(|s| !s.is_empty()).map(str::to_string)).collect();
68 return strings.map(Kind::OneOf).ok_or_else(|| format!("field `{name}`: `enum` holds non-empty strings"));
69 }
70 match o.get("type").and_then(Value::as_str) {
71 Some("string") => {
72 let max = match o.get("max") {
73 None => DEFAULT_MAX,
74 Some(m) => m
75 .as_u64()
76 .filter(|n| (1..=LIMIT_MAX as u64).contains(n))
77 .ok_or_else(|| format!("field `{name}`: `max` is 1 to {LIMIT_MAX}"))? as usize,
78 };
79 Ok(Kind::Text(max))
80 }
81 Some(other) => parse_kind(name, &Value::String(other.to_string())),
82 None => Err(format!("field `{name}`: a spec has `type` or `enum`")),
83 }
84 }
85 _ => Err(format!("field `{name}`: a spec is a type name or an object")),
86 }
87}
88
89impl Schema {
90 pub fn parse(declared: &Value) -> Result<Schema, String> {
92 let map = declared.as_object().ok_or("`output_schema` is an object of field: type")?;
93 if map.is_empty() {
94 return Err("`output_schema` declares no field".to_string());
95 }
96 if map.len() > MAX_FIELDS {
97 return Err(format!("`output_schema` declares {} fields; at most {MAX_FIELDS}", map.len()));
98 }
99 let mut fields = Vec::with_capacity(map.len());
100 for (name, spec) in map {
101 if !valid_name(name) {
102 return Err(format!("field `{name}`: a name is lowercase letters, digits and `_`, starting with a letter or `_`, 32 at most"));
103 }
104 fields.push(Field { name: name.clone(), kind: parse_kind(name, spec)? });
105 }
106 Ok(Schema { fields })
107 }
108
109 pub fn instructions(&self) -> String {
111 let mut out = String::from(
112 "\n\nEnd your reply with one JSON object and nothing after it. It has exactly these fields, all required:\n",
113 );
114 for f in &self.fields {
115 let what = match &f.kind {
116 Kind::Text(max) => format!("a short text, one line, at most {max} characters"),
117 Kind::Number => "a number".to_string(),
118 Kind::Bool => "true or false".to_string(),
119 Kind::OneOf(values) => format!("one of {}", values.iter().map(|v| format!("{v:?}")).collect::<Vec<_>>().join(", ")),
120 };
121 out.push_str(&format!("- {}: {what}\n", f.name));
122 }
123 out
124 }
125
126 pub fn extract(&self, reply: &str) -> Result<Value, String> {
129 let candidates = json_objects(reply);
130 if candidates.is_empty() {
131 return Err("the reply holds no JSON object".to_string());
132 }
133 let mut first_problem = None;
134 for object in candidates.iter().rev() {
135 match self.check(object) {
136 Ok(fields) => return Ok(Value::Object(fields)),
137 Err(problem) => {
138 first_problem.get_or_insert(problem);
139 }
140 }
141 }
142 Err(first_problem.unwrap_or_default())
143 }
144
145 fn check(&self, object: &Map<String, Value>) -> Result<Map<String, Value>, String> {
146 let mut out = Map::new();
147 for f in &self.fields {
148 let value = object.get(&f.name).ok_or_else(|| format!("field `{}` is missing", f.name))?;
149 let checked = match (&f.kind, value) {
150 (Kind::Text(max), Value::String(s)) => json!(one_line(s, *max)),
151 (Kind::Number, Value::Number(n)) if n.as_f64().is_some_and(f64::is_finite) => value.clone(),
152 (Kind::Bool, Value::Bool(_)) => value.clone(),
153 (Kind::OneOf(values), Value::String(s)) if values.iter().any(|v| v == s) => value.clone(),
154 (Kind::OneOf(_), Value::String(_)) => return Err(format!("field `{}` is not one of its allowed values", f.name)),
155 (kind, _) => return Err(format!("field `{}` is not {}", f.name, article(kind))),
156 };
157 out.insert(f.name.clone(), checked);
158 }
159 Ok(out)
160 }
161}
162
163fn article(kind: &Kind) -> &'static str {
164 match kind {
165 Kind::Text(_) => "a string",
166 Kind::Number => "a number",
167 Kind::Bool => "a boolean",
168 Kind::OneOf(_) => "a string",
169 }
170}
171
172fn one_line(s: &str, max: usize) -> String {
174 let mut out = String::new();
175 let mut space = true;
176 for c in s.chars() {
177 let c = if c.is_control() { ' ' } else { c };
178 if c == ' ' {
179 if !space {
180 out.push(' ');
181 }
182 space = true;
183 } else {
184 out.push(c);
185 space = false;
186 }
187 }
188 let trimmed = out.trim_end();
189 trimmed.chars().take(max).collect::<String>().trim_end().to_string()
190}
191
192const SEARCH_BYTES: usize = 64 * 1024;
194const MAX_TRIES: usize = 400;
195
196fn json_objects(text: &str) -> Vec<Map<String, Value>> {
199 let mut from = text.len().saturating_sub(SEARCH_BYTES);
200 while !text.is_char_boundary(from) {
201 from += 1;
202 }
203 let text = &text[from..];
204 let opens: Vec<usize> = text.match_indices('{').map(|(i, _)| i).collect();
205 let mut found = Vec::new();
206 let mut skip_to = 0;
207 for &i in &opens[opens.len().saturating_sub(MAX_TRIES)..] {
208 if i < skip_to {
209 continue;
210 }
211 let mut stream = serde_json::Deserializer::from_str(&text[i..]).into_iter::<Value>();
212 if let Some(Ok(Value::Object(o))) = stream.next() {
213 skip_to = i + stream.byte_offset();
214 found.push(o);
215 }
216 }
217 found
218}
219
220#[cfg(test)]
221#[path = "agent_output_tests.rs"]
222mod tests;