Skip to main content

adk_core/
tool_response.rs

1//! Function responses for tool calls that do not return their result.
2//!
3//! An agent answers every function call with exactly one function response. When the tool
4//! fails, when its result cannot be released, or when the model's arguments cannot be decoded,
5//! these builders produce that response without passing error detail to the model by default.
6//! A [`ToolResultScreen`] decides what of a tool's result the model and the session may see.
7//!
8//! An answer the agent writes in place of the tool's result carries a [`ToolResultStatus`] in
9//! the part's annotations ([`Part::tool_result_status`]), so a host, an eval, or an audit reads
10//! what happened to the call without parsing the payload.
11
12use async_trait::async_trait;
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15
16use crate::{ActionOutcome, AdkError, ErrorCategory, Part};
17
18/// The annotation key of a function response's [`ToolResultStatus`].
19pub const TOOL_RESULT_STATUS_KEY: &str = "adk.tool_result.status";
20
21/// The annotation key of the [`AdkError::code`] behind a function response's status.
22pub const TOOL_RESULT_ERROR_CODE_KEY: &str = "adk.tool_result.error_code";
23
24/// The annotation key of the [`ErrorCategory`] behind a function response's status.
25pub const TOOL_RESULT_ERROR_CATEGORY_KEY: &str = "adk.tool_result.error_category";
26
27/// What happened to a tool call that the agent, not the tool, answered.
28///
29/// An agent sets it on the function response it writes in place of the tool's result —
30/// a refusal, a hold, a failure, a withheld result, an unknown outcome, an action-ledger
31/// replay — as the [`TOOL_RESULT_STATUS_KEY`] annotation; the payload the model reads is
32/// unchanged. A response without a status is the tool's own result, an answer a callback or
33/// plugin supplied, or one stored before the status existed. The status is never derived from
34/// the payload, which a tool owns.
35///
36/// | Status | The call | Issued again |
37/// |--------|----------|--------------|
38/// | `Refused` | did not run: an authorization check refused it | meets the same check |
39/// | `NotRun` | did not run, for a reason other than an authorization decision | may run once the reason clears |
40/// | `Held` | waits for a confirmation decision; a later run answers it | should not be; decide it instead |
41/// | `Failed` | ran and failed with a known outcome | as the tool allows |
42/// | `OutcomeUnknown` | began and may have taken effect | only after checking its effect |
43/// | `Withheld` | ran; its result is withheld | should not be |
44/// | `Succeeded` | ran in an earlier attempt; this answer reports that, not the result | should not be |
45///
46/// # Example
47///
48/// ```rust
49/// use adk_core::ToolResultStatus;
50///
51/// assert_eq!(serde_json::to_value(ToolResultStatus::NotRun).unwrap(), "not_run");
52/// assert!(ToolResultStatus::Refused.is_error());
53/// assert!(!ToolResultStatus::OutcomeUnknown.is_error());
54/// ```
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57#[non_exhaustive]
58pub enum ToolResultStatus {
59    /// An authorization check refused the call, so it did not run: a `ToolPolicy` denial, a
60    /// tool guardrail's denial, an approver's or handler's decline, a held call resumed by
61    /// another agent or for another tool, an access guard inside the tool
62    /// ([`TOOL_PERMISSION_DENIED_CODE`]), or a call a person asked for that the agent does not
63    /// take.
64    Refused,
65    /// The call did not run, for a reason other than an authorization decision: the kill
66    /// switch, the run budget, a transfer to another agent, arguments that did not decode, an
67    /// unknown tool, an open circuit breaker, a concurrency limit, a before-tool callback or
68    /// plugin that failed or answered with text, or an action ledger that could not be used.
69    NotRun,
70    /// The call waits for a confirmation decision; a later run answers it.
71    Held,
72    /// The call ran and failed with a known outcome.
73    Failed,
74    /// The call began and may or may not have taken effect: a non-idempotent call that timed
75    /// out or panicked, a call in flight when the run was cancelled or its process stopped, or
76    /// one whose action-ledger record was begun without an outcome.
77    OutcomeUnknown,
78    /// The call ran, but its result is withheld: an after-tool stage failed, or the result
79    /// screen withheld it.
80    Withheld,
81    /// An earlier attempt of the call succeeded, as its action-ledger record shows; the answer
82    /// reports that instead of the result, and the call did not run again.
83    Succeeded,
84}
85
86impl ToolResultStatus {
87    /// Whether a provider with a tool-error flag marks the answer as an error: `Refused`,
88    /// `NotRun` and `Failed`. The others are not errors to report, or an error flag would
89    /// invite the model to repeat a call that ran, may have run, or waits for a decision.
90    ///
91    /// # Example
92    ///
93    /// ```rust
94    /// use adk_core::ToolResultStatus;
95    ///
96    /// assert!(ToolResultStatus::Failed.is_error());
97    /// assert!(!ToolResultStatus::Withheld.is_error());
98    /// assert!(!ToolResultStatus::Held.is_error());
99    /// ```
100    pub fn is_error(self) -> bool {
101        matches!(self, Self::Refused | Self::NotRun | Self::Failed)
102    }
103
104    /// The status of a call whose tool returned `error`: `Refused` for an access guard's
105    /// denial ([`TOOL_PERMISSION_DENIED_CODE`]), which the guard returns before the tool runs,
106    /// and `Failed` for any other error.
107    ///
108    /// # Example
109    ///
110    /// ```rust
111    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent, TOOL_PERMISSION_DENIED_CODE, ToolResultStatus};
112    ///
113    /// let denied = AdkError::new(
114    ///     ErrorComponent::Tool,
115    ///     ErrorCategory::Forbidden,
116    ///     TOOL_PERMISSION_DENIED_CODE,
117    ///     "missing scope: payments",
118    /// );
119    /// assert_eq!(ToolResultStatus::of_tool_error(&denied), ToolResultStatus::Refused);
120    /// assert_eq!(ToolResultStatus::of_tool_error(&AdkError::tool("boom")), ToolResultStatus::Failed);
121    /// ```
122    pub fn of_tool_error(error: &AdkError) -> Self {
123        if error.code == TOOL_PERMISSION_DENIED_CODE { Self::Refused } else { Self::Failed }
124    }
125
126    /// The status of an answer given from an action-ledger record whose outcome is `outcome`:
127    /// `Succeeded` and `Failed` as recorded, `NotRun` for a call the kill switch refused after
128    /// the record was begun ([`not_run_text`](crate::not_run_text)), and `OutcomeUnknown` for a
129    /// record begun without an outcome.
130    ///
131    /// # Example
132    ///
133    /// ```rust
134    /// use adk_core::{ActionOutcome, ToolResultStatus};
135    ///
136    /// let failed = ActionOutcome::Failed { error: "card declined".into() };
137    /// assert_eq!(ToolResultStatus::of_record(Some(&failed)), ToolResultStatus::Failed);
138    /// let frozen = ActionOutcome::Failed { error: "not run: execution is frozen".into() };
139    /// assert_eq!(ToolResultStatus::of_record(Some(&frozen)), ToolResultStatus::NotRun);
140    /// assert_eq!(ToolResultStatus::of_record(None), ToolResultStatus::OutcomeUnknown);
141    /// ```
142    pub fn of_record(outcome: Option<&ActionOutcome>) -> Self {
143        match outcome {
144            Some(ActionOutcome::Succeeded { .. }) => Self::Succeeded,
145            Some(ActionOutcome::Failed { error }) if crate::is_not_run(error) => Self::NotRun,
146            Some(ActionOutcome::Failed { .. }) => Self::Failed,
147            _ => Self::OutcomeUnknown,
148        }
149    }
150
151    /// The status of an answer whose result is withheld after it was written, given the
152    /// answer's `previous` status and whether the tool `executed` in this dispatch.
153    ///
154    /// Withholding a result does not change whether the call ran: `NotRun`, `Refused` and
155    /// `OutcomeUnknown` stand. Any other answer of a call that ran — now, or in the earlier
156    /// attempt an action-ledger replay reports — is `Withheld`. An answer without a status of a
157    /// call that did not execute, such as a before-tool callback's substitute, is `NotRun`.
158    ///
159    /// # Example
160    ///
161    /// ```rust
162    /// use adk_core::ToolResultStatus;
163    ///
164    /// // A ledger replay of a call that succeeded never executes now, but it ran.
165    /// let replay = Some(ToolResultStatus::Succeeded);
166    /// assert_eq!(ToolResultStatus::when_withheld(replay, false), ToolResultStatus::Withheld);
167    /// let refusal = Some(ToolResultStatus::Refused);
168    /// assert_eq!(ToolResultStatus::when_withheld(refusal, false), ToolResultStatus::Refused);
169    /// assert_eq!(ToolResultStatus::when_withheld(None, true), ToolResultStatus::Withheld);
170    /// assert_eq!(ToolResultStatus::when_withheld(None, false), ToolResultStatus::NotRun);
171    /// ```
172    pub fn when_withheld(previous: Option<Self>, executed: bool) -> Self {
173        match previous {
174            Some(kept @ (Self::NotRun | Self::Refused | Self::OutcomeUnknown)) => kept,
175            Some(Self::Failed | Self::Withheld | Self::Succeeded) => Self::Withheld,
176            Some(Self::Held) | None if executed => Self::Withheld,
177            Some(Self::Held) | None => Self::NotRun,
178        }
179    }
180}
181
182impl Part {
183    /// Returns the [`ToolResultStatus`] of a function response the agent wrote, or `None` for
184    /// a tool's own result, a callback's answer, another part, or an unknown status value.
185    ///
186    /// # Example
187    ///
188    /// ```rust
189    /// use adk_core::{FunctionResponseData, Part, ToolResultStatus};
190    /// use serde_json::json;
191    ///
192    /// let mut part = Part::FunctionResponse {
193    ///     function_response: FunctionResponseData::new("pay", json!({"error": "denied"})),
194    ///     id: Some("call-1".into()),
195    ///     annotations: None,
196    /// };
197    /// assert_eq!(part.tool_result_status(), None);
198    /// part.set_tool_result_status(ToolResultStatus::Refused, None);
199    /// assert_eq!(part.tool_result_status(), Some(ToolResultStatus::Refused));
200    /// ```
201    pub fn tool_result_status(&self) -> Option<ToolResultStatus> {
202        ToolResultStatus::deserialize(self.tool_result_annotation(TOOL_RESULT_STATUS_KEY)?).ok()
203    }
204
205    /// Returns the code of the error behind a function response's status, when one was.
206    ///
207    /// # Example
208    ///
209    /// ```rust
210    /// use adk_core::{AdkError, ErrorCategory, ErrorComponent, FunctionResponseData, Part, ToolResultStatus};
211    /// use serde_json::json;
212    ///
213    /// let timeout =
214    ///     AdkError::new(ErrorComponent::Tool, ErrorCategory::Timeout, "tool.timeout", "timed out");
215    /// let mut part = Part::FunctionResponse {
216    ///     function_response: FunctionResponseData::new("lookup", json!({"error": "timed out"})),
217    ///     id: None,
218    ///     annotations: None,
219    /// };
220    /// part.set_tool_result_status(ToolResultStatus::Failed, Some(&timeout));
221    /// assert_eq!(part.tool_result_error_code(), Some("tool.timeout"));
222    /// ```
223    pub fn tool_result_error_code(&self) -> Option<&str> {
224        self.tool_result_annotation(TOOL_RESULT_ERROR_CODE_KEY)?.as_str()
225    }
226
227    /// Returns the category of the error behind a function response's status, when one was.
228    ///
229    /// # Example
230    ///
231    /// ```rust
232    /// use adk_core::{AdkError, ErrorCategory, FunctionResponseData, Part, ToolResultStatus};
233    /// use serde_json::json;
234    ///
235    /// let frozen = AdkError::agent("execution is frozen");
236    /// let mut part = Part::FunctionResponse {
237    ///     function_response: FunctionResponseData::new("pay", json!({"error": "not run"})),
238    ///     id: None,
239    ///     annotations: None,
240    /// };
241    /// part.set_tool_result_status(ToolResultStatus::NotRun, Some(&frozen));
242    /// assert_eq!(part.tool_result_error_category(), Some(ErrorCategory::Internal));
243    /// ```
244    pub fn tool_result_error_category(&self) -> Option<ErrorCategory> {
245        ErrorCategory::deserialize(self.tool_result_annotation(TOOL_RESULT_ERROR_CATEGORY_KEY)?)
246            .ok()
247    }
248
249    /// Sets a function response's [`ToolResultStatus`], with the code and category of `cause`,
250    /// the error behind it, when there is one. The payload and the part's other annotations are
251    /// kept, a non-object annotation under `"value"`; an earlier cause is replaced. Other parts
252    /// are left as they are.
253    ///
254    /// # Example
255    ///
256    /// ```rust
257    /// use adk_core::{FunctionResponseData, Part, TOOL_RESULT_STATUS_KEY, ToolResultStatus};
258    /// use serde_json::json;
259    ///
260    /// let mut part = Part::FunctionResponse {
261    ///     function_response: FunctionResponseData::new("pay", json!({"error": "held"})),
262    ///     id: None,
263    ///     annotations: Some(json!({"priority": 1})),
264    /// };
265    /// part.set_tool_result_status(ToolResultStatus::Held, None);
266    /// assert_eq!(part.annotations(), Some(&json!({"priority": 1, TOOL_RESULT_STATUS_KEY: "held"})));
267    /// ```
268    pub fn set_tool_result_status(&mut self, status: ToolResultStatus, cause: Option<&AdkError>) {
269        let Part::FunctionResponse { annotations, .. } = self else { return };
270        let mut fields = match annotations.take() {
271            Some(Value::Object(fields)) => fields,
272            Some(other) => {
273                let mut fields = serde_json::Map::new();
274                fields.insert("value".to_string(), other);
275                fields
276            }
277            None => serde_json::Map::new(),
278        };
279        fields.insert(TOOL_RESULT_STATUS_KEY.to_string(), json!(status));
280        match cause {
281            Some(error) => {
282                fields.insert(TOOL_RESULT_ERROR_CODE_KEY.to_string(), json!(error.code));
283                fields.insert(TOOL_RESULT_ERROR_CATEGORY_KEY.to_string(), json!(error.category));
284            }
285            None => {
286                fields.remove(TOOL_RESULT_ERROR_CODE_KEY);
287                fields.remove(TOOL_RESULT_ERROR_CATEGORY_KEY);
288            }
289        }
290        *annotations = Some(Value::Object(fields));
291    }
292
293    fn tool_result_annotation(&self, key: &str) -> Option<&Value> {
294        match self {
295            Part::FunctionResponse { annotations: Some(annotations), .. } => annotations.get(key),
296            _ => None,
297        }
298    }
299}
300
301/// The error code for a call whose arguments do not fit the tool.
302///
303/// A tool returns an error with this code to tell the model what to change in its arguments,
304/// so [`tool_error_response`] always shows its message. The `#[tool]` macro uses it when the
305/// arguments do not deserialize.
306pub const TOOL_INVALID_ARGUMENTS_CODE: &str = "tool.invalid_arguments";
307
308/// The code adk-auth's scope and RBAC guards put on a denial; a rejection, so its message
309/// (the missing scopes or roles) reaches the model (spec 3.1 §7.14).
310pub const TOOL_PERMISSION_DENIED_CODE: &str = "tool.permission_denied";
311
312/// The `status` value of the function response for a call that ran but whose result is withheld.
313pub const RESULT_WITHHELD_STATUS: &str = "result_withheld";
314
315/// The key under which a function call's arguments record that the model's arguments did not
316/// decode to a JSON object.
317pub const INVALID_TOOL_ARGUMENTS_KEY: &str = "adk_invalid_tool_arguments";
318
319/// The most bytes of the model's undecodable arguments kept in [`invalid_tool_arguments`].
320const RAW_ARGUMENTS_MAX_BYTES: usize = 1024;
321
322/// The most characters of a rejection's message a function response carries.
323pub const TOOL_ERROR_MESSAGE_LIMIT: usize = 500;
324
325/// Builds the function response for a tool call that failed with `error`.
326///
327/// The response names the error's component, category, and code
328/// ([`AdkError::redacted`]). A rejection ([`ErrorCategory::is_rejection`](crate::ErrorCategory::is_rejection)) — the tool
329/// refused the call or could not use it as made — also carries its message, cut at
330/// [`TOOL_ERROR_MESSAGE_LIMIT`] characters, since that message is the reason the model
331/// needs to act on. The message of an upstream or internal failure stays out unless
332/// `expose_message` is set or the code is [`TOOL_INVALID_ARGUMENTS_CODE`]: it can quote
333/// credentials, internal hosts, or upstream bodies, and the function response is sent to
334/// the model provider and stored in the session.
335///
336/// # Example
337///
338/// ```rust
339/// use adk_core::{AdkError, ErrorCategory, ErrorComponent, tool_error_response};
340///
341/// let err = AdkError::new(
342///     ErrorComponent::Tool,
343///     ErrorCategory::Unavailable,
344///     "tool.orders_db.unavailable",
345///     "connect postgres://admin:secret@db.internal/prod failed",
346/// );
347/// let response = tool_error_response("lookup_order", &err, false);
348/// assert_eq!(
349///     response["error"],
350///     "tool 'lookup_order' failed: tool.unavailable (tool.orders_db.unavailable)"
351/// );
352/// assert!(tool_error_response("lookup_order", &err, true)["error"]
353///     .as_str()
354///     .unwrap()
355///     .contains("db.internal"));
356///
357/// let refused = AdkError::new(
358///     ErrorComponent::Tool,
359///     ErrorCategory::Forbidden,
360///     "harness.shell.protected",
361///     ".git/hooks is a protected path",
362/// );
363/// assert_eq!(
364///     tool_error_response("bash", &refused, false)["error"],
365///     "tool 'bash' failed: tool.forbidden (harness.shell.protected): .git/hooks is a protected path"
366/// );
367/// ```
368pub fn tool_error_response(tool_name: &str, error: &AdkError, expose_message: bool) -> Value {
369    let text = if expose_message || error.code == TOOL_INVALID_ARGUMENTS_CODE {
370        error.to_string()
371    } else if error.category.is_rejection() {
372        format!(
373            "tool '{tool_name}' failed: {}: {}",
374            error.redacted(),
375            bounded_message(&error.message)
376        )
377    } else {
378        format!("tool '{tool_name}' failed: {}", error.redacted())
379    };
380    json!({ "error": text })
381}
382
383/// `message` cut at [`TOOL_ERROR_MESSAGE_LIMIT`] characters, marked when cut.
384fn bounded_message(message: &str) -> String {
385    let mut chars = message.chars();
386    let head: String = chars.by_ref().take(TOOL_ERROR_MESSAGE_LIMIT).collect();
387    if chars.next().is_some() { format!("{head}… (truncated)") } else { head }
388}
389
390/// Builds the function response for a call that ran but whose after-tool pipeline failed.
391///
392/// An after-tool callback or plugin is where results are redacted and screened, so the result
393/// it did not finish with is withheld. The tool's side effect already happened, so the
394/// response tells the model not to call the tool again, as a fresh call has a fresh
395/// idempotency key and would repeat the effect. `error` is described as in
396/// [`tool_error_response`].
397///
398/// # Example
399///
400/// ```rust
401/// use adk_core::{AdkError, RESULT_WITHHELD_STATUS, result_withheld_response};
402///
403/// let response = result_withheld_response("charge_card", &AdkError::agent("audit sink down"), false);
404/// assert_eq!(response["status"], RESULT_WITHHELD_STATUS);
405/// let text = response["error"].as_str().unwrap();
406/// assert!(text.contains("do not call it again"));
407/// assert!(!text.contains("audit sink down"));
408/// ```
409pub fn result_withheld_response(tool_name: &str, error: &AdkError, expose_message: bool) -> Value {
410    let failure = if expose_message { error.to_string() } else { error.redacted() };
411    json!({
412        "status": RESULT_WITHHELD_STATUS,
413        "error": format!(
414            "tool '{tool_name}' ran, but its after-tool pipeline failed with {failure}, so its \
415             result is withheld; do not call it again for this request."
416        ),
417    })
418}
419
420/// Builds the function response for a call that ran but whose result a [`ToolResultScreen`]
421/// withheld.
422///
423/// The response carries the screen's `reason` and, as [`result_withheld_response`] does, tells
424/// the model not to call the tool again, since its side effect already happened.
425///
426/// # Example
427///
428/// ```rust
429/// use adk_core::{RESULT_WITHHELD_STATUS, result_blocked_response};
430///
431/// let response = result_blocked_response("lookup", "guardrail 'pii' (High): names a patient");
432/// assert_eq!(response["status"], RESULT_WITHHELD_STATUS);
433/// assert!(response["error"].as_str().unwrap().contains("guardrail 'pii'"));
434/// ```
435pub fn result_blocked_response(tool_name: &str, reason: &str) -> Value {
436    json!({
437        "status": RESULT_WITHHELD_STATUS,
438        "error": format!(
439            "tool '{tool_name}' ran, but its result was withheld: {reason}; do not call it again for \
440             this request."
441        ),
442    })
443}
444
445/// Screens a tool's result before the model and the session see it.
446///
447/// An agent runs the screen on every result it is about to send to the model, after its own
448/// after-tool callbacks and plugins, so nothing reaches the provider or the stored tool event
449/// that the screen did not pass. `adk-guardrail`'s `ToolGuardrailSet` implements it, so the
450/// guardrails' `validate_result` checks apply wherever a screen is accepted.
451///
452/// A screen that cannot decide, because the service it relies on is down for example, returns
453/// `Err`, and the result is withheld: the agent fails closed.
454///
455/// # Example
456///
457/// ```rust
458/// use adk_core::{ToolResultScreen, async_trait};
459/// use serde_json::{Value, json};
460///
461/// /// Drops a `secret` field from every result.
462/// struct DropSecrets;
463///
464/// #[async_trait]
465/// impl ToolResultScreen for DropSecrets {
466///     async fn screen_result(&self, _tool: &str, _args: &Value, result: &Value) -> Result<Value, String> {
467///         let mut result = result.clone();
468///         if let Some(fields) = result.as_object_mut() {
469///             fields.remove("secret");
470///         }
471///         Ok(result)
472///     }
473/// }
474///
475/// # futures::executor::block_on(async {
476/// let screened = DropSecrets.screen_result("lookup", &json!({}), &json!({"id": 1, "secret": "s"})).await;
477/// assert_eq!(screened, Ok(json!({"id": 1})));
478/// # });
479/// ```
480#[async_trait]
481pub trait ToolResultScreen: Send + Sync {
482    /// Returns the result to deliver, possibly rewritten, or why it is withheld.
483    ///
484    /// `args` are the arguments the model sent for the call.
485    async fn screen_result(
486        &self,
487        tool_name: &str,
488        args: &Value,
489        result: &Value,
490    ) -> std::result::Result<Value, String>;
491}
492
493/// Runs `screen` on `result`, returning the result to deliver, or the
494/// [`result_blocked_response`] that replaces a withheld one.
495///
496/// # Example
497///
498/// ```rust
499/// use adk_core::{RESULT_WITHHELD_STATUS, ToolResultScreen, async_trait, screen_tool_result};
500/// use serde_json::{Value, json};
501///
502/// struct Unavailable;
503///
504/// #[async_trait]
505/// impl ToolResultScreen for Unavailable {
506///     async fn screen_result(&self, _: &str, _: &Value, _: &Value) -> Result<Value, String> {
507///         Err("the redaction service is unavailable".to_string())
508///     }
509/// }
510///
511/// # futures::executor::block_on(async {
512/// let delivered = screen_tool_result(&Unavailable, "lookup", &json!({}), json!({"ssn": "x"})).await;
513/// assert_eq!(delivered["status"], RESULT_WITHHELD_STATUS);
514/// # });
515/// ```
516pub async fn screen_tool_result(
517    screen: &dyn ToolResultScreen,
518    tool_name: &str,
519    args: &Value,
520    result: Value,
521) -> Value {
522    match screen.screen_result(tool_name, args, &result).await {
523        Ok(screened) => screened,
524        Err(reason) => {
525            // The reason can describe the result, so it goes to the model, not the log.
526            tracing::warn!(tool.name = %tool_name, "tool result withheld by its screen");
527            result_blocked_response(tool_name, &reason)
528        }
529    }
530}
531
532/// Builds the arguments of a function call whose arguments the model sent as something other
533/// than a JSON object, such as truncated or malformed JSON.
534///
535/// A provider adapter emits the call with these arguments instead of failing the turn, so the
536/// agent can answer the call with an error and the model can try again. The value is a JSON
537/// object, so every provider accepts the call when it is replayed in history. `raw` is kept up
538/// to 1 KiB.
539///
540/// # Example
541///
542/// ```rust
543/// use adk_core::{invalid_tool_arguments, invalid_tool_arguments_reason};
544///
545/// let args = invalid_tool_arguments("arguments are not valid JSON", r#"{"city": "Nair"#);
546/// assert_eq!(invalid_tool_arguments_reason(&args), Some("arguments are not valid JSON"));
547/// ```
548pub fn invalid_tool_arguments(reason: impl Into<String>, raw: &str) -> Value {
549    let mut end = raw.len().min(RAW_ARGUMENTS_MAX_BYTES);
550    while !raw.is_char_boundary(end) {
551        end -= 1;
552    }
553    json!({ INVALID_TOOL_ARGUMENTS_KEY: { "reason": reason.into(), "raw": &raw[..end] } })
554}
555
556/// Returns why the model's arguments could not be decoded, when `args` were built by
557/// [`invalid_tool_arguments`].
558///
559/// An agent answers such a call with an error and does not execute the tool.
560///
561/// # Example
562///
563/// ```rust
564/// use adk_core::invalid_tool_arguments_reason;
565/// use serde_json::json;
566///
567/// assert_eq!(invalid_tool_arguments_reason(&json!({ "city": "Nairobi" })), None);
568/// ```
569pub fn invalid_tool_arguments_reason(args: &Value) -> Option<&str> {
570    let fields = args.as_object().filter(|fields| fields.len() == 1)?;
571    fields.get(INVALID_TOOL_ARGUMENTS_KEY)?.get("reason")?.as_str()
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577    use crate::{ErrorCategory, ErrorComponent};
578
579    #[test]
580    fn permission_denials_keep_their_message() {
581        let err = AdkError::new(
582            ErrorComponent::Tool,
583            ErrorCategory::Forbidden,
584            TOOL_PERMISSION_DENIED_CODE,
585            "missing required scopes: [verified] (tool requires: [verified])",
586        );
587        assert_eq!(
588            tool_error_response("transfer", &err, false)["error"],
589            "tool 'transfer' failed: tool.forbidden (tool.permission_denied): missing required \
590             scopes: [verified] (tool requires: [verified])"
591        );
592    }
593
594    #[test]
595    fn a_rejection_keeps_its_message_bounded_and_a_failure_does_not() {
596        let refused = AdkError::new(
597            ErrorComponent::Tool,
598            ErrorCategory::Forbidden,
599            "harness.shell.protected",
600            ".git/hooks is a protected path; ask for approval",
601        );
602        assert_eq!(
603            tool_error_response("bash", &refused, false)["error"],
604            "tool 'bash' failed: tool.forbidden (harness.shell.protected): .git/hooks is a \
605             protected path; ask for approval"
606        );
607
608        let long = AdkError::new(
609            ErrorComponent::Tool,
610            ErrorCategory::InvalidInput,
611            "tool.path.outside_workspace",
612            "é".repeat(TOOL_ERROR_MESSAGE_LIMIT + 7),
613        );
614        let text =
615            tool_error_response("read_file", &long, false)["error"].as_str().unwrap().to_string();
616        let expected_head = "é".repeat(TOOL_ERROR_MESSAGE_LIMIT);
617        assert_eq!(
618            text,
619            format!(
620                "tool 'read_file' failed: tool.invalid_input (tool.path.outside_workspace): \
621                 {expected_head}… (truncated)"
622            )
623        );
624
625        for category in [
626            ErrorCategory::Unauthorized,
627            ErrorCategory::RateLimited,
628            ErrorCategory::Timeout,
629            ErrorCategory::Unavailable,
630            ErrorCategory::Cancelled,
631            ErrorCategory::Internal,
632        ] {
633            let failed = AdkError::new(ErrorComponent::Tool, category, "tool.x", "secret body");
634            assert_eq!(
635                tool_error_response("x", &failed, false)["error"],
636                format!("tool 'x' failed: tool.{category} (tool.x)"),
637                "{category} withholds its message"
638            );
639        }
640    }
641
642    #[test]
643    fn invalid_arguments_errors_keep_their_message() {
644        let err = AdkError::new(
645            ErrorComponent::Tool,
646            ErrorCategory::InvalidInput,
647            TOOL_INVALID_ARGUMENTS_CODE,
648            "missing field `city`",
649        );
650        assert_eq!(
651            tool_error_response("weather", &err, false),
652            json!({ "error": "tool.invalid_input: missing field `city`" })
653        );
654    }
655
656    #[test]
657    fn withheld_response_exposes_the_message_only_when_asked() {
658        let err = AdkError::agent("audit sink https://u:token@audit.internal unavailable");
659        let hidden = result_withheld_response("charge", &err, false);
660        assert_eq!(
661            hidden,
662            json!({
663                "status": RESULT_WITHHELD_STATUS,
664                "error": "tool 'charge' ran, but its after-tool pipeline failed with \
665                          agent.internal (agent.legacy), so its result is withheld; do not call \
666                          it again for this request.",
667            })
668        );
669        let shown = result_withheld_response("charge", &err, true);
670        assert!(shown["error"].as_str().unwrap().contains("audit.internal"));
671    }
672
673    #[test]
674    fn raw_arguments_are_capped_on_a_char_boundary() {
675        let raw = "é".repeat(RAW_ARGUMENTS_MAX_BYTES);
676        let args = invalid_tool_arguments("too long", &raw);
677        let kept = args[INVALID_TOOL_ARGUMENTS_KEY]["raw"].as_str().unwrap();
678        assert!(kept.len() <= RAW_ARGUMENTS_MAX_BYTES);
679        assert!(raw.starts_with(kept));
680    }
681
682    #[test]
683    fn only_the_marker_object_is_invalid_arguments() {
684        let args = invalid_tool_arguments("bad", "{");
685        assert_eq!(invalid_tool_arguments_reason(&args), Some("bad"));
686        let mut extended = args.clone();
687        extended["city"] = json!("Nairobi");
688        assert_eq!(invalid_tool_arguments_reason(&extended), None);
689        assert_eq!(invalid_tool_arguments_reason(&json!("{")), None);
690    }
691
692    fn response(annotations: Option<Value>) -> Part {
693        Part::FunctionResponse {
694            function_response: crate::FunctionResponseData::new(
695                "lookup",
696                json!({"error": "x", TOOL_RESULT_STATUS_KEY: "failed"}),
697            ),
698            id: Some("call-1".into()),
699            annotations,
700        }
701    }
702
703    #[test]
704    fn every_status_round_trips_through_the_annotation() {
705        for (encoded, status) in [
706            ("refused", ToolResultStatus::Refused),
707            ("not_run", ToolResultStatus::NotRun),
708            ("held", ToolResultStatus::Held),
709            ("failed", ToolResultStatus::Failed),
710            ("outcome_unknown", ToolResultStatus::OutcomeUnknown),
711            ("withheld", ToolResultStatus::Withheld),
712            ("succeeded", ToolResultStatus::Succeeded),
713        ] {
714            let mut part = response(None);
715            part.set_tool_result_status(status, None);
716            assert_eq!(part, response(Some(json!({ TOOL_RESULT_STATUS_KEY: encoded }))));
717            let decoded: Part =
718                serde_json::from_value(serde_json::to_value(&part).unwrap()).unwrap();
719            assert_eq!(decoded.tool_result_status(), Some(status));
720        }
721    }
722
723    #[test]
724    fn the_status_is_read_from_the_annotation_never_the_payload() {
725        assert_eq!(response(None).tool_result_status(), None);
726        assert_eq!(
727            response(Some(json!({ TOOL_RESULT_STATUS_KEY: "cancelled" }))).tool_result_status(),
728            None
729        );
730        let file = Part::FileData {
731            mime_type: "text/plain".into(),
732            file_uri: "https://example.test/a".into(),
733            annotations: Some(json!({ TOOL_RESULT_STATUS_KEY: "failed" })),
734        };
735        assert_eq!(file.tool_result_status(), None);
736    }
737
738    #[test]
739    fn setting_a_status_keeps_other_annotations_and_replaces_the_cause() {
740        let timeout =
741            AdkError::new(ErrorComponent::Tool, ErrorCategory::Timeout, "tool.timeout", "slow");
742        let mut part = response(Some(json!({ "priority": 1 })));
743        part.set_tool_result_status(ToolResultStatus::OutcomeUnknown, Some(&timeout));
744        assert_eq!(
745            part,
746            response(Some(json!({
747                "priority": 1,
748                TOOL_RESULT_STATUS_KEY: "outcome_unknown",
749                TOOL_RESULT_ERROR_CODE_KEY: "tool.timeout",
750                TOOL_RESULT_ERROR_CATEGORY_KEY: "timeout",
751            })))
752        );
753        assert_eq!(part.tool_result_error_code(), Some("tool.timeout"));
754        assert_eq!(part.tool_result_error_category(), Some(ErrorCategory::Timeout));
755
756        part.set_tool_result_status(ToolResultStatus::Withheld, None);
757        assert_eq!(
758            part,
759            response(Some(json!({ "priority": 1, TOOL_RESULT_STATUS_KEY: "withheld" })))
760        );
761
762        let mut odd = response(Some(json!("note")));
763        odd.set_tool_result_status(ToolResultStatus::Held, None);
764        assert_eq!(odd, response(Some(json!({ "value": "note", TOOL_RESULT_STATUS_KEY: "held" }))));
765    }
766
767    #[test]
768    fn a_ledger_record_maps_to_one_status() {
769        let cases = [
770            (
771                Some(ActionOutcome::Succeeded { result_digest: "d".into() }),
772                ToolResultStatus::Succeeded,
773            ),
774            (Some(ActionOutcome::Failed { error: "declined".into() }), ToolResultStatus::Failed),
775            (
776                Some(ActionOutcome::Failed {
777                    error: crate::not_run_text(&AdkError::agent("frozen")),
778                }),
779                ToolResultStatus::NotRun,
780            ),
781            (None, ToolResultStatus::OutcomeUnknown),
782        ];
783        for (outcome, status) in cases {
784            assert_eq!(ToolResultStatus::of_record(outcome.as_ref()), status, "{outcome:?}");
785        }
786    }
787
788    #[test]
789    fn withholding_keeps_what_is_known_about_whether_the_call_ran() {
790        use ToolResultStatus::*;
791        let cases = [
792            (Some(NotRun), true, NotRun),
793            (Some(Refused), true, Refused),
794            (Some(OutcomeUnknown), false, OutcomeUnknown),
795            (Some(Failed), false, Withheld),
796            (Some(Succeeded), false, Withheld),
797            (Some(Withheld), false, Withheld),
798            (Some(Held), false, NotRun),
799            (None, true, Withheld),
800            (None, false, NotRun),
801        ];
802        for (previous, executed, expected) in cases {
803            assert_eq!(
804                ToolResultStatus::when_withheld(previous, executed),
805                expected,
806                "{previous:?}, executed {executed}"
807            );
808        }
809        let errors: Vec<_> = [Refused, NotRun, Held, Failed, OutcomeUnknown, Withheld, Succeeded]
810            .into_iter()
811            .filter(|status| status.is_error())
812            .collect();
813        assert_eq!(errors, [Refused, NotRun, Failed]);
814    }
815}