CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 12m45s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Community Release / release (push) Successful in 40m35s
Tool Draft фиксирует synchronous/background/adaptive, deadline и fallback; runtime применяет единый снимок политики (concurrency, очередь, approval, deadline) до внешнего действия. Насыщение отклоняется typed overload с retry guidance, mandatory safety store fail closed, background/adaptive используют опубликованный synchronous/unsupported fallback. Refs: #29
527 lines
17 KiB
Rust
527 lines
17 KiB
Rust
use std::collections::BTreeMap;
|
|
|
|
use crank_core::{
|
|
AgentId, AgentOperationBinding, InvocationLevel, InvocationSource, InvocationStatus,
|
|
MembershipRole, OperationId, OperationSecurityLevel, PlatformApiKeyKind, PlatformApiKeyScope,
|
|
PlatformApiKeyStatus, Protocol, Target, WizardState, WorkspaceId,
|
|
};
|
|
use crank_mapping::{JsonPathRoot, infer_mapping_from_samples};
|
|
use crank_mapping::{MappingRule, MappingSet};
|
|
use crank_registry::{ListInvocationLogsQuery, OperationSummary, RegistryError, SampleKind};
|
|
use crank_schema::Schema;
|
|
use serde_json::{Value, json};
|
|
|
|
use crate::{
|
|
error::ApiError,
|
|
service::{
|
|
AdminService, AgentBindingPayload, AgentPayload, AgentSummaryView, InvocationRecordRequest,
|
|
OperationPayload, PlatformApiKeyPayload,
|
|
},
|
|
};
|
|
|
|
impl AdminService {
|
|
pub(super) async fn seed_default_workspace_demo(
|
|
&self,
|
|
owner_user_id: &crank_core::UserId,
|
|
workspace_id: &WorkspaceId,
|
|
) -> Result<(), ApiError> {
|
|
self.registry
|
|
.ensure_membership(workspace_id, owner_user_id, MembershipRole::Owner)
|
|
.await?;
|
|
|
|
self.cleanup_legacy_demo_assets(workspace_id).await?;
|
|
|
|
let rest_operation = self
|
|
.ensure_demo_operation(workspace_id, demo_rest_operation_payload())
|
|
.await?;
|
|
self.ensure_operation_published(workspace_id, &rest_operation)
|
|
.await?;
|
|
self.ensure_demo_json_samples(
|
|
workspace_id,
|
|
&rest_operation.id,
|
|
&demo_rest_input_sample(),
|
|
&demo_rest_output_sample(),
|
|
)
|
|
.await?;
|
|
|
|
let currency_agent = self
|
|
.ensure_demo_agent(workspace_id, demo_currency_agent_payload())
|
|
.await?;
|
|
self.ensure_demo_agent_bindings(
|
|
workspace_id,
|
|
&AgentId::new(currency_agent.id.clone()),
|
|
vec![AgentBindingPayload {
|
|
operation_id: rest_operation.id.as_str().to_owned(),
|
|
operation_version: rest_operation.current_draft_version,
|
|
tool_name: "frankfurter_latest_rate".to_owned(),
|
|
tool_title: "Последний курс валюты".to_owned(),
|
|
tool_description_override: Some(
|
|
"Возвращает последний доступный курс одной валюты к другой через Frankfurter."
|
|
.to_owned(),
|
|
),
|
|
enabled: true,
|
|
}],
|
|
true,
|
|
)
|
|
.await?;
|
|
|
|
self.ensure_demo_platform_api_key(
|
|
workspace_id,
|
|
&AgentId::new(currency_agent.id.clone()),
|
|
"Frankfurter Demo Key",
|
|
vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
|
false,
|
|
)
|
|
.await?;
|
|
|
|
self.seed_demo_invocation_logs(
|
|
workspace_id,
|
|
&AgentId::new(currency_agent.id),
|
|
&rest_operation.id,
|
|
)
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn cleanup_legacy_demo_assets(&self, workspace_id: &WorkspaceId) -> Result<(), ApiError> {
|
|
for slug in ["revops-copilot", "support-triage"] {
|
|
if let Some(agent) = self.find_agent_by_slug(workspace_id, slug).await? {
|
|
self.delete_agent(
|
|
workspace_id,
|
|
&AgentId::new(agent.id.as_str().to_owned()),
|
|
None,
|
|
)
|
|
.await?;
|
|
}
|
|
}
|
|
|
|
let operations = self.registry.list_operations(workspace_id).await?;
|
|
for operation in operations {
|
|
if operation.name.starts_with("internal_health_smoke_")
|
|
|| operation
|
|
.name
|
|
.starts_with("weather_current_open_meteo_smoke_")
|
|
{
|
|
self.delete_legacy_demo_operation_if_safe(workspace_id, &operation.id)
|
|
.await?;
|
|
}
|
|
}
|
|
|
|
for name in [
|
|
"crm_create_lead",
|
|
"marketing_archive_contact",
|
|
"weather_current_open_meteo",
|
|
] {
|
|
if let Some(operation) = self.find_operation_by_name(workspace_id, name).await? {
|
|
self.delete_legacy_demo_operation_if_safe(workspace_id, &operation.id)
|
|
.await?;
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn delete_legacy_demo_operation_if_safe(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
operation_id: &OperationId,
|
|
) -> Result<(), ApiError> {
|
|
match self
|
|
.registry
|
|
.delete_operation(workspace_id, operation_id)
|
|
.await
|
|
{
|
|
Ok(()) => Ok(()),
|
|
Err(
|
|
RegistryError::OperationHasPublishedAgentBindings { .. }
|
|
| RegistryError::OperationDeleteForbidden { .. },
|
|
) => {
|
|
tracing::warn!(
|
|
name: "admin.demo_operation.cleanup_skipped",
|
|
operation_id = %operation_id.as_str(),
|
|
"legacy demo operation is still bound to a published agent; leaving it in place"
|
|
);
|
|
Ok(())
|
|
}
|
|
Err(error) => Err(ApiError::from(error)),
|
|
}
|
|
}
|
|
|
|
async fn ensure_demo_platform_api_key(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
agent_id: &AgentId,
|
|
name: &str,
|
|
scopes: Vec<PlatformApiKeyScope>,
|
|
revoke: bool,
|
|
) -> Result<(), ApiError> {
|
|
let existing = self
|
|
.registry
|
|
.list_platform_api_keys(workspace_id)
|
|
.await?
|
|
.into_iter()
|
|
.find(|record| record.api_key.name == name);
|
|
let key = match existing {
|
|
Some(record) => record,
|
|
None => {
|
|
self.create_agent_platform_api_key(
|
|
workspace_id,
|
|
agent_id,
|
|
PlatformApiKeyPayload {
|
|
name: name.to_owned(),
|
|
key_kind: PlatformApiKeyKind::McpClient,
|
|
scopes,
|
|
expires_at: None,
|
|
allowed_origins: Vec::new(),
|
|
},
|
|
None,
|
|
)
|
|
.await?
|
|
.api_key
|
|
}
|
|
};
|
|
|
|
if revoke && key.api_key.status != PlatformApiKeyStatus::Revoked {
|
|
self.revoke_agent_platform_api_key(workspace_id, agent_id, &key.api_key.id, None)
|
|
.await?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn ensure_demo_operation(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
payload: OperationPayload,
|
|
) -> Result<OperationSummary, ApiError> {
|
|
if let Some(existing) = self
|
|
.find_operation_by_name(workspace_id, &payload.name)
|
|
.await?
|
|
{
|
|
return Ok(existing);
|
|
}
|
|
|
|
let operation_name = payload.name.clone();
|
|
self.create_operation(workspace_id, payload).await?;
|
|
self.find_operation_by_name(workspace_id, &operation_name)
|
|
.await?
|
|
.ok_or_else(|| ApiError::internal("demo operation was created but not found"))
|
|
}
|
|
|
|
async fn ensure_operation_published(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
summary: &OperationSummary,
|
|
) -> Result<(), ApiError> {
|
|
if summary.latest_published_version.is_some() {
|
|
return Ok(());
|
|
}
|
|
|
|
self.publish_operation(
|
|
workspace_id,
|
|
&summary.id,
|
|
summary.current_draft_version,
|
|
&crank_registry::OperationStateExpectation {
|
|
current_draft_version: summary.current_draft_version,
|
|
status: summary.status,
|
|
latest_published_version: summary.latest_published_version,
|
|
},
|
|
)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
async fn ensure_demo_json_samples(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
operation_id: &OperationId,
|
|
input: &Value,
|
|
output: &Value,
|
|
) -> Result<(), ApiError> {
|
|
let summary = self.get_operation(workspace_id, operation_id).await?;
|
|
let samples = self
|
|
.registry
|
|
.list_sample_metadata(operation_id, summary.current_draft_version)
|
|
.await?;
|
|
|
|
if !samples
|
|
.iter()
|
|
.any(|sample| sample.sample_kind == SampleKind::InputJson)
|
|
{
|
|
self.save_json_sample(workspace_id, operation_id, SampleKind::InputJson, input)
|
|
.await?;
|
|
}
|
|
|
|
if !samples
|
|
.iter()
|
|
.any(|sample| sample.sample_kind == SampleKind::OutputJson)
|
|
{
|
|
self.save_json_sample(workspace_id, operation_id, SampleKind::OutputJson, output)
|
|
.await?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn ensure_demo_agent(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
payload: AgentPayload,
|
|
) -> Result<AgentSummaryView, ApiError> {
|
|
let summary =
|
|
if let Some(existing) = self.find_agent_by_slug(workspace_id, &payload.slug).await? {
|
|
existing
|
|
} else {
|
|
self.create_agent(workspace_id, payload.clone()).await?;
|
|
self.find_agent_by_slug(workspace_id, &payload.slug)
|
|
.await?
|
|
.ok_or_else(|| ApiError::internal("demo agent was created but not found"))?
|
|
};
|
|
|
|
self.get_agent(workspace_id, &summary.id).await
|
|
}
|
|
|
|
async fn ensure_demo_agent_bindings(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
agent_id: &AgentId,
|
|
bindings: Vec<AgentBindingPayload>,
|
|
publish: bool,
|
|
) -> Result<(), ApiError> {
|
|
let summary = self.get_agent(workspace_id, agent_id).await?;
|
|
let current = self
|
|
.get_agent_version(workspace_id, agent_id, summary.current_draft_version)
|
|
.await?;
|
|
if !demo_agent_bindings_match(¤t.bindings, &bindings) {
|
|
self.save_agent_bindings(workspace_id, agent_id, bindings.into(), None)
|
|
.await?;
|
|
}
|
|
if publish && summary.latest_published_version.is_none() {
|
|
self.publish_agent(workspace_id, agent_id, summary.current_draft_version, None)
|
|
.await?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
async fn seed_demo_invocation_logs(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
currency_agent_id: &AgentId,
|
|
rest_operation_id: &OperationId,
|
|
) -> Result<(), ApiError> {
|
|
if !self
|
|
.registry
|
|
.list_invocation_logs(ListInvocationLogsQuery {
|
|
workspace_id,
|
|
level: None,
|
|
status: None,
|
|
outcome_group: None,
|
|
search_text: None,
|
|
source: None,
|
|
operation_id: None,
|
|
agent_id: None,
|
|
created_after: None,
|
|
created_before: None,
|
|
cursor_created_at: None,
|
|
cursor_id: None,
|
|
limit: 1,
|
|
})
|
|
.await?
|
|
.is_empty()
|
|
{
|
|
return Ok(());
|
|
}
|
|
|
|
let rest_operation = self
|
|
.get_operation_version(
|
|
workspace_id,
|
|
rest_operation_id,
|
|
self.get_operation(workspace_id, rest_operation_id)
|
|
.await?
|
|
.current_draft_version,
|
|
)
|
|
.await?;
|
|
let correlation = crank_core::CorrelationContext::generate();
|
|
self.record_invocation(InvocationRecordRequest {
|
|
workspace_id,
|
|
agent_id: Some(currency_agent_id),
|
|
operation: &rest_operation.snapshot,
|
|
request_id: Some(correlation.request_id().as_str()),
|
|
trace_id: Some(correlation.trace_id().as_str()),
|
|
source: InvocationSource::AgentToolCall,
|
|
level: InvocationLevel::Info,
|
|
status: InvocationStatus::Ok,
|
|
message: "Frankfurter returned latest exchange rate".to_owned(),
|
|
status_code: Some(200),
|
|
error_kind: None,
|
|
execution_stage: Some(crank_core::ExecutionStage::Runtime),
|
|
execution_error_code: None,
|
|
retryability: Some(crank_core::Retryability::Never),
|
|
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
|
|
duration_ms: 124,
|
|
request_preview: json!({
|
|
"path": {},
|
|
"query": demo_rest_request_sample(),
|
|
"headers": { "Accept": "application/json" },
|
|
"body": null
|
|
}),
|
|
response_preview: demo_rest_response_sample(),
|
|
})
|
|
.await;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn demo_agent_bindings_match(
|
|
existing: &[AgentOperationBinding],
|
|
desired: &[AgentBindingPayload],
|
|
) -> bool {
|
|
if existing.len() != desired.len() {
|
|
return false;
|
|
}
|
|
let mut desired = desired.iter().collect::<Vec<_>>();
|
|
desired.sort_by(|left, right| left.tool_name.cmp(&right.tool_name));
|
|
existing.iter().zip(desired).all(|(existing, desired)| {
|
|
existing.operation_id.as_str() == desired.operation_id
|
|
&& existing.operation_version == desired.operation_version
|
|
&& existing.tool_name == desired.tool_name
|
|
&& existing.tool_title == desired.tool_title
|
|
&& existing.tool_description_override == desired.tool_description_override
|
|
&& existing.enabled == desired.enabled
|
|
})
|
|
}
|
|
|
|
fn demo_currency_agent_payload() -> AgentPayload {
|
|
AgentPayload {
|
|
slug: "currency-rates".to_owned(),
|
|
display_name: "Курсы валют".to_owned(),
|
|
description: "Агент с инструментами для получения курсов валют.".to_owned(),
|
|
instructions: json!({
|
|
"system": "Используй инструменты Frankfurter только для запросов о курсах валют."
|
|
}),
|
|
tool_selection_policy: Default::default(),
|
|
}
|
|
}
|
|
|
|
fn demo_rest_operation_payload() -> OperationPayload {
|
|
let input = demo_rest_input_sample();
|
|
let response = demo_rest_response_sample();
|
|
let output = demo_rest_output_sample();
|
|
|
|
OperationPayload {
|
|
name: "frankfurter_latest_rate".to_owned(),
|
|
display_name: "Последний курс валюты".to_owned(),
|
|
category: "frankfurter_rates".to_owned(),
|
|
protocol: Protocol::Rest,
|
|
security_level: OperationSecurityLevel::Standard,
|
|
target: Target::Rest(crank_core::RestTarget {
|
|
base_url: "https://api.frankfurter.dev".to_owned(),
|
|
method: crank_core::HttpMethod::Get,
|
|
path_template: "/v1/latest".to_owned(),
|
|
static_headers: BTreeMap::from([("Accept".to_owned(), "application/json".to_owned())]),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
}),
|
|
input_schema: Schema::from_json_sample(&input),
|
|
output_schema: Schema::from_json_sample(&output),
|
|
input_mapping: frankfurter_input_mapping(),
|
|
output_mapping: infer_mapping_from_samples(
|
|
&response,
|
|
JsonPathRoot::ResponseBody,
|
|
&output,
|
|
JsonPathRoot::Output,
|
|
),
|
|
execution_config: crank_core::ExecutionConfig {
|
|
timeout_ms: 10_000,
|
|
retry_policy: None,
|
|
response_cache: None,
|
|
idempotency: None,
|
|
safety: None,
|
|
approval_policy: None,
|
|
execution_policy: None,
|
|
auth_profile_ref: None,
|
|
headers: BTreeMap::new(),
|
|
},
|
|
tool_description: crank_core::ToolDescription {
|
|
title: "Последний курс валюты".to_owned(),
|
|
description:
|
|
"Возвращает последний доступный курс одной валюты к другой через Frankfurter."
|
|
.to_owned(),
|
|
tags: vec![
|
|
"frankfurter".to_owned(),
|
|
"currency".to_owned(),
|
|
"exchange-rate".to_owned(),
|
|
],
|
|
examples: vec![crank_core::ToolExample {
|
|
input: json!({
|
|
"base": "USD",
|
|
"quote": "EUR"
|
|
}),
|
|
}],
|
|
},
|
|
wizard_state: Some(WizardState {
|
|
input_sample: Some(input),
|
|
output_sample: Some(output),
|
|
test_input: Some(demo_rest_input_sample()),
|
|
import_findings: Vec::new(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
fn demo_rest_input_sample() -> Value {
|
|
json!({
|
|
"base": "USD",
|
|
"quote": "EUR"
|
|
})
|
|
}
|
|
|
|
fn demo_rest_request_sample() -> Value {
|
|
json!({
|
|
"base": "USD",
|
|
"symbols": "EUR"
|
|
})
|
|
}
|
|
|
|
fn demo_rest_response_sample() -> Value {
|
|
json!({
|
|
"amount": 1.0,
|
|
"base": "USD",
|
|
"date": "2026-06-19",
|
|
"rates": {
|
|
"EUR": 0.87207
|
|
}
|
|
})
|
|
}
|
|
|
|
fn demo_rest_output_sample() -> Value {
|
|
demo_rest_response_sample()
|
|
}
|
|
|
|
fn frankfurter_input_mapping() -> MappingSet {
|
|
MappingSet {
|
|
rules: vec![
|
|
MappingRule {
|
|
source: "$.mcp.base".to_owned(),
|
|
target: "$.request.query.base".to_owned(),
|
|
required: true,
|
|
default_value: None,
|
|
transform: None,
|
|
condition: None,
|
|
notes: None,
|
|
},
|
|
MappingRule {
|
|
source: "$.mcp.quote".to_owned(),
|
|
target: "$.request.query.symbols".to_owned(),
|
|
required: true,
|
|
default_value: None,
|
|
transform: None,
|
|
condition: None,
|
|
notes: None,
|
|
},
|
|
],
|
|
}
|
|
}
|