329 lines
12 KiB
Rust
329 lines
12 KiB
Rust
use crank_core::{
|
|
HttpMethod, OperationSafetyClass, OperationSafetyPolicy, SearchableTool, Target,
|
|
ToolAccessMode, ToolCatalogAnalysis, ToolCatalogAnalysisError, ToolQualityCatalogTool,
|
|
ToolSelectionPolicy, analyze_tool_catalog,
|
|
};
|
|
use crank_registry::{PublishedAgentCatalog, PublishedAgentTool};
|
|
use serde_json::{Value, json};
|
|
|
|
pub const SEARCH_TOOLS_NAME: &str = "search_tools";
|
|
pub const CALL_TOOL_NAME: &str = "call_tool";
|
|
|
|
pub fn catalog_tool_definitions(catalog: &PublishedAgentCatalog) -> Vec<Value> {
|
|
match catalog.tool_selection_policy.mode {
|
|
ToolAccessMode::Direct => catalog.tools.iter().flat_map(tool_definitions).collect(),
|
|
ToolAccessMode::Search => search_mode_tool_definitions(&catalog.tool_selection_policy),
|
|
}
|
|
}
|
|
|
|
pub fn searchable_tools(catalog: &PublishedAgentCatalog) -> Vec<SearchableTool> {
|
|
catalog
|
|
.tools
|
|
.iter()
|
|
.map(|tool| {
|
|
let groups = catalog
|
|
.tool_selection_policy
|
|
.groups
|
|
.iter()
|
|
.filter(|group| group.tool_names.iter().any(|name| name == &tool.tool_name))
|
|
.collect::<Vec<_>>();
|
|
SearchableTool {
|
|
name: tool.tool_name.clone(),
|
|
title: tool.tool_title.clone(),
|
|
description: tool.tool_description.clone(),
|
|
input_schema: tool_definitions(tool)
|
|
.into_iter()
|
|
.next()
|
|
.and_then(|definition| definition.get("inputSchema").cloned())
|
|
.unwrap_or_else(|| json!({"type": "object"})),
|
|
group_ids: groups.iter().map(|group| group.id.clone()).collect(),
|
|
group_context: groups
|
|
.iter()
|
|
.map(|group| format!("{} {}", group.name, group.description))
|
|
.collect::<Vec<_>>()
|
|
.join(" "),
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn search_mode_tool_definitions(policy: &ToolSelectionPolicy) -> Vec<Value> {
|
|
let group_catalog = if policy.groups.is_empty() {
|
|
"Разделы каталога не заданы; выполняйте поиск по всему каталогу.".to_owned()
|
|
} else {
|
|
policy
|
|
.groups
|
|
.iter()
|
|
.map(|group| format!("{} — {}: {}", group.id, group.name, group.description))
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
};
|
|
|
|
vec![
|
|
tool_definition(
|
|
SEARCH_TOOLS_NAME,
|
|
"Подобрать инструменты",
|
|
&format!(
|
|
"Находит подходящие инструменты агента и возвращает их полные входные схемы. Доступные разделы:\n{group_catalog}"
|
|
),
|
|
json!({
|
|
"type": "object",
|
|
"properties": {
|
|
"query": {
|
|
"type": "string",
|
|
"description": "Краткое описание требуемого действия"
|
|
},
|
|
"group_ids": {
|
|
"type": "array",
|
|
"items": {"type": "string"},
|
|
"description": "Необязательный список разделов каталога"
|
|
},
|
|
"max_results": {
|
|
"type": "integer",
|
|
"minimum": 1,
|
|
"maximum": 20,
|
|
"default": policy.search.max_results
|
|
}
|
|
},
|
|
"required": ["query"]
|
|
}),
|
|
),
|
|
tool_definition(
|
|
CALL_TOOL_NAME,
|
|
"Вызвать найденный инструмент",
|
|
"Вызывает инструмент, ранее найденный через search_tools. Передайте имя, аргументы по полученной схеме и версию каталога из результата поиска.",
|
|
json!({
|
|
"type": "object",
|
|
"properties": {
|
|
"name": {"type": "string"},
|
|
"arguments": {"type": "object"},
|
|
"catalog_revision": {"type": "string"}
|
|
},
|
|
"required": ["name", "arguments", "catalog_revision"]
|
|
}),
|
|
),
|
|
]
|
|
}
|
|
|
|
pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
|
|
let safety = effective_safety_policy(tool);
|
|
let requires_confirmation = safety.class.requires_confirmation();
|
|
let input_schema = operation_input_json_schema(tool);
|
|
let input_schema = if requires_confirmation {
|
|
add_confirmation_token(input_schema)
|
|
} else {
|
|
schema_to_json_schema(&tool.operation.input_schema)
|
|
};
|
|
let description = if requires_confirmation {
|
|
format!(
|
|
"{}\n\nЭта операция выполняется в два шага: первый вызов возвращает токен подтверждения без обращения к внешнему API, второй вызов должен повторить те же аргументы и добавить _crank_confirmation_token.",
|
|
tool.tool_description
|
|
)
|
|
} else {
|
|
tool.tool_description.clone()
|
|
};
|
|
|
|
vec![tool_definition(
|
|
&tool.tool_name,
|
|
&tool.tool_title,
|
|
&description,
|
|
input_schema,
|
|
)]
|
|
}
|
|
|
|
fn operation_input_json_schema(tool: &PublishedAgentTool) -> Value {
|
|
let mut projected = schema_to_json_schema(&tool.operation.input_schema);
|
|
if matches!(&tool.operation.target, Target::Rest(target) if target.request_contract.is_some()) {
|
|
close_request_objects(&mut projected);
|
|
}
|
|
projected
|
|
}
|
|
|
|
fn close_request_objects(schema: &mut Value) {
|
|
if let Some(variants) = schema.get_mut("anyOf").and_then(Value::as_array_mut) {
|
|
for variant in variants {
|
|
close_request_objects(variant);
|
|
}
|
|
return;
|
|
}
|
|
if schema.get("type").and_then(Value::as_str) == Some("object") {
|
|
schema["additionalProperties"] = Value::Bool(false);
|
|
}
|
|
}
|
|
|
|
pub fn analyze_published_tool_catalog(
|
|
tools: &[PublishedAgentTool],
|
|
) -> Result<ToolCatalogAnalysis, ToolCatalogAnalysisError> {
|
|
let mut quality_tools = Vec::new();
|
|
let mut definitions = Vec::new();
|
|
|
|
for tool in tools {
|
|
for definition in tool_definitions(tool) {
|
|
quality_tools.push(ToolQualityCatalogTool {
|
|
name: definition_string(&definition, "name")?,
|
|
display_name: definition_string(&definition, "title")?,
|
|
description: definition_string(&definition, "description")?,
|
|
});
|
|
definitions.push(definition);
|
|
}
|
|
}
|
|
|
|
analyze_tool_catalog(&quality_tools, &definitions)
|
|
}
|
|
|
|
fn definition_string(
|
|
definition: &Value,
|
|
field: &'static str,
|
|
) -> Result<String, ToolCatalogAnalysisError> {
|
|
definition
|
|
.get(field)
|
|
.and_then(Value::as_str)
|
|
.map(ToOwned::to_owned)
|
|
.ok_or(ToolCatalogAnalysisError::DefinitionFieldMissing(field))
|
|
}
|
|
|
|
pub fn tool_definition(name: &str, title: &str, description: &str, input_schema: Value) -> Value {
|
|
json!({
|
|
"name": name,
|
|
"title": title,
|
|
"description": description,
|
|
"inputSchema": input_schema
|
|
})
|
|
}
|
|
|
|
fn effective_safety_policy(tool: &PublishedAgentTool) -> OperationSafetyPolicy {
|
|
tool.operation
|
|
.execution_config
|
|
.safety
|
|
.clone()
|
|
.unwrap_or_else(|| OperationSafetyPolicy {
|
|
class: infer_safety_class(tool),
|
|
confirmation: None,
|
|
})
|
|
}
|
|
|
|
fn infer_safety_class(tool: &PublishedAgentTool) -> OperationSafetyClass {
|
|
match &tool.operation.target {
|
|
Target::Rest(target) => match target.method {
|
|
HttpMethod::Get => OperationSafetyClass::Read,
|
|
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
|
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
|
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
|
},
|
|
}
|
|
}
|
|
|
|
fn add_confirmation_token(mut schema: Value) -> Value {
|
|
if let Some(variants) = schema.get_mut("anyOf").and_then(Value::as_array_mut) {
|
|
for variant in variants {
|
|
add_confirmation_token_to_object(variant);
|
|
}
|
|
return schema;
|
|
}
|
|
add_confirmation_token_to_object(&mut schema);
|
|
schema
|
|
}
|
|
|
|
fn add_confirmation_token_to_object(schema: &mut Value) {
|
|
let Some(object) = schema.as_object_mut() else {
|
|
return;
|
|
};
|
|
let properties = object.entry("properties").or_insert_with(|| json!({}));
|
|
if let Some(properties) = properties.as_object_mut() {
|
|
properties.insert(
|
|
"_crank_confirmation_token".to_owned(),
|
|
json!({
|
|
"type": "string",
|
|
"description": "Одноразовый токен подтверждения, который Crank возвращает после первого вызова опасной операции."
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|
|
pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
|
|
let mut projected = match schema.kind {
|
|
crank_schema::SchemaKind::Object => {
|
|
let mut properties = serde_json::Map::new();
|
|
let mut required = Vec::new();
|
|
|
|
for (field_name, field_schema) in &schema.fields {
|
|
properties.insert(field_name.clone(), schema_to_json_schema(field_schema));
|
|
|
|
if field_schema.required {
|
|
required.push(Value::String(field_name.clone()));
|
|
}
|
|
}
|
|
|
|
json!({
|
|
"type": "object",
|
|
"properties": properties,
|
|
"required": required
|
|
})
|
|
}
|
|
crank_schema::SchemaKind::Array => json!({
|
|
"type": "array",
|
|
"items": schema
|
|
.items
|
|
.as_deref()
|
|
.map(schema_to_json_schema)
|
|
.unwrap_or_else(|| json!({}))
|
|
}),
|
|
crank_schema::SchemaKind::String => json!({ "type": "string" }),
|
|
crank_schema::SchemaKind::Integer => json!({ "type": "integer" }),
|
|
crank_schema::SchemaKind::Number => json!({ "type": "number" }),
|
|
crank_schema::SchemaKind::Boolean => json!({ "type": "boolean" }),
|
|
crank_schema::SchemaKind::Enum => json!({
|
|
"type": "string",
|
|
"enum": schema.enum_values.clone()
|
|
}),
|
|
crank_schema::SchemaKind::Null => json!({ "type": "null" }),
|
|
crank_schema::SchemaKind::Oneof => json!({
|
|
"anyOf": schema.variants.iter().map(schema_to_json_schema).collect::<Vec<_>>()
|
|
}),
|
|
};
|
|
if schema.kind == crank_schema::SchemaKind::Object
|
|
&& matches!(
|
|
schema.format.as_deref(),
|
|
Some("binary" | crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT)
|
|
)
|
|
{
|
|
projected["additionalProperties"] = Value::Bool(false);
|
|
}
|
|
if let Some(format) = &schema.format
|
|
&& format != crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT
|
|
{
|
|
projected["format"] = Value::String(format.clone());
|
|
}
|
|
if schema.nullable {
|
|
if schema.kind == crank_schema::SchemaKind::Enum
|
|
&& let Some(values) = projected.get_mut("enum").and_then(Value::as_array_mut)
|
|
&& !values.iter().any(Value::is_null)
|
|
{
|
|
values.push(Value::Null);
|
|
}
|
|
if let Some(kind) = projected.get_mut("type") {
|
|
match kind {
|
|
Value::String(name) => {
|
|
*kind = Value::Array(vec![
|
|
Value::String(name.clone()),
|
|
Value::String("null".to_owned()),
|
|
]);
|
|
}
|
|
Value::Array(kinds) if !kinds.iter().any(|kind| kind.as_str() == Some("null")) => {
|
|
kinds.push(Value::String("null".to_owned()));
|
|
}
|
|
_ => {}
|
|
}
|
|
} else if let Some(variants) = projected.get_mut("anyOf").and_then(Value::as_array_mut) {
|
|
variants.push(json!({"type": "null"}));
|
|
}
|
|
}
|
|
if let Some(default) = &schema.default_value {
|
|
projected["default"] = default.clone();
|
|
}
|
|
if let Some(description) = &schema.description {
|
|
projected["description"] = Value::String(description.clone());
|
|
}
|
|
projected
|
|
}
|