Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-mv/blob/main/rust/crates/interplane-lenshift/src/aien_legacy.rs # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-mv / rust / crates / interplane-lenshift / src / aien_legacy.rs` 283 lines ยท 10110 bytes Raw Blame History 1 //! Dialect `aien_legacy` (version 1): aien-cli's textual `` JSON protocol. 2 //! 3 //! Ground truth: aien-sovereign-core `7580039`, `crates/aien-cli/src/client.rs:350-419` (parser) 4 //! and `main.rs:330-340` (result reinjection). See `spec/LENSHIFT.md`. 5 use interplane_core::{ErrorCode, ToolRequest, ToolResult}; 6 use regex::Regex; 7 use serde_json::{Map, Value}; 8 9 use crate::*; 10 11 pub struct AienLegacy; 12 13 const TC_OPEN: &str = ""; 14 const TC_CLOSE: &str = ""; 15 /// ASCII whitespace, identical to the Python reference implementation. 16 const WS: &[char] = &[' ', '\t', '\n', '\r', '\x0b', '\x0c']; 17 const FENCE: &str = r#"(?s)```(?:json|tool_call)?[ \t\n\r\x0b\x0c]*(\{[ \t\n\r\x0b\x0c]*"name"[ \t\n\r\x0b\x0c]*:[ \t\n\r\x0b\x0c]*"[^"]+".*?\})[ \t\n\r\x0b\x0c]*```"#; 18 19 /// aien-cli `parse_tool_call_json` (client.rs:350-379). Returns the value and the repairs used. 20 fn repair_json(raw: &str) -> Result<(Value, Vec<&'static str>), String> { 21 let body = raw.trim_matches(WS); 22 if let Ok(v) = serde_json::from_str::(body) { 23 return Ok((v, vec![])); 24 } 25 if let Some(stripped) = body.strip_suffix(']') { 26 let fixed = format!("{stripped}}}"); 27 if let Ok(v) = serde_json::from_str::(&fixed) { 28 return Ok((v, vec!["bracket_to_brace"])); 29 } 30 } 31 let opens = body.chars().filter(|&c| c == '{').count(); 32 let closes = body.chars().filter(|&c| c == '}').count(); 33 if opens > closes { 34 let mut candidate = body.to_string(); 35 if body.chars().filter(|&c| c == '"').count() % 2 == 1 { 36 candidate.push('"'); 37 } 38 candidate.push_str(&"}".repeat(opens - closes)); 39 if let Ok(v) = serde_json::from_str::(&candidate) { 40 return Ok((v, vec!["close_braces"])); 41 } 42 } 43 Err("tool call body is not valid JSON".into()) 44 } 45 46 type Decoded = (String, Map, Vec<&'static str>); 47 48 fn decode(raw: &str) -> Result { 49 let (obj, repairs) = repair_json(raw)?; 50 let name = match obj.get("name").and_then(Value::as_str) { 51 Some(n) if !n.is_empty() => n.to_string(), 52 _ => return Err("tool call JSON has no name".into()), 53 }; 54 if name == "tool_name" { 55 return Err("placeholder tool name".into()); 56 } 57 let args = match obj.get("arguments") { 58 None => Map::new(), 59 Some(Value::Object(m)) => m.clone(), 60 Some(_) => return Err("arguments is not an object".into()), 61 }; 62 Ok((name, args, repairs)) 63 } 64 65 /// (body or None when truncated, source text, form) 66 type Block<'a> = (Option<&'a str>, &'a str, &'static str); 67 68 impl Dialect for AienLegacy { 69 fn name(&self) -> &str { 70 "aien_legacy" 71 } 72 fn version(&self) -> &str { 73 "1" 74 } 75 76 fn parse(&self, input: &Value, ctx: &ParseContext) -> LenshiftTurn { 77 let mut turn = LenshiftTurn { 78 dialect: "aien_legacy".into(), 79 dialect_version: "1".into(), 80 parser_version: PARSER_VERSION.into(), 81 model: ctx.model.clone(), 82 text: String::new(), 83 reasoning_digest: None, 84 intents: vec![], 85 rejected: vec![], 86 partial: false, 87 intent_indices: vec![], 88 }; 89 let Some(full) = input.as_str() else { 90 turn.rejected.push(RejectedCall { 91 index: 0, 92 code: ErrorCode::MalformedToolCall, 93 message: "assistant turn is not text".into(), 94 source_digest: None, 95 request_id: assign_request_id(None, ctx, 0), 96 }); 97 return turn; 98 }; 99 100 // 1. A leading ... block is removed and digested. 101 let mut text = full; 102 let lead = full.trim_start_matches(WS); 103 if let Some(after) = lead.strip_prefix("") { 104 if let Some(e) = after.find("") { 105 let reasoning = after[..e].trim(); 106 turn.reasoning_digest = if reasoning.is_empty() { 107 None 108 } else { 109 Some(text_digest(reasoning)) 110 }; 111 text = &after[e + "".len()..]; 112 } 113 } 114 115 // 2. Split into call blocks. The fenced fallback only runs when no marker exists. 116 let mut pieces = String::new(); 117 let mut blocks: Vec = vec![]; 118 if text.contains(TC_OPEN) { 119 let mut rest = text; 120 loop { 121 let Some(s) = rest.find(TC_OPEN) else { 122 pieces.push_str(rest); 123 break; 124 }; 125 pieces.push_str(&rest[..s]); 126 let from_open = &rest[s..]; 127 match from_open[TC_OPEN.len()..].find(TC_CLOSE) { 128 None => { 129 turn.partial = true; 130 blocks.push((None, from_open, "tool_call")); 131 break; 132 } 133 Some(e) => { 134 let close_at = TC_OPEN.len() + e; 135 let stop = close_at + TC_CLOSE.len(); 136 blocks.push(( 137 Some(&from_open[TC_OPEN.len()..close_at]), 138 &from_open[..stop], 139 "tool_call", 140 )); 141 rest = &from_open[stop..]; 142 } 143 } 144 } 145 } else { 146 let re = Regex::new(FENCE).expect("static regex"); 147 let mut pos = 0; 148 for caps in re.captures_iter(text) { 149 let m = caps.get(0).expect("whole match"); 150 pieces.push_str(&text[pos..m.start()]); 151 blocks.push(( 152 Some(caps.get(1).expect("group 1").as_str()), 153 m.as_str(), 154 "fenced_json", 155 )); 156 pos = m.end(); 157 } 158 pieces.push_str(&text[pos..]); 159 } 160 turn.text = pieces.trim().to_string(); 161 162 for (index, (body, source, form)) in blocks.into_iter().enumerate() { 163 let src = text_digest(source); 164 let request_id = assign_request_id(None, ctx, index); 165 let reject = |message: &str| RejectedCall { 166 index, 167 code: ErrorCode::MalformedToolCall, 168 message: message.into(), 169 source_digest: Some(src.clone()), 170 request_id: request_id.clone(), 171 }; 172 let Some(body) = body else { 173 turn.rejected.push(reject("truncated tool call")); 174 continue; 175 }; 176 let (name, args, repairs) = match decode(body) { 177 Ok(c) => c, 178 Err(m) => { 179 turn.rejected.push(reject(&m)); 180 continue; 181 } 182 }; 183 let Some(tool) = canonical_tool(&name) else { 184 turn.rejected.push(reject("invalid tool name")); 185 continue; 186 }; 187 let mut intent = make_intent( 188 "aien_legacy", 189 "1", 190 ctx, 191 request_id.clone(), 192 tool, 193 args, 194 None, 195 src.clone(), 196 &name, 197 "none", 198 ); 199 if !repairs.is_empty() { 200 intent.provenance.extensions.insert( 201 "repairs".into(), 202 Value::Array(repairs.iter().map(|r| Value::String((*r).into())).collect()), 203 ); 204 } 205 if form != "tool_call" { 206 intent 207 .provenance 208 .extensions 209 .insert("form".into(), Value::String(form.into())); 210 } 211 turn.intents.push(intent); 212 turn.intent_indices.push(index); 213 } 214 turn 215 } 216 217 fn render_result(&self, result: &ToolResult, intent: Option<&ToolRequest>) -> Value { 218 let name = intent 219 .and_then(|i| i.provenance.raw_name.as_deref()) 220 .filter(|n| !n.is_empty()) 221 .unwrap_or("unknown"); 222 serde_json::json!({ 223 "role": "user", 224 "content": format!( 225 "\n{}\n", 226 serialize_result(result) 227 ), 228 }) 229 } 230 } 231 232 #[cfg(test)] 233 mod tests { 234 use super::*; 235 use serde_json::json; 236 237 fn parse(s: &str) -> LenshiftTurn { 238 let ctx = ParseContext { 239 trace_id: "t".into(), 240 turn: 0, 241 model: "m".into(), 242 }; 243 AienLegacy.parse(&json!(s), &ctx) 244 } 245 246 #[test] 247 fn repairs_and_rejections() { 248 let t = parse("\n{\"name\": \"f\", \"arguments\": {\"s\": \"x\n"); 249 assert_eq!(t.intents[0].arguments["s"], json!("x")); 250 assert_eq!( 251 t.intents[0].provenance.extensions["repairs"], 252 json!(["close_braces"]) 253 ); 254 for body in [ 255 "{\"name\": \"f\",}", 256 "{'name': 'f'}", 257 "null", 258 "[]", 259 "{\"name\": \"\"}", 260 ] { 261 let t = parse(&format!("\n{body}\n")); 262 assert!( 263 t.intents.is_empty() && t.rejected.len() == 1 && !t.partial, 264 "{body}" 265 ); 266 } 267 let t = parse("x \n{\"name\": \"f\"}"); 268 assert!(t.partial && t.intents.is_empty() && t.text == "x"); 269 } 270 271 #[test] 272 fn fence_only_without_tag_and_render_shape() { 273 let fenced = "```json\n{\"name\": \"f\", \"arguments\": {}}\n```"; 274 let t = parse(&format!("a {fenced} b")); 275 assert_eq!( 276 t.intents[0].provenance.extensions["form"], 277 json!("fenced_json") 278 ); 279 assert_eq!(t.text, "a b"); 280 let t = parse(&format!("\nbroken\n\n{fenced}")); 281 assert!(t.intents.is_empty() && t.rejected.len() == 1); 282 } 283 }