Files
leleka/desktop-core/src/runtime_tools.rs
T

725 lines
24 KiB
Rust

//! Bounded, whole-completion tool semantics for the experimental native adapter.
//! This module performs no publication or execution and mints no identifiers.
use std::collections::{HashMap, HashSet};
use std::io::{self, Write};
use serde_json::{Value, json};
use crate::runtime_prompt::{Effort, Message, Role};
use crate::runtime_tool_catalog::{Catalog, alias};
use crate::runtime_tool_parser::{self, Segment};
const REQUEST_LIMIT: usize = 1024 * 1024;
const OUTPUT_LIMIT: usize = 8 * 1024 * 1024;
const TOOL_LIMIT: usize = 128;
const ITEM_LIMIT: usize = 1024;
pub struct ToolPlan {
pub prompt: String,
pub max_output_tokens: u32,
pub policy: ToolPolicy,
pub sampling: leleka_sampler_ref::params::FixedPoint,
}
pub enum ValidatedSegment {
Text(String),
Call(Value),
}
pub struct ToolPolicy {
catalog: Catalog,
identities: HashMap<String, Identity>,
schemas: HashMap<String, jsonschema::Validator>,
choice: Choice,
parallel: bool,
}
struct Identity {
name: String,
namespace: Option<String>,
custom: bool,
}
enum Choice {
None,
Auto,
Required,
Forced(String),
Allowed {
required: bool,
names: HashSet<String>,
},
}
fn fields<'a>(
value: &'a Value,
allowed: &[&str],
) -> Result<&'a serde_json::Map<String, Value>, &'static str> {
let object = value.as_object().ok_or("expected_object")?;
if object.keys().any(|key| !allowed.contains(&key.as_str())) {
return Err("unsupported_field");
}
Ok(object)
}
fn optional_text(value: &Value, key: &str) -> Result<(), &'static str> {
if value.get(key).is_some_and(|v| !v.is_string()) {
return Err("invalid_text_field");
}
Ok(())
}
fn local_refs(value: &Value) -> Result<(), &'static str> {
match value {
Value::Object(object) => {
for (key, child) in object {
if matches!(key.as_str(), "$ref" | "$dynamicRef" | "$recursiveRef")
&& child
.as_str()
.is_none_or(|reference| !reference.starts_with('#'))
{
return Err("schema_references_must_be_local");
}
local_refs(child)?;
}
}
Value::Array(array) => {
for child in array {
local_refs(child)?;
}
}
_ => {}
}
Ok(())
}
fn add_identity(
tool: &Value,
namespace: Option<&str>,
identities: &mut HashMap<String, Identity>,
) -> Result<(), &'static str> {
let custom = match tool["type"].as_str() {
Some("function") => false,
Some("custom") => true,
_ => return Err("unsupported_tool_type"),
};
fields(
tool,
if custom {
&["type", "name", "description", "format"]
} else {
&["type", "name", "description", "parameters", "strict"]
},
)?;
optional_text(tool, "description")?;
if tool.get("strict").is_some_and(|v| !v.is_boolean()) {
return Err("invalid_strict");
}
if let Some(schema) = tool.get("parameters") {
if !schema.is_object() || schema["type"] != "object" {
return Err("parameters_must_be_object_schema");
}
local_refs(schema)?;
}
let name = tool["name"].as_str().ok_or("tool_name_required")?;
let flat_name = alias(name, namespace)?;
if identities.len() >= TOOL_LIMIT
|| identities
.insert(
flat_name,
Identity {
name: name.to_owned(),
namespace: namespace.map(str::to_owned),
custom,
},
)
.is_some()
{
return Err("tool_limit_or_duplicate_identity");
}
Ok(())
}
impl ToolPolicy {
fn new(
tools: &[Value],
selection: Option<&Value>,
parallel: bool,
) -> Result<Self, &'static str> {
if tools.len() > TOOL_LIMIT {
return Err("tool_limit");
}
let mut identities = HashMap::new();
for tool in tools {
if tool["type"] == "namespace" {
fields(tool, &["type", "name", "description", "tools"])?;
optional_text(tool, "description")?;
let name = tool["name"].as_str().ok_or("namespace_name_required")?;
alias(name, None)?;
let children = tool["tools"].as_array().ok_or("namespace_tools_required")?;
if children.is_empty() || children.len() > TOOL_LIMIT {
return Err("invalid_namespace_tools");
}
for child in children {
add_identity(child, Some(name), &mut identities)?;
}
} else {
add_identity(tool, None, &mut identities)?;
}
}
let catalog = Catalog::new(tools)?;
let mut schemas = HashMap::new();
for tool in &catalog.flat {
let schema = tool
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object"}));
local_refs(&schema)?;
let validator = jsonschema::options()
.offline()
.build(&schema)
.map_err(|_| "invalid_tool_schema")?;
schemas.insert(
tool["name"]
.as_str()
.ok_or("tool_name_required")?
.to_owned(),
validator,
);
}
let mut policy = Self {
catalog,
identities,
schemas,
choice: Choice::Auto,
parallel,
};
policy.choice = match selection {
None => Choice::Auto,
Some(Value::String(choice)) => match choice.as_str() {
"none" => Choice::None,
"auto" => Choice::Auto,
"required" if !policy.identities.is_empty() => Choice::Required,
_ => return Err("invalid_tool_choice"),
},
Some(choice) if choice["type"] == "allowed_tools" => {
fields(choice, &["type", "mode", "tools"])?;
let required = match choice["mode"].as_str() {
Some("auto") => false,
Some("required") => true,
_ => return Err("invalid_allowed_tools_mode"),
};
let selectors = choice["tools"].as_array().ok_or("allowed_tools_required")?;
if selectors.is_empty() || selectors.len() > TOOL_LIMIT {
return Err("invalid_allowed_tools");
}
let mut names = HashSet::new();
for selector in selectors {
let name = policy.selector(selector)?;
if !names.insert(name) {
return Err("duplicate_allowed_tool");
}
}
Choice::Allowed { required, names }
}
Some(choice) => Choice::Forced(policy.selector(choice)?),
};
Ok(policy)
}
fn selector(&self, value: &Value) -> Result<String, &'static str> {
fields(value, &["type", "name", "namespace"])?;
let custom = match value["type"].as_str() {
Some("function") => false,
Some("custom") => true,
_ => return Err("invalid_tool_selector"),
};
self.identity(value, custom)
}
fn identity(&self, value: &Value, custom: bool) -> Result<String, &'static str> {
let name = value["name"].as_str().ok_or("tool_name_required")?;
let namespace = value
.get("namespace")
.map(|v| v.as_str().ok_or("invalid_namespace"))
.transpose()?;
let flat = alias(name, namespace)?;
let identity = self.identities.get(&flat).ok_or("undeclared_tool")?;
if identity.name != name
|| identity.namespace.as_deref() != namespace
|| identity.custom != custom
{
return Err("tool_identity_mismatch");
}
Ok(flat)
}
fn validated_call(&self, name: &str, arguments: &Value) -> Result<Value, &'static str> {
if !arguments.is_object()
|| !self
.schemas
.get(name)
.ok_or("undeclared_tool")?
.is_valid(arguments)
{
return Err("invalid_tool_arguments");
}
let mut item = json!({"type":"function_call","name":name,"arguments":arguments.to_string(),"status":"completed"});
self.catalog
.restore(&mut item)
.map_err(|_| "invalid_custom_input_or_grammar")?;
item.as_object_mut()
.ok_or("invalid_tool_item")?
.remove("status");
Ok(item)
}
pub fn parse_output(&self, output: &str) -> Result<Vec<ValidatedSegment>, &'static str> {
if output.len() > OUTPUT_LIMIT {
return Err("output_limit");
}
let parsed = runtime_tool_parser::parse_complete(output, &self.catalog.flat)
.map_err(|_| "invalid_tool_output")?;
let mut result = Vec::new();
let mut calls = 0usize;
for segment in parsed {
match segment {
Segment::Text(text) => {
if reserved_markup(&text) {
return Err("incomplete_or_orphan_tool_markup");
}
result.push(ValidatedSegment::Text(text));
}
Segment::Call { name, arguments } => {
calls += 1;
if calls > TOOL_LIMIT || (!self.parallel && calls > 1) {
return Err("tool_call_count");
}
match &self.choice {
Choice::None => return Err("tool_choice_none"),
Choice::Forced(wanted) if wanted != &name || calls > 1 => {
return Err("forced_tool_mismatch");
}
Choice::Allowed { names, .. } if !names.contains(&name) => {
return Err("tool_not_allowed");
}
_ => {}
}
result.push(ValidatedSegment::Call(
self.validated_call(&name, &arguments)?,
));
}
}
}
if calls == 0
&& matches!(
self.choice,
Choice::Required | Choice::Forced(_) | Choice::Allowed { required: true, .. }
)
{
return Err("required_tool_missing");
}
Ok(result)
}
fn choice_instruction(&self) -> Option<String> {
match &self.choice {
Choice::None => None,
Choice::Auto => None,
Choice::Required => {
Some("Call at least one declared tool in this response.".to_owned())
}
Choice::Forced(name) => Some(format!(
"Call exactly one tool named {name} in this response."
)),
Choice::Allowed { required, names } => {
let mut names = names.iter().map(String::as_str).collect::<Vec<_>>();
names.sort_unstable();
Some(format!(
"Only these tools may be called: {}. {}",
names.join(", "),
if *required {
"Call at least one."
} else {
"A text response is also allowed."
}
))
}
}
}
}
// Whole parsing cannot turn an unfinished or orphan control delimiter into text.
fn reserved_markup(text: &str) -> bool {
const TAGS: [&str; 6] = [
"<tool_call>",
"</tool_call>",
"<function=",
"</function>",
"<parameter=",
"</parameter>",
];
[
"<tool_",
"</tool_",
"<function",
"</function",
"<parameter",
"</parameter",
]
.iter()
.any(|prefix| text.contains(prefix))
|| TAGS.iter().any(|tag| {
text.contains(tag.trim_end_matches('>'))
|| (2..tag.len()).any(|length| text.ends_with(&tag[..length]))
})
}
struct Count(usize);
impl Write for Count {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0 = self
.0
.checked_add(bytes.len())
.filter(|size| *size <= REQUEST_LIMIT)
.ok_or_else(|| io::Error::other("request_limit"))?;
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
pub fn prepare(request: &Value) -> Result<ToolPlan, &'static str> {
serde_json::to_writer(Count(0), request).map_err(|_| "request_limit")?;
let object = fields(
request,
&[
"model",
"input",
"instructions",
"stream",
"max_output_tokens",
"temperature",
"top_p",
"top_k",
"min_p",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"penalty_last_n",
"seed",
"store",
"tools",
"tool_choice",
"parallel_tool_calls",
"text",
],
)?;
if request["model"].as_str().is_none_or(str::is_empty) {
return Err("model_required");
}
if object.get("stream").is_some_and(|v| !v.is_boolean()) {
return Err("invalid_stream");
}
if object
.get("store")
.is_some_and(|v| v != &Value::Bool(false))
{
return Err("unsupported_sampling_or_store");
}
let sampling = crate::runtime_sampling::from_json(object)?;
if object
.get("text")
.is_some_and(|v| v != &json!({"format":{"type":"text"}}))
{
return Err("unsupported_text_format");
}
let cap = object
.get("max_output_tokens")
.map(|v| v.as_u64().ok_or("invalid_output_limit"))
.transpose()?
.unwrap_or(256);
if !(1..=4096).contains(&cap) {
return Err("invalid_output_limit");
}
let tools = object
.get("tools")
.map(|v| v.as_array().ok_or("invalid_tools"))
.transpose()?
.map(Vec::as_slice)
.unwrap_or(&[]);
let parallel = object
.get("parallel_tool_calls")
.map(|v| v.as_bool().ok_or("invalid_parallel_tool_calls"))
.transpose()?
.unwrap_or(true);
let policy = ToolPolicy::new(tools, object.get("tool_choice"), parallel)?;
let mut owned = Vec::new();
if let Some(instructions) = object.get("instructions") {
owned.push((
Role::System,
instructions
.as_str()
.ok_or("invalid_instructions")?
.to_owned(),
));
}
if let Some(instruction) = policy.choice_instruction() {
owned.push((Role::System, instruction));
}
if !parallel && !tools.is_empty() {
owned.push((
Role::System,
"Call at most one tool in this response.".to_owned(),
));
}
history(
object.get("input").ok_or("input_required")?,
&policy,
&mut owned,
)?;
let messages = owned
.iter()
.map(|(role, content)| Message {
role: *role,
content,
reasoning: None,
parts: None,
})
.collect::<Vec<_>>();
let flat = if matches!(policy.choice, Choice::None) {
&[][..]
} else {
&policy.catalog.flat[..]
};
let prompt = crate::runtime_prompt::render_with_tools(&messages, Effort::None, flat)
.map_err(|_| "prompt template rendering failed")?;
if prompt.len() > REQUEST_LIMIT {
return Err("prompt_limit");
}
Ok(ToolPlan {
prompt,
max_output_tokens: cap as u32,
policy,
sampling,
})
}
struct Pending {
id: String,
custom: bool,
markup: String,
output: Option<String>,
}
fn content(value: &Value, output: bool) -> Result<String, &'static str> {
if let Some(text) = value.as_str() {
return Ok(text.to_owned());
}
let parts = value.as_array().ok_or("invalid_content")?;
if parts.len() > ITEM_LIMIT {
return Err("content_limit");
}
let mut text = String::new();
for (index, part) in parts.iter().enumerate() {
fields(part, &["type", "text", "annotations", "logprobs"])?;
for key in ["annotations", "logprobs"] {
if part.get(key).is_some_and(|metadata| {
part["type"] != "output_text"
|| metadata.as_array().is_none_or(|items| !items.is_empty())
}) {
return Err("unsupported_output_metadata");
}
}
if !matches!(part["type"].as_str(), Some("input_text" | "output_text"))
|| (output && part["type"] != "input_text")
{
return Err("unsupported_content");
}
if output && index > 0 {
text.push('\n');
}
text.push_str(part["text"].as_str().ok_or("invalid_text")?);
}
Ok(text)
}
fn valid_id(value: &Value) -> Result<&str, &'static str> {
let id = value.as_str().ok_or("call_id_required")?;
if id.is_empty() || id.len() > 256 || !id.bytes().all(|b| b.is_ascii_graphic()) {
return Err("invalid_call_id");
}
Ok(id)
}
fn history(
input: &Value,
policy: &ToolPolicy,
owned: &mut Vec<(Role, String)>,
) -> Result<(), &'static str> {
if let Some(text) = input.as_str() {
owned.push((Role::User, text.to_owned()));
return Ok(());
}
let items = input.as_array().ok_or("invalid_input")?;
if items.is_empty() || items.len() > ITEM_LIMIT {
return Err("input_item_limit");
}
let mut pending: Vec<Pending> = Vec::new();
let mut seen = HashSet::new();
let mut item_ids = HashSet::new();
for item in items {
if let Some(id) = item.get("id")
&& !item_ids.insert(valid_id(id)?.to_owned())
{
return Err("duplicate_item_id");
}
let kind = item
.get("type")
.map(|v| v.as_str().ok_or("invalid_item_type"))
.transpose()?
.unwrap_or("message");
match kind {
"message" => {
fields(item, &["type", "id", "status", "role", "content"])?;
completed_item(item)?;
if !pending.is_empty() {
return Err("unresolved_tool_history");
}
let role = match item["role"].as_str() {
Some("system") => Role::System,
Some("developer") => Role::Developer,
Some("user") => Role::User,
Some("assistant") => Role::Assistant,
_ => return Err("invalid_role"),
};
owned.push((
role,
content(item.get("content").ok_or("content_required")?, false)?,
));
}
"function_call" | "custom_tool_call" => {
let custom = kind == "custom_tool_call";
fields(
item,
if custom {
&[
"type",
"id",
"status",
"call_id",
"name",
"namespace",
"input",
]
} else {
&[
"type",
"id",
"status",
"call_id",
"name",
"namespace",
"arguments",
]
},
)?;
completed_item(item)?;
if pending.iter().any(|call| call.output.is_some()) {
return Err("call_after_tool_result");
}
let id = valid_id(&item["call_id"])?;
if !seen.insert(id.to_owned()) {
return Err("duplicate_call_id");
}
let name = policy.identity(item, custom)?;
let arguments = if custom {
json!({"input":item["input"].as_str().ok_or("custom_input_required")?})
} else {
serde_json::from_str(item["arguments"].as_str().ok_or("arguments_required")?)
.map_err(|_| "invalid_history_arguments")?
};
policy.validated_call(&name, &arguments)?;
let mut markup = format!("<tool_call>\n<function={name}>\n");
for (parameter, value) in arguments.as_object().ok_or("arguments_must_be_object")? {
alias(parameter, None).map_err(|_| "unsafe_parameter_name")?;
markup.push_str(&format!("<parameter={parameter}>\n"));
if let Some(text) = value.as_str() {
markup.push_str(text);
} else {
markup.push_str(&value.to_string());
}
markup.push_str("\n</parameter>\n");
}
markup.push_str("</function>\n</tool_call>");
pending.push(Pending {
id: id.to_owned(),
custom,
markup,
output: None,
});
}
"function_call_output" | "custom_tool_call_output" => {
fields(item, &["type", "id", "status", "call_id", "output"])?;
completed_item(item)?;
let id = valid_id(&item["call_id"])?;
let call = pending
.iter_mut()
.find(|call| call.id == id)
.ok_or("orphan_tool_result")?;
if call.custom != (kind == "custom_tool_call_output") || call.output.is_some() {
return Err("tool_result_identity_or_duplicate");
}
call.output = Some(content(item.get("output").ok_or("output_required")?, true)?);
if pending.iter().all(|call| call.output.is_some()) {
let call_text = pending
.iter()
.map(|call| call.markup.as_str())
.collect::<Vec<_>>()
.join("\n");
let output_text = pending
.iter()
.map(|call| {
format!(
"<tool_response>\n{}\n</tool_response>",
call.output.as_deref().unwrap_or_default()
)
})
.collect::<Vec<_>>()
.join("\n");
if let Some((Role::Assistant, text)) = owned.last_mut() {
text.truncate(text.trim_end().len());
if !text.is_empty() {
text.push_str("\n\n");
}
text.push_str(&call_text);
} else {
owned.push((Role::Assistant, call_text));
}
owned.push((Role::User, output_text));
pending.clear();
}
}
_ => return Err("unsupported_input_item"),
}
}
if !pending.is_empty() {
return Err("unresolved_tool_history");
}
Ok(())
}
fn completed_item(item: &Value) -> Result<(), &'static str> {
if let Some(id) = item.get("id") {
valid_id(id)?;
}
if item
.get("status")
.is_some_and(|status| status != "completed")
{
return Err("incomplete_history_item");
}
Ok(())
}