adk_agent/codeact/mod.rs
1//! A CodeAct agent: a peer to [`LlmAgent`](crate::LlmAgent) that acts by writing
2//! and executing code instead of emitting one tool call at a time.
3//!
4//! The framework is language-agnostic — the [`CodeRuntime`] defines the language
5//! (Python via Monty, JavaScript, a shell, ...) and reports it to the agent.
6//!
7//! # The loop
8//!
9//! Each turn, the model produces one code script. Tools are exposed as functions
10//! the model can call and compose. The script communicates its result by
11//! *returning a tagged value* — a [`ScriptOutput`] variant — which the host
12//! classifies:
13//!
14//! - [`ScriptOutput::Observation`] is fed back to the model for the next turn,
15//! - [`ScriptOutput::Error`] is fed back as an opaque message string,
16//! - [`ScriptOutput::FinalResult`] ends the loop and is returned to the caller,
17//! and
18//! - [`ScriptOutput::TransferToAgent`] ends the loop and hands control to
19//! another agent.
20//!
21//! Errors are just strings produced by the runtime in whatever form the model
22//! expects (a traceback, a stack, ...); any error consumes a model turn. When a
23//! tool fails, that surfaces as an error raised into the script.
24//!
25//! # Transfer to another agent
26//!
27//! Like [`LlmAgent`](crate::LlmAgent), a `CodeActAgent` can hand control to a
28//! sub-agent or to a peer/parent the Runner supplies via
29//! `RunConfig::transfer_targets`. The transfer output is only described to the
30//! model when at least one target exists; a transfer emits an event carrying
31//! [`EventActions::transfer_to_agent`](adk_core::EventActions::transfer_to_agent)
32//! and ends the run, exactly as the LlmAgent's `transfer_to_agent` tool does. An
33//! unknown target is fed back to the model as an error instead of transferring.
34//!
35//! # Deferred tool calls (HITL and long-running)
36//!
37//! The script never decides to suspend. The *host* defers a tool call when it
38//! cannot resolve inline:
39//!
40//! - a confirmation-gated tool with no decision yet, or
41//! - a [long-running](adk_core::Tool::is_long_running) tool whose result arrives
42//! out-of-band.
43//!
44//! In both cases the agent serializes the live interpreter continuation into a
45//! [`CodeActCheckpoint`] and writes it to **session state** (via an event's
46//! `state_delta`), then ends the run — exactly the "save to session, rebuild,
47//! continue" model of [`LlmAgent`](crate::LlmAgent). On the next invocation
48//! [`Agent::run`](adk_core::Agent::run) reads the checkpoint back and resumes:
49//! the confirmation decision arrives via `RunConfig::tool_confirmation_decisions`,
50//! and a long-running result arrives as a `FunctionResponse` in the new message.
51//! There is no out-of-band resume API and no side store — the Runner re-invokes
52//! `run()` and the agent self-routes.
53//!
54//! This requires a runtime that can snapshot/resume. A runtime that cannot runs
55//! long-running tools inline and rejects confirmation pauses.
56//!
57//! A held call without a decision is not put to the run's
58//! [`ToolConfirmationHandler`](adk_core::ToolConfirmationHandler) again once it waits
59//! in the run's approval store, for example after the handler timed out: it resumes
60//! only on a decision recorded for it (spec 3.3 §7.3), checked under the arguments it
61//! was held with, after plugin and screen rewrites. A run that brings a new
62//! message while the call waits answers it in a turn of its own, which cannot
63//! suspend and keeps the waiting call's checkpoint in session state; a call in that
64//! turn that needs a decision is refused into the script and withdrawn
65//! ([`withdraw_held_call`](adk_core::withdraw_held_call)), since only one call waits
66//! at a time (§7.4). An identical call that turn decides answers the waiting call,
67//! whose checkpoint is then cleared. A run that resumes the call on its decision adds
68//! the message it brought to the transcript, and every checkpoint after it, so the next
69//! model request carries it — also when the resumed script finishes, or first stops at
70//! another call that needs a decision. A runtime that cannot pause leaves no call waiting.
71//!
72//! # Tool side effects
73//!
74//! Like [`LlmAgent`](crate::LlmAgent), tool-produced session changes are
75//! propagated: any `state_delta`/`artifact_delta`/`route` a tool sets on its
76//! [`ToolContext`](adk_core::ToolContext) is merged onto the next persisted
77//! event (a checkpoint, or the final event when the runtime cannot checkpoint),
78//! and a tool that sets `escalate`, `skip_summarization`, or `transfer_to_agent`
79//! ends the run immediately, forwarding that signal to the Runner. This is what
80//! lets an [`AgentTool`](https://docs.rs/adk-tool) wrapping a sub-agent forward
81//! that sub-agent's state back to the session.
82//!
83//! Each tool call runs against a fresh per-call
84//! [`ToolContext`](adk_core::ToolContext) that carries the interpreter's call id
85//! and otherwise delegates artifacts, memory, shared state, user scopes, and
86//! secrets to the live invocation — so a tool behaves identically whether it is
87//! driven by a `CodeActAgent` or an `LlmAgent`.
88//!
89//! # Capabilities (parity with [`LlmAgent`](crate::LlmAgent))
90//!
91//! A `CodeActAgent` mirrors `LlmAgent`'s configuration surface, differing only
92//! where the CodeAct loop demands it:
93//!
94//! - **Model**: `generate_content_config` plus `temperature`/`top_p`/`top_k`/
95//! `max_output_tokens` shorthands.
96//! - **Instructions** (assembled per invocation): `instruction` and
97//! `instruction_provider`, `global_instruction` (+ provider), with session
98//! state placeholders (`{key}`, `{key?}`, `{app:key}`, `{artifact.name}`) in
99//! the static instructions; the selected skill block, when a skills index is
100//! configured (`skills` feature).
101//! - **History**: `include_contents` controls how much session history seeds
102//! the transcript.
103//! - **Tools**: static tools plus per-invocation `toolset`s; `tool_timeout`,
104//! `default_retry_budget`/`tool_retry_budget`, `circuit_breaker_threshold`,
105//! and `on_tool_error` fallbacks.
106//! - **Confirmation & transfer**: `ToolConfirmationPolicy`, sub-agents and the
107//! `disallow_transfer_to_parent`/`disallow_transfer_to_peers` flags.
108//! - **Output**: `output_key`, and `output_schema`/`output_type` validated with
109//! a correction-retry loop (`output_max_retries`).
110//! - **Lifecycle & interception hooks**: before/after-agent callbacks
111//! (after-agent runs on normal completion, not on suspension, transfer, or
112//! escalation), before/after-model callbacks (rewrite or short-circuit the
113//! model call), and before/after-tool callbacks plus the rich
114//! `after_tool_callback_full` (rewrite or short-circuit a tool call).
115//! - **Feature-gated**: input/output guardrails (`guardrails`), skills
116//! (`skills`), and the `EnhancedPlugin` pipeline intercepting tool and model
117//! calls (`enhanced-plugins`).
118//!
119//! Deliberate non-matches: code-execution sandboxing is the [`CodeRuntime`]'s
120//! responsibility (not a bolt-on); tool dispatch is sequential by design (see
121//! [`runtime`]), so there is no `tool_execution_strategy`/concurrency knob; and
122//! the agent has no `skip_summarization` *builder* option — the model ends the
123//! loop itself via [`ScriptOutput::FinalResult`] — though a tool that sets
124//! `skip_summarization` on its actions still ends the run.
125//!
126//! # Runtime
127//!
128//! Execution runs on a [`CodeRuntime`], the step-wise interpreter seam. The
129//! production adapter wraps [Monty](https://github.com/pydantic/monty), a
130//! Rust-native Python interpreter whose snapshot-at-call-boundary model makes
131//! suspend/resume a true continuation rather than a replay. It lives in the
132//! `adk-codeact-monty` crate.
133
134pub mod agent;
135pub mod checkpoint;
136pub mod error_map;
137pub mod output;
138pub mod runtime;
139
140#[cfg(test)]
141pub(crate) mod test_support;
142
143pub use agent::{
144 CODEACT_SYSTEM_PROMPT, CodeActAgent, CodeActAgentBuilder, DEFAULT_MAX_ERROR_CHARS,
145 DEFAULT_MAX_ITERATIONS, ToolMap, build_tool_map, extract_code_block,
146};
147pub use checkpoint::{CodeActCheckpoint, Disposition, PENDING_STATE_KEY, PendingToolCall};
148pub use error_map::{denied_message, tool_error_message, unknown_tool_message};
149pub use output::ScriptOutput;
150pub use runtime::{
151 CodeRuntime, PendingCall, ResumeWith, RunStep, RuntimeCapabilities, RuntimeError,
152 bind_call_args, default_tool_catalog,
153};