Files
leleka/control-plane/src/response_tools.rs
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

330 lines
12 KiB
Rust

//! Reversible namespace lowering for Qwen's flat function template.
use std::collections::HashMap;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
pub struct Catalog {
pub flat: Vec<Value>,
identities: HashMap<String, (String, Option<String>, bool)>,
grammars: HashMap<String, regex::Regex>,
grammar_bytes: usize,
}
pub fn alias(name: &str, namespace: Option<&str>) -> Result<String, &'static str> {
fn valid(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
if !valid(name) || namespace.is_some_and(|value| !valid(value)) {
return Err(
"tool and namespace names require 1..64 ASCII letters, digits, hyphens or underscores",
);
}
Ok(match namespace {
None => name.to_owned(),
Some(namespace) => format!(
"ns_{}",
hex::encode(Sha256::digest(format!("{namespace}/{name}")))[..24].to_owned()
),
})
}
impl Catalog {
pub fn new(tools: &[Value]) -> Result<Self, &'static str> {
let mut catalog = Self {
flat: Vec::new(),
identities: HashMap::new(),
grammars: HashMap::new(),
grammar_bytes: 0,
};
let mut namespaces = std::collections::HashSet::new();
for tool in tools {
if tool["type"] == "namespace" {
let namespace = tool["name"].as_str().ok_or("namespace needs a name")?;
alias(namespace, None)?;
if !namespaces.insert(namespace) {
return Err("duplicate namespace");
}
let children = tool["tools"].as_array().ok_or("namespace needs tools")?;
for child in children {
catalog.add(child, Some(namespace))?;
}
} else {
catalog.add(tool, None)?;
}
}
Ok(catalog)
}
fn add(&mut self, tool: &Value, namespace: Option<&str>) -> Result<(), &'static str> {
let custom = tool["type"] == "custom";
if tool["type"] != "function" && !custom {
return Err("only function or custom text tools and namespaces are supported");
}
let mut grammar = None;
if custom {
let fields = tool.as_object().ok_or("custom tool must be an object")?;
if fields
.keys()
.any(|key| !matches!(key.as_str(), "type" | "name" | "description" | "format"))
{
return Err("unsupported custom tool field");
}
if tool
.get("description")
.is_some_and(|value| !value.is_string())
{
return Err("custom tool description must be text");
}
if let Some(format) = tool.get("format")
&& format != &json!({"type":"text"})
{
let fields = format.as_object().ok_or("invalid custom tool format")?;
if fields.len() != 3 || format["type"] != "grammar" || format["syntax"] != "regex" {
return Err(
"custom tools support text or validated regex format; Lark is not implemented",
);
}
let definition = format["definition"]
.as_str()
.ok_or("regex definition must be text")?;
if self.grammars.len() >= 32
|| self.grammar_bytes.saturating_add(definition.len()) > 64 * 1024
{
return Err("request exceeds 32 regex tools or 64 KiB of regex definitions");
}
grammar = Some((definition, compile_regex(definition)?));
}
}
let name = tool["name"].as_str().ok_or("function needs a name")?;
let alias = alias(name, namespace)?;
if self
.identities
.insert(
alias.clone(),
(name.to_owned(), namespace.map(str::to_owned), custom),
)
.is_some()
{
return Err("duplicate tool identity or alias collision");
}
let mut flat = tool.clone();
if custom {
flat = json!({"type":"function", "name":name,
"description":tool["description"].as_str().unwrap_or(""),
"parameters":{"type":"object","properties":{"input":{"type":"string"}},
"required":["input"],"additionalProperties":false}});
if let Some((definition, compiled)) = grammar {
flat["parameters"]["properties"]["input"]["description"] = json!(format!(
"The complete input must match this Rust regex exactly: {}",
serde_json::to_string(definition).expect("string serialization")
));
self.grammar_bytes += definition.len();
self.grammars.insert(alias.clone(), compiled);
}
}
flat["name"] = Value::String(alias);
if let Some(namespace) = namespace {
flat["description"] = Value::String(format!(
"{namespace}.{name}\n{}",
tool["description"].as_str().unwrap_or("")
));
}
self.flat.push(flat);
Ok(())
}
pub fn restore(&self, item: &mut Value) -> Result<(), String> {
let name = item["name"].as_str().ok_or("tool item needs a name")?;
let grammar = self.grammars.get(name);
let (name, namespace, custom) = self
.identities
.get(name)
.ok_or("undeclared tool identity")?;
item["name"] = Value::String(name.clone());
if let Some(namespace) = namespace {
item["namespace"] = Value::String(namespace.clone());
}
if *custom {
let arguments = item["arguments"]
.as_str()
.ok_or("tool item needs arguments")?;
let input = custom_input(arguments, item["status"] == "in_progress")?;
if item["status"] != "in_progress"
&& grammar.is_some_and(|regex| !regex.is_match(&input))
{
return Err("custom tool input does not match its regex grammar".into());
}
item.as_object_mut()
.ok_or("tool item must be an object")?
.remove("arguments");
item["type"] = json!("custom_tool_call");
item["input"] = json!(input);
}
Ok(())
}
pub fn is_custom(&self, name: &str) -> bool {
self.identities
.get(name)
.is_some_and(|(_, _, custom)| *custom)
}
}
fn compile_regex(definition: &str) -> Result<regex::Regex, &'static str> {
use regex_syntax::ast::{Ast, Flag, Flags, FlagsItemKind};
if definition.is_empty() || definition.len() > 8192 || definition.contains(['\n', '\r']) {
return Err("regex definition requires 1..8192 bytes on one line");
}
let ast = regex_syntax::ast::parse::ParserBuilder::new()
.nest_limit(64)
.build()
.parse(definition)
.map_err(|_| "invalid or unsupported regex grammar")?;
fn flags_supported(flags: &Flags) -> bool {
!flags.items.iter().any(|item| {
matches!(
item.kind,
FlagsItemKind::Flag(Flag::IgnoreWhitespace | Flag::SwapGreed)
)
})
}
let mut pending = vec![&ast];
while let Some(node) = pending.pop() {
match node {
Ast::Flags(flags) if !flags_supported(&flags.flags) => {
return Err("regex verbose and swap-greed flags are unsupported");
}
Ast::Group(group) => {
if group.flags().is_some_and(|flags| !flags_supported(flags)) {
return Err("regex verbose and swap-greed flags are unsupported");
}
pending.push(&group.ast);
}
Ast::Repetition(repetition) => {
if !repetition.greedy {
return Err("lazy regex repetition is unsupported");
}
pending.push(&repetition.ast);
}
Ast::Concat(concat) => pending.extend(&concat.asts),
Ast::Alternation(alternation) => pending.extend(&alternation.asts),
_ => {}
}
}
regex::RegexBuilder::new(&format!(r"\A(?:{definition})\z"))
.nest_limit(66)
.size_limit(1024 * 1024)
.dfa_size_limit(1024 * 1024)
.build()
.map_err(|_| "invalid regex grammar or compiled regex exceeds 1 MiB")
}
fn custom_input(arguments: &str, pending: bool) -> Result<String, String> {
if pending && arguments.is_empty() {
return Ok(String::new());
}
let parsed: Value =
serde_json::from_str(arguments).map_err(|_| "invalid custom tool input envelope")?;
if parsed.as_object().is_none_or(|object| object.len() != 1) {
return Err("custom tool requires exactly one string input".into());
}
parsed["input"]
.as_str()
.map(str::to_owned)
.ok_or_else(|| "custom tool requires string input".into())
}
/// Public stream event names depend on the declared tool kind.
pub fn input_events(custom: bool) -> (&'static str, &'static str) {
if custom {
(
"response.custom_tool_call_input.delta",
"response.custom_tool_call_input.done",
)
} else {
(
"response.function_call_arguments.delta",
"response.function_call_arguments.done",
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tool(name: &str, definition: &str) -> Value {
json!({"type":"custom","name":name,"format":{"type":"grammar","syntax":"regex","definition":definition}})
}
#[test]
fn regex_whole_input_validation_preserves_unicode_and_namespaces() {
let catalog = Catalog::new(&[
json!({"type":"namespace","name":"code","tools":[tool("run", r"(?s)\n Привіт 🌍\n")]}),
])
.unwrap();
assert!(
catalog.flat[0]["parameters"]["properties"]["input"]["description"]
.as_str()
.unwrap()
.contains("Rust regex")
);
for (input, valid) in [
("\n Привіт 🌍\n", true),
("Привіт 🌍", false),
("\n Привіт 🌍\nextra", false),
] {
let mut item = json!({"name":alias("run",Some("code")).unwrap(),"status":"completed","arguments":json!({"input":input}).to_string()});
assert_eq!(catalog.restore(&mut item).is_ok(), valid);
if valid {
assert_eq!(item["input"], input);
assert_eq!(item["namespace"], "code");
assert_eq!(item["name"], "run");
}
}
let accepts_empty = compile_regex("a*").unwrap();
assert!(accepts_empty.is_match(""));
assert!(!compile_regex("a+").unwrap().is_match(""));
let alternation = compile_regex("a|ab").unwrap();
assert!(alternation.is_match("ab"));
assert!(!alternation.is_match("abc"));
}
#[test]
fn regex_dialect_and_resource_limits_fail_closed() {
for bad in [
"",
"[",
"(?=a)",
r"(a)\1",
"a*?",
"a+?",
"a??",
"a{2}?",
"(?x:a)",
"(?U)a",
"a\nb",
r"a{10000000}",
] {
assert!(compile_regex(bad).is_err(), "accepted {bad}");
}
assert!(compile_regex(&"a".repeat(8193)).is_err());
assert!(compile_regex(r"[\*\+\?]+").is_ok()); // Literal punctuation isn't a lazy modifier.
let many: Vec<_> = (0..33).map(|n| tool(&format!("t{n}"), "a")).collect();
assert!(Catalog::new(&many[..32]).is_ok());
assert!(Catalog::new(&many).is_err());
let large: Vec<_> = (0..9)
.map(|n| tool(&format!("t{n}"), &"a".repeat(8192)))
.collect();
assert!(Catalog::new(&large).is_err());
let mut extra = tool("run", "a");
extra["format"]["ignored"] = json!(true);
assert!(Catalog::new(&[extra]).is_err());
}
}