refactor: remove retry_count from ProviderConfig and enhance error handling in tool execution

- Removed the `retry_count` field from `ProviderConfig` as it is no longer needed.
- Introduced `argument_error` field in `ToolCall` to capture errors related to tool arguments.
- Updated various components to handle argument errors more gracefully, including in the `ToolDispatcher` and `ConversationOutput`.
- Enhanced tests to validate the new error handling and ensure proper functionality of tool calls.
This commit is contained in:
leokun committed 2026-09-01 10:14:53 +08:00
1 parent 29fde7d7c7
commit d83e14af9a
38 files changed
+1105 -444

No files matched your search

@@ -102,6 +102,12 @@ pub fn decode_pending(value: &str) -> Result<RecoveredToolRound> {
.into_iter()
.enumerate()
.map(|(index, call)| {
let argument_error = wire
.pointer("/providerOptions/cursor/pendingToolExecutionContracts")
.and_then(|contracts| contracts.get(&call.call_id))
.and_then(|contract| contract.get("argumentError"))
.and_then(Value::as_str)
.map(str::to_string);
Ok(ToolCall {
index,
call_id: call.call_id,
@@ -109,6 +115,7 @@ pub fn decode_pending(value: &str) -> Result<RecoveredToolRound> {
name: call.name,
arguments_text: serde_json::to_string(&call.arguments)?,
arguments: call.arguments,
argument_error,
})
})
.collect::<Result<Vec<_>>>()?;
+20 -10
View File
@@ -71,6 +71,7 @@ pub fn staged_tool_round(
allowed_tools,
dynamic_tools,
started_at_ms,
tool_calls: Some(calls),
}),
)?)?)
}
@@ -96,6 +97,7 @@ pub fn staged_final(
allowed_tools,
dynamic_tools,
started_at_ms,
tool_calls: None,
}),
)?)?)
}
@@ -105,6 +107,7 @@ pub(super) struct PendingContext<'a> {
allowed_tools: &'a [String],
dynamic_tools: &'a HashSet<String>,
started_at_ms: u64,
tool_calls: Option<&'a [ToolCall]>,
}
pub(super) fn wire_message(
@@ -132,16 +135,23 @@ pub(super) fn wire_message(
calls
.iter()
.map(|call| {
(
call.call_id.clone(),
json!({
"toolCallId": call.call_id,
"outerToolName": call.name,
"toolIdentifier": tool_identifier(&call.name, pending.dynamic_tools),
"isDynamic": pending.dynamic_tools.contains(&call.name),
"allowedToolNames": pending.allowed_tools,
}),
)
let mut contract = json!({
"toolCallId": call.call_id,
"outerToolName": call.name,
"toolIdentifier": tool_identifier(&call.name, pending.dynamic_tools),
"isDynamic": pending.dynamic_tools.contains(&call.name),
"allowedToolNames": pending.allowed_tools,
});
if let Some(error) = pending
.tool_calls
.and_then(|calls| {
calls.iter().find(|candidate| candidate.call_id == call.call_id)
})
.and_then(|call| call.argument_error.as_deref())
{
contract["argumentError"] = Value::String(error.into());
}
(call.call_id.clone(), contract)
})
.collect(),
),
@@ -30,6 +30,7 @@ fn pending_tool_round_is_one_complete_assistant_message_and_round_trips() {
name: "Read".into(),
arguments_text: r#"{"path":"/a"}"#.into(),
arguments: json!({"path":"/a"}),
argument_error: Some("Read arguments are not valid JSON".into()),
},
ToolCall {
index: 1,
@@ -38,6 +39,7 @@ fn pending_tool_round_is_one_complete_assistant_message_and_round_trips() {
name: "Grep".into(),
arguments_text: r#"{"pattern":"x"}"#.into(),
arguments: json!({"pattern":"x"}),
argument_error: None,
},
];
let pending = staged_tool_round(
@@ -55,6 +57,10 @@ fn pending_tool_round_is_one_complete_assistant_message_and_round_trips() {
wire["providerOptions"]["cursor"]["pendingToolExecutionContracts"]["a"]["toolIdentifier"],
"READ"
);
assert_eq!(
wire["providerOptions"]["cursor"]["pendingToolExecutionContracts"]["a"]["argumentError"],
"Read arguments are not valid JSON"
);
assert_eq!(wire["role"], "assistant");
assert_eq!(
wire["providerOptions"]["cursor"]["pendingToolExecutionContracts"]
@@ -77,6 +83,10 @@ fn pending_tool_round_is_one_complete_assistant_message_and_round_trips() {
assert_eq!(recovered.assistant.replay_state, Some(replay_state));
assert_eq!(recovered.calls.len(), 2);
assert_eq!(recovered.calls[0].call_id, "a");
assert_eq!(
recovered.calls[0].argument_error.as_deref(),
Some("Read arguments are not valid JSON")
);
assert_eq!(recovered.calls[1].call_id, "b");
}
+27
View File
@@ -75,6 +75,11 @@ impl StepBuffer {
});
}
pub fn finish_model_attempt(&mut self) {
self.finish_text();
self.finish_thinking(Duration::ZERO);
}
pub fn discard_model_output(&mut self) {
self.text.clear();
self.thinking.clear();
@@ -101,6 +106,28 @@ impl StepBuffer {
mod tests {
use super::*;
#[test]
fn failed_attempt_output_is_retained_for_the_next_checkpoint() {
let mut buffer = StepBuffer::default();
buffer.text_delta("partial answer");
buffer.thinking_delta("partial reasoning");
buffer.finish_model_attempt();
let steps = buffer.take().steps;
assert_eq!(steps.len(), 2);
assert!(matches!(
&steps[0].message,
Some(pb::conversation_step::Message::AssistantMessage(message))
if message.text == "partial answer"
));
assert!(matches!(
&steps[1].message,
Some(pb::conversation_step::Message::ThinkingMessage(message))
if message.text == "partial reasoning"
));
}
#[test]
fn interrupted_model_output_is_not_persisted_as_checkpoint_steps() {
let mut buffer = StepBuffer::default();
+79 -10
View File
@@ -21,7 +21,7 @@ use crate::{
protocol::proto::agent::v1 as pb,
services::blob_sync::BlobSynchronizer,
tools::{
codec,
codec, compat,
runtime::CursorToolRuntime,
stream::ToolCallStream,
tool_call_result::{ToolCompletion, ToolResultReceiver},
@@ -264,6 +264,32 @@ impl ConversationOutput {
streams.clear();
presentation.discard_model_output();
}
RunEvent::ModelAttemptFailed { attempt, message } => {
tracing::warn!(
run_id = %self.run.run_id(),
attempt,
%message,
"retrying model call from current checkpoint"
);
presentation.finish_model_attempt();
for call in calls.values_mut() {
if call.arguments.is_null() {
call.arguments = serde_json::from_str(&call.arguments_text)
.unwrap_or_else(|_| serde_json::json!({}));
}
let completion = compat::failure_with_message(
call,
format!("Model attempt failed before tool completion: {message}"),
);
self.handle
.emit(&codec::tool_completed(call, &completion))?;
presentation.tool_completed(&completion);
}
response_text.clear();
response_thinking.clear();
calls.clear();
streams.clear();
}
RunEvent::TextStart => {}
RunEvent::TextEnd => {
if !self.context.compacting {
@@ -312,6 +338,7 @@ impl ConversationOutput {
name: name.clone(),
arguments_text: String::new(),
arguments: serde_json::Value::Null,
argument_error: None,
};
self.emit_model_event(
crate::provider::ModelEvent::ToolCallStart {
@@ -335,8 +362,27 @@ impl ConversationOutput {
let stream = streams.get_mut(&index).ok_or_else(|| {
Error::Protocol(format!("missing Cursor tool stream: {index}"))
})?;
for message in stream.arguments_delta(call, &delta)? {
self.handle.emit(&message)?;
match stream.arguments_delta(call, &delta) {
Ok(messages) => {
for message in messages {
self.handle.emit(&message)?;
}
}
Err(Error::Protocol(message)) => {
tracing::warn!(
call_id = %call.call_id,
%message,
"ignoring invalid streaming tool arguments until completion"
);
}
Err(Error::Json(error)) => {
tracing::warn!(
call_id = %call.call_id,
%error,
"ignoring invalid streaming tool arguments until completion"
);
}
Err(error) => return Err(error),
}
}
RunEvent::ToolCallEnd { index } => {
@@ -349,7 +395,8 @@ impl ConversationOutput {
call.arguments = if call.arguments_text.trim().is_empty() {
serde_json::json!({})
} else {
serde_json::from_str(&call.arguments_text)?
serde_json::from_str(&call.arguments_text)
.unwrap_or_else(|_| serde_json::json!({}))
};
}
RunEvent::Usage(usage) => {
@@ -359,10 +406,7 @@ impl ConversationOutput {
}
}
if !self.context.compacting {
context_tokens = usage
.input_tokens
.zip(usage.output_tokens)
.and_then(|(input, output)| input.checked_add(output));
context_tokens = usage.context_input_tokens;
}
match &mut turn_usage {
Some(total) => *total += usage,
@@ -523,6 +567,7 @@ impl ConversationOutput {
.map_err(|_| Error::Protocol("checkpoint worker stopped".into()))?
{
Ok(checkpoint) => {
context_tokens = checkpoint_context_tokens(&checkpoint);
compaction_checkpoint = Some(checkpoint);
state.barrier.complete(Ok(()));
}
@@ -1029,10 +1074,34 @@ pub(crate) fn finish_cancelled(handle: &TransportHandle) -> Result<()> {
Ok(())
}
fn checkpoint_context_tokens(checkpoint: &pb::ConversationStateStructure) -> Option<u64> {
checkpoint
.token_details
.as_ref()
.map(|details| u64::from(details.used_tokens))
}
#[cfg(test)]
mod tests {
use super::accept_tool_completion;
use crate::{run::CommandResult, Error};
use super::{accept_tool_completion, checkpoint_context_tokens};
use crate::{cursor::protocol::proto::agent::v1 as pb, run::CommandResult, Error};
#[test]
fn compacted_checkpoint_replaces_the_in_memory_context_usage() {
let compacted = pb::ConversationStateStructure {
token_details: Some(pb::ConversationTokenDetails {
used_tokens: 20_000,
..Default::default()
}),
..Default::default()
};
assert_eq!(checkpoint_context_tokens(&compacted), Some(20_000));
assert_eq!(
checkpoint_context_tokens(&pb::ConversationStateStructure::default()),
None
);
}
#[test]
fn closing_and_ended_runs_ignore_known_tool_completions() {
+12 -11
View File
@@ -11,7 +11,7 @@ use crate::{
protocol::proto::agent::v1 as pb,
services::{blob_sync::BlobSynchronizer, context_sync::RequestContextSynchronizer},
tools::{
codec,
codec, compat,
runtime::CursorToolRuntime,
tool_call_result::{tool_result_channel, ToolResultReceiver, ToolResultSender},
ClientToolEvent, ToolDispatcher,
@@ -262,17 +262,18 @@ impl ConversationRuntime {
.take_exec(throw.id)
.await
{
Some(pending) => generation.results.send_error(
crate::Error::Protocol(format!(
"Exec {} failed: {}",
pending.call.call_id, throw.error
)),
Some(pending) => generation.results.send(
compat::failure_with_message(
&pending.call,
format!(
"Exec {} failed: {}",
pending.call.call_id, throw.error
),
),
),
None => generation.results.send_error(
crate::Error::Protocol(format!(
"unknown ExecClientThrow id: {}",
throw.id
)),
None => tracing::warn!(
id = throw.id,
"ignoring failure for unknown tool execution"
),
}
}
+1
View File
@@ -542,6 +542,7 @@ mod tests {
name: "Bash".into(),
arguments_text: String::new(),
arguments: json!({ "command": "ls -la" }),
argument_error: None,
};
let message = request(1, &call, &ExecContext::default()).unwrap();
let Some(pb::agent_server_message::Message::ExecServerMessage(exec)) = message.message
+35 -18
View File
@@ -3,7 +3,7 @@ use crate::{
cursor::{
protocol::{events, proto::agent::v1 as pb},
tools::{
edit,
compat, edit,
runtime::{CursorToolRuntime, ExecStage, PendingExec},
tool_call_result::{self as result, ToolCompletion},
},
@@ -34,16 +34,15 @@ pub async fn client_event(
let call = match pending.exec_call(message.id).await {
Some(call) => call,
None if pending.completed_call(message.id).await.is_some() => {
return Err(Error::Protocol(format!(
"duplicate terminal ExecClientMessage id: {}",
message.id
)))
tracing::warn!(id = message.id, "ignoring duplicate terminal tool response");
return Ok(ClientExecEvent::Pending);
}
None => {
return Err(Error::Protocol(format!(
"unknown ExecClientMessage id: {}",
message.id
)))
tracing::warn!(
id = message.id,
"ignoring response for unknown tool execution"
);
return Ok(ClientExecEvent::Pending);
}
};
let Some(wire_result) = &message.message else {
@@ -174,9 +173,22 @@ pub async fn stream_closed(id: u32, pending: &CursorToolRuntime) -> Result<Optio
}
let rendered = match &entry.stage {
ExecStage::DynamicMcp(definition) => {
super::render_dynamic_mcp(&entry.call, definition, false)
Ok(super::render_dynamic_mcp(&entry.call, definition, false))
}
_ => super::render_tool_call(&entry.call, false)?,
_ => super::render_tool_call(&entry.call, false),
};
let rendered = match rendered {
Ok(rendered) => rendered,
Err(Error::Protocol(message)) => {
return Ok(Some(compat::failure_with_message(&entry.call, message)));
}
Err(Error::Json(error)) => {
return Ok(Some(compat::failure_with_message(
&entry.call,
error.to_string(),
)));
}
Err(error) => return Err(error),
};
Ok(Some(ToolCompletion::from_rendered(
&entry.call,
@@ -212,10 +224,10 @@ async fn advance_edit(
pb::exec_client_message::Message::ReadResult(result)
| pb::exec_client_message::Message::RedactedReadResult(result) => result,
_ => {
return Err(Error::Protocol(format!(
"expected ReadResult for edit tool {}",
entry.call.name
)))
let message = format!("expected ReadResult for edit tool {}", entry.call.name);
return Ok(ClientExecEvent::Completed(Box::new(
compat::failure_with_message(&entry.call, message),
)));
}
};
let write = match edit::after_read(&entry.call, read) {
@@ -260,9 +272,14 @@ fn completed(
pending: PendingExec,
result: pb::exec_client_message::Message,
) -> Result<ClientExecEvent> {
Ok(ClientExecEvent::Completed(Box::new(result::from_exec(
pending, &result,
)?)))
let call = pending.call.clone();
let completion = match result::from_exec(pending, &result) {
Ok(completion) => completion,
Err(Error::Protocol(message)) => compat::failure_with_message(&call, message),
Err(Error::Json(error)) => compat::failure_with_message(&call, error.to_string()),
Err(error) => return Err(error),
};
Ok(ClientExecEvent::Completed(Box::new(completion)))
}
fn shell_exit_result(
+4 -1
View File
@@ -49,7 +49,10 @@ pub(crate) fn render(call: &ToolCall, completed: bool) -> pb::ToolCall {
}
pub(crate) fn failure(call: &ToolCall) -> ToolCompletion {
let error = failure_message(&call.name);
failure_with_message(call, failure_message(&call.name))
}
pub(crate) fn failure_with_message(call: &ToolCall, error: String) -> ToolCompletion {
let arguments = call
.arguments
.as_object()
+1
View File
@@ -265,6 +265,7 @@ mod tests {
"old_string": old_string,
"new_string": "replacement",
}),
argument_error: None,
}
}
+91 -41
View File
@@ -103,10 +103,20 @@ impl ToolDispatcher {
}
let message_index = first_tool_index + position;
let publish_started = !state.started.contains(&call.call_id);
if let Some(error) = &call.argument_error {
dispatched.push(validation_failure(call, error.clone()));
continue;
}
let edit_path = if dynamic_mcp.contains_key(&call.name) {
None
} else {
edit::execution_path(call)?
match edit::execution_path(call) {
Ok(path) => path,
Err(error) => {
dispatched.push(recover_validation_failure(call, error)?);
continue;
}
}
};
if let Some(path) = edit_path {
let next = self.edit_schedule.lock().await.start_or_defer(
@@ -121,22 +131,28 @@ impl ToolDispatcher {
let Some(next) = next else {
continue;
};
dispatched.push(
self.start(
let started = self
.start(
&next.call,
next.message_index,
next.publish_started,
dynamic_mcp,
&next.context,
)
.await?,
);
.await;
dispatched.push(match started {
Ok(started) => started,
Err(error) => recover_validation_failure(&next.call, error)?,
});
continue;
}
dispatched.push(
self.start(call, message_index, publish_started, dynamic_mcp, context)
.await?,
);
let started = self
.start(call, message_index, publish_started, dynamic_mcp, context)
.await;
dispatched.push(match started {
Ok(started) => started,
Err(error) => recover_validation_failure(call, error)?,
});
}
Ok(dispatched)
}
@@ -146,15 +162,19 @@ impl ToolDispatcher {
let Some(next) = next else {
return Ok(None);
};
self.start(
&next.call,
next.message_index,
next.publish_started,
&BTreeMap::new(),
&next.context,
)
.await
.map(Some)
match self
.start(
&next.call,
next.message_index,
next.publish_started,
&BTreeMap::new(),
&next.context,
)
.await
{
Ok(started) => Ok(Some(started)),
Err(error) => recover_validation_failure(&next.call, error).map(Some),
}
}
pub async fn interrupt_for_message(&self) -> Vec<u32> {
@@ -203,34 +223,64 @@ impl ToolDispatcher {
let pending = match self.runtime.take_interaction(response.id).await {
Some(pending) => pending,
None if self.runtime.completed_call(response.id).await.is_some() => {
return Err(Error::Protocol(format!(
"duplicate terminal InteractionResponse id: {}",
response.id
)));
tracing::warn!(
id = response.id,
"ignoring duplicate terminal interaction response"
);
return Ok(ClientToolEvent::Pending);
}
None => {
return Err(Error::Protocol(format!(
"unknown InteractionResponse id: {}",
response.id
)));
tracing::warn!(
id = response.id,
"ignoring response for unknown interaction"
);
return Ok(ClientToolEvent::Pending);
}
};
Ok(
match tool_call_dispatch::resume_interaction(
&self.results,
&self.search,
&self.fetch,
pending,
response,
)
.await?
{
tool_call_dispatch::InteractionContinuation::Completed(completion) => {
ClientToolEvent::Completed(completion)
}
tool_call_dispatch::InteractionContinuation::Pending => ClientToolEvent::Pending,
},
let call = pending.call.clone();
let continuation = match tool_call_dispatch::resume_interaction(
&self.results,
&self.search,
&self.fetch,
pending,
response,
)
.await
{
Ok(continuation) => continuation,
Err(Error::Protocol(message)) => {
return Ok(ClientToolEvent::Completed(Box::new(
compat::failure_with_message(&call, message),
)));
}
Err(Error::Json(error)) => {
return Ok(ClientToolEvent::Completed(Box::new(
compat::failure_with_message(&call, error.to_string()),
)));
}
Err(error) => return Err(error),
};
Ok(match continuation {
tool_call_dispatch::InteractionContinuation::Completed(completion) => {
ClientToolEvent::Completed(completion)
}
tool_call_dispatch::InteractionContinuation::Pending => ClientToolEvent::Pending,
})
}
}
fn validation_failure(call: &ToolCall, message: String) -> DispatchedTool {
DispatchedTool {
messages: Vec::new(),
completion: Some(compat::failure_with_message(call, message)),
}
}
fn recover_validation_failure(call: &ToolCall, error: Error) -> Result<DispatchedTool> {
match error {
Error::Protocol(message) => Ok(validation_failure(call, message)),
Error::Json(error) => Ok(validation_failure(call, error.to_string())),
error => Err(error),
}
}
+1
View File
@@ -248,6 +248,7 @@ mod tests {
name: "Task".into(),
arguments_text: arguments_text.into(),
arguments: serde_json::Value::Null,
argument_error: None,
}
}
@@ -406,6 +406,7 @@ mod tests {
name: "WebFetch".into(),
arguments_text: r#"{"url":"https://example.com"}"#.into(),
arguments: json!({"url": "https://example.com"}),
argument_error: None,
},
started_at_ms: 1,
}