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/lib.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 / lib.rs` 237 lines ยท 7585 bytes Raw Blame History 1 //! Lenshift: model-native representation <-> canonical intent. Never executes, never authorizes. 2 use std::collections::BTreeMap; 3 4 use interplane_core::{ 5 canonicalize, digest_bytes, is_valid_id, ErrorCode, Provenance, ToolRef, ToolRequest, 6 ToolRequestKind, ToolResult, 7 }; 8 use serde::{Deserialize, Serialize}; 9 use serde_json::{json, Map, Value}; 10 11 pub mod aien_legacy; 12 pub mod ajax; 13 pub mod openai; 14 pub mod openai_stream; 15 pub mod qwen35; 16 pub mod replay; 17 18 /// What a dialect needs to know to fill request ids and provenance. 19 #[derive(Debug, Clone)] 20 pub struct ParseContext { 21 pub trace_id: String, 22 pub turn: u64, 23 pub model: String, 24 } 25 26 /// A malformed call. It also becomes a `rejected` / `malformed_tool_call` result. 27 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 28 pub struct RejectedCall { 29 pub index: usize, 30 pub code: ErrorCode, 31 pub message: String, 32 pub source_digest: Option, 33 /// The id the pipeline uses for the rejected call's result (source call id when valid, 34 /// otherwise `:t:c`). 35 pub request_id: String, 36 } 37 38 /// The parsed result of one model turn. 39 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 40 pub struct LenshiftTurn { 41 pub dialect: String, 42 pub dialect_version: String, 43 pub parser_version: String, 44 pub model: String, 45 pub text: String, 46 pub reasoning_digest: Option, 47 pub intents: Vec, 48 pub rejected: Vec, 49 pub partial: bool, 50 /// Emission index of each entry of `intents` (for interleaving with `rejected`). 51 #[serde(default)] 52 pub intent_indices: Vec, 53 } 54 55 /// A model dialect. 56 pub trait Dialect { 57 fn name(&self) -> &str; 58 fn version(&self) -> &str; 59 fn parse(&self, input: &Value, ctx: &ParseContext) -> LenshiftTurn; 60 /// Render a result as the dialect-native tool message. `intent` supplies the native call id. 61 fn render_result(&self, result: &ToolResult, intent: Option<&ToolRequest>) -> Value; 62 } 63 64 /// Parser version recorded in provenance. 65 pub const PARSER_VERSION: &str = "1.0.0"; 66 67 /// Dialects keyed by name. Registering a new one needs no Core change. 68 #[derive(Default)] 69 pub struct DialectRegistry { 70 dialects: BTreeMap>, 71 } 72 73 impl DialectRegistry { 74 pub fn new() -> Self { 75 Self::default() 76 } 77 /// `aien_legacy`, `openai`, `openai_stream` and `qwen35`. `ajax` is reserved and deliberately absent. 78 pub fn with_defaults() -> Self { 79 let mut r = Self::new(); 80 r.register(Box::new(aien_legacy::AienLegacy)); 81 r.register(Box::new(openai::OpenAi)); 82 r.register(Box::new(openai_stream::OpenAiStream)); 83 r.register(Box::new(qwen35::Qwen35)); 84 r 85 } 86 pub fn register(&mut self, d: Box) { 87 self.dialects.insert(d.name().to_string(), d); 88 } 89 /// Unknown name -> `unsupported_dialect`. 90 pub fn get(&self, name: &str) -> Result<&dyn Dialect, ErrorCode> { 91 self.dialects 92 .get(name) 93 .map(|b| b.as_ref()) 94 .ok_or(ErrorCode::UnsupportedDialect) 95 } 96 pub fn names(&self) -> Vec<&str> { 97 self.dialects.keys().map(String::as_str).collect() 98 } 99 } 100 101 /// Split `raw` on the last `.` into namespace + name only when the prefix matches 102 /// `^[a-z][a-z0-9_]*$`. Returns `None` when the name is not a legal `ToolRef` name. 103 pub fn canonical_tool(raw: &str) -> Option { 104 fn name_ok(n: &str) -> bool { 105 !n.is_empty() 106 && n.len() <= 128 107 && n.bytes() 108 .all(|c| c.is_ascii_alphanumeric() || b"_.:-".contains(&c)) 109 } 110 fn ns_ok(p: &str) -> bool { 111 let mut b = p.bytes(); 112 matches!(b.next(), Some(c) if c.is_ascii_lowercase()) 113 && b.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_') 114 } 115 if !name_ok(raw) { 116 return None; 117 } 118 if let Some((pre, post)) = raw.rsplit_once('.') { 119 if ns_ok(pre) && name_ok(post) { 120 return Some(ToolRef { 121 namespace: Some(pre.into()), 122 name: post.into(), 123 }); 124 } 125 } 126 Some(ToolRef { 127 namespace: None, 128 name: raw.into(), 129 }) 130 } 131 132 /// Request id: the dialect's call id when it is a valid Id, else `:t:c`. 133 pub fn assign_request_id(call_id: Option<&str>, ctx: &ParseContext, index: usize) -> String { 134 match call_id { 135 Some(id) if is_valid_id(id) => id.to_string(), 136 _ => format!("{}:t{}:c{}", ctx.trace_id, ctx.turn, index), 137 } 138 } 139 140 /// Build a `ToolRequest` with filled provenance. 141 #[allow(clippy::too_many_arguments)] 142 pub fn make_intent( 143 dialect: &str, 144 dialect_version: &str, 145 ctx: &ParseContext, 146 request_id: String, 147 tool: ToolRef, 148 arguments: Map, 149 source_call_id: Option, 150 source_digest: String, 151 raw_name: &str, 152 coercion: &str, 153 ) -> ToolRequest { 154 ToolRequest { 155 kind: ToolRequestKind, 156 request_id, 157 tool, 158 arguments, 159 provenance: Provenance { 160 dialect: dialect.into(), 161 dialect_version: Some(dialect_version.into()), 162 model: Some(ctx.model.clone()), 163 parser_version: PARSER_VERSION.into(), 164 source_turn: Some(ctx.turn), 165 source_call_id, 166 source_digest: Some(source_digest), 167 raw_name: Some(raw_name.into()), 168 coercion: Some(coercion.into()), 169 extensions: Map::new(), 170 }, 171 extensions: Map::new(), 172 } 173 } 174 175 /// `sha256:` of UTF-8 text. 176 pub fn text_digest(s: &str) -> String { 177 digest_bytes(s.as_bytes()) 178 } 179 180 /// Shared result serialization: canonical `data` for ok, otherwise 181 /// `{"error": {"code","message"}, "status": ...}`. 182 pub fn serialize_result(result: &ToolResult) -> String { 183 if result.status == interplane_core::ResultStatus::Ok { 184 canonicalize(&result.data) 185 } else { 186 let (code, message) = match &result.error { 187 Some(e) => (e.code.as_str().to_string(), e.message.clone()), 188 None => ("execution_error".to_string(), String::new()), 189 }; 190 canonicalize( 191 &json!({"error": {"code": code, "message": message}, "status": result.status.as_str()}), 192 ) 193 } 194 } 195 196 #[cfg(test)] 197 mod tests { 198 use super::*; 199 200 #[test] 201 fn tool_names_split_on_last_dot() { 202 assert_eq!( 203 canonical_tool("filesystem.read").unwrap(), 204 ToolRef { 205 namespace: Some("filesystem".into()), 206 name: "read".into() 207 } 208 ); 209 assert_eq!(canonical_tool("read_file").unwrap().namespace, None); 210 assert_eq!( 211 canonical_tool("a.b.c").unwrap(), 212 ToolRef { 213 namespace: None, 214 name: "a.b.c".into() 215 } 216 ); 217 assert_eq!(canonical_tool("Files.read").unwrap().namespace, None); 218 assert_eq!(canonical_tool("x.").unwrap().namespace, None); 219 assert!(canonical_tool("has space").is_none()); 220 assert!(canonical_tool("").is_none()); 221 } 222 223 #[test] 224 fn unknown_dialect_is_unsupported() { 225 let r = DialectRegistry::with_defaults(); 226 assert_eq!( 227 r.names(), 228 vec!["aien_legacy", "openai", "openai_stream", "qwen35"] 229 ); 230 assert!(r.get("openai").is_ok()); 231 assert_eq!( 232 r.get("frobnicate").err(), 233 Some(ErrorCode::UnsupportedDialect) 234 ); 235 assert_eq!(r.get("ajax").err(), Some(ErrorCode::UnsupportedDialect)); 236 } 237 }