feat(epic3): progress и безопасная отмена Tool calls (Story 3.4, FR-14)
- request-scoped lifecycle одного tools/call: валидированный `_meta.progressToken` (строковый/числовой, 1..=128 байт) и bounded очередь реальных этапов (tool_resolved → authorization_resolved → execution_dispatched) в собственный SSE-stream запроса; без token или без stream-carrier результат не меняется; - сериализация `notifications/progress` по pinned схеме обеих revisions (progressToken/progress/message, total не изобретается); - отмена по revision: 2025-11-25 — `notifications/cancelled` через bounded in-flight таблицу (владение = session + platform credential, не progress token); 2026-07-28 — закрытие response stream; в обоих случаях drop будущего вызова = кооперативная остановка, terminal-сообщение не отправляется; - streamed ответ сохраняет проекцию Story 3.18: closed `notifications/message` перед финальным кадром (перенос logging-scope в тело стрима); - ATDD: 12 end-to-end тестов на реальном endpoint/каталоге/counted upstream (обе revisions, malformed/oversized/reused token, owner/foreign/late cancel, disconnect, ambiguous outbound, representative client smoke) + 7 unit-тестов границ lifecycle; entry в scripts/ci-story-checks.sh.
This commit is contained in:
1 parent
49c8af24ed
commit
862cde8559
18 files changed
+2207
-112
No files matched your search
@@ -22,7 +22,7 @@ use super::response::{
|
||||
completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result,
|
||||
prompts_list_result, resource_error_response, resource_read_result,
|
||||
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||
tool_command_response, tools_list_result,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
@@ -41,7 +41,7 @@ use crate::{
|
||||
handle_tools_command,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, transport_response},
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
};
|
||||
|
||||
// The transport invariants of one request travel together here; a parameter struct would only
|
||||
@@ -138,6 +138,8 @@ pub(super) async fn handle_legacy_request(
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::List(list_command),
|
||||
// A list command has no progress or cancellation lifecycle (Story 3.4).
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
@@ -192,30 +194,43 @@ pub(super) async fn handle_legacy_request(
|
||||
// response mode or the protocol revision (spec section 6.2).
|
||||
let mut arguments = tool_call_params.arguments.unwrap_or_else(|| json!({}));
|
||||
let confirmation_token = take_confirmation_token(&mut arguments);
|
||||
let outcome = handle_tools_command(
|
||||
&state,
|
||||
ServiceContext {
|
||||
workspace_slug: &session.workspace_slug,
|
||||
agent_slug: &session.agent_slug,
|
||||
credential,
|
||||
correlation: transport_correlation,
|
||||
// Story 3.4: the client's own `_meta.progressToken`, validated and bounded, and the
|
||||
// session/credential ownership of the in-flight cancellation table.
|
||||
let progress = crate::app::lifecycle::token_from_meta(tool_call_params.meta.as_ref());
|
||||
super::lifecycle::run_tool_call(
|
||||
Arc::clone(&state),
|
||||
crate::app::lifecycle::ToolCallRequest {
|
||||
workspace_slug: session.workspace_slug.clone(),
|
||||
agent_slug: session.agent_slug.clone(),
|
||||
credential: credential.clone(),
|
||||
correlation: transport_correlation.clone(),
|
||||
continuation: ContinuationSupport::from_supported(session.supports_elicitation),
|
||||
locale: execution_locale(message),
|
||||
},
|
||||
ToolsCommand::Call(ToolCallCommand {
|
||||
crate::app::lifecycle::ToolCallWire {
|
||||
message: message.clone(),
|
||||
protocol_version: session.protocol_version.clone(),
|
||||
response_mode,
|
||||
progress,
|
||||
session_id: Some(session.id.clone()),
|
||||
in_flight: Some(crate::app::lifecycle::InFlightScope {
|
||||
session_id: session.id.clone(),
|
||||
owner: in_flight_owner(credential),
|
||||
}),
|
||||
},
|
||||
ToolCallCommand {
|
||||
tool_name: tool_call_params.name,
|
||||
arguments,
|
||||
confirmation_token,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
tool_command_response(
|
||||
message,
|
||||
response_mode,
|
||||
&session.protocol_version,
|
||||
transport_correlation,
|
||||
outcome,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::Cancelled,
|
||||
kind: Kind::Notification,
|
||||
} if is_notification(message) => {
|
||||
handle_cancelled_notification(&state, path, headers, message, credential).await
|
||||
}
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::ResourceList,
|
||||
@@ -729,3 +744,51 @@ pub(super) async fn handle_legacy_request(
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The credential half of the cancellation ownership of one call (Story 3.4). The progress token is
|
||||
/// deliberately not part of it: a token never authorizes a cancellation.
|
||||
fn in_flight_owner(credential: &VerifiedMachineCredential) -> String {
|
||||
credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map_or_else(String::new, |id| id.as_str().to_owned())
|
||||
}
|
||||
|
||||
/// Route one legacy `notifications/cancelled` to the call it names, then acknowledge it.
|
||||
///
|
||||
/// The pinned rules of a cancelled request are all "ignore": an unknown or already finished request,
|
||||
/// a foreign session or credential, a malformed `requestId` and an unknown session are acknowledged
|
||||
/// without any effect. That is also why this handler never fails the transport — a client that
|
||||
/// cancels must not learn anything about another client's calls.
|
||||
async fn handle_cancelled_notification(
|
||||
state: &Arc<AppState>,
|
||||
path: &AgentRoutePath,
|
||||
headers: &HeaderMap,
|
||||
message: &Value,
|
||||
credential: &VerifiedMachineCredential,
|
||||
) -> Response {
|
||||
let request_id = params(message).get("requestId").cloned();
|
||||
let session_id = session_id_from_headers(headers).ok().flatten();
|
||||
if let (Some(request_id), Some(session_id)) = (request_id, session_id) {
|
||||
// Only a string or a number is a pinned `RequestId`; anything else cannot name a call.
|
||||
if matches!(request_id, Value::String(_) | Value::Number(_)) {
|
||||
let owned_by_session = match state.sessions.get(&session_id).await {
|
||||
Ok(Some(session)) => {
|
||||
session.workspace_slug == path.workspace_slug
|
||||
&& session.agent_slug == path.agent_slug
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if owned_by_session {
|
||||
state.in_flight.cancel(
|
||||
&crate::app::lifecycle::InFlightScope {
|
||||
session_id,
|
||||
owner: in_flight_owner(credential),
|
||||
},
|
||||
&request_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
StatusCode::ACCEPTED.into_response()
|
||||
}
|
||||
Reference in new issue
Block a user