Add destructive confirmation and import guidance

This commit is contained in:
github-ops
2026-06-21 01:42:45 +00:00
parent ef2912855b
commit 5447e1bad0
29 changed files with 1099 additions and 24 deletions
+32 -6
View File
@@ -98,6 +98,12 @@ struct ResolvedToolCall {
tool: PublishedAgentTool,
}
struct ToolCallExecution {
tool: PublishedAgentTool,
arguments: Value,
confirmation_token: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
struct AgentRoutePath {
workspace_slug: String,
@@ -381,11 +387,12 @@ async fn mcp_post(
}
};
let arguments = if tool_call_params.arguments.is_null() {
let mut arguments = if tool_call_params.arguments.is_null() {
json!({})
} else {
tool_call_params.arguments
};
let confirmation_token = take_confirmation_token(&mut arguments);
match state
.catalog
@@ -402,6 +409,7 @@ async fn mcp_post(
&credential,
resolved,
arguments,
confirmation_token,
&transport_request_id,
)
.await
@@ -457,6 +465,7 @@ async fn handle_tool_call(
credential: &VerifiedMachineCredential,
resolved: ResolvedToolCall,
arguments: Value,
confirmation_token: Option<String>,
transport_request_id: &str,
) -> Response {
if !credential_allows_security_level(credential, resolved.tool.operation.security_level) {
@@ -483,8 +492,11 @@ async fn handle_tool_call(
session,
message,
response_mode,
resolved.tool,
arguments,
ToolCallExecution {
tool: resolved.tool,
arguments,
confirmation_token,
},
transport_request_id,
)
.await
@@ -583,12 +595,13 @@ async fn handle_base_tool_call(
session: &SessionState,
message: &Value,
response_mode: ResponseMode,
tool: PublishedAgentTool,
arguments: Value,
execution: ToolCallExecution,
transport_request_id: &str,
) -> Response {
let tool = execution.tool;
let arguments = execution.arguments;
let operation = runtime_operation(&tool);
let runtime_request_context = RuntimeRequestContext::from_request_id(transport_request_id)
let mut runtime_request_context = RuntimeRequestContext::from_request_id(transport_request_id)
.with_response_cache_scope(
tool.workspace_id.as_str().to_owned(),
tool.agent_id.as_str().to_owned(),
@@ -598,6 +611,9 @@ async fn handle_base_tool_call(
Some(tool.agent_id.clone()),
InvocationSource::AgentToolCall,
);
if let Some(token) = execution.confirmation_token {
runtime_request_context = runtime_request_context.with_confirmation_token(token);
}
let request_preview = build_request_preview(&state.runtime, &operation, &arguments);
let started_at = Instant::now();
let resolved_auth =
@@ -1151,6 +1167,16 @@ fn internal_jsonrpc_error(message: &Value, error: impl std::fmt::Display) -> Res
)
}
fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
let Value::Object(object) = arguments else {
return None;
};
object
.remove("_crank_confirmation_token")
.and_then(|value| value.as_str().map(str::to_owned))
.filter(|value| !value.trim().is_empty())
}
fn build_request_preview(
runtime: &RuntimeExecutor,
operation: &RuntimeOperation,
+57 -2
View File
@@ -1,12 +1,29 @@
use crank_core::{HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Target};
use crank_registry::PublishedAgentTool;
use serde_json::{Value, json};
pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
let safety = effective_safety_policy(tool);
let requires_confirmation = safety.class.requires_confirmation();
let input_schema = if requires_confirmation {
add_confirmation_token(schema_to_json_schema(&tool.operation.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,
&tool.tool_description,
schema_to_json_schema(&tool.operation.input_schema),
&description,
input_schema,
)]
}
@@ -19,6 +36,44 @@ pub fn tool_definition(name: &str, title: &str, description: &str, 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,
},
}
}
fn add_confirmation_token(mut schema: Value) -> Value {
let Some(object) = schema.as_object_mut() else {
return schema;
};
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 возвращает после первого вызова опасной операции."
}),
);
}
schema
}
pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
match schema.kind {
crank_schema::SchemaKind::Object => {
@@ -83,6 +83,9 @@ pub fn runtime_error_code(error: &RuntimeError) -> &'static str {
RuntimeError::ConcurrencyLimitExceeded { .. } => "runtime_overloaded",
RuntimeError::UnsupportedExecutionMode { .. } => "streaming_mode_error",
RuntimeError::InvalidPreparedRequest { .. } => "runtime_error",
RuntimeError::ConfirmationRequired { .. } => "confirmation_required",
RuntimeError::InvalidConfirmationToken { .. } => "invalid_confirmation_token",
RuntimeError::ConfirmationStoreUnavailable { .. } => "confirmation_unavailable",
RuntimeError::MissingAuthProfile { .. } => "auth_profile_not_found",
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
"secret_not_found"
@@ -128,6 +131,21 @@ fn safe_runtime_error_message(error: &RuntimeError) -> String {
RuntimeError::InvalidPreparedRequest { .. } => {
"Не удалось подготовить корректный API-запрос.".to_owned()
}
RuntimeError::ConfirmationRequired {
confirmation_token,
expires_in_ms,
..
} => format!(
"Операция требует подтверждения. Повторите вызов с _crank_confirmation_token=\"{}\" в течение {} секунд.",
confirmation_token,
expires_in_ms / 1000
),
RuntimeError::InvalidConfirmationToken { .. } => {
"Токен подтверждения недействителен, истек или уже был использован.".to_owned()
}
RuntimeError::ConfirmationStoreUnavailable { .. } => {
"Хранилище подтверждений временно недоступно.".to_owned()
}
RuntimeError::MissingAuthProfile { .. } => "Профиль авторизации не найден.".to_owned(),
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
"Секрет авторизации не найден.".to_owned()
@@ -150,6 +168,7 @@ fn is_recoverable_runtime_error(error: &RuntimeError) -> bool {
}) | RuntimeError::RestAdapter(RestAdapterError::Transport(_))
| RuntimeError::ConcurrencyLimitExceeded { .. }
| RuntimeError::SecretCrypto { .. }
| RuntimeError::ConfirmationRequired { .. }
)
}
@@ -172,6 +191,13 @@ fn suggested_action(error: &RuntimeError) -> Option<&'static str> {
| RuntimeError::InvalidPreparedRequest { .. } => {
Some("Проверьте параметры вызова инструмента.")
}
RuntimeError::ConfirmationRequired { .. } => {
Some("Повторите вызов с указанным токеном подтверждения.")
}
RuntimeError::InvalidConfirmationToken { .. } => {
Some("Запросите новый токен подтверждения.")
}
RuntimeError::ConfirmationStoreUnavailable { .. } => Some("Повторите запрос позже."),
RuntimeError::MissingAuthProfile { .. }
| RuntimeError::MissingSecret { .. }
| RuntimeError::MissingSecretVersion { .. }