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/aien-sovereign-core-mv/blob/main/crates/aien-inference-abi/src/tool_boundary.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. 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 `aien-sovereign-core-mv / crates / aien-inference-abi / src / tool_boundary.rs` 392 lines ยท 15231 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Trusted boundary for tool output entering a Qwen3 conversation (issue #310). 17 //! 18 //! The Qwen3-Instruct-2507 chat template does not escape tool content, and 19 //! [`ChatTemplate::ChatMlQwen3`] matches it byte for byte (that is correct and stays so). A tool 20 //! result containing `<|im_end|>` or `` would therefore close the tool turn 21 //! early and let untrusted text forge the next message. The renderer is not the place to fix 22 //! this; the place is the code that turns tool output into a conversation turn. 23 //! 24 //! This module is that place. Honest status: UNVERIFIED that any production caller forwards tool 25 //! turns today (the daemon sends user/system only). So the boundary is the single entry point a 26 //! tool turn must pass: a tool turn can only be built as a [`ToolOutput`] (private fields, made 27 //! only by [`ToolGuard::admit`]) and only added to a [`ToolConversation`], which pairs it with an 28 //! assistant tool call. The runtime's `ChatTurn` path refuses role `tool` outright and points 29 //! here (`aien_runtime::control`). 30 //! 31 //! Policy: fail closed with a named [`ToolBoundaryError`]. Nothing is escaped or stripped. 32 //! Source of truth for the refusal list: the template's own structural strings (below, pinned by 33 //! a test against what the renderer actually emits) united with every added token of the loaded 34 //! tokenizer ([`ToolGuard::from_tokenizer`]), so a vocabulary change cannot drift past the check. 35 36 use crate::tokenizer::{ChatTemplate, ChatTokenizer}; 37 use std::collections::HashSet; 38 use std::fmt; 39 40 /// Structural strings of the Qwen3-Instruct-2507 template and tokenizer (lowercase). 41 pub const QWEN3_CONTROL_STRINGS: &[&str] = &[ 42 "<|im_start|>", 43 "<|im_end|>", 44 "<|endoftext|>", 45 "", 46 "", 47 "", 48 "", 49 "", 50 "", 51 "", 52 "", 53 ]; 54 55 /// Tag names refused in any `), 78 /// The tool turn was asked of a template that does not define role `tool`. 79 UnsupportedTemplate, 80 /// The renderer itself refused (message from the renderer). 81 Render(String), 82 } 83 84 impl fmt::Display for ToolBoundaryError { 85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 86 match self { 87 Self::ControlSequence { pattern } => { 88 write!( 89 f, 90 "tool output refused: contains template control sequence {pattern}" 91 ) 92 } 93 Self::NoToolCalls => write!(f, "assistant tool-call turn declares no calls"), 94 Self::EmptyCallId => write!(f, "tool call id is empty"), 95 Self::DuplicateCallId(id) => write!(f, "tool call id {id:?} declared twice"), 96 Self::UnknownCallId(id) => write!(f, "tool result for undeclared call id {id:?}"), 97 Self::DuplicateToolResult(id) => { 98 write!(f, "second tool result for call id {id:?} (replay refused)") 99 } 100 Self::ToolResultWithoutCall => { 101 write!( 102 f, 103 "tool result with no unanswered assistant tool call before it" 104 ) 105 } 106 Self::ToolCallsPending(ids) => { 107 write!(f, "tool calls still unanswered: {ids:?}") 108 } 109 Self::UnsupportedTemplate => { 110 write!(f, "this chat template does not define role tool; refused") 111 } 112 Self::Render(e) => write!(f, "render refused: {e}"), 113 } 114 } 115 } 116 117 impl std::error::Error for ToolBoundaryError {} 118 119 /// Characters that render as nothing (or are control characters) and are dropped before 120 /// matching: soft hyphen, combining grapheme joiner, Arabic letter mark, Mongolian vowel 121 /// separator, zero-width and bidi marks, invisible operators, variation selectors, braille 122 /// blank, Hangul fillers, Khmer inherent vowels, tag characters, BOM, and all non-whitespace 123 /// control characters (NUL included). 124 fn is_invisible(c: char) -> bool { 125 matches!(c, 126 '\u{00AD}' | '\u{034F}' | '\u{061C}' | '\u{115F}' | '\u{1160}' | '\u{17B4}' | '\u{17B5}' 127 | '\u{180B}'..='\u{180F}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' 128 | '\u{2060}'..='\u{206F}' | '\u{2800}' | '\u{3164}' | '\u{FE00}'..='\u{FE0F}' 129 | '\u{FEFF}' | '\u{FFA0}' | '\u{FFF9}'..='\u{FFFB}' | '\u{E0000}'..='\u{E0FFF}') 130 || (c.is_control() && !c.is_whitespace()) 131 } 132 133 /// Folds text for matching: drops invisible characters, maps full-width ASCII and a small set 134 /// of angle/bar/slash and letter lookalikes (long s, dotless i) to ASCII, and lowercases (which 135 /// also maps the Kelvin sign to `k`). This is NOT full NFKC: no normalization crate is in 136 /// Cargo.lock (only `unicode-normalization-alignments`, unrelated) and the sovereignty rule 137 /// forbids adding one. 138 fn fold(text: &str) -> String { 139 let mut out = String::with_capacity(text.len()); 140 for c in text.chars() { 141 if is_invisible(c) { 142 continue; 143 } 144 let c = match c { 145 '\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c), 146 '\u{2039}' | '\u{27E8}' | '\u{2329}' | '\u{3008}' => '<', 147 '\u{203A}' | '\u{27E9}' | '\u{232A}' | '\u{3009}' => '>', 148 '\u{2758}' | '\u{2502}' | '\u{2223}' | '\u{01C0}' => '|', 149 '\u{29F8}' | '\u{2215}' => '/', 150 '\u{017F}' => 's', 151 '\u{0131}' => 'i', 152 other => other, 153 }; 154 out.extend(c.to_lowercase()); 155 } 156 out 157 } 158 159 /// The refusal list. Construct with [`ToolGuard::from_tokenizer`] (the only public constructor). 160 #[derive(Debug, Clone)] 161 pub struct ToolGuard { 162 patterns: Vec, 163 } 164 165 impl ToolGuard { 166 /// The template's structural strings only. 167 pub(crate) fn qwen3() -> Self { 168 Self { 169 patterns: QWEN3_CONTROL_STRINGS 170 .iter() 171 .map(|s| s.to_string()) 172 .collect(), 173 } 174 } 175 176 /// The template's structural strings united with every added token (special or not) of 177 /// `tok`, so the refusal list follows the real vocabulary. 178 pub fn from_tokenizer(tok: &ChatTokenizer) -> Self { 179 let mut g = Self::qwen3(); 180 for added in tok.inner().get_added_tokens_decoder().values() { 181 let p = fold(&added.content); 182 if !p.trim().is_empty() && !g.patterns.contains(&p) { 183 g.patterns.push(p); 184 } 185 } 186 g 187 } 188 189 fn scan(&self, text: &str) -> Result<(), ToolBoundaryError> { 190 let f = fold(text); 191 // Also match with every whitespace character removed, so `` is caught. 192 let squeezed: String = f.chars().filter(|c| !c.is_whitespace()).collect(); 193 for p in &self.patterns { 194 let squeezed_p: String = p.chars().filter(|c| !c.is_whitespace()).collect(); 195 if f.contains(p.as_str()) || squeezed.contains(squeezed_p.as_str()) { 196 return Err(ToolBoundaryError::ControlSequence { pattern: p.clone() }); 197 } 198 } 199 // Spacing variants: `<` [ws] `|`, and `<` [ws] [`/`] [ws] tag-name (Unicode whitespace). 200 let ch: Vec = f.chars().collect(); 201 let skip_ws = |mut j: usize| { 202 while j < ch.len() && ch[j].is_whitespace() { 203 j += 1; 204 } 205 j 206 }; 207 for i in (0..ch.len()).filter(|&i| ch[i] == '<') { 208 let mut j = skip_ws(i + 1); 209 if ch.get(j) == Some(&'|') { 210 return Err(ToolBoundaryError::ControlSequence { 211 pattern: "<|".into(), 212 }); 213 } 214 if ch.get(j) == Some(&'/') { 215 j = skip_ws(j + 1); 216 } 217 let rest: String = ch[j..].iter().take(16).collect(); 218 for name in REFUSED_TAG_NAMES { 219 if rest.starts_with(name) { 220 return Err(ToolBoundaryError::ControlSequence { 221 pattern: format!("<{name}> (spacing variant)"), 222 }); 223 } 224 } 225 } 226 Ok(()) 227 } 228 229 /// The only way to make a [`ToolOutput`]: untrusted `text` for call `call_id`, or a named 230 /// refusal. 231 pub fn admit(&self, call_id: &str, text: &str) -> Result { 232 if call_id.is_empty() { 233 return Err(ToolBoundaryError::EmptyCallId); 234 } 235 self.scan(text)?; 236 Ok(ToolOutput { 237 call_id: call_id.to_string(), 238 text: text.to_string(), 239 }) 240 } 241 } 242 243 /// Tool text that passed the guard, bound to one call id. Private fields, no `Clone`: it cannot 244 /// be built around the check, and one value can be submitted once. 245 #[derive(Debug)] 246 pub struct ToolOutput { 247 call_id: String, 248 text: String, 249 } 250 251 impl ToolOutput { 252 pub fn call_id(&self) -> &str { 253 &self.call_id 254 } 255 } 256 257 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 258 enum Role { 259 System, 260 User, 261 Assistant, 262 Tool, 263 } 264 265 impl Role { 266 fn name(self) -> &'static str { 267 match self { 268 Self::System => "system", 269 Self::User => "user", 270 Self::Assistant => "assistant", 271 Self::Tool => "tool", 272 } 273 } 274 } 275 276 /// A conversation that can carry tool turns. Tool turns enter only through 277 /// [`ToolConversation::tool_result`], which enforces call/result pairing. 278 #[derive(Debug)] 279 pub struct ToolConversation { 280 turns: Vec<(Role, String)>, 281 declared: HashSet, 282 pending: Vec, 283 } 284 285 impl Default for ToolConversation { 286 fn default() -> Self { 287 Self::new() 288 } 289 } 290 291 impl ToolConversation { 292 pub fn new() -> Self { 293 Self { 294 turns: Vec::new(), 295 declared: HashSet::new(), 296 pending: Vec::new(), 297 } 298 } 299 300 fn plain(&mut self, role: Role, text: &str) -> Result<(), ToolBoundaryError> { 301 if !self.pending.is_empty() { 302 return Err(ToolBoundaryError::ToolCallsPending(self.pending.clone())); 303 } 304 self.turns.push((role, text.to_string())); 305 Ok(()) 306 } 307 308 /// Trusted system text. 309 pub fn system(&mut self, text: &str) -> Result<(), ToolBoundaryError> { 310 self.plain(Role::System, text) 311 } 312 313 /// Trusted user text. 314 pub fn user(&mut self, text: &str) -> Result<(), ToolBoundaryError> { 315 self.plain(Role::User, text) 316 } 317 318 /// An assistant turn with no tool calls. 319 pub fn assistant(&mut self, text: &str) -> Result<(), ToolBoundaryError> { 320 self.plain(Role::Assistant, text) 321 } 322 323 /// An assistant turn that calls tools with ids `call_ids`. Results are then expected, one 324 /// per id, before any other turn. The assistant `text` is model output and is not scanned 325 /// here (it is not tool output). 326 pub fn assistant_tool_calls( 327 &mut self, 328 text: &str, 329 call_ids: &[&str], 330 ) -> Result<(), ToolBoundaryError> { 331 if !self.pending.is_empty() { 332 return Err(ToolBoundaryError::ToolCallsPending(self.pending.clone())); 333 } 334 let mut fresh = HashSet::new(); 335 for id in call_ids { 336 if id.is_empty() { 337 return Err(ToolBoundaryError::EmptyCallId); 338 } 339 if self.declared.contains(*id) || !fresh.insert(*id) { 340 return Err(ToolBoundaryError::DuplicateCallId((*id).to_string())); 341 } 342 } 343 if fresh.is_empty() { 344 return Err(ToolBoundaryError::NoToolCalls); 345 } 346 for id in call_ids { 347 self.declared.insert((*id).to_string()); 348 self.pending.push((*id).to_string()); 349 } 350 self.turns.push((Role::Assistant, text.to_string())); 351 Ok(()) 352 } 353 354 /// Adds a guarded tool result. Refused unless an unanswered call with this id exists. 355 pub fn tool_result(&mut self, out: ToolOutput) -> Result<(), ToolBoundaryError> { 356 if self.pending.is_empty() && !self.declared.contains(&out.call_id) { 357 return Err(ToolBoundaryError::ToolResultWithoutCall); 358 } 359 if !self.declared.contains(&out.call_id) { 360 return Err(ToolBoundaryError::UnknownCallId(out.call_id)); 361 } 362 match self.pending.iter().position(|p| *p == out.call_id) { 363 Some(i) => { 364 self.pending.remove(i); 365 self.turns.push((Role::Tool, out.text)); 366 Ok(()) 367 } 368 None => Err(ToolBoundaryError::DuplicateToolResult(out.call_id)), 369 } 370 } 371 372 /// Renders with `template`. Refused while calls are unanswered, or if the conversation has 373 /// tool turns and `template` is not [`ChatTemplate::ChatMlQwen3`] (other templates would 374 /// silently downgrade role `tool` to `user`). 375 pub fn render(&self, template: &ChatTemplate) -> Result { 376 if !self.pending.is_empty() { 377 return Err(ToolBoundaryError::ToolCallsPending(self.pending.clone())); 378 } 379 let has_tool = self.turns.iter().any(|(r, _)| *r == Role::Tool); 380 if has_tool && *template != ChatTemplate::ChatMlQwen3 { 381 return Err(ToolBoundaryError::UnsupportedTemplate); 382 } 383 let turns: Vec<(&str, &str)> = self 384 .turns 385 .iter() 386 .map(|(r, t)| (r.name(), t.as_str())) 387 .collect(); 388 template 389 .try_render(&turns) 390 .map_err(|e| ToolBoundaryError::Render(e.to_string())) 391 } 392 }