use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::{ActionOutcome, AdkError, ErrorCategory, Part};
pub const TOOL_RESULT_STATUS_KEY: &str = "adk.tool_result.status";
pub const TOOL_RESULT_ERROR_CODE_KEY: &str = "adk.tool_result.error_code";
pub const TOOL_RESULT_ERROR_CATEGORY_KEY: &str = "adk.tool_result.error_category";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ToolResultStatus {
Refused,
NotRun,
Held,
Failed,
OutcomeUnknown,
Withheld,
Succeeded,
}
impl ToolResultStatus {
pub fn is_error(self) -> bool {
matches!(self, Self::Refused | Self::NotRun | Self::Failed)
}
pub fn of_tool_error(error: &AdkError) -> Self {
if error.code == TOOL_PERMISSION_DENIED_CODE { Self::Refused } else { Self::Failed }
}
pub fn of_record(outcome: Option<&ActionOutcome>) -> Self {
match outcome {
Some(ActionOutcome::Succeeded { .. }) => Self::Succeeded,
Some(ActionOutcome::Failed { error }) if crate::is_not_run(error) => Self::NotRun,
Some(ActionOutcome::Failed { .. }) => Self::Failed,
_ => Self::OutcomeUnknown,
}
}
pub fn when_withheld(previous: Option<Self>, executed: bool) -> Self {
match previous {
Some(kept @ (Self::NotRun | Self::Refused | Self::OutcomeUnknown)) => kept,
Some(Self::Failed | Self::Withheld | Self::Succeeded) => Self::Withheld,
Some(Self::Held) | None if executed => Self::Withheld,
Some(Self::Held) | None => Self::NotRun,
}
}
}
impl Part {
pub fn tool_result_status(&self) -> Option<ToolResultStatus> {
ToolResultStatus::deserialize(self.tool_result_annotation(TOOL_RESULT_STATUS_KEY)?).ok()
}
pub fn tool_result_error_code(&self) -> Option<&str> {
self.tool_result_annotation(TOOL_RESULT_ERROR_CODE_KEY)?.as_str()
}
pub fn tool_result_error_category(&self) -> Option<ErrorCategory> {
ErrorCategory::deserialize(self.tool_result_annotation(TOOL_RESULT_ERROR_CATEGORY_KEY)?)
.ok()
}
pub fn set_tool_result_status(&mut self, status: ToolResultStatus, cause: Option<&AdkError>) {
let Part::FunctionResponse { annotations, .. } = self else { return };
let mut fields = match annotations.take() {
Some(Value::Object(fields)) => fields,
Some(other) => {
let mut fields = serde_json::Map::new();
fields.insert("value".to_string(), other);
fields
}
None => serde_json::Map::new(),
};
fields.insert(TOOL_RESULT_STATUS_KEY.to_string(), json!(status));
match cause {
Some(error) => {
fields.insert(TOOL_RESULT_ERROR_CODE_KEY.to_string(), json!(error.code));
fields.insert(TOOL_RESULT_ERROR_CATEGORY_KEY.to_string(), json!(error.category));
}
None => {
fields.remove(TOOL_RESULT_ERROR_CODE_KEY);
fields.remove(TOOL_RESULT_ERROR_CATEGORY_KEY);
}
}
*annotations = Some(Value::Object(fields));
}
fn tool_result_annotation(&self, key: &str) -> Option<&Value> {
match self {
Part::FunctionResponse { annotations: Some(annotations), .. } => annotations.get(key),
_ => None,
}
}
}
pub const TOOL_INVALID_ARGUMENTS_CODE: &str = "tool.invalid_arguments";
pub const TOOL_PERMISSION_DENIED_CODE: &str = "tool.permission_denied";
pub const RESULT_WITHHELD_STATUS: &str = "result_withheld";
pub const INVALID_TOOL_ARGUMENTS_KEY: &str = "adk_invalid_tool_arguments";
const RAW_ARGUMENTS_MAX_BYTES: usize = 1024;
pub const TOOL_ERROR_MESSAGE_LIMIT: usize = 500;
pub fn tool_error_response(tool_name: &str, error: &AdkError, expose_message: bool) -> Value {
let text = if expose_message || error.code == TOOL_INVALID_ARGUMENTS_CODE {
error.to_string()
} else if error.category.is_rejection() {
format!(
"tool '{tool_name}' failed: {}: {}",
error.redacted(),
bounded_message(&error.message)
)
} else {
format!("tool '{tool_name}' failed: {}", error.redacted())
};
json!({ "error": text })
}
fn bounded_message(message: &str) -> String {
let mut chars = message.chars();
let head: String = chars.by_ref().take(TOOL_ERROR_MESSAGE_LIMIT).collect();
if chars.next().is_some() { format!("{head}… (truncated)") } else { head }
}
pub fn result_withheld_response(tool_name: &str, error: &AdkError, expose_message: bool) -> Value {
let failure = if expose_message { error.to_string() } else { error.redacted() };
json!({
"status": RESULT_WITHHELD_STATUS,
"error": format!(
"tool '{tool_name}' ran, but its after-tool pipeline failed with {failure}, so its \
result is withheld; do not call it again for this request."
),
})
}
pub fn result_blocked_response(tool_name: &str, reason: &str) -> Value {
json!({
"status": RESULT_WITHHELD_STATUS,
"error": format!(
"tool '{tool_name}' ran, but its result was withheld: {reason}; do not call it again for \
this request."
),
})
}
#[async_trait]
pub trait ToolResultScreen: Send + Sync {
async fn screen_result(
&self,
tool_name: &str,
args: &Value,
result: &Value,
) -> std::result::Result<Value, String>;
}
pub async fn screen_tool_result(
screen: &dyn ToolResultScreen,
tool_name: &str,
args: &Value,
result: Value,
) -> Value {
match screen.screen_result(tool_name, args, &result).await {
Ok(screened) => screened,
Err(reason) => {
tracing::warn!(tool.name = %tool_name, "tool result withheld by its screen");
result_blocked_response(tool_name, &reason)
}
}
}
pub fn invalid_tool_arguments(reason: impl Into<String>, raw: &str) -> Value {
let mut end = raw.len().min(RAW_ARGUMENTS_MAX_BYTES);
while !raw.is_char_boundary(end) {
end -= 1;
}
json!({ INVALID_TOOL_ARGUMENTS_KEY: { "reason": reason.into(), "raw": &raw[..end] } })
}
pub fn invalid_tool_arguments_reason(args: &Value) -> Option<&str> {
let fields = args.as_object().filter(|fields| fields.len() == 1)?;
fields.get(INVALID_TOOL_ARGUMENTS_KEY)?.get("reason")?.as_str()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ErrorCategory, ErrorComponent};
#[test]
fn permission_denials_keep_their_message() {
let err = AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Forbidden,
TOOL_PERMISSION_DENIED_CODE,
"missing required scopes: [verified] (tool requires: [verified])",
);
assert_eq!(
tool_error_response("transfer", &err, false)["error"],
"tool 'transfer' failed: tool.forbidden (tool.permission_denied): missing required \
scopes: [verified] (tool requires: [verified])"
);
}
#[test]
fn a_rejection_keeps_its_message_bounded_and_a_failure_does_not() {
let refused = AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Forbidden,
"harness.shell.protected",
".git/hooks is a protected path; ask for approval",
);
assert_eq!(
tool_error_response("bash", &refused, false)["error"],
"tool 'bash' failed: tool.forbidden (harness.shell.protected): .git/hooks is a \
protected path; ask for approval"
);
let long = AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"tool.path.outside_workspace",
"é".repeat(TOOL_ERROR_MESSAGE_LIMIT + 7),
);
let text =
tool_error_response("read_file", &long, false)["error"].as_str().unwrap().to_string();
let expected_head = "é".repeat(TOOL_ERROR_MESSAGE_LIMIT);
assert_eq!(
text,
format!(
"tool 'read_file' failed: tool.invalid_input (tool.path.outside_workspace): \
{expected_head}… (truncated)"
)
);
for category in [
ErrorCategory::Unauthorized,
ErrorCategory::RateLimited,
ErrorCategory::Timeout,
ErrorCategory::Unavailable,
ErrorCategory::Cancelled,
ErrorCategory::Internal,
] {
let failed = AdkError::new(ErrorComponent::Tool, category, "tool.x", "secret body");
assert_eq!(
tool_error_response("x", &failed, false)["error"],
format!("tool 'x' failed: tool.{category} (tool.x)"),
"{category} withholds its message"
);
}
}
#[test]
fn invalid_arguments_errors_keep_their_message() {
let err = AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
TOOL_INVALID_ARGUMENTS_CODE,
"missing field `city`",
);
assert_eq!(
tool_error_response("weather", &err, false),
json!({ "error": "tool.invalid_input: missing field `city`" })
);
}
#[test]
fn withheld_response_exposes_the_message_only_when_asked() {
let err = AdkError::agent("audit sink https://u:token@audit.internal unavailable");
let hidden = result_withheld_response("charge", &err, false);
assert_eq!(
hidden,
json!({
"status": RESULT_WITHHELD_STATUS,
"error": "tool 'charge' ran, but its after-tool pipeline failed with \
agent.internal (agent.legacy), so its result is withheld; do not call \
it again for this request.",
})
);
let shown = result_withheld_response("charge", &err, true);
assert!(shown["error"].as_str().unwrap().contains("audit.internal"));
}
#[test]
fn raw_arguments_are_capped_on_a_char_boundary() {
let raw = "é".repeat(RAW_ARGUMENTS_MAX_BYTES);
let args = invalid_tool_arguments("too long", &raw);
let kept = args[INVALID_TOOL_ARGUMENTS_KEY]["raw"].as_str().unwrap();
assert!(kept.len() <= RAW_ARGUMENTS_MAX_BYTES);
assert!(raw.starts_with(kept));
}
#[test]
fn only_the_marker_object_is_invalid_arguments() {
let args = invalid_tool_arguments("bad", "{");
assert_eq!(invalid_tool_arguments_reason(&args), Some("bad"));
let mut extended = args.clone();
extended["city"] = json!("Nairobi");
assert_eq!(invalid_tool_arguments_reason(&extended), None);
assert_eq!(invalid_tool_arguments_reason(&json!("{")), None);
}
fn response(annotations: Option<Value>) -> Part {
Part::FunctionResponse {
function_response: crate::FunctionResponseData::new(
"lookup",
json!({"error": "x", TOOL_RESULT_STATUS_KEY: "failed"}),
),
id: Some("call-1".into()),
annotations,
}
}
#[test]
fn every_status_round_trips_through_the_annotation() {
for (encoded, status) in [
("refused", ToolResultStatus::Refused),
("not_run", ToolResultStatus::NotRun),
("held", ToolResultStatus::Held),
("failed", ToolResultStatus::Failed),
("outcome_unknown", ToolResultStatus::OutcomeUnknown),
("withheld", ToolResultStatus::Withheld),
("succeeded", ToolResultStatus::Succeeded),
] {
let mut part = response(None);
part.set_tool_result_status(status, None);
assert_eq!(part, response(Some(json!({ TOOL_RESULT_STATUS_KEY: encoded }))));
let decoded: Part =
serde_json::from_value(serde_json::to_value(&part).unwrap()).unwrap();
assert_eq!(decoded.tool_result_status(), Some(status));
}
}
#[test]
fn the_status_is_read_from_the_annotation_never_the_payload() {
assert_eq!(response(None).tool_result_status(), None);
assert_eq!(
response(Some(json!({ TOOL_RESULT_STATUS_KEY: "cancelled" }))).tool_result_status(),
None
);
let file = Part::FileData {
mime_type: "text/plain".into(),
file_uri: "https://example.test/a".into(),
annotations: Some(json!({ TOOL_RESULT_STATUS_KEY: "failed" })),
};
assert_eq!(file.tool_result_status(), None);
}
#[test]
fn setting_a_status_keeps_other_annotations_and_replaces_the_cause() {
let timeout =
AdkError::new(ErrorComponent::Tool, ErrorCategory::Timeout, "tool.timeout", "slow");
let mut part = response(Some(json!({ "priority": 1 })));
part.set_tool_result_status(ToolResultStatus::OutcomeUnknown, Some(&timeout));
assert_eq!(
part,
response(Some(json!({
"priority": 1,
TOOL_RESULT_STATUS_KEY: "outcome_unknown",
TOOL_RESULT_ERROR_CODE_KEY: "tool.timeout",
TOOL_RESULT_ERROR_CATEGORY_KEY: "timeout",
})))
);
assert_eq!(part.tool_result_error_code(), Some("tool.timeout"));
assert_eq!(part.tool_result_error_category(), Some(ErrorCategory::Timeout));
part.set_tool_result_status(ToolResultStatus::Withheld, None);
assert_eq!(
part,
response(Some(json!({ "priority": 1, TOOL_RESULT_STATUS_KEY: "withheld" })))
);
let mut odd = response(Some(json!("note")));
odd.set_tool_result_status(ToolResultStatus::Held, None);
assert_eq!(odd, response(Some(json!({ "value": "note", TOOL_RESULT_STATUS_KEY: "held" }))));
}
#[test]
fn a_ledger_record_maps_to_one_status() {
let cases = [
(
Some(ActionOutcome::Succeeded { result_digest: "d".into() }),
ToolResultStatus::Succeeded,
),
(Some(ActionOutcome::Failed { error: "declined".into() }), ToolResultStatus::Failed),
(
Some(ActionOutcome::Failed {
error: crate::not_run_text(&AdkError::agent("frozen")),
}),
ToolResultStatus::NotRun,
),
(None, ToolResultStatus::OutcomeUnknown),
];
for (outcome, status) in cases {
assert_eq!(ToolResultStatus::of_record(outcome.as_ref()), status, "{outcome:?}");
}
}
#[test]
fn withholding_keeps_what_is_known_about_whether_the_call_ran() {
use ToolResultStatus::*;
let cases = [
(Some(NotRun), true, NotRun),
(Some(Refused), true, Refused),
(Some(OutcomeUnknown), false, OutcomeUnknown),
(Some(Failed), false, Withheld),
(Some(Succeeded), false, Withheld),
(Some(Withheld), false, Withheld),
(Some(Held), false, NotRun),
(None, true, Withheld),
(None, false, NotRun),
];
for (previous, executed, expected) in cases {
assert_eq!(
ToolResultStatus::when_withheld(previous, executed),
expected,
"{previous:?}, executed {executed}"
);
}
let errors: Vec<_> = [Refused, NotRun, Held, Failed, OutcomeUnknown, Withheld, Succeeded]
.into_iter()
.filter(|status| status.is_error())
.collect();
assert_eq!(errors, [Refused, NotRun, Failed]);
}
}