Skip to main content

adk_agent/codeact/
output.rs

1//! The typed value a script returns to the host.
2//!
3//! A CodeAct script communicates its result by *returning a tagged value* (the
4//! runtime's completion value, decoded to JSON). The host classifies it into
5//! one of three outcomes:
6//!
7//! - [`ScriptOutput::Observation`] — fed back to the model for the next turn,
8//! - [`ScriptOutput::Error`] — fed back to the model (an opaque message string),
9//! - [`ScriptOutput::FinalResult`] — returned to the caller; ends the loop,
10//! - [`ScriptOutput::TransferToAgent`] — hands control to another agent; ends
11//!   the loop. Only offered to the model when transfer targets exist.
12//!
13//! Errors are just strings. The framework is language-agnostic: it does not
14//! model exception types, tracebacks, or "kinds". Whatever the runtime engine
15//! produces — a Python traceback, a JS stack, a shell error — is passed through
16//! verbatim, because that is what the LLM expects for that engine.
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21/// The typed value a CodeAct script must return.
22///
23/// Encoded as an internally tagged object keyed on `type`, e.g.
24/// `{"type": "final_result", "value": ...}`. This wire shape is
25/// language-agnostic; how a script *constructs* it is described to the model by
26/// the runtime (see [`RuntimeCapabilities::prompt`](crate::codeact::RuntimeCapabilities)).
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(tag = "type", rename_all = "snake_case")]
29pub enum ScriptOutput {
30    /// Intermediate information the model wants to inspect before continuing.
31    Observation {
32        /// Arbitrary JSON payload surfaced back to the model.
33        value: Value,
34    },
35    /// An error the model should react to. Just a message string.
36    Error {
37        /// The error text, in whatever form the model expects.
38        message: String,
39    },
40    /// The terminal answer. Ends the CodeAct loop.
41    FinalResult {
42        /// Arbitrary JSON payload returned to the caller.
43        value: Value,
44    },
45    /// Hand control to another agent (a sub-agent, or a target the Runner
46    /// supplied via `RunConfig::transfer_targets`). Ends this agent's loop; the
47    /// named agent takes over, exactly as a [`LlmAgent`](crate::LlmAgent)
48    /// `transfer_to_agent` call would.
49    ///
50    /// This variant is only described to the model when transfer targets are
51    /// available. If the model emits it with an unknown target, the host feeds
52    /// the error back instead of transferring.
53    TransferToAgent {
54        /// The name of the agent to transfer control to.
55        agent_name: String,
56    },
57}
58
59impl ScriptOutput {
60    /// Decode a completed script's returned value into a [`ScriptOutput`].
61    ///
62    /// A value that does not conform to the tagged contract becomes an
63    /// [`ScriptOutput::Error`] telling the model to return a proper value next
64    /// turn, rather than crashing the run.
65    ///
66    /// # Example
67    ///
68    /// ```
69    /// use adk_agent::codeact::ScriptOutput;
70    /// use serde_json::json;
71    ///
72    /// let out = ScriptOutput::decode(json!({"type": "final_result", "value": 42}));
73    /// assert!(matches!(out, ScriptOutput::FinalResult { .. }));
74    /// ```
75    pub fn decode(value: Value) -> Self {
76        match serde_json::from_value::<ScriptOutput>(value.clone()) {
77            Ok(output) => output,
78            Err(err) => ScriptOutput::Error {
79                message: format!(
80                    "script must return an observation/error/final_result value; got {value} ({err})"
81                ),
82            },
83        }
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90    use serde_json::json;
91
92    #[test]
93    fn script_output_round_trips() {
94        let cases = [
95            ScriptOutput::Observation { value: json!({"rows": 3}) },
96            ScriptOutput::FinalResult { value: json!("done") },
97            ScriptOutput::Error { message: "boom".to_string() },
98            ScriptOutput::TransferToAgent { agent_name: "billing".to_string() },
99        ];
100        for case in cases {
101            let encoded = serde_json::to_value(&case).unwrap();
102            let decoded: ScriptOutput = serde_json::from_value(encoded).unwrap();
103            assert_eq!(case, decoded);
104        }
105    }
106
107    #[test]
108    fn final_result_wire_shape_is_tagged() {
109        let encoded = serde_json::to_value(ScriptOutput::FinalResult { value: json!(7) }).unwrap();
110        assert_eq!(encoded, json!({"type": "final_result", "value": 7}));
111    }
112
113    #[test]
114    fn transfer_wire_shape_is_tagged() {
115        let encoded = serde_json::to_value(ScriptOutput::TransferToAgent {
116            agent_name: "billing".to_string(),
117        })
118        .unwrap();
119        assert_eq!(encoded, json!({"type": "transfer_to_agent", "agent_name": "billing"}));
120    }
121
122    #[test]
123    fn decode_rejects_non_variant() {
124        let out = ScriptOutput::decode(json!({"not": "a variant"}));
125        assert!(matches!(out, ScriptOutput::Error { .. }));
126    }
127}