feat: complete Epic 1 production foundation
This commit is contained in:
1 parent
767428436d
commit
182bde8ac0
298 files changed
+35711
-5291
No files matched your search
@@ -1,5 +1,7 @@
|
||||
use crank_adapter_rest::RestAdapterError;
|
||||
use crank_runtime::RuntimeError;
|
||||
use crank_core::{
|
||||
CorrelationContext, ExecutionFailure, ExecutionLocale, RequestId, Retryability, TraceContext,
|
||||
};
|
||||
use crank_runtime::{RuntimeError, normalize_runtime_error};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -7,6 +9,9 @@ use serde_json::{Value, json};
|
||||
pub struct ToolErrorContract {
|
||||
pub code: &'static str,
|
||||
pub error_code: &'static str,
|
||||
pub stage: &'static str,
|
||||
pub retryability: &'static str,
|
||||
pub outcome_certainty: &'static str,
|
||||
pub message: String,
|
||||
pub recoverable: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -21,32 +26,95 @@ pub fn tool_error_contract_from_runtime(
|
||||
error: &RuntimeError,
|
||||
request_id: &str,
|
||||
trace_id: &str,
|
||||
locale: ExecutionLocale,
|
||||
) -> ToolErrorContract {
|
||||
let error_code = runtime_error_code(error);
|
||||
let correlation = correlation_from_safe_ids(request_id, trace_id);
|
||||
project_failure(&normalize_runtime_error(error, &correlation), locale)
|
||||
}
|
||||
|
||||
pub fn tool_error_contract_from_failure(
|
||||
failure: &ExecutionFailure,
|
||||
locale: ExecutionLocale,
|
||||
) -> ToolErrorContract {
|
||||
project_failure(failure, locale)
|
||||
}
|
||||
|
||||
fn project_failure(failure: &ExecutionFailure, locale: ExecutionLocale) -> ToolErrorContract {
|
||||
let code = failure.error_code();
|
||||
let retryability = failure.retryability();
|
||||
let message = if let Some(challenge) = failure.confirmation() {
|
||||
confirmation_message(
|
||||
code.message(locale),
|
||||
challenge.token(),
|
||||
challenge.expires_in_ms(),
|
||||
locale,
|
||||
)
|
||||
} else {
|
||||
code.message(locale).to_owned()
|
||||
};
|
||||
ToolErrorContract {
|
||||
code: error_code,
|
||||
error_code,
|
||||
message: safe_runtime_error_message(error),
|
||||
recoverable: is_recoverable_runtime_error(error),
|
||||
suggested_action: suggested_action(error),
|
||||
upstream_status: upstream_status(error),
|
||||
request_id: request_id.to_owned(),
|
||||
trace_id: trace_id.to_owned(),
|
||||
code: code.as_str(),
|
||||
error_code: code.as_str(),
|
||||
stage: failure.stage().as_str(),
|
||||
retryability: retryability.as_str(),
|
||||
outcome_certainty: failure.outcome_certainty().as_str(),
|
||||
message,
|
||||
recoverable: matches!(
|
||||
retryability,
|
||||
Retryability::Safe | Retryability::AfterDelay | Retryability::RequiresConfirmation
|
||||
),
|
||||
suggested_action: suggested_action(retryability, locale),
|
||||
upstream_status: failure.upstream_status(),
|
||||
request_id: failure.correlation().request_id().to_string(),
|
||||
trace_id: failure.correlation().trace_id().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generic_tool_error_contract(
|
||||
error_code: &'static str,
|
||||
message: impl Into<String>,
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum McpControlError {
|
||||
CatalogRevisionChanged,
|
||||
ApprovalElicitationNotSupported,
|
||||
}
|
||||
|
||||
pub fn control_tool_error_contract(
|
||||
error: McpControlError,
|
||||
request_id: &str,
|
||||
trace_id: &str,
|
||||
recoverable: bool,
|
||||
suggested_action: Option<&'static str>,
|
||||
locale: ExecutionLocale,
|
||||
) -> ToolErrorContract {
|
||||
let (error_code, message, recoverable, suggested_action) = match (error, locale) {
|
||||
(McpControlError::CatalogRevisionChanged, ExecutionLocale::Ru) => (
|
||||
"agent_catalog_result_stale",
|
||||
"Версия каталога изменилась.",
|
||||
true,
|
||||
Some("Повторите search_tools и вызовите инструмент с новой версией каталога."),
|
||||
),
|
||||
(McpControlError::CatalogRevisionChanged, ExecutionLocale::En) => (
|
||||
"agent_catalog_result_stale",
|
||||
"The catalog revision changed.",
|
||||
true,
|
||||
Some("Run search_tools again and call the tool with the new catalog revision."),
|
||||
),
|
||||
(McpControlError::ApprovalElicitationNotSupported, ExecutionLocale::Ru) => (
|
||||
"approval_elicitation_not_supported",
|
||||
"Клиент не поддерживает MCP Elicitation, обязательный для этой операции.",
|
||||
false,
|
||||
Some("Используйте Custom MCP Approval или клиент с поддержкой elicitation."),
|
||||
),
|
||||
(McpControlError::ApprovalElicitationNotSupported, ExecutionLocale::En) => (
|
||||
"approval_elicitation_not_supported",
|
||||
"The client does not support MCP Elicitation required by this operation.",
|
||||
false,
|
||||
Some("Use Custom MCP Approval or an elicitation-capable client."),
|
||||
),
|
||||
};
|
||||
ToolErrorContract {
|
||||
code: error_code,
|
||||
error_code,
|
||||
message: message.into(),
|
||||
stage: "authorization",
|
||||
retryability: if recoverable { "after_delay" } else { "never" },
|
||||
outcome_certainty: "certain",
|
||||
message: message.to_owned(),
|
||||
recoverable,
|
||||
suggested_action,
|
||||
upstream_status: None,
|
||||
@@ -55,6 +123,19 @@ pub fn generic_tool_error_contract(
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execution_locale(message: &Value) -> ExecutionLocale {
|
||||
let locale = message
|
||||
.pointer("/params/_meta/locale")
|
||||
.or_else(|| message.pointer("/params/locale"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("en");
|
||||
if locale.eq_ignore_ascii_case("ru") || locale.to_ascii_lowercase().starts_with("ru-") {
|
||||
ExecutionLocale::Ru
|
||||
} else {
|
||||
ExecutionLocale::En
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tool_error_text(error: &ToolErrorContract) -> String {
|
||||
match error.suggested_action {
|
||||
Some(action) => format!("{} {}", error.message, action),
|
||||
@@ -65,9 +146,12 @@ pub fn tool_error_text(error: &ToolErrorContract) -> String {
|
||||
pub fn tool_error_value(error: &ToolErrorContract) -> Value {
|
||||
serde_json::to_value(error).unwrap_or_else(|_| {
|
||||
json!({
|
||||
"code": "runtime_error",
|
||||
"error_code": "runtime_error",
|
||||
"message": "Не удалось выполнить инструмент.",
|
||||
"code": "runtime_internal",
|
||||
"error_code": "runtime_internal",
|
||||
"stage": "runtime",
|
||||
"retryability": "never",
|
||||
"outcome_certainty": "certain",
|
||||
"message": "Внутренняя ошибка выполнения.",
|
||||
"recoverable": false,
|
||||
"request_id": error.request_id,
|
||||
"trace_id": error.trace_id
|
||||
@@ -75,178 +159,54 @@ pub fn tool_error_value(error: &ToolErrorContract) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn runtime_error_code(error: &RuntimeError) -> &'static str {
|
||||
match error {
|
||||
RuntimeError::Schema(_) => "schema_validation_error",
|
||||
RuntimeError::Mapping(_) => "mapping_error",
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus { status, .. }) => {
|
||||
upstream_status_code(*status)
|
||||
}
|
||||
RuntimeError::RestAdapter(RestAdapterError::Transport(_)) => "upstream_transport_error",
|
||||
RuntimeError::RestAdapter(_) => "adapter_execution_error",
|
||||
RuntimeError::ProtocolAdapter(_) => "adapter_execution_error",
|
||||
RuntimeError::UnsupportedProtocol { .. } => "unsupported_protocol",
|
||||
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::IdempotencyStoreUnavailable { .. } => "idempotency_unavailable",
|
||||
RuntimeError::IdempotencyInProgress { .. } => "idempotency_in_progress",
|
||||
RuntimeError::IdempotencyConflict { .. } => "idempotency_conflict",
|
||||
RuntimeError::IdempotencyOutcomeUnknown { .. } => "idempotency_outcome_unknown",
|
||||
RuntimeError::MissingAuthProfile { .. } => "auth_profile_not_found",
|
||||
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
|
||||
"secret_not_found"
|
||||
}
|
||||
RuntimeError::InvalidAuthSecretValue { .. } => "secret_value_error",
|
||||
RuntimeError::SecretCrypto { .. } => "secret_crypto_error",
|
||||
}
|
||||
fn correlation_from_safe_ids(request_id: &str, trace_id: &str) -> CorrelationContext {
|
||||
let request_id = RequestId::parse(request_id).unwrap_or_else(|_| RequestId::generate());
|
||||
let trace_context = TraceContext::from_span_parts(trace_id, "0000000000000001", false)
|
||||
.unwrap_or_else(|_| TraceContext::generate());
|
||||
CorrelationContext::new(request_id, trace_context)
|
||||
}
|
||||
|
||||
fn upstream_status_code(status: u16) -> &'static str {
|
||||
match status {
|
||||
401 | 403 => "upstream_auth_error",
|
||||
404 => "upstream_not_found",
|
||||
408 | 429 => "upstream_rate_limited",
|
||||
500..=599 => "upstream_server_error",
|
||||
_ => "upstream_status_error",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn safe_runtime_error_message(error: &RuntimeError) -> String {
|
||||
match error {
|
||||
RuntimeError::Schema(_) => "Входные параметры не прошли проверку схемы.".to_owned(),
|
||||
RuntimeError::Mapping(_) => {
|
||||
"Не удалось сопоставить параметры инструмента с API-запросом.".to_owned()
|
||||
}
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus { status, .. }) => {
|
||||
format!("Внешний API вернул HTTP {}.", status)
|
||||
}
|
||||
RuntimeError::RestAdapter(RestAdapterError::Transport(_)) => {
|
||||
"Не удалось подключиться к внешнему API.".to_owned()
|
||||
}
|
||||
RuntimeError::RestAdapter(_) => "Не удалось выполнить запрос к внешнему API.".to_owned(),
|
||||
RuntimeError::ProtocolAdapter(_) => "Не удалось выполнить протокольный адаптер.".to_owned(),
|
||||
RuntimeError::UnsupportedProtocol { .. } => {
|
||||
"Протокол операции не поддерживается.".to_owned()
|
||||
}
|
||||
RuntimeError::ConcurrencyLimitExceeded { .. } => {
|
||||
"Сервис временно перегружен и не может выполнить инструмент.".to_owned()
|
||||
}
|
||||
RuntimeError::UnsupportedExecutionMode { .. } => {
|
||||
"Режим выполнения операции не поддерживается.".to_owned()
|
||||
}
|
||||
RuntimeError::InvalidPreparedRequest { .. } => {
|
||||
"Не удалось подготовить корректный API-запрос.".to_owned()
|
||||
}
|
||||
RuntimeError::ConfirmationRequired {
|
||||
confirmation_token,
|
||||
expires_in_ms,
|
||||
..
|
||||
} => format!(
|
||||
"Операция требует подтверждения. Повторите вызов с _crank_confirmation_token=\"{}\" в течение {} секунд.",
|
||||
confirmation_token,
|
||||
fn confirmation_message(
|
||||
base_message: &str,
|
||||
token: &str,
|
||||
expires_in_ms: u64,
|
||||
locale: ExecutionLocale,
|
||||
) -> String {
|
||||
match locale {
|
||||
ExecutionLocale::Ru => format!(
|
||||
"{base_message} Повторите вызов с _crank_confirmation_token=\"{token}\" в течение {} секунд.",
|
||||
expires_in_ms / 1000
|
||||
),
|
||||
ExecutionLocale::En => format!(
|
||||
"{base_message} Repeat the call with _crank_confirmation_token=\"{token}\" within {} seconds.",
|
||||
expires_in_ms / 1000
|
||||
),
|
||||
RuntimeError::InvalidConfirmationToken { .. } => {
|
||||
"Токен подтверждения недействителен, истек или уже был использован.".to_owned()
|
||||
}
|
||||
RuntimeError::ConfirmationStoreUnavailable { .. } => {
|
||||
"Хранилище подтверждений временно недоступно.".to_owned()
|
||||
}
|
||||
RuntimeError::IdempotencyStoreUnavailable { .. } => {
|
||||
"Хранилище идемпотентности временно недоступно.".to_owned()
|
||||
}
|
||||
RuntimeError::IdempotencyInProgress { .. } => {
|
||||
"Операция с этим ключом идемпотентности уже выполняется.".to_owned()
|
||||
}
|
||||
RuntimeError::IdempotencyConflict { .. } => {
|
||||
"Ключ идемпотентности уже использован с другими параметрами.".to_owned()
|
||||
}
|
||||
RuntimeError::IdempotencyOutcomeUnknown { .. } => {
|
||||
"Результат предыдущего выполнения неизвестен; автоматический повтор заблокирован."
|
||||
.to_owned()
|
||||
}
|
||||
RuntimeError::MissingAuthProfile { .. } => "Профиль авторизации не найден.".to_owned(),
|
||||
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
|
||||
"Секрет авторизации не найден.".to_owned()
|
||||
}
|
||||
RuntimeError::InvalidAuthSecretValue { .. } => {
|
||||
"Секрет авторизации имеет неподходящий формат.".to_owned()
|
||||
}
|
||||
RuntimeError::SecretCrypto { .. } => {
|
||||
"Не удалось расшифровать секрет авторизации.".to_owned()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_recoverable_runtime_error(error: &RuntimeError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus {
|
||||
status: 408 | 429 | 500..=599,
|
||||
..
|
||||
}) | RuntimeError::RestAdapter(RestAdapterError::Transport(_))
|
||||
| RuntimeError::ConcurrencyLimitExceeded { .. }
|
||||
| RuntimeError::SecretCrypto { .. }
|
||||
| RuntimeError::ConfirmationRequired { .. }
|
||||
| RuntimeError::IdempotencyStoreUnavailable { .. }
|
||||
| RuntimeError::IdempotencyInProgress { .. }
|
||||
)
|
||||
}
|
||||
|
||||
fn suggested_action(error: &RuntimeError) -> Option<&'static str> {
|
||||
match error {
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus {
|
||||
status: 401 | 403, ..
|
||||
}) => Some("Проверьте настройки авторизации внешнего API."),
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus { status: 404, .. }) => {
|
||||
Some("Проверьте путь endpoint-а и параметры запроса.")
|
||||
const fn suggested_action(
|
||||
retryability: Retryability,
|
||||
locale: ExecutionLocale,
|
||||
) -> Option<&'static str> {
|
||||
match (retryability, locale) {
|
||||
(Retryability::AfterDelay | Retryability::Safe, ExecutionLocale::Ru) => {
|
||||
Some("Повторите запрос позже.")
|
||||
}
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus {
|
||||
status: 408 | 429 | 500..=599,
|
||||
..
|
||||
})
|
||||
| RuntimeError::RestAdapter(RestAdapterError::Transport(_))
|
||||
| RuntimeError::ConcurrencyLimitExceeded { .. } => Some("Повторите запрос позже."),
|
||||
RuntimeError::Schema(_)
|
||||
| RuntimeError::Mapping(_)
|
||||
| RuntimeError::InvalidPreparedRequest { .. } => {
|
||||
Some("Проверьте параметры вызова инструмента.")
|
||||
(Retryability::AfterDelay | Retryability::Safe, ExecutionLocale::En) => {
|
||||
Some("Retry the request later.")
|
||||
}
|
||||
RuntimeError::ConfirmationRequired { .. } => {
|
||||
Some("Повторите вызов с указанным токеном подтверждения.")
|
||||
}
|
||||
RuntimeError::InvalidConfirmationToken { .. } => {
|
||||
Some("Запросите новый токен подтверждения.")
|
||||
}
|
||||
RuntimeError::ConfirmationStoreUnavailable { .. } => Some("Повторите запрос позже."),
|
||||
RuntimeError::IdempotencyStoreUnavailable { .. }
|
||||
| RuntimeError::IdempotencyInProgress { .. } => Some("Повторите запрос позже."),
|
||||
RuntimeError::IdempotencyConflict { .. } => {
|
||||
Some("Используйте новый ключ идемпотентности для изменённого запроса.")
|
||||
}
|
||||
RuntimeError::IdempotencyOutcomeUnknown { .. } => {
|
||||
(Retryability::ManualReconcile, ExecutionLocale::Ru) => {
|
||||
Some("Проверьте результат во внешней системе перед ручным повтором.")
|
||||
}
|
||||
RuntimeError::MissingAuthProfile { .. }
|
||||
| RuntimeError::MissingSecret { .. }
|
||||
| RuntimeError::MissingSecretVersion { .. }
|
||||
| RuntimeError::InvalidAuthSecretValue { .. }
|
||||
| RuntimeError::SecretCrypto { .. } => {
|
||||
Some("Проверьте настройки авторизации и секретов в Crank.")
|
||||
(Retryability::ManualReconcile, ExecutionLocale::En) => {
|
||||
Some("Check the result in the external system before retrying manually.")
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn upstream_status(error: &RuntimeError) -> Option<u16> {
|
||||
match error {
|
||||
RuntimeError::RestAdapter(RestAdapterError::UnexpectedStatus { status, .. }) => {
|
||||
Some(*status)
|
||||
(Retryability::RequiresConfirmation, ExecutionLocale::Ru) => {
|
||||
Some("Повторите вызов с указанным токеном подтверждения.")
|
||||
}
|
||||
_ => None,
|
||||
(Retryability::RequiresConfirmation, ExecutionLocale::En) => {
|
||||
Some("Repeat the call with the provided confirmation token.")
|
||||
}
|
||||
(Retryability::Never, _) => None,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user