adk_agent/codeact/runtime.rs
1//! The step-wise interpreter seam — language-agnostic.
2//!
3//! The CodeAct driver does not depend on any concrete interpreter or language.
4//! It drives a [`CodeRuntime`]: start a script, and on each external-function
5//! call decide whether to resume with a value, resume by raising an error, or
6//! suspend (serialize the continuation and stop).
7//!
8//! # Errors: script vs. host
9//!
10//! Two error channels, kept deliberately distinct:
11//!
12//! - **Script errors** — anything the *model* should see and react to (a syntax
13//! error, an uncaught exception, a resource-limit cancellation) are
14//! [`RunStep::Raised`]: an opaque string the runtime renders however its
15//! language expects (a Python traceback, a JS stack, a shell error). The
16//! framework never inspects them; they are fed back to the model verbatim and
17//! the run continues. **Returning `Ok(RunStep::Raised(..))` is always the right
18//! move for a model mistake — including a parse/compile failure.**
19//! - **Host failures** — genuine interpreter/host breakage that should abort the
20//! run (snapshot (de)serialization failure, an internal interpreter error) are
21//! [`RuntimeError`].
22//!
23//! When in doubt: if the model could fix it by writing different code, it is a
24//! [`RunStep::Raised`], not a [`RuntimeError`].
25//!
26//! # Async note
27//!
28//! Advancing the interpreter (`resume`) is synchronous and fast. Tool execution
29//! (which produces the value passed to `resume`) is async and happens in the
30//! driver *between* steps, so this trait stays synchronous.
31//!
32//! # Sequential by design
33//!
34//! The seam is a *single continuation*: [`RunStep::Call`] surfaces exactly one
35//! pending call, and [`PendingCall::resume`] consumes it and yields the next
36//! single step. Tool execution is therefore strictly sequential, even if the
37//! script's language supports `async`/threads — a concurrency-capable runtime
38//! must serialize script-level parallelism at the call boundary.
39//!
40//! This is deliberate: durability rests on snapshotting *one* continuation at
41//! *one* call boundary (see [`PendingCall::dump`]). Multiple in-flight calls
42//! would force a checkpoint to capture partial completion (e.g. a long-running
43//! tool inside an `asyncio.gather` alongside two finished tools), which has no
44//! clean suspend/resume semantics. Concurrent host dispatch would require a
45//! different seam (e.g. a multi-call step) and is intentionally out of scope.
46
47use std::sync::Arc;
48
49use adk_core::Tool;
50use serde_json::{Map, Value};
51use thiserror::Error;
52
53/// A host-level failure of the runtime itself (not a script-level error).
54///
55/// Script errors — including syntax/parse failures — are modelled as
56/// [`RunStep::Raised`] (an opaque string fed back to the model). This type is
57/// reserved for genuine interpreter/host failures that should abort the run:
58/// snapshot (de)serialization failure or an internal interpreter error.
59#[derive(Debug, Error)]
60pub enum RuntimeError {
61 /// A snapshot could not be serialized or restored.
62 #[error("snapshot error: {0}")]
63 Snapshot(String),
64 /// The interpreter failed for an internal reason.
65 #[error("interpreter error: {0}")]
66 Internal(String),
67}
68
69/// How to resume a paused external-function call.
70#[derive(Debug, Clone)]
71pub enum ResumeWith {
72 /// Return this value from the external function back into the script.
73 Value(Value),
74 /// Raise an error inside the script at the call site, with this message.
75 ///
76 /// The runtime represents it in its own language (an exception, a thrown
77 /// value, etc.). If the script does not catch it, it propagates and the
78 /// runtime surfaces it as [`RunStep::Raised`].
79 Raise(String),
80}
81
82/// The result of advancing the interpreter to its next host-relevant stop.
83///
84/// Every variant carries the `stdout` (e.g. `print`) the script produced *since
85/// the previous step*. Runtimes that capture output attach it (see
86/// [`RunStep::with_stdout`]); those that don't leave it empty. The driver
87/// surfaces captured output back to the model so it can see what its code
88/// printed. Construct values with [`RunStep::call`], [`RunStep::complete`], and
89/// [`RunStep::raised`].
90pub enum RunStep {
91 /// The script called an external function (a tool). Resume it to continue.
92 Call {
93 /// The paused external-function call.
94 call: Box<dyn PendingCall>,
95 /// Output the script produced since the previous step (empty if none or
96 /// if the runtime does not capture output).
97 stdout: String,
98 },
99 /// The script ran to completion; carries the returned value (decoded to JSON).
100 Complete {
101 /// The value the script returned, decoded to JSON.
102 value: Value,
103 /// Output the script produced since the previous step.
104 stdout: String,
105 },
106 /// The script failed: an error propagated to the top. The message is the
107 /// runtime's native error rendering, fed back to the model verbatim. This
108 /// also covers resource-limit cancellations and parse/compile failures — the
109 /// framework does not care which; the message says so.
110 Raised {
111 /// The runtime's native error rendering.
112 message: String,
113 /// Output the script produced before the error.
114 stdout: String,
115 },
116}
117
118impl RunStep {
119 /// A tool-call step with no captured output.
120 #[must_use]
121 pub fn call(call: Box<dyn PendingCall>) -> Self {
122 Self::Call { call, stdout: String::new() }
123 }
124
125 /// A completion step with no captured output.
126 #[must_use]
127 pub fn complete(value: Value) -> Self {
128 Self::Complete { value, stdout: String::new() }
129 }
130
131 /// A script-error step with no captured output.
132 #[must_use]
133 pub fn raised(message: impl Into<String>) -> Self {
134 Self::Raised { message: message.into(), stdout: String::new() }
135 }
136
137 /// Attach captured `stdout` to this step (builder-style).
138 ///
139 /// # Example
140 ///
141 /// ```
142 /// use adk_agent::codeact::RunStep;
143 /// use serde_json::json;
144 ///
145 /// let step = RunStep::complete(json!({"type": "final_result", "value": 1}))
146 /// .with_stdout("hello\n");
147 /// ```
148 #[must_use]
149 pub fn with_stdout(mut self, stdout: impl Into<String>) -> Self {
150 let slot = match &mut self {
151 Self::Call { stdout, .. } => stdout,
152 Self::Complete { stdout, .. } => stdout,
153 Self::Raised { stdout, .. } => stdout,
154 };
155 *slot = stdout.into();
156 self
157 }
158}
159
160impl std::fmt::Debug for RunStep {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 match self {
163 Self::Call { call, stdout } => f
164 .debug_struct("Call")
165 .field("function_name", &call.function_name())
166 .field("call_id", &call.call_id())
167 .field("stdout", stdout)
168 .finish(),
169 Self::Complete { value, stdout } => {
170 f.debug_struct("Complete").field("value", value).field("stdout", stdout).finish()
171 }
172 Self::Raised { message, stdout } => {
173 f.debug_struct("Raised").field("message", message).field("stdout", stdout).finish()
174 }
175 }
176 }
177}
178
179/// A paused external-function call awaiting a result.
180///
181/// It can be resumed exactly once (consuming it), or its continuation can be
182/// serialized with [`dump`](Self::dump) for suspend-to-store before resuming.
183///
184/// # Arguments
185///
186/// A call exposes its arguments the way an interpreter actually produces them —
187/// [`positional_args`](Self::positional_args) and
188/// [`keyword_args`](Self::keyword_args), separately. The driver binds them onto
189/// the tool's parameter names (via [`bind_call_args`]) before invoking the tool,
190/// so a runtime never needs the tool's schema to name positional arguments. A
191/// runtime whose language has only keyword arguments returns an empty positional
192/// slice; one with only positional arguments returns an empty keyword slice.
193pub trait PendingCall: Send {
194 /// The name of the external function (tool) the script called.
195 fn function_name(&self) -> &str;
196 /// The positional arguments, in call order, marshalled to JSON.
197 fn positional_args(&self) -> &[Value];
198 /// The keyword arguments, in call order, marshalled to JSON.
199 fn keyword_args(&self) -> &[(String, Value)];
200 /// The interpreter-assigned unique id for this call.
201 fn call_id(&self) -> u64;
202 /// Serialize the suspended continuation to bytes (valid while paused here).
203 ///
204 /// The returned bytes can later be passed to [`CodeRuntime::resume`].
205 fn dump(&self) -> Result<Vec<u8>, RuntimeError>;
206 /// Resume execution, consuming this call. Advances to the next [`RunStep`].
207 fn resume(self: Box<Self>, with: ResumeWith) -> Result<RunStep, RuntimeError>;
208}
209
210/// A step-wise, language-agnostic code interpreter capable of suspend/resume at
211/// call boundaries.
212pub trait CodeRuntime: Send + Sync {
213 /// Parse and begin executing `script`, running until the first external
214 /// call, completion, or error.
215 ///
216 /// `script_name` is used by the runtime for error messages (e.g. a
217 /// traceback filename). A parse/compile failure is a *model* mistake and
218 /// should be returned as `Ok(`[`RunStep::Raised`]`)`, not as a
219 /// [`RuntimeError`].
220 fn start(&self, script: &str, script_name: &str) -> Result<RunStep, RuntimeError>;
221
222 /// Restore a suspended continuation (from [`PendingCall::dump`]) and resume
223 /// it with the given value or error.
224 ///
225 /// Used on a later turn to resume after a human confirmation decision or a
226 /// long-running tool completion. Interpreter-captured callbacks (e.g. a
227 /// stdout sink) are not serialized and must be re-attached by the adapter.
228 fn resume(&self, snapshot: &[u8], with: ResumeWith) -> Result<RunStep, RuntimeError>;
229
230 /// Report what this runtime can do and which language/environment it
231 /// accepts.
232 ///
233 /// The default assumes a fully capable runtime with an empty prompt;
234 /// concrete adapters override this to describe their real environment.
235 fn capabilities(&self) -> RuntimeCapabilities {
236 RuntimeCapabilities::default()
237 }
238
239 /// Render the tool catalog for the system prompt, in this runtime's language
240 /// and conventions.
241 ///
242 /// How a tool is *named and called* is language-dependent, so the runtime
243 /// owns this rendering. This is a **pure function of `tools`** — called once
244 /// per invocation purely to produce prompt text. A runtime does not need to
245 /// remember anything from it: argument binding is handled centrally by the
246 /// driver (see [`bind_call_args`]), so there is no need to stash schemas or
247 /// parameter orderings here.
248 ///
249 /// The default emits a generic, language-neutral listing via
250 /// [`default_tool_catalog`]; a language-specific runtime (e.g. a Python
251 /// runtime) overrides this to emit idiomatic signatures or stubs the model
252 /// should call. Returns an empty string when there are no tools.
253 fn render_tools(&self, tools: &[Arc<dyn Tool>]) -> String {
254 let catalog = default_tool_catalog(tools);
255 if catalog.trim().is_empty() {
256 return String::new();
257 }
258 format!("Available tools:\n{catalog}")
259 }
260}
261
262/// Bind a call's positional and keyword arguments onto a tool's parameters,
263/// producing the single JSON object a [`Tool`] expects.
264///
265/// This is the *one* place positional arguments are mapped onto names, so no
266/// runtime needs the tool's schema at the call boundary. Keyword arguments are
267/// inserted by name; positional arguments are matched, in order, against the
268/// tool's parameter names (the schema's `required` list first, then any
269/// remaining `properties`). A positional argument with no corresponding name
270/// (or for a tool with no schema) falls back to `arg0`, `arg1`, ... so nothing
271/// is silently dropped. A keyword always wins over a positional for the same
272/// name.
273///
274/// # Example
275///
276/// ```
277/// use std::sync::Arc;
278/// use adk_agent::codeact::bind_call_args;
279/// # use adk_core::{Tool, ToolContext};
280/// # use async_trait::async_trait;
281/// use serde_json::{json, Value};
282///
283/// # struct Add;
284/// # #[async_trait]
285/// # impl Tool for Add {
286/// # fn name(&self) -> &str { "add" }
287/// # fn description(&self) -> &str { "add" }
288/// # fn parameters_schema(&self) -> Option<Value> {
289/// # Some(json!({"type": "object", "properties": {"a": {}, "b": {}}, "required": ["a", "b"]}))
290/// # }
291/// # async fn execute(&self, _c: Arc<dyn ToolContext>, _a: Value) -> adk_core::Result<Value> { Ok(Value::Null) }
292/// # }
293/// let tool = Add;
294/// let bound = bind_call_args(&tool, &[json!(1), json!(2)], &[]);
295/// assert_eq!(bound, json!({"a": 1, "b": 2}));
296/// ```
297pub fn bind_call_args(tool: &dyn Tool, positional: &[Value], keyword: &[(String, Value)]) -> Value {
298 let mut map = Map::new();
299 for (name, value) in keyword {
300 map.insert(name.clone(), value.clone());
301 }
302 if !positional.is_empty() {
303 let names = ordered_parameter_names(tool);
304 for (index, value) in positional.iter().enumerate() {
305 let key = names.get(index).cloned().unwrap_or_else(|| format!("arg{index}"));
306 map.entry(key).or_insert_with(|| value.clone());
307 }
308 }
309 Value::Object(map)
310}
311
312/// The tool's parameter names in positional order: `required` (ordered) first,
313/// then any remaining `properties` keys.
314fn ordered_parameter_names(tool: &dyn Tool) -> Vec<String> {
315 let Some(schema) = tool.parameters_schema() else {
316 return Vec::new();
317 };
318 let required: Vec<String> = schema
319 .get("required")
320 .and_then(Value::as_array)
321 .map(|arr| arr.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
322 .unwrap_or_default();
323 let mut ordered = required.clone();
324 if let Some(props) = schema.get("properties").and_then(Value::as_object) {
325 for key in props.keys() {
326 if !ordered.contains(key) {
327 ordered.push(key.clone());
328 }
329 }
330 }
331 ordered
332}
333
334/// A generic, language-neutral tool listing.
335///
336/// Rendering branches on the kind of tool:
337///
338/// - **Built-in tools** ([`Tool::is_builtin`]) are executed server-side by the
339/// model provider and cannot be invoked from scripted code, so they are
340/// omitted entirely.
341/// - **Long-running tools** ([`Tool::is_long_running`]) are annotated, since
342/// their result arrives out-of-band.
343///
344/// Each remaining tool is listed as one line with its parameter names and
345/// description. Runtimes may build on this for their own
346/// [`CodeRuntime::render_tools`].
347pub fn default_tool_catalog(tools: &[Arc<dyn Tool>]) -> String {
348 let mut out = String::new();
349 for tool in tools {
350 // Built-in (server-side) tools are not callable from a script.
351 if tool.is_builtin() {
352 continue;
353 }
354 let decl = tool.declaration();
355 let params = decl
356 .get("parameters")
357 .and_then(|p| p.get("properties"))
358 .and_then(|p| p.as_object())
359 .map(|props| props.keys().cloned().collect::<Vec<_>>().join(", "))
360 .unwrap_or_default();
361 let annotation = if tool.is_long_running() { " [long-running]" } else { "" };
362 out.push_str(&format!(
363 "- {}({}): {}{}\n",
364 tool.name(),
365 params,
366 tool.description(),
367 annotation
368 ));
369 }
370 out
371}
372
373/// What a [`CodeRuntime`] reports about itself.
374///
375/// [`prompt`](Self::prompt) is freeform text the runtime supplies describing its
376/// language and environment (e.g. "you are writing Python for the Monty
377/// interpreter; no `class`/`match`; stdlib limited to ..."); the agent injects
378/// it verbatim into the system prompt so the model knows what code it may write.
379/// There is no fixed schema on purpose.
380#[derive(Debug, Clone, Default)]
381pub struct RuntimeCapabilities {
382 /// Whether the runtime can serialize a paused continuation and resume it.
383 ///
384 /// Required for HITL confirmation and long-running tool deferral. When
385 /// `false`, the agent warns that those features cannot pause execution.
386 pub supports_suspension: bool,
387 /// Freeform description of the runtime/language environment for the model.
388 pub prompt: String,
389}
390
391impl RuntimeCapabilities {
392 /// Construct capabilities from a suspension flag and a prompt description.
393 pub fn new(supports_suspension: bool, prompt: impl Into<String>) -> Self {
394 Self { supports_suspension, prompt: prompt.into() }
395 }
396}
397
398#[cfg(test)]
399mod tests {
400 use super::*;
401
402 #[test]
403 fn default_capabilities_do_not_claim_suspension() {
404 // Default is conservative: a runtime must opt in to suspension.
405 assert!(!RuntimeCapabilities::default().supports_suspension);
406 assert!(RuntimeCapabilities::default().prompt.is_empty());
407 }
408
409 #[test]
410 fn new_carries_prompt_and_flag() {
411 let caps = RuntimeCapabilities::new(true, "Monty: no class/match");
412 assert!(caps.supports_suspension);
413 assert_eq!(caps.prompt, "Monty: no class/match");
414 }
415
416 #[test]
417 fn default_catalog_lists_function_tools() {
418 let catalog = default_tool_catalog(&[crate::codeact::test_support::echo_tool()]);
419 assert!(catalog.contains("echo"));
420 assert!(catalog.contains("echoes its arguments"));
421 }
422
423 #[test]
424 fn default_catalog_omits_builtin_tools() {
425 use crate::codeact::test_support::{builtin_tool, echo_tool};
426 let catalog = default_tool_catalog(&[echo_tool(), builtin_tool()]);
427 assert!(catalog.contains("echo"));
428 assert!(!catalog.contains("web_search"));
429 }
430
431 #[test]
432 fn default_catalog_annotates_long_running() {
433 let catalog = default_tool_catalog(&[crate::codeact::test_support::long_running_tool()]);
434 assert!(catalog.contains("slow"));
435 assert!(catalog.contains("[long-running]"));
436 }
437
438 #[test]
439 fn render_tools_empty_when_only_builtin_or_none() {
440 use crate::codeact::test_support::{ScriptedRuntime, builtin_tool, echo_tool};
441 let rt = ScriptedRuntime::new(vec![]);
442 assert!(rt.render_tools(&[]).is_empty());
443 // A roster of only server-side tools yields no callable catalog.
444 assert!(rt.render_tools(&[builtin_tool()]).is_empty());
445 assert!(rt.render_tools(&[echo_tool()]).starts_with("Available tools:"));
446 }
447
448 #[test]
449 fn bind_call_args_maps_positional_and_prefers_keyword() {
450 use crate::codeact::test_support::echo_tool;
451 use serde_json::json;
452 // echo_tool's schema has no parameters, so positional args fall back to
453 // arg0/arg1; keyword args bind by name.
454 let tool = echo_tool();
455 let bound =
456 bind_call_args(tool.as_ref(), &[json!(1)], &[("label".to_string(), json!("x"))]);
457 assert_eq!(bound, json!({"arg0": 1, "label": "x"}));
458 }
459
460 #[test]
461 fn run_step_constructors_and_with_stdout() {
462 use serde_json::json;
463 let step = RunStep::complete(json!(1)).with_stdout("hi");
464 match step {
465 RunStep::Complete { value, stdout } => {
466 assert_eq!(value, json!(1));
467 assert_eq!(stdout, "hi");
468 }
469 other => panic!("expected Complete, got {other:?}"),
470 }
471 }
472}