Skip to main content

adk_agent/codeact/
agent.rs

1//! The [`CodeActAgent`] and its streaming loop.
2//!
3//! A peer to [`LlmAgent`](crate::LlmAgent), stateless across invocations: the
4//! Runner calls [`Agent::run`], durable state lives in the **Session**.
5//!
6//! Durability mirrors LlmAgent's per-tool event persistence. The loop is a
7//! stream that yields a checkpoint event **before** and **after** every inline
8//! tool call (a write-ahead log written to session state via `state_delta`):
9//!
10//! - **before** ([`Disposition::PendingResult`]): if the process crashes during
11//!   the tool, recovery re-runs the call. With `RunConfig::action_ledger` set, a
12//!   non-idempotent call keeps its idempotency key on recovery, so the ledger
13//!   answers it instead of executing it again;
14//! - **after** ([`Disposition::Resolved`]): once the tool has returned, recovery
15//!   resumes with the stored result and never re-runs the tool.
16//!
17//! Deferred calls suspend to session state too:
18//! [`Disposition::AwaitingConfirmation`] (decision via
19//! `RunConfig::tool_confirmation_decisions`) and
20//! [`Disposition::AwaitingCompletion`] (result via a `FunctionResponse` in the
21//! next message). On the next invocation `run()` reads the checkpoint back and
22//! resumes. This needs a runtime that can snapshot/resume; one that can't runs
23//! long-running tools inline and persists nothing.
24
25use std::collections::HashMap;
26use std::sync::{Arc, Mutex};
27use std::time::Duration;
28
29use adk_core::{
30    AdkError, AfterAgentCallback, AfterModelCallback, AfterToolCallback, AfterToolCallbackFull,
31    Agent, Artifacts, BeforeAgentCallback, BeforeModelCallback, BeforeModelResult,
32    BeforeToolCallback, CallbackContext, Content, ErrorCategory, ErrorComponent, Event,
33    EventActions, EventStream, GenerateContentConfig, GlobalInstructionProvider, GovernedCall,
34    GroundingSource, IncludeContents, InstructionProvider, InvocationContext, Llm, LlmRequest,
35    LlmResponse, MemoryEntry, OnToolErrorCallback, Part, ReadonlyContext, RetryBudget, SharedState,
36    Tool, ToolAuthorization, ToolCallbackContext, ToolConfirmationDecision, ToolConfirmationPolicy,
37    ToolConfirmationRequest, ToolContext, ToolEffect, ToolGate, ToolOutcome, ToolResultStatus,
38    Toolset, authorize_tool_call,
39};
40use async_stream::stream;
41use async_trait::async_trait;
42use futures::{Stream, StreamExt};
43use serde_json::Value;
44
45use crate::codeact::checkpoint::{
46    CodeActCheckpoint, Disposition, PENDING_STATE_KEY, PendingToolCall, ResolutionRecord,
47};
48use crate::codeact::error_map::{
49    denied_message, render_value, tool_error_message, unknown_tool_message,
50};
51use crate::codeact::output::ScriptOutput;
52use crate::codeact::runtime::{CodeRuntime, ResumeWith, RunStep, RuntimeError, bind_call_args};
53use crate::grounding::answer_citations;
54use crate::guardrails::{Grounding, GuardrailSet, Phase, enforce_final_output, enforce_guardrails};
55use crate::invocation_hooks::HookCallbacks;
56use crate::skill_shim::{SelectionPolicy, SkillIndex, select_skill_prompt_block};
57#[cfg(feature = "enhanced-plugins")]
58use adk_plugin::{
59    AfterModelCallResult, AfterToolCallResult, BeforeModelCallResult, BeforeToolCallResult,
60    EnhancedPlugin, EnhancedPluginManager,
61};
62
63/// Default number of model turns before the loop gives up.
64pub const DEFAULT_MAX_ITERATIONS: u32 = 12;
65
66/// Default cap (in chars) on an error message fed back to the model.
67pub const DEFAULT_MAX_ERROR_CHARS: usize = 4000;
68
69/// Default per-tool execution timeout (5 minutes), matching `LlmAgent`.
70pub const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(300);
71
72/// Default number of correction retries for output-schema validation.
73pub const DEFAULT_OUTPUT_MAX_RETRIES: usize = 3;
74
75/// Default cap (in chars) on injected skill content.
76pub const DEFAULT_MAX_SKILL_CHARS: usize = 2000;
77
78/// The default, language-agnostic CodeAct system prompt.
79pub const CODEACT_SYSTEM_PROMPT: &str = "\
80You act by writing code. Each turn, emit exactly ONE code block in the language
81described below. Tools are available as functions you can call and compose.
82
83Return your result by returning a value tagged with a \"type\":
84- {\"type\": \"observation\", \"value\": ...}: something to inspect; you continue.
85- {\"type\": \"final_result\", \"value\": ...}: the task is done; this ends it.
86- {\"type\": \"error\", \"message\": \"...\"}: a problem to record; you continue.
87
88If your code errors, you will see the error and can try again. Use final_result
89only when the task is genuinely done.";
90
91/// A tool lookup table keyed by tool name.
92pub type ToolMap = HashMap<String, Arc<dyn Tool>>;
93
94/// Build a [`ToolMap`] from a tool list, excluding built-in (server-side) tools
95/// which cannot be invoked from a script.
96pub fn build_tool_map(tools: &[Arc<dyn Tool>]) -> ToolMap {
97    tools.iter().filter(|t| !t.is_builtin()).map(|t| (t.name().to_string(), t.clone())).collect()
98}
99
100// ===========================================================================
101// The streaming loop
102// ===========================================================================
103
104/// All the (owned) inputs the loop needs.
105struct LoopInputs {
106    model: Arc<dyn Llm>,
107    runtime: Arc<dyn CodeRuntime>,
108    tools: Vec<Arc<dyn Tool>>,
109    policy: ToolConfirmationPolicy,
110    /// The live invocation context; a fresh [`CodeToolContext`] is built from it
111    /// per tool call so each call carries its own function-call id and actions.
112    invocation_ctx: Arc<dyn InvocationContext>,
113    incoming: Content,
114    /// The fully-assembled system prompt (instructions + contract + runtime +
115    /// tools + transfer section), built once per invocation in `run`.
116    system_prompt: String,
117    /// The seeded conversation (history + current turn) per `include_contents`.
118    conversation: Vec<Content>,
119    pending: Option<CodeActCheckpoint>,
120    invocation_id: String,
121    agent_name: String,
122    max_iterations: u32,
123    max_error_chars: usize,
124    supports_suspension: bool,
125    /// Agent names this script may transfer to (sub-agents + runner targets).
126    /// Empty means transfer is not offered to the model.
127    transfer_targets: Vec<String>,
128    /// Generation config (temperature, etc.) applied to every model request.
129    generate_content_config: Option<GenerateContentConfig>,
130    /// Per-tool execution timeout.
131    tool_timeout: Duration,
132    /// State key to store the final result under, if any.
133    output_key: Option<String>,
134    /// Retry budget applied to tools without a per-tool override.
135    default_retry_budget: Option<RetryBudget>,
136    /// Per-tool retry budget overrides, keyed by tool name.
137    tool_retry_budgets: HashMap<String, RetryBudget>,
138    /// Consecutive-failure threshold before a tool is short-circuited.
139    circuit_breaker_threshold: Option<u32>,
140    /// Fallback callbacks tried when a tool ultimately fails.
141    on_tool_error: Arc<Vec<OnToolErrorCallback>>,
142    /// Callbacks invoked before each model request (may rewrite or short-circuit).
143    before_model_callbacks: Arc<Vec<BeforeModelCallback>>,
144    /// Callbacks invoked after each model response (may rewrite it).
145    after_model_callbacks: Arc<Vec<AfterModelCallback>>,
146    /// Callbacks invoked before each tool call (may short-circuit with content).
147    before_tool_callbacks: Arc<Vec<BeforeToolCallback>>,
148    /// Callbacks invoked after each tool attempt resolves (may rewrite the result).
149    after_tool_callbacks: Arc<Vec<AfterToolCallback>>,
150    /// Rich after-tool callbacks receiving the tool, args, and response value.
151    after_tool_callbacks_full: Arc<Vec<AfterToolCallbackFull>>,
152    /// JSON schema the final result must validate against, if any.
153    output_schema: Option<Value>,
154    /// Max correction retries when the final result fails schema validation.
155    output_max_retries: usize,
156    /// Guardrails applied to the final result content before it is emitted.
157    output_guardrails: Arc<GuardrailSet>,
158    /// Plugin pipeline intercepting tool and model calls.
159    #[cfg(feature = "enhanced-plugins")]
160    enhanced_plugin_manager: Option<Arc<EnhancedPluginManager>>,
161}
162
163/// Per-invocation consecutive-failure tracker. When a tool's failure count
164/// reaches `threshold` it is "open" and short-circuited until the next run.
165struct CircuitBreaker {
166    threshold: u32,
167    failures: HashMap<String, u32>,
168}
169
170impl CircuitBreaker {
171    fn new(threshold: u32) -> Self {
172        Self { threshold, failures: HashMap::new() }
173    }
174
175    fn is_open(&self, tool: &str) -> bool {
176        self.failures.get(tool).copied().unwrap_or(0) >= self.threshold
177    }
178
179    fn record(&mut self, tool: &str, success: bool) {
180        if success {
181            self.failures.remove(tool);
182        } else {
183            *self.failures.entry(tool.to_string()).or_insert(0) += 1;
184        }
185    }
186}
187
188/// The tool-execution policy shared across every call in one invocation.
189struct ToolPolicy<'a> {
190    /// The agent's own confirmation requirement.
191    confirmation: &'a ToolConfirmationPolicy,
192    /// The invocation the calls belong to; its run config drives the governed path.
193    invocation_ctx: &'a Arc<dyn InvocationContext>,
194    tool_timeout: Duration,
195    default_budget: Option<&'a RetryBudget>,
196    tool_budgets: &'a HashMap<String, RetryBudget>,
197    on_tool_error: &'a [OnToolErrorCallback],
198    before_tool: &'a [BeforeToolCallback],
199    after_tool: &'a [AfterToolCallback],
200    after_tool_full: &'a [AfterToolCallbackFull],
201    /// The run's invocation hooks, iterated ahead of the agent's own tool callbacks.
202    hooks: &'a HookCallbacks,
203    #[cfg(feature = "enhanced-plugins")]
204    plugins: Option<&'a EnhancedPluginManager>,
205}
206
207impl ToolPolicy<'_> {
208    /// The retry budget for `tool`: a per-tool override, else the default.
209    fn budget_for(&self, tool: &str) -> Option<&RetryBudget> {
210        self.tool_budgets.get(tool).or(self.default_budget)
211    }
212}
213
214/// Drive CodeAct to completion as a stream of events.
215///
216/// Yields durability/suspend events as it goes (persisted by the Runner) and a
217/// final event at the end. [`CodeActAgent::run`] just gathers [`LoopInputs`] from
218/// `self` + the context and forwards.
219///
220/// A call held for confirmation that has no decision yet is not put to the run's
221/// confirmation handler again: it waits for a decision recorded for it, as in
222/// [`LlmAgent`](crate::LlmAgent) (spec 3.3 §7.3). A run that brings a new message
223/// answers it in a turn of its own while the call keeps waiting: that turn cannot
224/// suspend, and the checkpoint of the waiting call stays in session state (§7.4), unless
225/// the turn answered the call by deciding an identical one.
226fn run_codeact(mut input: LoopInputs) -> impl Stream<Item = adk_core::Result<Event>> {
227    stream! {
228        let mut hold = None;
229        let mut waiting = None;
230        if let Some(cp) = input.pending.clone()
231            && cp.disposition == Disposition::AwaitingConfirmation
232            && let Some(tool) = input.tools.iter().find(|tool| tool.name() == cp.call.tool)
233        {
234            let gate = ToolGate::for_context(input.invocation_ctx.as_ref());
235            // The call waits under the arguments it was held with, after plugin, callback and
236            // screen rewrites; its held event carries them, the checkpoint the script's own.
237            let call_id = cp.call.call_id.to_string();
238            let held = input
239                .invocation_ctx
240                .session()
241                .held_tool_calls(&input.agent_name, input.invocation_ctx.branch())
242                .into_iter()
243                .rev()
244                .map(|held| held.request)
245                .find(|request| {
246                    request.tool_name == cp.call.tool
247                        && request.function_call_id.as_deref() == Some(call_id.as_str())
248                });
249            let request = held.unwrap_or_else(|| {
250                ToolConfirmationRequest::for_tool(tool.as_ref(), cp.call.args.clone())
251                    .with_function_call_id(call_id)
252                    .with_acting_context(gate.acting_context().clone())
253            });
254            match adk_core::confirmation_decision_available(&gate, &request).await {
255                Ok(true) => {}
256                Ok(false) if input.incoming.carries_user_input() => waiting = Some((cp, request)),
257                Ok(false) => hold = Some(request),
258                Err(error) => {
259                    yield Err(error);
260                    return;
261                }
262            }
263        }
264        // The waiting call's fingerprint, with the store it waits in when it is pending there
265        // as the turn starts.
266        let mut beside = None;
267        if let Some((_, request)) = &waiting {
268            input.pending = None;
269            input.supports_suspension = false;
270            let fingerprint = request.fingerprint();
271            let gate = ToolGate::for_context(input.invocation_ctx.as_ref());
272            let mut watched = None;
273            if let Some(store) = &input.invocation_ctx.run_config().approval_store {
274                match store.pending(gate.scope()).await {
275                    Ok(entries) => {
276                        if entries.iter().any(|entry| entry.fingerprint == fingerprint) {
277                            watched = Some(store.clone());
278                        }
279                    }
280                    Err(error) => {
281                        yield Err(error);
282                        return;
283                    }
284                }
285            }
286            beside = Some((fingerprint, watched));
287        }
288        let ctx = input.invocation_ctx.clone();
289        let (invocation_id, agent_name) = (input.invocation_id.clone(), input.agent_name.clone());
290        let waiting_call = waiting.as_ref().map(|(cp, _)| cp.call.clone());
291        let mut inner = Box::pin(drive_codeact(input, hold, waiting.map(|(_, request)| request)));
292        while let Some(mut item) = inner.next().await {
293            // The turn that answered the message ends; the waiting call's checkpoint stays,
294            // unless an identical call this turn made was decided: that closed the call's
295            // pending entry and left no decision for it (spec 3.3 §7.3).
296            if let (Ok(event), Some((fingerprint, watched))) = (&mut item, &beside)
297                && event.actions.state_delta.get(PENDING_STATE_KEY).is_some_and(Value::is_null)
298            {
299                let answered = match watched {
300                    Some(store) => {
301                        let gate = ToolGate::for_context(ctx.as_ref());
302                        let scope = gate.scope();
303                        match (store.pending(scope).await, store.has_decision(scope, fingerprint).await) {
304                            (Ok(entries), Ok(decided)) => {
305                                !decided && !entries.iter().any(|entry| entry.fingerprint == *fingerprint)
306                            }
307                            (Err(error), _) | (_, Err(error)) => {
308                                tracing::warn!(error = %error, "could not read the approval store; the waiting call keeps its checkpoint");
309                                false
310                            }
311                        }
312                    }
313                    None => false,
314                };
315                if !answered {
316                    event.actions.state_delta.remove(PENDING_STATE_KEY);
317                } else if let Some(call) = &waiting_call {
318                    // The waiting call took no decision of its own: it is answered here, or the
319                    // session would hold it for good.
320                    let mut answer = Event::new(&invocation_id);
321                    answer.author = agent_name.clone();
322                    answer.llm_response.content = Some(held_call_answer(
323                        call,
324                        &ResolutionRecord::Value(serde_json::json!({
325                            "status": "decided",
326                            "detail": "an identical call in a later turn took this call's decision",
327                        })),
328                        // The identical call ran in its place; this one never did.
329                        Some(ToolResultStatus::NotRun),
330                    ));
331                    yield Ok(answer);
332                }
333            }
334            yield item;
335        }
336    }
337}
338
339/// The CodeAct loop. `hold` re-holds a pending checkpoint's call without asking about it
340/// again; `waiting` is the call that waits while this turn answers a new message.
341fn drive_codeact(
342    input: LoopInputs,
343    mut hold: Option<ToolConfirmationRequest>,
344    waiting: Option<ToolConfirmationRequest>,
345) -> impl Stream<Item = adk_core::Result<Event>> {
346    stream! {
347        let LoopInputs {
348            model, runtime, tools, policy, invocation_ctx, incoming, system_prompt, conversation,
349            pending, invocation_id, agent_name, max_iterations, max_error_chars, supports_suspension,
350            transfer_targets, generate_content_config, tool_timeout, output_key,
351            default_retry_budget, tool_retry_budgets, circuit_breaker_threshold, on_tool_error,
352            before_model_callbacks, after_model_callbacks, before_tool_callbacks,
353            after_tool_callbacks, after_tool_callbacks_full,
354            output_schema, output_max_retries, output_guardrails,
355            #[cfg(feature = "enhanced-plugins")]
356            enhanced_plugin_manager,
357        } = input;
358
359        let tool_map = build_tool_map(&tools);
360        // Runner plugins and other run-wide hooks reach this agent through the run config.
361        let hook_callbacks = HookCallbacks::new(&invocation_ctx.run_config().invocation_hooks);
362        let roster = roster(&tool_map);
363
364        // Tool-robustness state for this invocation.
365        let tool_policy = ToolPolicy {
366            confirmation: &policy,
367            invocation_ctx: &invocation_ctx,
368            tool_timeout,
369            default_budget: default_retry_budget.as_ref(),
370            tool_budgets: &tool_retry_budgets,
371            on_tool_error: on_tool_error.as_slice(),
372            before_tool: before_tool_callbacks.as_slice(),
373            after_tool: after_tool_callbacks.as_slice(),
374            after_tool_full: after_tool_callbacks_full.as_slice(),
375            hooks: &hook_callbacks,
376            #[cfg(feature = "enhanced-plugins")]
377            plugins: enhanced_plugin_manager.as_deref(),
378        };
379        let mut circuit = circuit_breaker_threshold.map(CircuitBreaker::new);
380        // Tool calls are keyed under the run that started the program, so a call replayed
381        // from a checkpoint in a later invocation keeps its idempotency key.
382        let run_id = pending
383            .as_ref()
384            .and_then(|cp| cp.run_id.clone())
385            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
386
387        // Callback context for model-level hooks (the invocation context is also a
388        // callback context). Tool-level callbacks get a fresh per-call context.
389        let model_ctx: Arc<dyn CallbackContext> = invocation_ctx.clone();
390        // Shared with every agent in the invocation through the run config.
391        let budget_tracker = invocation_ctx.run_config().budget_tracker.clone();
392        // Model calls reserve their upper-bound cost and count against the run budget.
393        let model_scope = adk_core::ModelCallScope::for_run(
394            invocation_ctx.run_config(),
395            invocation_ctx.app_name(),
396            invocation_ctx.agent_name(),
397        );
398        let model_hooks = ModelHooks {
399            before: before_model_callbacks.as_slice(),
400            after: after_model_callbacks.as_slice(),
401            hooks: &hook_callbacks,
402            ctx: &model_ctx,
403            scope: &model_scope,
404            #[cfg(feature = "enhanced-plugins")]
405            plugins: enhanced_plugin_manager.as_deref(),
406        };
407
408        let mut transcript: Vec<Content>;
409        let mut iteration: u32;
410        let mut pending_step: Option<RunStep>;
411
412        // Tool-produced state/artifact deltas not yet persisted. Drained into
413        // the next yielded event so they reach the session, mirroring how
414        // LlmAgent puts each tool's actions on its function-response event.
415        let mut pending_actions = EventActions::default();
416
417        // Sources the run's tool calls recorded, which the final result may cite.
418        let mut retrieved: Vec<GroundingSource> = Vec::new();
419
420        // Count of output-schema correction retries used so far.
421        let mut schema_retries: usize = 0;
422
423        // Whether the transcript carries a message the model has not been sent yet.
424        let mut unanswered = false;
425
426        // Set by each script turn that hands control back, so the next model call is
427        // preceded by a safe point.
428        let mut steering_due = false;
429
430        // ----- self-route: resume a pending checkpoint, or start fresh -----
431        match pending {
432            None => {
433                // The system prompt (including any transfer section) is assembled
434                // in `run`; seed it followed by the resolved conversation.
435                transcript = std::iter::once(Content::new("user").with_text(system_prompt))
436                    .chain(conversation)
437                    .collect();
438                iteration = 0;
439                pending_step = None;
440            }
441            Some(mut cp) => {
442                if cp.tool_roster != roster {
443                    yield Err(AdkError::new(
444                        ErrorComponent::Agent,
445                        ErrorCategory::InvalidInput,
446                        "codeact.resume.roster_mismatch",
447                        "tool roster changed since suspend; cannot resume continuation",
448                    ));
449                    return;
450                }
451                // A script resumed on a decision continues the earlier transcript, so a message
452                // this run brought joins it, and every checkpoint after it, until a model request
453                // carries it (spec 3.3 §12). A run replayed with a message the transcript already
454                // holds brings nothing new. After the script's last model turn the transcript
455                // holds only its printed output, so anything else there is such a message.
456                let incoming_value = serde_json::to_value(&incoming).ok();
457                if cp.disposition == Disposition::AwaitingConfirmation
458                    && incoming.carries_user_input()
459                    && !cp
460                        .transcript
461                        .iter()
462                        .any(|content| serde_json::to_value(content).ok() == incoming_value)
463                {
464                    cp.transcript.push(incoming.clone());
465                }
466                let script_turn =
467                    cp.transcript.iter().rposition(|content| content.role == "model");
468                unanswered = script_turn.is_some_and(|turn| {
469                    cp.transcript[turn + 1..].iter().any(|content| {
470                        content.carries_user_input()
471                            && !content
472                                .parts
473                                .first()
474                                .and_then(Part::text)
475                                .is_some_and(|text| text.starts_with(STDOUT_PREFIX))
476                    })
477                });
478                // Resolve the value/error to feed back. For the dispositions
479                // that execute (or decide) a tool now, capture a
480                // [`ResolutionRecord`] so we can persist a SAVE-AFTER checkpoint
481                // *before* resuming the interpreter — recovery then never re-runs
482                // the tool, even if the process crashes mid-resume.
483                // A terminal signal raised by a freshly-executed tool on this
484                // resume (escalate / skip-summarization / transfer). Checked
485                // before resuming the interpreter, mirroring the inline path.
486                let mut resume_control = ToolControl::default();
487                // A call still waiting for a decision, re-held with its final arguments.
488                let mut held: Option<ToolConfirmationRequest> = None;
489                // The status of the answer a call resolved now carries, when the agent wrote it.
490                let mut resolved_status: Option<ToolResultStatus> = None;
491                let resolution: Option<ResolutionRecord> = match &cp.disposition {
492                    // No decision is recorded for the call: it keeps waiting, unasked.
493                    Disposition::AwaitingConfirmation if hold.is_some() => {
494                        held = hold.take();
495                        None
496                    }
497                    // Recovery re-runs an unfinished call, and a confirmed call runs now.
498                    // Both pass through the governed path, which finds the decision.
499                    Disposition::PendingResult | Disposition::AwaitingConfirmation => {
500                        let tool_ctx: Arc<dyn ToolContext> = Arc::new(CodeToolContext::new(
501                            invocation_ctx.clone(), &run_id, cp.iteration, cp.call.call_id,
502                        ));
503                        match execute_for_resume(
504                            &tool_map, tool_ctx, &cp.call, &mut pending_actions,
505                            &mut retrieved, &tool_policy, &mut circuit,
506                        )
507                        .await
508                        {
509                            Resumed::Ready(with, control, status) => {
510                                resume_control = control;
511                                resolved_status = status;
512                                Some(resume_to_record(with))
513                            }
514                            Resumed::Held(request) => {
515                                held = Some(request);
516                                None
517                            }
518                            Resumed::Abort(error) => {
519                                yield Err(error);
520                                return;
521                            }
522                        }
523                    }
524                    Disposition::Resolved(rec) => Some(rec.clone()),
525                    Disposition::AwaitingCompletion { .. } => {
526                        completion_for(&incoming, &cp.call.tool, cp.call.call_id)
527                            .map(ResolutionRecord::Value)
528                    }
529                };
530                match resolution {
531                    // No resolution available yet — keep waiting (re-persist).
532                    None => {
533                        let mut event = match held {
534                            Some(request) => {
535                                let waiting = CodeActCheckpoint {
536                                    disposition: Disposition::AwaitingConfirmation,
537                                    ..cp.clone()
538                                };
539                                held_event(&invocation_id, &agent_name, &waiting, request)
540                            }
541                            None => suspend_event(&invocation_id, &agent_name, &cp),
542                        };
543                        flush_actions(&mut event, &mut pending_actions);
544                        yield Ok(event);
545                        return;
546                    }
547                    Some(rec) => {
548                        // A decided call is answered on the event that records its
549                        // resolution, as LlmAgent answers a resumed one (spec 3.3 §7.3).
550                        let answer = (cp.disposition == Disposition::AwaitingConfirmation)
551                            .then(|| held_call_answer(&cp.call, &rec, resolved_status));
552                        // A tool that escalated / requested skip-summarization /
553                        // a transfer on this resume ends the run now, before the
554                        // result is fed back to the script (matches the inline
555                        // path and LlmAgent's terminal actions).
556                        if resume_control.is_terminal() {
557                            let mut event = control_terminal_event(
558                                &invocation_id, &agent_name, &resume_control,
559                            );
560                            event.llm_response.content = answer;
561                            flush_actions(&mut event, &mut pending_actions);
562                            yield Ok(event);
563                            return;
564                        }
565                        // SAVE-AFTER: persist the resolution unless this checkpoint
566                        // was already `Resolved` (in which case it is on disk).
567                        if !matches!(cp.disposition, Disposition::Resolved(_)) {
568                            let after = mk_checkpoint(
569                                cp.iteration,
570                                cp.transcript.clone(),
571                                cp.snapshot.clone(),
572                                cp.call.clone(),
573                                Disposition::Resolved(rec.clone()),
574                                &roster,
575                                &run_id,
576                            );
577                            let mut after_ev =
578                                checkpoint_event(&invocation_id, &agent_name, &after);
579                            after_ev.llm_response.content = answer;
580                            flush_actions(&mut after_ev, &mut pending_actions);
581                            yield Ok(after_ev);
582                        }
583                        match runtime.resume(&cp.snapshot, resolution_to_resume(rec)) {
584                            Ok(step) => {
585                                transcript = cp.transcript;
586                                iteration = cp.iteration;
587                                pending_step = Some(step);
588                            }
589                            Err(e) => {
590                                yield Err(runtime_err(e));
591                                return;
592                            }
593                        }
594                    }
595                }
596            }
597        }
598
599        // ----- main loop -----
600        loop {
601            let mut step = match pending_step.take() {
602                Some(step) => step,
603                None => {
604                    iteration += 1;
605                    if iteration > max_iterations {
606                        // Mirror LlmAgent: exceeding the turn budget is an error,
607                        // not a silent terminal message.
608                        yield Err(AdkError::agent(format!(
609                            "max iterations ({max_iterations}) exceeded without a final result"
610                        )));
611                        return;
612                    }
613                    // The kill switch is checked before every model call.
614                    if let Err(error) = invocation_ctx.run_config().check_governance() {
615                        yield Err(error);
616                        return;
617                    }
618                    // The safe point: the last script turn's results are in the transcript and
619                    // the next request is not built yet. Taken only once the checks above pass,
620                    // so a run they end returns its queued messages to their senders.
621                    if std::mem::take(&mut steering_due)
622                        && let Some(inbox) = invocation_ctx.steering_inbox()
623                    {
624                        for message in inbox.drain() {
625                            yield Ok(message.to_event(&invocation_id, invocation_ctx.branch()));
626                            transcript.push(message.content);
627                        }
628                    }
629                    unanswered = false;
630                    // Auto-compaction before the model call, and once more after the model
631                    // rejected the request as too long; the system prompt is never compacted.
632                    let mut rejected: Option<AdkError> = None;
633                    let mut resent = false;
634                    let script = loop {
635                        let rejection = rejected.take();
636                        if let Some(compactor) =
637                            invocation_ctx.run_config().history_compactor.clone()
638                        {
639                            let trigger = if rejection.is_some() {
640                                adk_core::CompactionTrigger::ContextLimitExceeded
641                            } else {
642                                adk_core::CompactionTrigger::BeforeModelCall
643                            };
644                            let request =
645                                adk_core::HistoryCompactionRequest::new(&transcript[1..], trigger)
646                                    .with_preamble(&transcript[..1]);
647                            match compactor
648                                .compact(invocation_ctx.clone(), model.clone(), request)
649                                .await
650                            {
651                                Ok(Some(compacted)) => {
652                                    transcript.truncate(1);
653                                    transcript.extend(compacted.history);
654                                    if let Some(event) = compacted.event {
655                                        yield Ok(event);
656                                    }
657                                }
658                                Ok(None) => {
659                                    if let Some(error) = rejection {
660                                        yield Err(error);
661                                        return;
662                                    }
663                                }
664                                Err(error) => {
665                                    yield Err(error);
666                                    return;
667                                }
668                            }
669                        }
670                        match next_script(
671                            model.as_ref(),
672                            &transcript,
673                            &generate_content_config,
674                            &model_hooks,
675                        )
676                        .await
677                        {
678                            Ok(s) => break s,
679                            Err(e)
680                                if invocation_ctx.run_config().history_compactor.is_some()
681                                    && adk_core::intra_compaction::is_context_limit_error(&e)
682                                    && !std::mem::replace(&mut resent, true) =>
683                            {
684                                rejected = Some(e);
685                            }
686                            Err(e) => {
687                                yield Err(e);
688                                return;
689                            }
690                        }
691                    };
692                    transcript.push(Content::new("model").with_text(script.clone()));
693                    // A parse/compile failure arrives as `RunStep::Raised`, not a
694                    // `RuntimeError` — it is handled in the loop like any other
695                    // script error and fed back to the model.
696                    match runtime.start(&script, "agent") {
697                        Ok(step) => step,
698                        Err(e) => {
699                            yield Err(runtime_err(e));
700                            return;
701                        }
702                    }
703                }
704            };
705
706            // stdout (`print`) the script emits across this turn, accumulated
707            // step by step and surfaced to the model when the turn hands control
708            // back so it can see what its code printed. It is also baked into any
709            // checkpoint written mid-turn (see `transcript_with_stdout`) so it
710            // survives suspend/resume and crash recovery. On a *terminal* outcome
711            // (`final_result`, transfer, or a terminal tool signal) the run ends
712            // and there is no next turn, so the accumulated output is
713            // intentionally not surfaced — the final result is the answer.
714            let mut script_output = String::new();
715
716            'script: loop {
717                match step {
718                    RunStep::Call { call, stdout } => {
719                        script_output.push_str(&stdout);
720                        let name = call.function_name().to_string();
721                        let call_id = call.call_id();
722
723                        let Some(tool) = tool_map.get(&name).cloned() else {
724                            match call.resume(ResumeWith::Raise(unknown_tool_message(&name))) {
725                                Ok(s) => step = s,
726                                Err(e) => {
727                                    yield Err(runtime_err(e));
728                                    return;
729                                }
730                            }
731                            continue 'script;
732                        };
733
734                        // Bind the call's positional + keyword arguments onto the
735                        // tool's parameters centrally, so runtimes never need a
736                        // schema at the call boundary.
737                        let args = bind_call_args(
738                            tool.as_ref(),
739                            call.positional_args(),
740                            call.keyword_args(),
741                        );
742                        let pcall = PendingToolCall {
743                            call_id,
744                            tool: name.clone(),
745                            args: args.clone(),
746                        };
747
748                        // The call counts against the run budget before it starts.
749                        if let Some(tracker) = budget_tracker.as_ref()
750                            && let Err(exceeded) = tracker.begin_tool_calls(1)
751                        {
752                            yield Err(exceeded.into());
753                            return;
754                        }
755
756                        // Long-running deferral (needs suspension).
757                        if supports_suspension && tool.is_long_running() {
758                            let snapshot = match call.dump() {
759                                Ok(s) => s,
760                                Err(e) => {
761                                    yield Err(runtime_err(e));
762                                    return;
763                                }
764                            };
765                            let tool_ctx: Arc<dyn ToolContext> =
766                                Arc::new(CodeToolContext::new(
767                                    invocation_ctx.clone(), &run_id, iteration, call_id,
768                                ));
769                            let exec = match run_tool(&tool, &tool_ctx, args, &tool_policy, &mut circuit).await {
770                                ToolRun::Finished(exec, _) => exec,
771                                ToolRun::Held(request) => {
772                                    let cp = mk_checkpoint(
773                                        iteration,
774                                        transcript_with_stdout(
775                                            &transcript,
776                                            &script_output,
777                                            max_error_chars,
778                                        ),
779                                        snapshot,
780                                        pcall,
781                                        Disposition::AwaitingConfirmation,
782                                        &roster,
783                                        &run_id,
784                                    );
785                                    let mut event =
786                                        held_event(&invocation_id, &agent_name, &cp, request);
787                                    flush_actions(&mut event, &mut pending_actions);
788                                    yield Ok(event);
789                                    return;
790                                }
791                                ToolRun::Abort(error) => {
792                                    yield Err(error);
793                                    return;
794                                }
795                            };
796                            let control = capture_actions(&mut pending_actions, &mut retrieved, tool_ctx.actions());
797                            // A terminal signal (escalate / skip-summarization /
798                            // transfer) ends the run before suspending, matching
799                            // the inline path and LlmAgent's terminal actions.
800                            if control.is_terminal() {
801                                let mut event =
802                                    control_terminal_event(&invocation_id, &agent_name, &control);
803                                flush_actions(&mut event, &mut pending_actions);
804                                yield Ok(event);
805                                return;
806                            }
807                            match exec {
808                                Ok(handle) => {
809                                    let cp = mk_checkpoint(
810                                        iteration,
811                                        transcript_with_stdout(
812                                            &transcript,
813                                            &script_output,
814                                            max_error_chars,
815                                        ),
816                                        snapshot,
817                                        pcall,
818                                        Disposition::AwaitingCompletion { pending_handle: Some(handle) },
819                                        &roster,
820                                        &run_id,
821                                    );
822                                    let mut event = suspend_event(&invocation_id, &agent_name, &cp);
823                                    flush_actions(&mut event, &mut pending_actions);
824                                    yield Ok(event);
825                                    return;
826                                }
827                                Err(msg) => {
828                                    match call.resume(ResumeWith::Raise(msg)) {
829                                        Ok(s) => step = s,
830                                        Err(e) => {
831                                            yield Err(runtime_err(e));
832                                            return;
833                                        }
834                                    }
835                                    continue 'script;
836                                }
837                            }
838                        }
839
840                        // Inline tool: bracket with before/after checkpoints when
841                        // the runtime can snapshot.
842                        let resume = if supports_suspension {
843                            let snapshot = match call.dump() {
844                                Ok(s) => s,
845                                Err(e) => {
846                                    yield Err(runtime_err(e));
847                                    return;
848                                }
849                            };
850                            // SAVE-BEFORE (carries any deltas captured on resume).
851                            let before = mk_checkpoint(
852                                iteration,
853                                transcript_with_stdout(
854                                    &transcript,
855                                    &script_output,
856                                    max_error_chars,
857                                ),
858                                snapshot.clone(),
859                                pcall.clone(),
860                                Disposition::PendingResult,
861                                &roster,
862                                &run_id,
863                            );
864                            let mut before_ev = checkpoint_event(&invocation_id, &agent_name, &before);
865                            flush_actions(&mut before_ev, &mut pending_actions);
866                            yield Ok(before_ev);
867
868                            let tool_ctx: Arc<dyn ToolContext> =
869                                Arc::new(CodeToolContext::new(
870                                    invocation_ctx.clone(), &run_id, iteration, call_id,
871                                ));
872                            let exec = match run_tool(&tool, &tool_ctx, args, &tool_policy, &mut circuit).await {
873                                ToolRun::Finished(exec, _) => exec,
874                                ToolRun::Held(request) => {
875                                    // Supersedes the SAVE-BEFORE checkpoint: the tool did not run.
876                                    let cp = mk_checkpoint(
877                                        iteration,
878                                        transcript_with_stdout(
879                                            &transcript,
880                                            &script_output,
881                                            max_error_chars,
882                                        ),
883                                        snapshot,
884                                        pcall,
885                                        Disposition::AwaitingConfirmation,
886                                        &roster,
887                                        &run_id,
888                                    );
889                                    let mut event =
890                                        held_event(&invocation_id, &agent_name, &cp, request);
891                                    flush_actions(&mut event, &mut pending_actions);
892                                    yield Ok(event);
893                                    return;
894                                }
895                                ToolRun::Abort(error) => {
896                                    yield Err(error);
897                                    return;
898                                }
899                            };
900                            let control = capture_actions(&mut pending_actions, &mut retrieved, tool_ctx.actions());
901                            let resolution = match exec {
902                                Ok(v) => ResolutionRecord::Value(v),
903                                Err(msg) => ResolutionRecord::Raise(msg),
904                            };
905
906                            // A tool that escalated / requested skip-summarization /
907                            // a transfer ends the run before the result is fed back
908                            // to the script (matches LlmAgent's terminal actions).
909                            if control.is_terminal() {
910                                let mut event =
911                                    control_terminal_event(&invocation_id, &agent_name, &control);
912                                flush_actions(&mut event, &mut pending_actions);
913                                yield Ok(event);
914                                return;
915                            }
916
917                            // SAVE-AFTER
918                            let after = mk_checkpoint(
919                                iteration,
920                                transcript_with_stdout(
921                                    &transcript,
922                                    &script_output,
923                                    max_error_chars,
924                                ),
925                                snapshot,
926                                pcall,
927                                Disposition::Resolved(resolution.clone()),
928                                &roster,
929                                &run_id,
930                            );
931                            let mut after_ev = checkpoint_event(&invocation_id, &agent_name, &after);
932                            flush_actions(&mut after_ev, &mut pending_actions);
933                            yield Ok(after_ev);
934                            resolution_to_resume(resolution)
935                        } else {
936                            let tool_ctx: Arc<dyn ToolContext> =
937                                Arc::new(CodeToolContext::new(
938                                    invocation_ctx.clone(), &run_id, iteration, call_id,
939                                ));
940                            let exec = match run_tool(&tool, &tool_ctx, args, &tool_policy, &mut circuit).await {
941                                ToolRun::Finished(exec, _) => exec,
942                                ToolRun::Held(request) => match &waiting {
943                                    // This turn answers a message while another call waits
944                                    // for a decision; it cannot wait for a second one.
945                                    Some(waiting) if request.fingerprint() == waiting.fingerprint() => {
946                                        Err(format!(
947                                            "this call to '{name}' is already waiting for a decision; it runs once that decision is made"
948                                        ))
949                                    }
950                                    Some(waiting) => {
951                                        let gate = ToolGate::for_context(invocation_ctx.as_ref());
952                                        if let Err(error) = adk_core::withdraw_held_call(&gate, &request).await {
953                                            yield Err(error);
954                                            return;
955                                        }
956                                        Err(format!(
957                                            "tool '{name}' needs a decision, but a call to '{}' is already waiting for one; call it again once that call is decided",
958                                            waiting.tool_name
959                                        ))
960                                    }
961                                    // Nothing resumes the call, so a later decision on it must not
962                                    // authorize an identical call (spec 3.3 §7.3).
963                                    None => {
964                                        let gate = ToolGate::for_context(invocation_ctx.as_ref());
965                                        if let Err(error) = adk_core::withdraw_held_call(&gate, &request).await {
966                                            yield Err(error);
967                                            return;
968                                        }
969                                        Err(format!(
970                                            "tool '{name}' requires confirmation but this runtime cannot pause"
971                                        ))
972                                    }
973                                },
974                                ToolRun::Abort(error) => {
975                                    yield Err(error);
976                                    return;
977                                }
978                            };
979                            let control = capture_actions(&mut pending_actions, &mut retrieved, tool_ctx.actions());
980                            if control.is_terminal() {
981                                let mut event =
982                                    control_terminal_event(&invocation_id, &agent_name, &control);
983                                flush_actions(&mut event, &mut pending_actions);
984                                yield Ok(event);
985                                return;
986                            }
987                            match exec {
988                                Ok(v) => ResumeWith::Value(v),
989                                Err(msg) => ResumeWith::Raise(msg),
990                            }
991                        };
992
993                        match call.resume(resume) {
994                            Ok(s) => step = s,
995                            Err(e) => {
996                                yield Err(runtime_err(e));
997                                return;
998                            }
999                        }
1000                    }
1001                    RunStep::Complete { value, stdout } => {
1002                        script_output.push_str(&stdout);
1003                        match ScriptOutput::decode(value) {
1004                        ScriptOutput::Observation { value } => {
1005                            transcript.push(observation_content(&value));
1006                            break 'script;
1007                        }
1008                        ScriptOutput::Error { message } => {
1009                            transcript.push(error_content(&truncate_middle(&message, max_error_chars)));
1010                            break 'script;
1011                        }
1012                        // The resumed script finished before any model request carried a
1013                        // message a run brought; the model answers it with the result in view.
1014                        ScriptOutput::FinalResult { value } if unanswered => {
1015                            transcript.push(observation_content(&value));
1016                            break 'script;
1017                        }
1018                        ScriptOutput::FinalResult { value } => {
1019                            // Validate against the output schema, if any. On
1020                            // failure, feed a correction back to the model and
1021                            // let it retry, up to `output_max_retries`.
1022                            if let Some(schema) = &output_schema
1023                                && let Err(err) = validate_against_schema(&value, schema)
1024                            {
1025                                if schema_retries >= output_max_retries {
1026                                    yield Err(AdkError::agent(format!(
1027                                        "final result failed schema validation after {output_max_retries} attempts: {err}"
1028                                    )));
1029                                    return;
1030                                }
1031                                schema_retries += 1;
1032                                transcript.push(error_content(&format!(
1033                                    "final_result did not match the required schema: {err}. Return a conforming final_result."
1034                                )));
1035                                break 'script;
1036                            }
1037                            let mut event = final_event(&invocation_id, &agent_name, &value);
1038                            // Apply output guardrails to the rendered result
1039                            // (block or transform, e.g. PII redaction). When a
1040                            // guardrail transforms the content, the redacted text
1041                            // — not the raw value — is what gets stored under
1042                            // `output_key`, so nothing unredacted leaks into state.
1043                            let mut stored_value = value.clone();
1044                            let rendered = Content::new("model").with_text(render_final(&value));
1045                            event.llm_response.citation_metadata =
1046                                answer_citations(&rendered, &retrieved, None);
1047                            if !output_guardrails.is_empty() {
1048                                let original_text = render_final(&value);
1049                                let content =
1050                                    Content::new("model").with_text(original_text.clone());
1051                                let grounding = Grounding {
1052                                    retrieved: &retrieved,
1053                                    citations: event.llm_response.citation_metadata.as_ref(),
1054                                };
1055                                match enforce_final_output(&output_guardrails, &content, grounding)
1056                                    .await
1057                                {
1058                                    Ok(screened) => {
1059                                        let guarded_text: String = screened
1060                                            .content
1061                                            .parts
1062                                            .iter()
1063                                            .filter_map(|p| p.text())
1064                                            .collect();
1065                                        if guarded_text != original_text {
1066                                            event.llm_response.citation_metadata = answer_citations(
1067                                                &screened.content,
1068                                                &retrieved,
1069                                                None,
1070                                            );
1071                                            stored_value = Value::String(guarded_text);
1072                                        }
1073                                        screened.warnings.record_on(&mut event);
1074                                        event.llm_response.content = Some(screened.content);
1075                                    }
1076                                    Err(e) => {
1077                                        yield Err(e);
1078                                        return;
1079                                    }
1080                                }
1081                            }
1082                            if let Some(key) = &output_key {
1083                                event.actions.state_delta.insert(key.clone(), stored_value);
1084                            }
1085                            flush_actions(&mut event, &mut pending_actions);
1086                            yield Ok(event);
1087                            return;
1088                        }
1089                        ScriptOutput::TransferToAgent { agent_name: target } => {
1090                            if transfer_targets.iter().any(|n| n == &target) {
1091                                let mut event = transfer_event(&invocation_id, &agent_name, &target);
1092                                flush_actions(&mut event, &mut pending_actions);
1093                                yield Ok(event);
1094                                return;
1095                            }
1096                            // Unknown target: tell the model and let it retry.
1097                            transcript.push(error_content(&format!(
1098                                "cannot transfer to '{target}'; valid agents: {}",
1099                                roster_list(&transfer_targets)
1100                            )));
1101                            break 'script;
1102                        }
1103                        }
1104                    }
1105                    RunStep::Raised { message, stdout } => {
1106                        script_output.push_str(&stdout);
1107                        transcript.push(error_content(&truncate_middle(&message, max_error_chars)));
1108                        break 'script;
1109                    }
1110                }
1111            }
1112
1113            // The turn handed control back to the model: surface any stdout the
1114            // script printed so the model can see its own output next turn.
1115            if !script_output.is_empty() {
1116                transcript.push(stdout_content(&truncate_middle(&script_output, max_error_chars)));
1117            }
1118            steering_due = true;
1119        }
1120    }
1121}
1122
1123/// How a resumed or recovered call ended.
1124enum Resumed {
1125    /// The value or error to feed back, with any terminal signal the tool raised and the
1126    /// status of an answer the agent wrote.
1127    Ready(ResumeWith, ToolControl, Option<ToolResultStatus>),
1128    /// The call still needs a confirmation decision.
1129    Held(ToolConfirmationRequest),
1130    /// The run must end.
1131    Abort(AdkError),
1132}
1133
1134/// Execute a tool to produce the value/error fed back into a resumed
1135/// continuation (used on recovery for `PendingResult`/confirmed calls).
1136///
1137/// Any state/artifact deltas the tool sets are captured into `pending` so they
1138/// ride on the next persisted event, just like inline execution. The returned
1139/// [`ToolControl`] carries any terminal signal (escalate / skip-summarization /
1140/// transfer) the tool raised, so the caller can end the run before resuming the
1141/// interpreter, exactly as the inline path does.
1142async fn execute_for_resume(
1143    tools: &ToolMap,
1144    tool_ctx: Arc<dyn ToolContext>,
1145    call: &PendingToolCall,
1146    pending: &mut EventActions,
1147    retrieved: &mut Vec<GroundingSource>,
1148    policy: &ToolPolicy<'_>,
1149    circuit: &mut Option<CircuitBreaker>,
1150) -> Resumed {
1151    match tools.get(&call.tool) {
1152        Some(tool) => {
1153            let (result, status) =
1154                match run_tool(tool, &tool_ctx, call.args.clone(), policy, circuit).await {
1155                    ToolRun::Finished(Ok(v), status) => (ResumeWith::Value(v), status),
1156                    ToolRun::Finished(Err(msg), status) => (ResumeWith::Raise(msg), status),
1157                    ToolRun::Held(request) => return Resumed::Held(request),
1158                    ToolRun::Abort(error) => return Resumed::Abort(error),
1159                };
1160            let control = capture_actions(pending, retrieved, tool_ctx.actions());
1161            Resumed::Ready(result, control, status)
1162        }
1163        None => Resumed::Ready(
1164            ResumeWith::Raise(unknown_tool_message(&call.tool)),
1165            ToolControl::default(),
1166            Some(ToolResultStatus::NotRun),
1167        ),
1168    }
1169}
1170
1171/// How one tool call ended.
1172enum ToolRun {
1173    /// A value to feed back into the script, or a message to raise in it, with the status of
1174    /// the answer when the agent, not the tool, wrote it.
1175    Finished(Result<Value, String>, Option<ToolResultStatus>),
1176    /// The call needs a confirmation decision that does not exist yet.
1177    Held(ToolConfirmationRequest),
1178    /// The run must end: the kill switch is set, or the approval service failed.
1179    Abort(AdkError),
1180}
1181
1182/// Execute a tool with the full robustness policy and report a single outcome.
1183///
1184/// In order: a tripped circuit breaker short-circuits with an error; before-tool
1185/// plugins and callbacks may rewrite the arguments or answer the call; the governed
1186/// path (policy, guardrails, confirmation) authorizes the final arguments; the tool
1187/// runs under a timeout, retrying per its [`RetryBudget`]; the circuit breaker
1188/// records success/failure; and on ultimate failure the `on_tool_error` callbacks
1189/// are tried for a fallback value.
1190async fn run_tool(
1191    tool: &Arc<dyn Tool>,
1192    tool_ctx: &Arc<dyn ToolContext>,
1193    args: Value,
1194    policy: &ToolPolicy<'_>,
1195    circuit: &mut Option<CircuitBreaker>,
1196) -> ToolRun {
1197    let name = tool.name().to_string();
1198
1199    if let Some(cb) = circuit.as_ref()
1200        && cb.is_open(&name)
1201    {
1202        return ToolRun::Finished(
1203            Err(format!(
1204                "tool '{name}' is temporarily disabled after {} consecutive failures",
1205                cb.threshold
1206            )),
1207            Some(ToolResultStatus::NotRun),
1208        );
1209    }
1210
1211    match run_authorized_tool(tool, tool_ctx, args, policy, circuit).await {
1212        Ok(outcome) => outcome,
1213        Err((message, status)) => ToolRun::Finished(Err(message), Some(status)),
1214    }
1215}
1216
1217/// The body of [`run_tool`] after the circuit-breaker check, with `?` for raised
1218/// messages and their status.
1219async fn run_authorized_tool(
1220    tool: &Arc<dyn Tool>,
1221    tool_ctx: &Arc<dyn ToolContext>,
1222    args: Value,
1223    policy: &ToolPolicy<'_>,
1224    circuit: &mut Option<CircuitBreaker>,
1225) -> Result<ToolRun, (String, ToolResultStatus)> {
1226    let name = tool.name().to_string();
1227
1228    // before-tool plugins: rewrite args or short-circuit with a synthetic result.
1229    #[cfg(feature = "enhanced-plugins")]
1230    let args = match policy.plugins {
1231        Some(epm) => match epm
1232            .run_before_tool_call(tool.clone(), args, tool_ctx.clone() as Arc<dyn CallbackContext>)
1233            .await
1234        {
1235            Ok(BeforeToolCallResult::Continue(modified)) => modified,
1236            Ok(BeforeToolCallResult::ShortCircuit(result)) => {
1237                return Ok(ToolRun::Finished(Ok(result), None));
1238            }
1239            Err(e) => return Err((e.to_string(), ToolResultStatus::NotRun)),
1240        },
1241        None => args,
1242    };
1243
1244    // before-tool callbacks: the first to return content short-circuits the call
1245    // (its value is fed back into the script as if the tool had returned it).
1246    if !policy.hooks.before_tool.is_empty() || !policy.before_tool.is_empty() {
1247        let cb_ctx: Arc<dyn CallbackContext> = Arc::new(ToolCallbackContext::new(
1248            tool_ctx.clone() as Arc<dyn CallbackContext>,
1249            name.clone(),
1250            args.clone(),
1251        ));
1252        for callback in policy.hooks.before_tool.iter().chain(policy.before_tool) {
1253            // A panic fails the call closed, as an error does.
1254            match adk_core::guard_callback("before-tool callback", callback(cb_ctx.clone())).await {
1255                Ok(Some(content)) => {
1256                    return Ok(ToolRun::Finished(Ok(content_to_tool_value(&content)), None));
1257                }
1258                Ok(None) => continue,
1259                Err(e) => return Err((e.to_string(), ToolResultStatus::NotRun)),
1260            }
1261        }
1262    }
1263
1264    // The governed path sees the final arguments, after every rewrite above.
1265    let invocation_ctx = policy.invocation_ctx;
1266    let call = GovernedCall::for_tool(tool.as_ref(), tool_ctx.function_call_id(), args)
1267        .requiring_confirmation(
1268            policy.confirmation.requires_confirmation(&name)
1269                || invocation_ctx.requires_tool_confirmation(&name),
1270        );
1271    let args =
1272        match authorize_tool_call(&ToolGate::for_context(invocation_ctx.as_ref()), call).await {
1273            Ok(ToolAuthorization::Execute { args, .. }) => args,
1274            Ok(ToolAuthorization::Refuse { reason, confirmation }) => {
1275                let message = match confirmation {
1276                    Some(ToolConfirmationDecision::Deny) => denied_message(&name),
1277                    _ => reason,
1278                };
1279                return Err((message, ToolResultStatus::Refused));
1280            }
1281            Ok(ToolAuthorization::Pending { request, .. }) => return Ok(ToolRun::Held(request)),
1282            Err(error) => return Ok(ToolRun::Abort(error)),
1283        };
1284
1285    // A non-idempotent call executes at most once per idempotency key. A ledger
1286    // answer is raised into the script, so the code sees that the call did not run.
1287    let effect = tool.effect();
1288    let ledgered = match crate::tool_ledger::begin_ledgered_call(
1289        invocation_ctx.as_ref(),
1290        effect,
1291        tool_ctx.idempotency_key(),
1292        &name,
1293        &args,
1294    )
1295    .await
1296    {
1297        Ok(Ok(ledgered)) => ledgered,
1298        Ok(Err(answer)) => {
1299            return Ok(ToolRun::Finished(Err(render_value(&answer.response)), Some(answer.status)));
1300        }
1301        Err(error) => return Ok(ToolRun::Abort(error)),
1302    };
1303
1304    // The kill switch again, after the ledger write, which can take long enough for a freeze
1305    // to arrive: a call it refuses now never starts (spec 3.1 I20). The step ends as at
1306    // authorization, and the begun record is completed with the not-run text, so a replay
1307    // is answered the same way.
1308    if let Err(refusal) = invocation_ctx.run_config().check_governance() {
1309        if let Some(ledgered) = ledgered {
1310            ledgered.complete(&name, None, &adk_core::not_run_text(&refusal)).await;
1311        }
1312        return Ok(ToolRun::Abort(refusal));
1313    }
1314
1315    // Only a call that cannot repeat a side effect is retried, and only after a
1316    // retryable error.
1317    let budget = policy.budget_for(&name).filter(|_| effect.is_retry_safe());
1318    let max_attempts = budget.map(|b| b.max_retries + 1).unwrap_or(1);
1319    let timeout = tool.timeout_override().unwrap_or(Some(policy.tool_timeout));
1320    // Actions are reset before each retry, so a failed attempt's state delta and
1321    // escalation are never committed.
1322    let initial_actions = tool_ctx.actions();
1323
1324    let started = std::time::Instant::now();
1325    let mut last_error = String::new();
1326    let mut last_failure: Option<Arc<AdkError>> = None;
1327    let mut value = None;
1328    // Set when the last attempt ended mid-flight (timeout or panic), so its side
1329    // effect may or may not have happened.
1330    let mut interrupted = false;
1331    // 0-based index of the attempt that produced the outcome (the successful
1332    // attempt, or the last failed one). Surfaced via `ToolOutcome::attempt`.
1333    let mut final_attempt: u32 = 0;
1334    for attempt in 0..max_attempts {
1335        if attempt > 0 {
1336            if let Some(budget) = budget {
1337                tokio::time::sleep(budget.backoff_delay(attempt)).await;
1338            }
1339            // A retry is a new start, and none begins once a freeze is observed; the last
1340            // attempt's failure stands.
1341            if invocation_ctx.run_config().check_governance().is_err() {
1342                break;
1343            }
1344            tool_ctx.set_actions(initial_actions.clone());
1345        }
1346        final_attempt = attempt;
1347        let execution = adk_core::ModelCallScope::within_tool(
1348            tool_ctx.as_ref(),
1349            tool.execute(tool_ctx.clone(), args.clone()),
1350        );
1351        let bounded = async {
1352            match timeout {
1353                Some(limit) => tokio::time::timeout(limit, execution).await.map_err(|_| limit),
1354                None => Ok(execution.await),
1355            }
1356        };
1357        // Catch panics so a misbehaving tool surfaces as a script-level error
1358        // rather than aborting the whole loop (matches LlmAgent).
1359        let retryable =
1360            match futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(bounded)).await {
1361                Ok(Ok(Ok(v))) => {
1362                    value = Some(v);
1363                    interrupted = false;
1364                    break;
1365                }
1366                Ok(Ok(Err(err))) => {
1367                    last_error = tool_error_message(&err);
1368                    interrupted = false;
1369                    let retryable = err.is_retryable();
1370                    last_failure = Some(Arc::new(err));
1371                    retryable
1372                }
1373                Ok(Err(limit)) => {
1374                    last_error = format!("tool timed out after {limit:?}");
1375                    last_failure = Some(Arc::new(AdkError::new(
1376                        ErrorComponent::Tool,
1377                        ErrorCategory::Timeout,
1378                        "tool.timeout",
1379                        last_error.clone(),
1380                    )));
1381                    interrupted = true;
1382                    true
1383                }
1384                Err(_) => {
1385                    last_error = format!("tool '{name}' panicked during execution");
1386                    last_failure = Some(Arc::new(AdkError::new(
1387                        ErrorComponent::Tool,
1388                        ErrorCategory::Internal,
1389                        "tool.panicked",
1390                        last_error.clone(),
1391                    )));
1392                    interrupted = true;
1393                    false
1394                }
1395            };
1396        if !retryable {
1397            break;
1398        }
1399    }
1400
1401    let outcome_unknown = interrupted && effect == ToolEffect::NonIdempotent;
1402    if outcome_unknown
1403        && let Err(error) = crate::tool_ledger::record_outcome_unknown(
1404            invocation_ctx.as_ref(),
1405            &name,
1406            &args,
1407            "interrupted",
1408        )
1409        .await
1410    {
1411        return Ok(ToolRun::Abort(error));
1412    }
1413    // A call that ended mid-flight keeps its begun record, so a replay is answered
1414    // with an unknown outcome instead of executing again.
1415    if let Some(ledgered) = ledgered
1416        && !outcome_unknown
1417    {
1418        ledgered.complete(&name, value.as_ref(), &last_error).await;
1419    }
1420    // What the script and the after-tool callbacks see when the call failed.
1421    let failure = if outcome_unknown {
1422        crate::tool_ledger::interrupted_call_response(&last_error)
1423    } else {
1424        serde_json::json!({ "error": last_error })
1425    };
1426    let failure_message = if outcome_unknown { render_value(&failure) } else { last_error.clone() };
1427
1428    let tool_succeeded = value.is_some();
1429    if let Some(cb) = circuit.as_mut() {
1430        cb.record(&name, tool_succeeded);
1431    }
1432    // The status of a failure, as `LlmAgent` reports it. A value that stands in for the result
1433    // (a fallback or a callback's) has none, except an unknown outcome, which no value settles.
1434    let failure_status = match last_failure.as_deref() {
1435        _ if outcome_unknown => ToolResultStatus::OutcomeUnknown,
1436        Some(error) => ToolResultStatus::of_tool_error(error),
1437        None => ToolResultStatus::Failed,
1438    };
1439    let unknown = outcome_unknown.then_some(ToolResultStatus::OutcomeUnknown);
1440    let withheld = unknown.unwrap_or(ToolResultStatus::Withheld);
1441
1442    let outcome = ToolOutcome {
1443        tool_name: name.clone(),
1444        tool_args: args.clone(),
1445        success: tool_succeeded,
1446        duration: started.elapsed(),
1447        error_message: (!tool_succeeded).then(|| last_error.clone()),
1448        error: if tool_succeeded { None } else { last_failure },
1449        attempt: final_attempt,
1450    };
1451
1452    let mut result = match value {
1453        Some(v) => Ok(v),
1454        None => {
1455            // Try fallbacks; the first to return a value wins. As in LlmAgent,
1456            // after-tool callbacks still see the original failed outcome even
1457            // when an on-tool-error fallback supplies the response value.
1458            let mut fallback = None;
1459            for callback in policy.hooks.on_tool_error.iter().chain(policy.on_tool_error) {
1460                match callback(
1461                    tool_ctx.clone() as Arc<dyn CallbackContext>,
1462                    tool.clone(),
1463                    args.clone(),
1464                    last_error.clone(),
1465                )
1466                .await
1467                {
1468                    Ok(Some(result)) => {
1469                        fallback = Some(result);
1470                        break;
1471                    }
1472                    Ok(None) => continue,
1473                    Err(err) => {
1474                        tracing::warn!(error = %err.diagnostics(), "on_tool_error callback failed");
1475                        break;
1476                    }
1477                }
1478            }
1479            fallback.ok_or(failure_message)
1480        }
1481    };
1482
1483    // Legacy after-tool callbacks (content-returning), then the rich
1484    // after-tool-full callbacks (value-returning); the first of each to return
1485    // Some replaces the tool result fed back into the script. They run for both
1486    // success and failure, with `ToolOutcome` carrying success/error metadata,
1487    // matching LlmAgent.
1488    if !policy.hooks.after_tool.is_empty()
1489        || !policy.after_tool.is_empty()
1490        || !policy.after_tool_full.is_empty()
1491    {
1492        let outcome_ctx: Arc<dyn CallbackContext> = Arc::new(ToolOutcomeContext::new(
1493            tool_ctx.clone() as Arc<dyn CallbackContext>,
1494            outcome,
1495        ));
1496        let cb_ctx: Arc<dyn CallbackContext> =
1497            Arc::new(ToolCallbackContext::new(outcome_ctx, name.clone(), args.clone()));
1498        for callback in policy.hooks.after_tool.iter().chain(policy.after_tool) {
1499            match callback(cb_ctx.clone()).await {
1500                Ok(Some(content)) => {
1501                    result = Ok(content_to_tool_value(&content));
1502                    break;
1503                }
1504                Ok(None) => continue,
1505                Err(e) => return Err((e.to_string(), withheld)),
1506            }
1507        }
1508        let callback_value = match &result {
1509            Ok(value) => value.clone(),
1510            Err(_) => failure.clone(),
1511        };
1512        for callback in policy.after_tool_full {
1513            match callback(cb_ctx.clone(), tool.clone(), args.clone(), callback_value.clone()).await
1514            {
1515                Ok(Some(modified)) => {
1516                    result = Ok(modified);
1517                    break;
1518                }
1519                Ok(None) => continue,
1520                Err(e) => return Err((e.to_string(), withheld)),
1521            }
1522        }
1523    }
1524
1525    let result = result.map_err(|message| (message, failure_status))?;
1526
1527    // after-tool plugins may transform the successful result last.
1528    #[cfg(feature = "enhanced-plugins")]
1529    if let Some(epm) = policy.plugins {
1530        return match epm
1531            .run_after_tool_call(
1532                tool.clone(),
1533                &args,
1534                result,
1535                tool_ctx.clone() as Arc<dyn CallbackContext>,
1536            )
1537            .await
1538        {
1539            Ok(AfterToolCallResult::Continue(modified)) => {
1540                Ok(ToolRun::Finished(Ok(modified), unknown))
1541            }
1542            Err(e) => Err((e.to_string(), withheld)),
1543        };
1544    }
1545    Ok(ToolRun::Finished(Ok(result), unknown))
1546}
1547
1548/// Run-control signals a tool may raise via its [`EventActions`].
1549///
1550/// Any of these ends the run before the result is fed back into the script,
1551/// mirroring how `LlmAgent` treats `escalate`/`skip_summarization` as terminal
1552/// and forwards a tool-set `transfer_to_agent`.
1553#[derive(Default)]
1554struct ToolControl {
1555    escalate: bool,
1556    skip_summarization: bool,
1557    transfer_to_agent: Option<String>,
1558}
1559
1560impl ToolControl {
1561    /// Whether any signal requires ending the run now.
1562    fn is_terminal(&self) -> bool {
1563        self.escalate || self.skip_summarization || self.transfer_to_agent.is_some()
1564    }
1565}
1566
1567/// Merge a tool's resulting data deltas (state, artifacts, route, grounding
1568/// sources) into the pending accumulator and return the run-control signals it
1569/// raised. Mirrors LlmAgent, which forwards the full tool `EventActions` onto the
1570/// tool event. Grounding sources are also kept in `retrieved`, the run's
1571/// evidence for the final result's citations.
1572fn capture_actions(
1573    pending: &mut EventActions,
1574    retrieved: &mut Vec<GroundingSource>,
1575    actions: EventActions,
1576) -> ToolControl {
1577    retrieved.extend(actions.grounding_sources.iter().cloned());
1578    pending.grounding_sources.extend(actions.grounding_sources);
1579    for (key, value) in actions.state_delta {
1580        pending.state_delta.insert(key, value);
1581    }
1582    for (key, version) in actions.artifact_delta {
1583        pending.artifact_delta.insert(key, version);
1584    }
1585    if let Some(route) = actions.route {
1586        pending.route = Some(route);
1587    }
1588    ToolControl {
1589        escalate: actions.escalate,
1590        skip_summarization: actions.skip_summarization,
1591        transfer_to_agent: actions.transfer_to_agent,
1592    }
1593}
1594
1595/// Drain accumulated tool deltas into an event's actions so the Runner persists
1596/// them, leaving the accumulator empty. Tool keys are merged alongside any
1597/// pending-checkpoint key already on the event.
1598fn flush_actions(event: &mut Event, pending: &mut EventActions) {
1599    for (key, value) in std::mem::take(&mut pending.state_delta) {
1600        event.actions.state_delta.insert(key, value);
1601    }
1602    for (key, version) in std::mem::take(&mut pending.artifact_delta) {
1603        event.actions.artifact_delta.insert(key, version);
1604    }
1605    if let Some(route) = pending.route.take() {
1606        event.actions.route = Some(route);
1607    }
1608    event.actions.grounding_sources.append(&mut pending.grounding_sources);
1609}
1610
1611/// A terminal event raised by a tool's control signals (escalation,
1612/// skip-summarization, or transfer). Clears the pending checkpoint and forwards
1613/// the signals to the Runner, mirroring LlmAgent's terminal tool actions.
1614fn control_terminal_event(invocation_id: &str, agent_name: &str, control: &ToolControl) -> Event {
1615    let mut event = Event::new(invocation_id);
1616    event.author = agent_name.to_string();
1617    event.actions.escalate = control.escalate;
1618    event.actions.skip_summarization = control.skip_summarization;
1619    event.actions.transfer_to_agent = control.transfer_to_agent.clone();
1620    event.actions.state_delta.insert(PENDING_STATE_KEY.to_string(), Value::Null);
1621    event
1622}
1623
1624fn mk_checkpoint(
1625    iteration: u32,
1626    transcript: Vec<Content>,
1627    snapshot: Vec<u8>,
1628    call: PendingToolCall,
1629    disposition: Disposition,
1630    roster: &[String],
1631    run_id: &str,
1632) -> CodeActCheckpoint {
1633    CodeActCheckpoint {
1634        iteration,
1635        transcript,
1636        snapshot,
1637        call,
1638        disposition,
1639        tool_roster: roster.to_vec(),
1640        run_id: Some(run_id.to_string()),
1641    }
1642}
1643
1644fn resolution_to_resume(resolution: ResolutionRecord) -> ResumeWith {
1645    match resolution {
1646        ResolutionRecord::Value(v) => ResumeWith::Value(v),
1647        ResolutionRecord::Raise(m) => ResumeWith::Raise(m),
1648    }
1649}
1650
1651/// Convert a freshly-produced [`ResumeWith`] into a persistable
1652/// [`ResolutionRecord`] for a SAVE-AFTER checkpoint.
1653fn resume_to_record(with: ResumeWith) -> ResolutionRecord {
1654    match with {
1655        ResumeWith::Value(v) => ResolutionRecord::Value(v),
1656        ResumeWith::Raise(m) => ResolutionRecord::Raise(m),
1657    }
1658}
1659
1660/// Extract a tool result value from callback-supplied [`Content`].
1661///
1662/// A `FunctionResponse` part's payload is used directly; otherwise the
1663/// concatenated text is wrapped as a JSON string so the script always receives
1664/// a value to continue with.
1665fn content_to_tool_value(content: &Content) -> Value {
1666    for part in &content.parts {
1667        if let Part::FunctionResponse { function_response, .. } = part {
1668            return function_response.response.clone();
1669        }
1670    }
1671    let text: String = content.parts.iter().filter_map(|p| p.text()).collect();
1672    Value::String(text)
1673}
1674
1675/// The response that answers a call held for confirmation once it is decided:
1676/// [`held_tool_calls`](adk_core::held_tool_calls) holds a call until a response with its ID,
1677/// and compaction never passes a held call (spec 3.3 §7.3). The model is never sent it: a
1678/// CodeAct model issues no function calls, and the history leaves out a response that
1679/// answers none. `status` is the answer's status when the agent, not the tool, wrote it.
1680fn held_call_answer(
1681    call: &PendingToolCall,
1682    rec: &ResolutionRecord,
1683    status: Option<ToolResultStatus>,
1684) -> Content {
1685    let response = match rec {
1686        ResolutionRecord::Value(value) => value.clone(),
1687        ResolutionRecord::Raise(message) => serde_json::json!({ "error": message }),
1688    };
1689    let mut part = Part::FunctionResponse {
1690        function_response: adk_core::FunctionResponseData::new(call.tool.clone(), response),
1691        id: Some(call.call_id.to_string()),
1692        annotations: None,
1693    };
1694    if let Some(status) = status {
1695        part.set_tool_result_status(status, None);
1696    }
1697    Content { role: "function".to_string(), parts: vec![part] }
1698}
1699
1700/// A durability event: persists the checkpoint to session state, no content.
1701///
1702/// Serializing a [`CodeActCheckpoint`] cannot fail (it is plain data), so a
1703/// serialization error here is a programming bug, not a recoverable condition.
1704fn checkpoint_event(invocation_id: &str, agent_name: &str, cp: &CodeActCheckpoint) -> Event {
1705    let mut event = Event::new(invocation_id);
1706    event.author = agent_name.to_string();
1707    let value = serde_json::to_value(cp).expect("CodeActCheckpoint serialization cannot fail");
1708    event.actions.state_delta.insert(PENDING_STATE_KEY.to_string(), value);
1709    event
1710}
1711
1712/// A suspend event: persists the checkpoint and carries the HITL / long-running
1713/// signal so the caller knows what's awaited.
1714fn suspend_event(invocation_id: &str, agent_name: &str, cp: &CodeActCheckpoint) -> Event {
1715    let mut event = checkpoint_event(invocation_id, agent_name, cp);
1716    match &cp.disposition {
1717        Disposition::AwaitingConfirmation => {
1718            event.actions.tool_confirmation = Some(ToolConfirmationRequest {
1719                tool_name: cp.call.tool.clone(),
1720                function_call_id: Some(cp.call.call_id.to_string()),
1721                args: cp.call.args.clone(),
1722                acting: None,
1723                origin: None,
1724                evidence: Vec::new(),
1725            });
1726            // Mark the turn as interrupted and carry a human-readable prompt,
1727            // mirroring LlmAgent's confirmation interrupt event.
1728            event.llm_response.interrupted = true;
1729            event.llm_response.turn_complete = true;
1730            event.llm_response.content = Some(Content::new("model").with_text(format!(
1731                "Tool confirmation required for '{}'. Provide approve/deny decision to continue.",
1732                cp.call.tool
1733            )));
1734        }
1735        Disposition::AwaitingCompletion { .. } => {
1736            event.long_running_tool_ids = vec![cp.call.tool.clone()];
1737            let mut content = Content::new("model");
1738            content.parts.push(Part::FunctionCall {
1739                name: cp.call.tool.clone(),
1740                args: cp.call.args.clone(),
1741                id: Some(cp.call.call_id.to_string()),
1742                thought_signature: None,
1743            });
1744            event.llm_response.content = Some(content);
1745        }
1746        Disposition::PendingResult | Disposition::Resolved(_) => {}
1747    }
1748    event
1749}
1750
1751/// A suspend event for a call held for confirmation, carrying the request with the
1752/// call's final arguments — the ones a decision's fingerprint must match.
1753fn held_event(
1754    invocation_id: &str,
1755    agent_name: &str,
1756    cp: &CodeActCheckpoint,
1757    request: ToolConfirmationRequest,
1758) -> Event {
1759    let mut event = suspend_event(invocation_id, agent_name, cp);
1760    event.actions.tool_confirmation = Some(request);
1761    event
1762}
1763
1764/// A final result event: clears the pending checkpoint from session state.
1765fn final_event(invocation_id: &str, agent_name: &str, value: &Value) -> Event {
1766    terminal_event(invocation_id, agent_name, &render_final(value))
1767}
1768
1769/// A terminal event with the given text that clears the pending checkpoint.
1770fn terminal_event(invocation_id: &str, agent_name: &str, text: &str) -> Event {
1771    let mut event = Event::new(invocation_id);
1772    event.author = agent_name.to_string();
1773    event.llm_response.content = Some(Content::new("model").with_text(text));
1774    event.actions.state_delta.insert(PENDING_STATE_KEY.to_string(), Value::Null);
1775    event
1776}
1777
1778/// A transfer event: hands control to `target` and clears the pending
1779/// checkpoint. Mirrors how [`LlmAgent`](crate::LlmAgent) signals a transfer via
1780/// `EventActions::transfer_to_agent`.
1781fn transfer_event(invocation_id: &str, agent_name: &str, target: &str) -> Event {
1782    let mut event = Event::new(invocation_id);
1783    event.author = agent_name.to_string();
1784    event.actions.transfer_to_agent = Some(target.to_string());
1785    event.actions.state_delta.insert(PENDING_STATE_KEY.to_string(), Value::Null);
1786    event
1787}
1788
1789/// The prompt section that reveals the `transfer_to_agent` output and lists the
1790/// valid targets. Appended to the system prompt only when targets exist.
1791fn transfer_prompt(targets: &[String]) -> String {
1792    format!(
1793        "You may also hand the task to another agent by returning a value tagged \
1794\"transfer_to_agent\":\n- {{\"type\": \"transfer_to_agent\", \"agent_name\": \"...\"}}: \
1795transfer control to that agent; this ends your turn.\nValid agents: {}.",
1796        roster_list(targets)
1797    )
1798}
1799
1800/// Render a list of agent names for a prompt or error message.
1801fn roster_list(targets: &[String]) -> String {
1802    targets.join(", ")
1803}
1804
1805/// The model-call hooks applied around each [`next_script`] request: legacy
1806/// before/after-model callbacks plus the optional enhanced-plugin pipeline.
1807struct ModelHooks<'a> {
1808    before: &'a [BeforeModelCallback],
1809    after: &'a [AfterModelCallback],
1810    /// The run's invocation hooks, iterated ahead of `before` and `after`.
1811    hooks: &'a HookCallbacks,
1812    ctx: &'a Arc<dyn CallbackContext>,
1813    /// The run budget and spend ledger model calls count against.
1814    scope: &'a adk_core::ModelCallScope,
1815    #[cfg(feature = "enhanced-plugins")]
1816    plugins: Option<&'a EnhancedPluginManager>,
1817}
1818
1819/// Pull one script out of the model and extract the fenced code block.
1820///
1821/// The request passes through before-model hooks (enhanced plugins, then legacy
1822/// `before_model_callback`s), either of which may rewrite it or short-circuit
1823/// with a synthetic response; the response then passes through after-model hooks
1824/// (legacy `after_model_callback`s, then enhanced plugins).
1825async fn next_script(
1826    model: &dyn Llm,
1827    transcript: &[Content],
1828    config: &Option<GenerateContentConfig>,
1829    hooks: &ModelHooks<'_>,
1830) -> Result<String, AdkError> {
1831    let mut request = LlmRequest::new(model.name().to_string(), transcript.to_vec());
1832    if let Some(config) = config {
1833        request = request.with_config(config.clone());
1834    }
1835
1836    let mut content: Option<Content> = None;
1837
1838    // Plugins and callbacks take the request: one that skips the call leaves nothing to send.
1839    // before-model plugins: modify the request or short-circuit.
1840    #[cfg(feature = "enhanced-plugins")]
1841    if let Some(epm) = hooks.plugins {
1842        let taken = std::mem::replace(&mut request, LlmRequest::new("", vec![]));
1843        match epm.run_before_model_call(taken, hooks.ctx.clone()).await? {
1844            BeforeModelCallResult::Continue(modified) => request = modified,
1845            BeforeModelCallResult::ShortCircuit(response) => content = response.content,
1846        }
1847    }
1848
1849    // before-model callbacks: rewrite the request or skip the call with a response.
1850    if content.is_none() {
1851        for callback in hooks.hooks.before_model.iter().chain(hooks.before) {
1852            let taken = std::mem::replace(&mut request, LlmRequest::new("", vec![]));
1853            match callback(hooks.ctx.clone(), taken).await? {
1854                BeforeModelResult::Continue(modified) => request = modified,
1855                BeforeModelResult::Skip(response) => {
1856                    content = response.content;
1857                    break;
1858                }
1859            }
1860        }
1861    }
1862
1863    if content.is_none() {
1864        let mut stream = hooks.scope.generate(model, request, false).await?;
1865        let mut text = String::new();
1866        let mut finish_reason = None;
1867        let mut provider_error = (None, None);
1868        while let Some(chunk) = stream.next().await {
1869            let chunk = chunk?;
1870            finish_reason = chunk.finish_reason.or(finish_reason);
1871            if chunk.error_code.is_some() {
1872                provider_error = (chunk.error_code, chunk.error_message);
1873            }
1874            if let Some(c) = chunk.content {
1875                for part in &c.parts {
1876                    if let Part::Text { text: t } = part {
1877                        text.push_str(t);
1878                    }
1879                }
1880            }
1881        }
1882        // A refusal is not a script to run, and a malformed tool call is not one either.
1883        let (provider_code, provider_message) = provider_error;
1884        if let Some(error) = crate::llm_agent::finish_error(
1885            finish_reason,
1886            provider_message.as_deref().or(Some(text.as_str())),
1887            provider_code.as_deref(),
1888        ) {
1889            return Err(error);
1890        }
1891        content = Some(Content::new("model").with_text(text));
1892    }
1893
1894    // after-model callbacks: rewrite the accumulated response.
1895    for callback in hooks.hooks.after_model.iter().chain(hooks.after) {
1896        let response = LlmResponse { content: content.clone(), ..Default::default() };
1897        if let Some(modified) = callback(hooks.ctx.clone(), response).await? {
1898            content = modified.content;
1899        }
1900    }
1901
1902    // after-model plugins: modify the response.
1903    #[cfg(feature = "enhanced-plugins")]
1904    if let Some(epm) = hooks.plugins {
1905        let response = LlmResponse { content: content.clone(), ..Default::default() };
1906        let AfterModelCallResult::Continue(modified) =
1907            epm.run_after_model_call(response, hooks.ctx.clone()).await?;
1908        content = modified.content;
1909    }
1910
1911    let text = content
1912        .map(|c| c.parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join(""))
1913        .unwrap_or_default();
1914    Ok(extract_code_block(&text))
1915}
1916
1917/// Extract the body of the first fenced code block, skipping any language tag on
1918/// the fence line. Falls back to the trimmed input when no fence is present.
1919pub fn extract_code_block(text: &str) -> String {
1920    if let Some(start) = text.find("```") {
1921        let after = &text[start + 3..];
1922        if let Some(newline) = after.find('\n') {
1923            let body = &after[newline + 1..];
1924            if let Some(end) = body.find("```") {
1925                return body[..end].trim().to_string();
1926            }
1927        }
1928    }
1929    text.trim().to_string()
1930}
1931
1932/// Find the `FunctionResponse` carrying a long-running tool's result in an
1933/// incoming message (how the result is delivered on the next invocation).
1934///
1935/// To avoid resuming the wrong continuation when there are stale responses or
1936/// repeated calls to the same tool, a response whose `id` matches the awaited
1937/// `call_id` is preferred. A response that carries no id falls back to matching
1938/// on the tool name alone.
1939fn completion_for(content: &Content, tool: &str, call_id: u64) -> Option<Value> {
1940    let want_id = call_id.to_string();
1941    let by_id = content.parts.iter().find_map(|part| match part {
1942        Part::FunctionResponse { function_response, id, .. }
1943            if function_response.name == tool && id.as_deref() == Some(want_id.as_str()) =>
1944        {
1945            Some(function_response.response.clone())
1946        }
1947        _ => None,
1948    });
1949    if by_id.is_some() {
1950        return by_id;
1951    }
1952    content.parts.iter().find_map(|part| match part {
1953        Part::FunctionResponse { function_response, id, .. }
1954            if function_response.name == tool && id.is_none() =>
1955        {
1956            Some(function_response.response.clone())
1957        }
1958        _ => None,
1959    })
1960}
1961
1962fn roster(tools: &ToolMap) -> Vec<String> {
1963    let mut names: Vec<String> = tools.keys().cloned().collect();
1964    names.sort();
1965    names
1966}
1967
1968fn observation_content(value: &Value) -> Content {
1969    Content::new("user").with_text(format!("Observation:\n{}", render_value(value)))
1970}
1971
1972fn error_content(message: &str) -> Content {
1973    Content::new("user").with_text(format!("Error during execution:\n{message}"))
1974}
1975
1976/// How [`stdout_content`] begins.
1977const STDOUT_PREFIX: &str = "Output (stdout):\n";
1978
1979/// Surface captured stdout (`print` output) back to the model.
1980fn stdout_content(output: &str) -> Content {
1981    Content::new("user").with_text(format!("{STDOUT_PREFIX}{output}"))
1982}
1983
1984/// A *copy* of `transcript` with any stdout printed this turn appended, for
1985/// baking into a checkpoint.
1986///
1987/// The live transcript is left untouched — stdout is flushed onto it at the end
1988/// of the turn instead. Persisting the same output into the checkpoint ensures
1989/// anything the script printed *before* a suspend (HITL confirmation, a
1990/// long-running deferral) or an inline write-ahead checkpoint survives the
1991/// suspend/resume boundary and crash recovery, without being counted twice on
1992/// the in-process path (a resumed continuation only re-emits output produced
1993/// after the call boundary).
1994fn transcript_with_stdout(transcript: &[Content], stdout: &str, max: usize) -> Vec<Content> {
1995    let mut out = transcript.to_vec();
1996    if !stdout.is_empty() {
1997        out.push(stdout_content(&truncate_middle(stdout, max)));
1998    }
1999    out
2000}
2001
2002fn truncate_middle(message: &str, max: usize) -> String {
2003    if message.chars().count() <= max {
2004        return message.to_string();
2005    }
2006    let head: String = message.chars().take(max / 2).collect();
2007    let tail: String =
2008        message.chars().rev().take(max / 2).collect::<Vec<_>>().into_iter().rev().collect();
2009    format!("{head}\n...[truncated]...\n{tail}")
2010}
2011
2012/// Validate a JSON value against an output schema, collecting all errors.
2013fn validate_against_schema(value: &Value, schema: &Value) -> Result<(), String> {
2014    let validator =
2015        jsonschema::validator_for(schema).map_err(|e| format!("invalid output schema: {e}"))?;
2016    let errors: Vec<String> = validator.iter_errors(value).map(|e| e.to_string()).collect();
2017    if errors.is_empty() { Ok(()) } else { Err(errors.join("; ")) }
2018}
2019
2020fn render_final(value: &Value) -> String {
2021    match value {
2022        Value::String(s) => s.clone(),
2023        other => serde_json::to_string_pretty(other).unwrap_or_else(|_| other.to_string()),
2024    }
2025}
2026
2027fn runtime_err(err: RuntimeError) -> AdkError {
2028    AdkError::new(
2029        ErrorComponent::Agent,
2030        ErrorCategory::Internal,
2031        "codeact.runtime",
2032        err.to_string(),
2033    )
2034}
2035
2036// ===========================================================================
2037// Agent
2038// ===========================================================================
2039
2040/// A configured CodeAct agent.
2041///
2042/// Build one with [`CodeActAgent::builder`], supplying a [`Llm`] and a
2043/// [`CodeRuntime`]. The agent then drives the CodeAct loop: each turn the model
2044/// writes one script, tools are exposed as callable functions, and the script
2045/// returns a tagged [`ScriptOutput`].
2046///
2047/// # Example
2048///
2049/// ```rust,ignore
2050/// use std::sync::Arc;
2051/// use adk_agent::codeact::CodeActAgent;
2052///
2053/// // `model` implements `adk_core::Llm`; `runtime` implements `CodeRuntime`
2054/// // (e.g. a Monty-backed Python interpreter).
2055/// let agent = CodeActAgent::builder()
2056///     .name("analyst")
2057///     .model(model)
2058///     .runtime(runtime)
2059///     .instruction("Prefer pandas-style transformations.")
2060///     .tool(Arc::new(load_csv_tool))
2061///     .output_key("report")
2062///     .build()?;
2063/// # Ok::<(), adk_core::AdkError>(())
2064/// ```
2065pub struct CodeActAgent {
2066    name: String,
2067    description: String,
2068    model: Arc<dyn Llm>,
2069    tools: Vec<Arc<dyn Tool>>,
2070    toolsets: Vec<Arc<dyn Toolset>>,
2071    runtime: Arc<dyn CodeRuntime>,
2072    policy: ToolConfirmationPolicy,
2073    skills_index: Option<Arc<SkillIndex>>,
2074    skill_policy: SelectionPolicy,
2075    max_skill_chars: usize,
2076    instruction: Option<String>,
2077    instruction_provider: Option<Arc<InstructionProvider>>,
2078    static_instruction: Option<String>,
2079    global_instruction: Option<String>,
2080    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
2081    include_contents: IncludeContents,
2082    max_iterations: u32,
2083    max_error_chars: usize,
2084    supports_suspension: bool,
2085    sub_agents: Vec<Arc<dyn Agent>>,
2086    disallow_transfer_to_parent: bool,
2087    disallow_transfer_to_peers: bool,
2088    generate_content_config: Option<GenerateContentConfig>,
2089    tool_timeout: Duration,
2090    output_key: Option<String>,
2091    before_callbacks: Arc<Vec<BeforeAgentCallback>>,
2092    after_callbacks: Arc<Vec<AfterAgentCallback>>,
2093    before_model_callbacks: Arc<Vec<BeforeModelCallback>>,
2094    after_model_callbacks: Arc<Vec<AfterModelCallback>>,
2095    before_tool_callbacks: Arc<Vec<BeforeToolCallback>>,
2096    after_tool_callbacks: Arc<Vec<AfterToolCallback>>,
2097    after_tool_callbacks_full: Arc<Vec<AfterToolCallbackFull>>,
2098    default_retry_budget: Option<RetryBudget>,
2099    tool_retry_budgets: HashMap<String, RetryBudget>,
2100    circuit_breaker_threshold: Option<u32>,
2101    on_tool_error: Arc<Vec<OnToolErrorCallback>>,
2102    input_schema: Option<Value>,
2103    output_schema: Option<Value>,
2104    output_max_retries: usize,
2105    input_guardrails: Arc<GuardrailSet>,
2106    output_guardrails: Arc<GuardrailSet>,
2107    #[cfg(feature = "enhanced-plugins")]
2108    enhanced_plugin_manager: Option<Arc<EnhancedPluginManager>>,
2109}
2110
2111impl CodeActAgent {
2112    /// Start building a [`CodeActAgent`].
2113    pub fn builder() -> CodeActAgentBuilder {
2114        CodeActAgentBuilder::new()
2115    }
2116
2117    /// The JSON schema describing this agent's input, if set.
2118    ///
2119    /// Like `LlmAgent`, this is descriptive metadata (e.g. for exposing the
2120    /// agent as a tool); it is not enforced on the incoming user message.
2121    pub fn input_schema(&self) -> Option<&Value> {
2122        self.input_schema.as_ref()
2123    }
2124
2125    /// Resolve the global instruction for this invocation (dynamic provider or
2126    /// static `{key}` template), or `None` when unset/empty.
2127    async fn resolve_global_instruction(
2128        &self,
2129        ctx: &Arc<dyn InvocationContext>,
2130    ) -> adk_core::Result<Option<String>> {
2131        if let Some(provider) = &self.global_instruction_provider {
2132            let text = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
2133            Ok((!text.is_empty()).then_some(text))
2134        } else if let Some(template) = &self.global_instruction {
2135            let text = adk_core::inject_session_state(ctx.as_ref(), template).await?;
2136            Ok((!text.is_empty()).then_some(text))
2137        } else {
2138            Ok(None)
2139        }
2140    }
2141
2142    /// Resolve the agent instruction for this invocation.
2143    async fn resolve_instruction(
2144        &self,
2145        ctx: &Arc<dyn InvocationContext>,
2146    ) -> adk_core::Result<Option<String>> {
2147        if let Some(provider) = &self.instruction_provider {
2148            let text = provider(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
2149            Ok((!text.is_empty()).then_some(text))
2150        } else if let Some(template) = &self.instruction {
2151            let text = adk_core::inject_session_state(ctx.as_ref(), template).await?;
2152            Ok((!text.is_empty()).then_some(text))
2153        } else {
2154            Ok(None)
2155        }
2156    }
2157
2158    /// Resolve the callable tool set for this invocation: static tools plus the
2159    /// tools each [`Toolset`] yields for `ctx`. Rejects duplicate names
2160    /// (static-vs-toolset and toolset-vs-toolset), mirroring `LlmAgent`.
2161    async fn resolve_tools(
2162        &self,
2163        ctx: &Arc<dyn InvocationContext>,
2164    ) -> adk_core::Result<Vec<Arc<dyn Tool>>> {
2165        if self.toolsets.is_empty() && ctx.run_config().runtime_toolsets.is_empty() {
2166            return Ok(self.tools.clone());
2167        }
2168        let mut resolved = self.tools.clone();
2169        let static_names: std::collections::HashSet<String> =
2170            self.tools.iter().map(|t| t.name().to_string()).collect();
2171        let mut source: HashMap<String, String> = HashMap::new();
2172        let mut active_toolsets: Vec<&dyn Toolset> =
2173            self.toolsets.iter().map(AsRef::as_ref).collect();
2174        active_toolsets.extend(
2175            ctx.run_config().runtime_toolsets.iter().map(|runtime| runtime.toolset().as_ref()),
2176        );
2177        for toolset in active_toolsets {
2178            let provided = toolset.tools(ctx.clone() as Arc<dyn ReadonlyContext>).await?;
2179            for tool in provided {
2180                let name = tool.name().to_string();
2181                if static_names.contains(&name) {
2182                    return Err(AdkError::agent(format!(
2183                        "duplicate tool name '{name}': conflict between a static tool and toolset '{}'",
2184                        toolset.name()
2185                    )));
2186                }
2187                if let Some(other) = source.get(&name) {
2188                    return Err(AdkError::agent(format!(
2189                        "duplicate tool name '{name}': conflict between toolset '{other}' and toolset '{}'",
2190                        toolset.name()
2191                    )));
2192                }
2193                source.insert(name, toolset.name().to_string());
2194                resolved.push(tool);
2195            }
2196        }
2197        Ok(resolved)
2198    }
2199
2200    /// Apply input guardrails to the incoming user content. Returns a context
2201    /// whose user content is the (possibly transformed) result, or an error if
2202    /// the content is blocked. A no-op when no input guardrails are set.
2203    async fn apply_input_guardrails(
2204        &self,
2205        ctx: Arc<dyn InvocationContext>,
2206    ) -> adk_core::Result<Arc<dyn InvocationContext>> {
2207        if self.input_guardrails.is_empty() {
2208            return Ok(ctx);
2209        }
2210        let content =
2211            enforce_guardrails(self.input_guardrails.as_ref(), ctx.user_content(), Phase::Input)
2212                .await?
2213                .content;
2214        if content.role != ctx.user_content().role || content.parts != ctx.user_content().parts {
2215            Ok(crate::workflow::with_user_content_override(ctx, content))
2216        } else {
2217            Ok(ctx)
2218        }
2219    }
2220
2221    /// Select the most relevant skill's prompt block for this invocation's
2222    /// user query, if a skills index is configured. Returns `None` when skills
2223    /// are unset, disabled, or nothing meets the policy threshold.
2224    fn select_skill_block(&self, ctx: &Arc<dyn InvocationContext>) -> Option<String> {
2225        let index = self.skills_index.as_ref()?;
2226        let query =
2227            ctx.user_content().parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join("\n");
2228        select_skill_prompt_block(index.as_ref(), &query, &self.skill_policy, self.max_skill_chars)
2229            .map(|(_, block)| block)
2230    }
2231
2232    /// Resolve the conversation that seeds the transcript, honoring
2233    /// [`IncludeContents`] and transfer history filtering. Always ends with the
2234    /// current user turn.
2235    fn resolve_conversation(&self, ctx: &Arc<dyn InvocationContext>) -> Vec<Content> {
2236        let current = ctx.user_content().clone();
2237        match self.include_contents {
2238            IncludeContents::None => vec![current],
2239            IncludeContents::Default => {
2240                let mut history = if ctx.run_config().transfer_targets.is_empty()
2241                    && !ctx.authoritative_transfer_targets()
2242                {
2243                    ctx.session().conversation_history()
2244                } else {
2245                    ctx.session().conversation_history_for_agent(&self.name)
2246                };
2247                // Session history already contains the current user message;
2248                // ensure the latest user turn reflects the current content. The run's own
2249                // message is preferred, so a steering message a run-mate took after it stays.
2250                if let Some(idx) = history
2251                    .iter()
2252                    .rposition(|c| *c == current)
2253                    .or_else(|| history.iter().rposition(|c| c.role == "user"))
2254                {
2255                    history[idx] = current;
2256                } else {
2257                    history.push(current);
2258                }
2259                history
2260            }
2261        }
2262    }
2263}
2264
2265impl std::fmt::Debug for CodeActAgent {
2266    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2267        f.debug_struct("CodeActAgent")
2268            .field("name", &self.name)
2269            .field("tools", &self.tools.len())
2270            .field("supports_suspension", &self.supports_suspension)
2271            .finish()
2272    }
2273}
2274
2275#[async_trait]
2276impl Agent for CodeActAgent {
2277    fn name(&self) -> &str {
2278        &self.name
2279    }
2280
2281    fn description(&self) -> &str {
2282        &self.description
2283    }
2284
2285    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
2286        &self.sub_agents
2287    }
2288
2289    fn allows_transfer_to_parent(&self) -> bool {
2290        !self.disallow_transfer_to_parent
2291    }
2292
2293    fn allows_transfer_to_peers(&self) -> bool {
2294        !self.disallow_transfer_to_peers
2295    }
2296
2297    async fn close(&self) {
2298        for toolset in &self.toolsets {
2299            toolset.close().await;
2300        }
2301        for agent in &self.sub_agents {
2302            agent.close().await;
2303        }
2304    }
2305
2306    async fn prewarm(&self) -> adk_core::Result<()> {
2307        self.model.prewarm().await?;
2308        for agent in &self.sub_agents {
2309            agent.prewarm().await?;
2310        }
2311        Ok(())
2312    }
2313
2314    async fn screen_user_input(&self, content: &Content) -> adk_core::Result<Option<Content>> {
2315        let own = if self.input_guardrails.is_empty() {
2316            None
2317        } else {
2318            Some(
2319                enforce_guardrails(self.input_guardrails.as_ref(), content, Phase::Input)
2320                    .await?
2321                    .content,
2322            )
2323        };
2324        let below =
2325            adk_core::screen_user_input_with(&self.sub_agents, own.as_ref().unwrap_or(content))
2326                .await?;
2327        Ok(below.or(own))
2328    }
2329
2330    fn capabilities(&self) -> adk_core::AgentCapabilities {
2331        adk_core::AgentCapabilities {
2332            runtime_tools: true,
2333            handoff: true,
2334            relationship_confirmation: false,
2335            checkpoint_resume: false,
2336            shared_state: true,
2337            invocation_metadata: true,
2338        }
2339    }
2340
2341    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> adk_core::Result<EventStream> {
2342        // A call a person asked for needs an agent that can hold it for their decision, which
2343        // a script cannot (spec 3.3 §7.4 rule 5, wave 4 decision 13).
2344        if let Some(refused) = crate::requested_call::refused_by_root(
2345            ctx.as_ref(),
2346            self.name(),
2347            "this agent runs code and cannot hold a call for a person's decision",
2348        ) {
2349            return Ok(refused);
2350        }
2351        // Under a workflow or team parent, the agent still acts as itself.
2352        let ctx = crate::acting_agent_context::ActingAgentContext::scope(ctx, self.name());
2353        // Input guardrails run first; a block aborts the run, a transform
2354        // (e.g. PII redaction) rewrites the user content downstream.
2355        let ctx = self.apply_input_guardrails(ctx).await?;
2356
2357        let pending = ctx
2358            .session()
2359            .state()
2360            .get(PENDING_STATE_KEY)
2361            .and_then(|v| serde_json::from_value(v).ok());
2362
2363        // Valid transfer targets: sub-agents (always) plus runner-provided
2364        // targets (parent/peers) from RunConfig, de-duplicated and filtered by
2365        // the `disallow_transfer_to_parent`/`disallow_transfer_to_peers` flags
2366        // (which apply only to the runner-provided parent/peers, never to
2367        // sub-agents). Mirrors LlmAgent.
2368        let mut transfer_targets: Vec<String> = if ctx.authoritative_transfer_targets() {
2369            Vec::new()
2370        } else {
2371            self.sub_agents.iter().map(|a| a.name().to_string()).collect()
2372        };
2373        let parent = ctx.run_config().parent_agent.as_deref();
2374        for target in &ctx.run_config().transfer_targets {
2375            if transfer_targets.contains(target) {
2376                continue;
2377            }
2378            let is_parent = parent == Some(target.as_str());
2379            if is_parent && self.disallow_transfer_to_parent {
2380                continue;
2381            }
2382            if !is_parent && self.disallow_transfer_to_peers {
2383                continue;
2384            }
2385            transfer_targets.push(target.clone());
2386        }
2387
2388        let invocation_id = ctx.invocation_id().to_string();
2389        let agent_name = self.name.clone();
2390
2391        // Resolve toolsets for this invocation and merge with static tools,
2392        // rejecting name conflicts (mirrors LlmAgent).
2393        let resolved_tools = self.resolve_tools(&ctx).await?;
2394
2395        // Resolve instructions per-invocation (providers are async, statics get
2396        // `{key}` template injection), then assemble the full prompt.
2397        let global = self.resolve_global_instruction(&ctx).await?;
2398        let instruction = self.resolve_instruction(&ctx).await?;
2399        let transfer_section =
2400            (!transfer_targets.is_empty()).then(|| transfer_prompt(&transfer_targets));
2401        let skill_block = self.select_skill_block(&ctx);
2402        let mut system_prompt = assemble_system_prompt(
2403            skill_block.as_deref(),
2404            self.static_instruction.as_deref(),
2405            global.as_deref(),
2406            instruction.as_deref(),
2407            &self.runtime.capabilities().prompt,
2408            &self.runtime.render_tools(&resolved_tools),
2409            transfer_section.as_deref(),
2410        );
2411        // Tell the model the final result must conform to the output schema.
2412        if let Some(schema) = &self.output_schema {
2413            system_prompt.push_str(&format!(
2414                "\n\nYour final_result value MUST be valid JSON conforming to this schema:\n{schema}"
2415            ));
2416        }
2417
2418        let conversation = self.resolve_conversation(&ctx);
2419
2420        let input = LoopInputs {
2421            model: self.model.clone(),
2422            runtime: self.runtime.clone(),
2423            tools: resolved_tools,
2424            policy: self.policy.clone(),
2425            invocation_ctx: ctx.clone(),
2426            incoming: ctx.user_content().clone(),
2427            system_prompt,
2428            conversation,
2429            pending,
2430            invocation_id: invocation_id.clone(),
2431            agent_name: agent_name.clone(),
2432            max_iterations: self.max_iterations,
2433            max_error_chars: self.max_error_chars,
2434            supports_suspension: self.supports_suspension,
2435            transfer_targets,
2436            generate_content_config: self.generate_content_config.clone(),
2437            tool_timeout: self.tool_timeout,
2438            output_key: self.output_key.clone(),
2439            default_retry_budget: self.default_retry_budget.clone(),
2440            tool_retry_budgets: self.tool_retry_budgets.clone(),
2441            circuit_breaker_threshold: self.circuit_breaker_threshold,
2442            on_tool_error: self.on_tool_error.clone(),
2443            before_model_callbacks: self.before_model_callbacks.clone(),
2444            after_model_callbacks: self.after_model_callbacks.clone(),
2445            before_tool_callbacks: self.before_tool_callbacks.clone(),
2446            after_tool_callbacks: self.after_tool_callbacks.clone(),
2447            after_tool_callbacks_full: self.after_tool_callbacks_full.clone(),
2448            output_schema: self.output_schema.clone(),
2449            output_max_retries: self.output_max_retries,
2450            output_guardrails: self.output_guardrails.clone(),
2451            #[cfg(feature = "enhanced-plugins")]
2452            enhanced_plugin_manager: self.enhanced_plugin_manager.clone(),
2453        };
2454
2455        let before = self.before_callbacks.clone();
2456        let after = self.after_callbacks.clone();
2457        let hooks = HookCallbacks::new(&ctx.run_config().invocation_hooks);
2458        // Agent-level callbacks receive the invocation context as a callback
2459        // context (upcast), exactly like LlmAgent.
2460        let cb_ctx = ctx as Arc<dyn CallbackContext>;
2461
2462        Ok(Box::pin(run_with_agent_callbacks(
2463            input,
2464            AgentCallbacks { hooks, before, after },
2465            cb_ctx,
2466            invocation_id,
2467            agent_name,
2468        )))
2469    }
2470}
2471
2472/// Wrap the CodeAct loop with before/after-agent callbacks, mirroring LlmAgent:
2473///
2474/// - Before-agent callbacks run first; the first one returning `Some(content)`
2475///   short-circuits the loop (its content is emitted, then after-agent
2476///   callbacks run, then the run ends).
2477/// - Otherwise the loop runs; after-agent callbacks run only when the loop
2478///   *completes normally* (a final result) — not when it suspends, errors, or
2479///   ends via a transfer/escalation. The first after-callback returning `Some`
2480///   wins.
2481fn run_with_agent_callbacks(
2482    input: LoopInputs,
2483    callbacks: AgentCallbacks,
2484    cb_ctx: Arc<dyn CallbackContext>,
2485    invocation_id: String,
2486    agent_name: String,
2487) -> impl Stream<Item = adk_core::Result<Event>> {
2488    stream! {
2489        let AgentCallbacks { hooks, before, after } = callbacks;
2490        // ----- before-agent callbacks -----
2491        for callback in hooks.before_agent.iter().chain(before.iter()) {
2492            match callback(cb_ctx.clone()).await {
2493                Ok(Some(content)) => {
2494                    yield Ok(callback_event(&invocation_id, &agent_name, content));
2495                    // Short-circuit: run after-agent callbacks, then stop.
2496                    for after_cb in hooks.after_agent.iter().chain(after.iter()) {
2497                        match after_cb(cb_ctx.clone()).await {
2498                            Ok(Some(c)) => {
2499                                yield Ok(callback_event(&invocation_id, &agent_name, c));
2500                                return;
2501                            }
2502                            Ok(None) => continue,
2503                            Err(e) => {
2504                                yield Err(e);
2505                                return;
2506                            }
2507                        }
2508                    }
2509                    return;
2510                }
2511                Ok(None) => continue,
2512                Err(e) => {
2513                    yield Err(e);
2514                    return;
2515                }
2516            }
2517        }
2518
2519        // ----- main loop -----
2520        // Track how the loop ended. The last event that touched the pending
2521        // checkpoint cleared it (Null) on a terminal turn, but set it on suspend; a
2522        // turn beside a waiting call leaves that call's checkpoint untouched.
2523        // A transfer/escalation/skip-summarization also clears it but must NOT
2524        // run after-agent callbacks (control is handed off / the run is told to
2525        // stop), matching LlmAgent's early return on those terminal actions.
2526        let mut completed = true;
2527        let mut errored = false;
2528        let mut handed_off = false;
2529        let mut inner = Box::pin(run_codeact(input));
2530        while let Some(item) = inner.next().await {
2531            match &item {
2532                Ok(event) => {
2533                    if let Some(value) = event.actions.state_delta.get(PENDING_STATE_KEY) {
2534                        completed = value.is_null();
2535                    }
2536                    if event.actions.escalate
2537                        || event.actions.skip_summarization
2538                        || event.actions.transfer_to_agent.is_some()
2539                    {
2540                        handed_off = true;
2541                    }
2542                }
2543                Err(_) => errored = true,
2544            }
2545            yield item;
2546        }
2547
2548        // ----- after-agent callbacks -----
2549        if !errored && completed && !handed_off {
2550            for after_cb in hooks.after_agent.iter().chain(after.iter()) {
2551                match after_cb(cb_ctx.clone()).await {
2552                    Ok(Some(c)) => {
2553                        yield Ok(callback_event(&invocation_id, &agent_name, c));
2554                        break;
2555                    }
2556                    Ok(None) => continue,
2557                    Err(e) => {
2558                        yield Err(e);
2559                        return;
2560                    }
2561                }
2562            }
2563        }
2564    }
2565}
2566
2567/// Agent-level callbacks: the run's invocation hooks first, then the agent's own.
2568struct AgentCallbacks {
2569    hooks: HookCallbacks,
2570    before: Arc<Vec<BeforeAgentCallback>>,
2571    after: Arc<Vec<AfterAgentCallback>>,
2572}
2573
2574/// An event carrying content produced by an agent-level callback.
2575fn callback_event(invocation_id: &str, agent_name: &str, content: Content) -> Event {
2576    let mut event = Event::new(invocation_id);
2577    event.author = agent_name.to_string();
2578    event.llm_response.content = Some(content);
2579    event
2580}
2581
2582/// Builder for [`CodeActAgent`].
2583///
2584/// [`model`](Self::model) and [`runtime`](Self::runtime) are required; every
2585/// other setting has a default. The configuration surface mirrors
2586/// [`LlmAgentBuilder`](crate::LlmAgentBuilder) (instructions, tools, toolsets,
2587/// retries, guardrails, callbacks, transfer, output schema, ...).
2588///
2589/// # Example
2590///
2591/// ```rust,ignore
2592/// use std::sync::Arc;
2593/// use std::time::Duration;
2594/// use adk_agent::codeact::CodeActAgent;
2595///
2596/// let agent = CodeActAgent::builder()
2597///     .name("assistant")
2598///     .model(model)
2599///     .runtime(runtime)
2600///     .temperature(0.2)
2601///     .tool_timeout(Duration::from_secs(30))
2602///     .require_tool_confirmation("delete_file")
2603///     .build()?;
2604/// # Ok::<(), adk_core::AdkError>(())
2605/// ```
2606pub struct CodeActAgentBuilder {
2607    name: String,
2608    description: String,
2609    model: Option<Arc<dyn Llm>>,
2610    tools: Vec<Arc<dyn Tool>>,
2611    toolsets: Vec<Arc<dyn Toolset>>,
2612    runtime: Option<Arc<dyn CodeRuntime>>,
2613    policy: ToolConfirmationPolicy,
2614    skills_index: Option<Arc<SkillIndex>>,
2615    skill_policy: SelectionPolicy,
2616    max_skill_chars: usize,
2617    instruction: Option<String>,
2618    instruction_provider: Option<Arc<InstructionProvider>>,
2619    static_instruction: Option<String>,
2620    global_instruction: Option<String>,
2621    global_instruction_provider: Option<Arc<GlobalInstructionProvider>>,
2622    include_contents: IncludeContents,
2623    max_iterations: u32,
2624    max_error_chars: usize,
2625    sub_agents: Vec<Arc<dyn Agent>>,
2626    disallow_transfer_to_parent: bool,
2627    disallow_transfer_to_peers: bool,
2628    generate_content_config: Option<GenerateContentConfig>,
2629    tool_timeout: Duration,
2630    output_key: Option<String>,
2631    before_callbacks: Vec<BeforeAgentCallback>,
2632    after_callbacks: Vec<AfterAgentCallback>,
2633    before_model_callbacks: Vec<BeforeModelCallback>,
2634    after_model_callbacks: Vec<AfterModelCallback>,
2635    before_tool_callbacks: Vec<BeforeToolCallback>,
2636    after_tool_callbacks: Vec<AfterToolCallback>,
2637    after_tool_callbacks_full: Vec<AfterToolCallbackFull>,
2638    default_retry_budget: Option<RetryBudget>,
2639    tool_retry_budgets: HashMap<String, RetryBudget>,
2640    circuit_breaker_threshold: Option<u32>,
2641    on_tool_error: Vec<OnToolErrorCallback>,
2642    input_schema: Option<Value>,
2643    output_schema: Option<Value>,
2644    output_max_retries: usize,
2645    input_guardrails: GuardrailSet,
2646    output_guardrails: GuardrailSet,
2647    #[cfg(feature = "enhanced-plugins")]
2648    enhanced_plugins: Vec<Arc<dyn EnhancedPlugin>>,
2649}
2650
2651impl CodeActAgentBuilder {
2652    /// Create a builder with default settings.
2653    pub fn new() -> Self {
2654        Self {
2655            name: "code-agent".to_string(),
2656            description: "A CodeAct agent that acts by writing and running code.".to_string(),
2657            model: None,
2658            tools: Vec::new(),
2659            toolsets: Vec::new(),
2660            runtime: None,
2661            policy: ToolConfirmationPolicy::Never,
2662            skills_index: None,
2663            skill_policy: SelectionPolicy::default(),
2664            max_skill_chars: DEFAULT_MAX_SKILL_CHARS,
2665            instruction: None,
2666            instruction_provider: None,
2667            static_instruction: None,
2668            global_instruction: None,
2669            global_instruction_provider: None,
2670            include_contents: IncludeContents::default(),
2671            max_iterations: DEFAULT_MAX_ITERATIONS,
2672            max_error_chars: DEFAULT_MAX_ERROR_CHARS,
2673            sub_agents: Vec::new(),
2674            disallow_transfer_to_parent: false,
2675            disallow_transfer_to_peers: false,
2676            generate_content_config: None,
2677            tool_timeout: DEFAULT_TOOL_TIMEOUT,
2678            output_key: None,
2679            before_callbacks: Vec::new(),
2680            after_callbacks: Vec::new(),
2681            before_model_callbacks: Vec::new(),
2682            after_model_callbacks: Vec::new(),
2683            before_tool_callbacks: Vec::new(),
2684            after_tool_callbacks: Vec::new(),
2685            after_tool_callbacks_full: Vec::new(),
2686            default_retry_budget: None,
2687            tool_retry_budgets: HashMap::new(),
2688            circuit_breaker_threshold: None,
2689            on_tool_error: Vec::new(),
2690            input_schema: None,
2691            output_schema: None,
2692            output_max_retries: DEFAULT_OUTPUT_MAX_RETRIES,
2693            input_guardrails: GuardrailSet::new(),
2694            output_guardrails: GuardrailSet::new(),
2695            #[cfg(feature = "enhanced-plugins")]
2696            enhanced_plugins: Vec::new(),
2697        }
2698    }
2699
2700    /// Set the agent name.
2701    pub fn name(mut self, name: impl Into<String>) -> Self {
2702        self.name = name.into();
2703        self
2704    }
2705
2706    /// Set the agent description.
2707    pub fn description(mut self, description: impl Into<String>) -> Self {
2708        self.description = description.into();
2709        self
2710    }
2711
2712    /// Set the model (required).
2713    pub fn model(mut self, model: Arc<dyn Llm>) -> Self {
2714        self.model = Some(model);
2715        self
2716    }
2717
2718    /// Set the code runtime (required).
2719    pub fn runtime(mut self, runtime: Arc<dyn CodeRuntime>) -> Self {
2720        self.runtime = Some(runtime);
2721        self
2722    }
2723
2724    /// Register a tool callable from scripts.
2725    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
2726        self.tools.push(tool);
2727        self
2728    }
2729
2730    /// Add a sub-agent this agent may transfer control to.
2731    ///
2732    /// When any sub-agent is present (or the Runner supplies transfer targets),
2733    /// the [`transfer_to_agent`](crate::codeact::ScriptOutput::TransferToAgent)
2734    /// output is described to the model.
2735    pub fn sub_agent(mut self, agent: Arc<dyn Agent>) -> Self {
2736        self.sub_agents.push(agent);
2737        self
2738    }
2739
2740    /// Add a toolset whose tools are resolved fresh on each invocation from the
2741    /// run's [`ReadonlyContext`] (e.g. per-user or pooled tools). Resolved tools
2742    /// are merged with static tools; duplicate names are rejected at run time.
2743    pub fn toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
2744        self.toolsets.push(toolset);
2745        self
2746    }
2747
2748    /// Set a preloaded skills index. The most relevant skill for each user
2749    /// query is injected into the system prompt.
2750    #[cfg(feature = "skills")]
2751    pub fn with_skills(mut self, index: SkillIndex) -> Self {
2752        self.skills_index = Some(Arc::new(index));
2753        self
2754    }
2755
2756    /// Auto-load skills from `.skills/` in the current working directory.
2757    ///
2758    /// # Errors
2759    /// Returns an error if the skills directory cannot be loaded.
2760    #[cfg(feature = "skills")]
2761    pub fn with_auto_skills(self) -> adk_core::Result<Self> {
2762        self.with_skills_from_root(".")
2763    }
2764
2765    /// Load skills from `.skills/` under a custom root directory.
2766    ///
2767    /// # Errors
2768    /// Returns an error if the skills directory cannot be loaded.
2769    #[cfg(feature = "skills")]
2770    pub fn with_skills_from_root(
2771        mut self,
2772        root: impl AsRef<std::path::Path>,
2773    ) -> adk_core::Result<Self> {
2774        let index = crate::skill_shim::load_skill_index(root)
2775            .map_err(|e| AdkError::agent(e.to_string()))?;
2776        self.skills_index = Some(Arc::new(index));
2777        Ok(self)
2778    }
2779
2780    /// Customize skill selection behavior.
2781    #[cfg(feature = "skills")]
2782    pub fn with_skill_policy(mut self, policy: SelectionPolicy) -> Self {
2783        self.skill_policy = policy;
2784        self
2785    }
2786
2787    /// Limit injected skill content length (default 2000 chars).
2788    #[cfg(feature = "skills")]
2789    pub fn with_skill_budget(mut self, max_chars: usize) -> Self {
2790        self.max_skill_chars = max_chars;
2791        self
2792    }
2793
2794    /// Prevent this agent from transferring control back to its parent.
2795    ///
2796    /// Applies only to the parent the Runner supplies via
2797    /// `RunConfig::parent_agent`; sub-agents are unaffected.
2798    pub fn disallow_transfer_to_parent(mut self, disallow: bool) -> Self {
2799        self.disallow_transfer_to_parent = disallow;
2800        self
2801    }
2802
2803    /// Prevent this agent from transferring control to peer agents.
2804    ///
2805    /// Applies only to the runner-provided peers in `RunConfig::transfer_targets`;
2806    /// sub-agents are unaffected.
2807    pub fn disallow_transfer_to_peers(mut self, disallow: bool) -> Self {
2808        self.disallow_transfer_to_peers = disallow;
2809        self
2810    }
2811
2812    /// Set the tool confirmation policy.
2813    pub fn tool_confirmation_policy(mut self, policy: ToolConfirmationPolicy) -> Self {
2814        self.policy = policy;
2815        self
2816    }
2817
2818    /// Require human confirmation for a specific tool.
2819    pub fn require_tool_confirmation(mut self, tool_name: impl Into<String>) -> Self {
2820        self.policy = self.policy.with_tool(tool_name);
2821        self
2822    }
2823
2824    /// Require human confirmation for every tool call.
2825    pub fn require_tool_confirmation_for_all(mut self) -> Self {
2826        self.policy = ToolConfirmationPolicy::Always;
2827        self
2828    }
2829
2830    /// Set the generation config (temperature, tokens, etc.) applied to every
2831    /// model request.
2832    pub fn generate_content_config(mut self, config: GenerateContentConfig) -> Self {
2833        self.generate_content_config = Some(config);
2834        self
2835    }
2836
2837    /// Set the default sampling temperature for model requests.
2838    pub fn temperature(mut self, temperature: f32) -> Self {
2839        self.generate_content_config
2840            .get_or_insert_with(GenerateContentConfig::default)
2841            .temperature = Some(temperature);
2842        self
2843    }
2844
2845    /// Set the default top-p for model requests.
2846    pub fn top_p(mut self, top_p: f32) -> Self {
2847        self.generate_content_config.get_or_insert_with(GenerateContentConfig::default).top_p =
2848            Some(top_p);
2849        self
2850    }
2851
2852    /// Set the default top-k for model requests.
2853    pub fn top_k(mut self, top_k: i32) -> Self {
2854        self.generate_content_config.get_or_insert_with(GenerateContentConfig::default).top_k =
2855            Some(top_k);
2856        self
2857    }
2858
2859    /// Set the default maximum output tokens for model requests.
2860    pub fn max_output_tokens(mut self, max_tokens: i32) -> Self {
2861        self.generate_content_config
2862            .get_or_insert_with(GenerateContentConfig::default)
2863            .max_output_tokens = Some(max_tokens);
2864        self
2865    }
2866
2867    /// Set the per-tool execution timeout (default: 5 minutes).
2868    ///
2869    /// A [`ToolEffect::NonIdempotent`] call that times out is raised into the
2870    /// script as an [`outcome_unknown_response`](adk_core::outcome_unknown_response),
2871    /// because its side effect may already have happened.
2872    pub fn tool_timeout(mut self, timeout: Duration) -> Self {
2873        self.tool_timeout = timeout;
2874        self
2875    }
2876
2877    /// Set a session state key under which the final result value is stored.
2878    pub fn output_key(mut self, key: impl Into<String>) -> Self {
2879        self.output_key = Some(key.into());
2880        self
2881    }
2882
2883    /// Add a before-agent callback.
2884    ///
2885    /// Callbacks run in registration order before the loop starts; the first to
2886    /// return `Some(content)` short-circuits the run with that content.
2887    pub fn before_callback(mut self, callback: BeforeAgentCallback) -> Self {
2888        self.before_callbacks.push(callback);
2889        self
2890    }
2891
2892    /// Add an after-agent callback.
2893    ///
2894    /// Callbacks run after the loop completes (not on suspension); the first to
2895    /// return `Some(content)` emits that content and wins.
2896    pub fn after_callback(mut self, callback: AfterAgentCallback) -> Self {
2897        self.after_callbacks.push(callback);
2898        self
2899    }
2900
2901    /// Add a before-model callback, invoked before each model request.
2902    ///
2903    /// A callback may rewrite the request
2904    /// ([`BeforeModelResult::Continue`])
2905    /// or skip the model call entirely with a synthetic response
2906    /// ([`BeforeModelResult::Skip`]).
2907    pub fn before_model_callback(mut self, callback: BeforeModelCallback) -> Self {
2908        self.before_model_callbacks.push(callback);
2909        self
2910    }
2911
2912    /// Add an after-model callback, invoked after each model response is
2913    /// assembled. Returning `Some(response)` replaces the response the loop uses
2914    /// to extract the next script.
2915    pub fn after_model_callback(mut self, callback: AfterModelCallback) -> Self {
2916        self.after_model_callbacks.push(callback);
2917        self
2918    }
2919
2920    /// Add a before-tool callback, invoked before each tool call. The first to
2921    /// return `Some(content)` short-circuits the call; that content is converted
2922    /// to a value and fed back into the script as the tool's result.
2923    pub fn before_tool_callback(mut self, callback: BeforeToolCallback) -> Self {
2924        self.before_tool_callbacks.push(callback);
2925        self
2926    }
2927
2928    /// Add an after-tool callback, invoked after each tool attempt resolves. The
2929    /// first to return `Some(content)` replaces the result fed back to the script.
2930    pub fn after_tool_callback(mut self, callback: AfterToolCallback) -> Self {
2931        self.after_tool_callbacks.push(callback);
2932        self
2933    }
2934
2935    /// Add a rich after-tool callback receiving the tool, arguments, and response
2936    /// value. Returning `Some(value)` replaces the result fed back to the script.
2937    /// These run after the plain [`after_tool_callback`](Self::after_tool_callback)
2938    /// chain.
2939    pub fn after_tool_callback_full(mut self, callback: AfterToolCallbackFull) -> Self {
2940        self.after_tool_callbacks_full.push(callback);
2941        self
2942    }
2943
2944    /// Add an on-tool-error callback. When a tool ultimately fails, callbacks
2945    /// run in order; the first to return `Some(value)` supplies a fallback
2946    /// result (fed back as if the tool succeeded). If none do, the error is
2947    /// raised into the script.
2948    pub fn on_tool_error(mut self, callback: OnToolErrorCallback) -> Self {
2949        self.on_tool_error.push(callback);
2950        self
2951    }
2952
2953    /// Set the default retry budget applied to tools without a per-tool override.
2954    pub fn default_retry_budget(mut self, budget: RetryBudget) -> Self {
2955        self.default_retry_budget = Some(budget);
2956        self
2957    }
2958
2959    /// Set a per-tool retry budget override (takes precedence over the default).
2960    pub fn tool_retry_budget(mut self, tool_name: impl Into<String>, budget: RetryBudget) -> Self {
2961        self.tool_retry_budgets.insert(tool_name.into(), budget);
2962        self
2963    }
2964
2965    /// Set the circuit-breaker threshold: after this many consecutive failures
2966    /// in one invocation, a tool is short-circuited with an immediate error
2967    /// until the next run.
2968    pub fn circuit_breaker_threshold(mut self, threshold: u32) -> Self {
2969        self.circuit_breaker_threshold = Some(threshold);
2970        self
2971    }
2972
2973    /// Set a JSON schema describing this agent's input (descriptive metadata,
2974    /// e.g. for exposing the agent as a tool; not enforced at runtime).
2975    pub fn input_schema(mut self, schema: Value) -> Self {
2976        self.input_schema = Some(schema);
2977        self
2978    }
2979
2980    /// Require the final result to validate against this JSON schema. On a
2981    /// mismatch the model is asked to correct it, up to
2982    /// [`output_max_retries`](Self::output_max_retries) times.
2983    pub fn output_schema(mut self, schema: Value) -> Self {
2984        self.output_schema = Some(schema);
2985        self
2986    }
2987
2988    /// Require the final result to match `T`'s JSON schema. Convenience over
2989    /// [`output_schema`](Self::output_schema) using `schemars`.
2990    pub fn output_type<T: schemars::JsonSchema>(mut self) -> Self {
2991        let schema = schemars::schema_for!(T);
2992        self.output_schema =
2993            Some(serde_json::to_value(schema).expect("schema serialization cannot fail"));
2994        self
2995    }
2996
2997    /// Set the maximum number of output-schema correction retries (default 3).
2998    pub fn output_max_retries(mut self, retries: usize) -> Self {
2999        self.output_max_retries = retries;
3000        self
3001    }
3002
3003    /// Set guardrails applied to the incoming user content before the run. A
3004    /// block aborts the run; a transform (e.g. PII redaction) rewrites it.
3005    /// No-op unless the `guardrails` feature is enabled.
3006    pub fn input_guardrails(mut self, guardrails: GuardrailSet) -> Self {
3007        self.input_guardrails = guardrails;
3008        self
3009    }
3010
3011    /// Set guardrails applied to the final result before it is emitted.
3012    /// No-op unless the `guardrails` feature is enabled.
3013    pub fn output_guardrails(mut self, guardrails: GuardrailSet) -> Self {
3014        self.output_guardrails = guardrails;
3015        self
3016    }
3017
3018    /// Register an enhanced plugin. Plugins intercept tool and model calls
3019    /// (modify args/results/requests/responses or short-circuit them), running
3020    /// in priority order. Requires the `enhanced-plugins` feature.
3021    #[cfg(feature = "enhanced-plugins")]
3022    pub fn enhanced_plugin(mut self, plugin: Arc<dyn EnhancedPlugin>) -> Self {
3023        self.enhanced_plugins.push(plugin);
3024        self
3025    }
3026
3027    /// Register multiple enhanced plugins at once.
3028    #[cfg(feature = "enhanced-plugins")]
3029    pub fn enhanced_plugins(mut self, plugins: Vec<Arc<dyn EnhancedPlugin>>) -> Self {
3030        self.enhanced_plugins.extend(plugins);
3031        self
3032    }
3033
3034    /// Set the agent instruction, placed first in the system prompt.
3035    ///
3036    /// `{key}` is replaced with the session state value under `key` (an error when it is
3037    /// missing), `{key?}` with the value or nothing, `{app:key}`, `{user:key}`, and
3038    /// `{temp:key}` with prefixed state, and `{artifact.name}` with the artifact's text. See
3039    /// [`adk_core::inject_session_state`].
3040    pub fn instruction(mut self, instruction: impl Into<String>) -> Self {
3041        self.instruction = Some(instruction.into());
3042        self
3043    }
3044
3045    /// Set a dynamic instruction provider evaluated per invocation (takes
3046    /// precedence over the static [`instruction`](Self::instruction)).
3047    pub fn instruction_provider(mut self, provider: InstructionProvider) -> Self {
3048        self.instruction_provider = Some(Arc::new(provider));
3049        self
3050    }
3051
3052    /// Set an instruction sent exactly as written, after any selected skill and before the
3053    /// global instruction and [`instruction`](Self::instruction).
3054    ///
3055    /// No `{key}` placeholder is read, so text you do not control — a skill file, a tool's
3056    /// documentation — keeps its braces.
3057    pub fn static_instruction(mut self, instruction: impl Into<String>) -> Self {
3058        self.static_instruction = Some(instruction.into());
3059        self
3060    }
3061
3062    /// Set a global instruction placed before the agent instruction. Supports the same
3063    /// `{key}` placeholders as [`instruction`](Self::instruction).
3064    pub fn global_instruction(mut self, instruction: impl Into<String>) -> Self {
3065        self.global_instruction = Some(instruction.into());
3066        self
3067    }
3068
3069    /// Set a dynamic global instruction provider evaluated per invocation (takes
3070    /// precedence over the static [`global_instruction`](Self::global_instruction)).
3071    pub fn global_instruction_provider(mut self, provider: GlobalInstructionProvider) -> Self {
3072        self.global_instruction_provider = Some(Arc::new(provider));
3073        self
3074    }
3075
3076    /// Control which conversation history the agent sees (default: full).
3077    pub fn include_contents(mut self, include: IncludeContents) -> Self {
3078        self.include_contents = include;
3079        self
3080    }
3081
3082    /// Set the maximum number of model turns.
3083    pub fn max_iterations(mut self, max: u32) -> Self {
3084        self.max_iterations = max;
3085        self
3086    }
3087
3088    /// Set the maximum error-message length fed back to the model.
3089    pub fn max_error_chars(mut self, max: usize) -> Self {
3090        self.max_error_chars = max;
3091        self
3092    }
3093
3094    /// Build the [`CodeActAgent`].
3095    ///
3096    /// # Errors
3097    /// Returns a config error if the model or runtime was not set, and an
3098    /// error with code `agent.duplicate_tool_name` when two tools share a name.
3099    pub fn build(self) -> adk_core::Result<CodeActAgent> {
3100        let model = self.model.ok_or_else(|| AdkError::config("CodeActAgent requires a model"))?;
3101        let runtime =
3102            self.runtime.ok_or_else(|| AdkError::config("CodeActAgent requires a code runtime"))?;
3103
3104        // Reject duplicate sub-agent names: transfer targets are addressed by
3105        // name, so duplicates would make routing ambiguous (mirrors LlmAgent).
3106        let mut seen_names = std::collections::HashSet::new();
3107        for agent in &self.sub_agents {
3108            if !seen_names.insert(agent.name()) {
3109                return Err(AdkError::agent(format!("duplicate sub-agent name: {}", agent.name())));
3110            }
3111        }
3112        adk_core::ensure_unique_tool_names(&self.name, &self.tools)?;
3113
3114        let capabilities = runtime.capabilities();
3115        if !capabilities.supports_suspension {
3116            let needs_suspension = !matches!(self.policy, ToolConfirmationPolicy::Never)
3117                || self.tools.iter().any(|t| t.is_long_running());
3118            if needs_suspension {
3119                tracing::warn!(
3120                    agent.name = %self.name,
3121                    "runtime cannot suspend; confirmations are rejected, long-running tools run inline, and nothing is checkpointed"
3122                );
3123            }
3124        }
3125
3126        Ok(CodeActAgent {
3127            name: self.name,
3128            description: self.description,
3129            model,
3130            tools: self.tools,
3131            toolsets: self.toolsets,
3132            runtime,
3133            policy: self.policy,
3134            skills_index: self.skills_index,
3135            skill_policy: self.skill_policy,
3136            max_skill_chars: self.max_skill_chars,
3137            instruction: self.instruction,
3138            instruction_provider: self.instruction_provider,
3139            static_instruction: self.static_instruction,
3140            global_instruction: self.global_instruction,
3141            global_instruction_provider: self.global_instruction_provider,
3142            include_contents: self.include_contents,
3143            max_iterations: self.max_iterations,
3144            max_error_chars: self.max_error_chars,
3145            supports_suspension: capabilities.supports_suspension,
3146            sub_agents: self.sub_agents,
3147            disallow_transfer_to_parent: self.disallow_transfer_to_parent,
3148            disallow_transfer_to_peers: self.disallow_transfer_to_peers,
3149            generate_content_config: self.generate_content_config,
3150            tool_timeout: self.tool_timeout,
3151            output_key: self.output_key,
3152            before_callbacks: Arc::new(self.before_callbacks),
3153            after_callbacks: Arc::new(self.after_callbacks),
3154            before_model_callbacks: Arc::new(self.before_model_callbacks),
3155            after_model_callbacks: Arc::new(self.after_model_callbacks),
3156            before_tool_callbacks: Arc::new(self.before_tool_callbacks),
3157            after_tool_callbacks: Arc::new(self.after_tool_callbacks),
3158            after_tool_callbacks_full: Arc::new(self.after_tool_callbacks_full),
3159            default_retry_budget: self.default_retry_budget,
3160            tool_retry_budgets: self.tool_retry_budgets,
3161            circuit_breaker_threshold: self.circuit_breaker_threshold,
3162            on_tool_error: Arc::new(self.on_tool_error),
3163            input_schema: self.input_schema,
3164            output_schema: self.output_schema,
3165            output_max_retries: self.output_max_retries,
3166            input_guardrails: Arc::new(self.input_guardrails),
3167            output_guardrails: Arc::new(self.output_guardrails),
3168            // Build the plugin manager only when plugins are registered
3169            // (zero overhead otherwise).
3170            #[cfg(feature = "enhanced-plugins")]
3171            enhanced_plugin_manager: (!self.enhanced_plugins.is_empty())
3172                .then(|| Arc::new(EnhancedPluginManager::new(self.enhanced_plugins))),
3173        })
3174    }
3175}
3176
3177impl Default for CodeActAgentBuilder {
3178    fn default() -> Self {
3179        Self::new()
3180    }
3181}
3182
3183/// Assemble the system prompt in priority order, omitting empty sections:
3184/// selected skill block, global instruction, agent instruction, base CodeAct
3185/// contract, runtime environment, runtime-rendered tools, and the transfer
3186/// section.
3187fn assemble_system_prompt(
3188    skill: Option<&str>,
3189    static_instruction: Option<&str>,
3190    global: Option<&str>,
3191    instruction: Option<&str>,
3192    runtime_prompt: &str,
3193    tools_section: &str,
3194    transfer_section: Option<&str>,
3195) -> String {
3196    [
3197        skill.unwrap_or_default(),
3198        static_instruction.unwrap_or_default(),
3199        global.unwrap_or_default(),
3200        instruction.unwrap_or_default(),
3201        CODEACT_SYSTEM_PROMPT,
3202        runtime_prompt,
3203        tools_section,
3204        transfer_section.unwrap_or_default(),
3205    ]
3206    .into_iter()
3207    .map(str::trim)
3208    .filter(|s| !s.is_empty())
3209    .collect::<Vec<_>>()
3210    .join("\n\n")
3211}
3212
3213/// A per-call [`ToolContext`] for CodeAct tool calls.
3214///
3215/// One is built for each tool invocation. It carries the interpreter's call id
3216/// (so `function_call_id` is meaningful and correlatable) and its own actions
3217/// buffer, and otherwise delegates every capability — artifacts, memory, shared
3218/// state, user scopes, and secrets — to the live invocation context, matching
3219/// `LlmAgent`'s `AgentToolContext` so tools behave identically under either
3220/// agent.
3221struct CodeToolContext {
3222    inner: Arc<dyn InvocationContext>,
3223    function_call_id: String,
3224    idempotency_key: String,
3225    actions: Mutex<EventActions>,
3226}
3227
3228impl CodeToolContext {
3229    /// Builds the context for call `call_id` of the program on model turn
3230    /// `iteration` of run `run_id`.
3231    ///
3232    /// Interpreter call ids restart with every program, so the idempotency key
3233    /// names the run and the turn as well: two calls in one program never share
3234    /// a key, and a call replayed from a checkpoint keeps its key.
3235    fn new(inner: Arc<dyn InvocationContext>, run_id: &str, iteration: u32, call_id: u64) -> Self {
3236        let idempotency_key = format!(
3237            "{}/{}/{}/codeact/{run_id}/{iteration}/{call_id}",
3238            inner.app_name(),
3239            inner.user_id(),
3240            inner.session_id(),
3241        );
3242        Self {
3243            inner,
3244            function_call_id: call_id.to_string(),
3245            idempotency_key,
3246            actions: Mutex::new(EventActions::default()),
3247        }
3248    }
3249}
3250
3251#[async_trait]
3252impl ReadonlyContext for CodeToolContext {
3253    fn invocation_id(&self) -> &str {
3254        self.inner.invocation_id()
3255    }
3256    fn agent_name(&self) -> &str {
3257        self.inner.agent_name()
3258    }
3259    fn user_id(&self) -> &str {
3260        self.inner.user_id()
3261    }
3262    fn app_name(&self) -> &str {
3263        self.inner.app_name()
3264    }
3265    fn session_id(&self) -> &str {
3266        self.inner.session_id()
3267    }
3268    fn branch(&self) -> &str {
3269        self.inner.branch()
3270    }
3271    fn user_content(&self) -> &Content {
3272        self.inner.user_content()
3273    }
3274
3275    fn acting_context(&self) -> adk_core::ActingContext {
3276        self.inner.acting_context()
3277    }
3278
3279    fn is_authenticated(&self) -> bool {
3280        self.inner.is_authenticated()
3281    }
3282}
3283
3284#[async_trait]
3285impl CallbackContext for CodeToolContext {
3286    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
3287        self.inner.artifacts()
3288    }
3289    fn shared_state(&self) -> Option<Arc<SharedState>> {
3290        self.inner.shared_state()
3291    }
3292}
3293
3294#[async_trait]
3295impl ToolContext for CodeToolContext {
3296    fn function_call_id(&self) -> &str {
3297        &self.function_call_id
3298    }
3299    fn idempotency_key(&self) -> String {
3300        self.idempotency_key.clone()
3301    }
3302    fn actions(&self) -> EventActions {
3303        self.actions.lock().unwrap().clone()
3304    }
3305    fn set_actions(&self, actions: EventActions) {
3306        *self.actions.lock().unwrap() = actions;
3307    }
3308    async fn search_memory(&self, query: &str) -> adk_core::Result<Vec<MemoryEntry>> {
3309        match self.inner.memory() {
3310            Some(memory) => memory.search(query).await,
3311            None => Ok(vec![]),
3312        }
3313    }
3314    fn memory(&self) -> Option<Arc<dyn adk_core::Memory>> {
3315        self.inner.memory()
3316    }
3317    fn session(&self) -> Option<&dyn adk_core::Session> {
3318        Some(self.inner.session())
3319    }
3320    fn run_config(&self) -> Option<&adk_core::RunConfig> {
3321        Some(self.inner.run_config())
3322    }
3323    fn is_cancelled(&self) -> bool {
3324        self.inner.is_cancelled()
3325    }
3326    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
3327        self.inner.request_metadata()
3328    }
3329    fn delegation_depth(&self) -> u32 {
3330        self.inner.delegation_depth()
3331    }
3332    fn max_delegation_depth(&self) -> Option<u32> {
3333        self.inner.max_delegation_depth()
3334    }
3335
3336    fn orchestration_root_invocation_id(&self) -> &str {
3337        self.inner.orchestration_root_invocation_id()
3338    }
3339
3340    fn orchestration_edge_id(&self) -> Option<&str> {
3341        self.inner.orchestration_edge_id()
3342    }
3343    fn user_scopes(&self) -> Vec<String> {
3344        self.inner.user_scopes()
3345    }
3346    async fn get_secret(&self, name: &str) -> adk_core::Result<Option<String>> {
3347        self.inner.get_secret(name).await
3348    }
3349
3350    async fn get_secret_for_purpose(
3351        &self,
3352        name: &str,
3353        purpose: &str,
3354    ) -> adk_core::Result<Option<String>> {
3355        // Inline code runs under the CodeAct agent rather than a named tool, so the
3356        // identity presented is the run's, with the stated purpose attached.
3357        let request = adk_core::SecretRequest::new(name)
3358            .with_identity(self.inner.app_name(), self.inner.user_id(), self.inner.session_id())
3359            .with_invocation_id(self.inner.invocation_id())
3360            .with_purpose(purpose);
3361        self.inner.get_secret_for(&request).await
3362    }
3363}
3364
3365/// Wraps a [`CallbackContext`] to expose a [`ToolOutcome`] to after-tool
3366/// callbacks via [`CallbackContext::tool_outcome`], matching `LlmAgent`'s
3367/// after-tool callback surface. Every other capability delegates to `inner`.
3368struct ToolOutcomeContext {
3369    inner: Arc<dyn CallbackContext>,
3370    outcome: ToolOutcome,
3371}
3372
3373impl ToolOutcomeContext {
3374    fn new(inner: Arc<dyn CallbackContext>, outcome: ToolOutcome) -> Self {
3375        Self { inner, outcome }
3376    }
3377}
3378
3379#[async_trait]
3380impl ReadonlyContext for ToolOutcomeContext {
3381    fn invocation_id(&self) -> &str {
3382        self.inner.invocation_id()
3383    }
3384    fn agent_name(&self) -> &str {
3385        self.inner.agent_name()
3386    }
3387    fn user_id(&self) -> &str {
3388        self.inner.user_id()
3389    }
3390    fn app_name(&self) -> &str {
3391        self.inner.app_name()
3392    }
3393    fn session_id(&self) -> &str {
3394        self.inner.session_id()
3395    }
3396    fn branch(&self) -> &str {
3397        self.inner.branch()
3398    }
3399    fn user_content(&self) -> &Content {
3400        self.inner.user_content()
3401    }
3402
3403    fn acting_context(&self) -> adk_core::ActingContext {
3404        self.inner.acting_context()
3405    }
3406
3407    fn is_authenticated(&self) -> bool {
3408        self.inner.is_authenticated()
3409    }
3410}
3411
3412#[async_trait]
3413impl CallbackContext for ToolOutcomeContext {
3414    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
3415        self.inner.artifacts()
3416    }
3417    fn shared_state(&self) -> Option<Arc<SharedState>> {
3418        self.inner.shared_state()
3419    }
3420    fn tool_outcome(&self) -> Option<ToolOutcome> {
3421        Some(self.outcome.clone())
3422    }
3423}
3424
3425#[cfg(test)]
3426mod tests {
3427    use super::*;
3428    use crate::codeact::test_support::{
3429        MockInvocationContext, Planned, ScriptedRuntime, call_id_tool, echo_tool,
3430        escalating_long_running_tool, escalating_tool, failing_tool, fake_agent, fake_toolset,
3431        flaky_tool, flaky_tool_with_effect, long_running_tool, route_tool, skip_summarization_tool,
3432        sleeping_tool, state_tool, text_agent,
3433    };
3434    use adk_core::FunctionResponseData;
3435    use serde_json::json;
3436    use std::sync::Mutex as StdMutex;
3437
3438    struct FakeLlm {
3439        script: String,
3440        calls: StdMutex<u32>,
3441        seen: StdMutex<Vec<Vec<Content>>>,
3442        seen_config: StdMutex<Vec<Option<GenerateContentConfig>>>,
3443    }
3444
3445    impl FakeLlm {
3446        fn new(script: &str) -> Arc<Self> {
3447            Arc::new(Self {
3448                script: script.to_string(),
3449                calls: StdMutex::new(0),
3450                seen: StdMutex::new(vec![]),
3451                seen_config: StdMutex::new(vec![]),
3452            })
3453        }
3454        fn calls(&self) -> u32 {
3455            *self.calls.lock().unwrap()
3456        }
3457        fn last_config(&self) -> Option<GenerateContentConfig> {
3458            self.seen_config.lock().unwrap().last().cloned().flatten()
3459        }
3460    }
3461
3462    #[async_trait]
3463    impl Llm for FakeLlm {
3464        fn name(&self) -> &str {
3465            "fake"
3466        }
3467        async fn generate_content(
3468            &self,
3469            req: LlmRequest,
3470            _stream: bool,
3471        ) -> adk_core::Result<adk_core::LlmResponseStream> {
3472            *self.calls.lock().unwrap() += 1;
3473            self.seen.lock().unwrap().push(req.contents.clone());
3474            self.seen_config.lock().unwrap().push(req.config.clone());
3475            let response = adk_core::model::LlmResponse::new(
3476                Content::new("model").with_text(self.script.clone()),
3477            );
3478            Ok(Box::pin(futures::stream::once(async move { Ok(response) })))
3479        }
3480    }
3481
3482    /// A `LoopInputs` with test defaults: empty tools, no policy, suspension on,
3483    /// system prompt `"sys"`. Tests override individual fields as needed.
3484    fn base_inputs(
3485        model: Arc<dyn Llm>,
3486        runtime: Arc<dyn CodeRuntime>,
3487        incoming: Content,
3488    ) -> LoopInputs {
3489        LoopInputs {
3490            model,
3491            runtime,
3492            tools: vec![],
3493            policy: ToolConfirmationPolicy::Never,
3494            invocation_ctx: Arc::new(MockInvocationContext::new(incoming.clone())),
3495            conversation: vec![incoming.clone()],
3496            incoming,
3497            system_prompt: "sys".to_string(),
3498            pending: None,
3499            invocation_id: "inv-1".to_string(),
3500            agent_name: "code-agent".to_string(),
3501            max_iterations: DEFAULT_MAX_ITERATIONS,
3502            max_error_chars: DEFAULT_MAX_ERROR_CHARS,
3503            supports_suspension: true,
3504            transfer_targets: Vec::new(),
3505            generate_content_config: None,
3506            tool_timeout: DEFAULT_TOOL_TIMEOUT,
3507            output_key: None,
3508            default_retry_budget: None,
3509            tool_retry_budgets: HashMap::new(),
3510            circuit_breaker_threshold: None,
3511            on_tool_error: Arc::new(Vec::new()),
3512            before_model_callbacks: Arc::new(Vec::new()),
3513            after_model_callbacks: Arc::new(Vec::new()),
3514            before_tool_callbacks: Arc::new(Vec::new()),
3515            after_tool_callbacks: Arc::new(Vec::new()),
3516            after_tool_callbacks_full: Arc::new(Vec::new()),
3517            output_schema: None,
3518            output_max_retries: DEFAULT_OUTPUT_MAX_RETRIES,
3519            output_guardrails: Arc::new(GuardrailSet::new()),
3520            #[cfg(feature = "enhanced-plugins")]
3521            enhanced_plugin_manager: None,
3522        }
3523    }
3524
3525    /// Drive `run_codeact` with fakes and collect all emitted events.
3526    #[allow(clippy::too_many_arguments)]
3527    async fn drive(
3528        model: Arc<dyn Llm>,
3529        runtime: Arc<dyn CodeRuntime>,
3530        tools: Vec<Arc<dyn Tool>>,
3531        policy: ToolConfirmationPolicy,
3532        decisions: HashMap<String, ToolConfirmationDecision>,
3533        incoming: Content,
3534        pending: Option<CodeActCheckpoint>,
3535        supports_suspension: bool,
3536    ) -> Vec<Event> {
3537        let mut input = base_inputs(model, runtime, incoming.clone());
3538        input.invocation_ctx =
3539            Arc::new(MockInvocationContext::new(incoming).with_confirmation_decisions(decisions));
3540        input.tools = tools;
3541        input.policy = policy;
3542        input.pending = pending;
3543        input.supports_suspension = supports_suspension;
3544        collect(input).await
3545    }
3546
3547    /// Drive a fresh loop whose pre-assembled system prompt includes a transfer
3548    /// section for `targets` (mirroring what `run` builds).
3549    async fn drive_targets(
3550        model: Arc<dyn Llm>,
3551        runtime: Arc<dyn CodeRuntime>,
3552        targets: Vec<String>,
3553        incoming: Content,
3554    ) -> Vec<Event> {
3555        let mut input = base_inputs(model, runtime, incoming);
3556        input.system_prompt = format!("sys\n\n{}", transfer_prompt(&targets));
3557        input.transfer_targets = targets;
3558        collect(input).await
3559    }
3560
3561    /// Run a loop to exhaustion and collect every emitted event.
3562    async fn collect(input: LoopInputs) -> Vec<Event> {
3563        let mut events = Vec::new();
3564        let mut stream = Box::pin(run_codeact(input));
3565        while let Some(item) = stream.next().await {
3566            events.push(item.expect("ok event"));
3567        }
3568        events
3569    }
3570
3571    fn user(text: &str) -> Content {
3572        Content::new("user").with_text(text)
3573    }
3574
3575    fn final_text(event: &Event) -> Option<String> {
3576        event.llm_response.content.as_ref()?.parts.first()?.text().map(str::to_string)
3577    }
3578
3579    fn pending_in(event: &Event) -> Option<CodeActCheckpoint> {
3580        event
3581            .actions
3582            .state_delta
3583            .get(PENDING_STATE_KEY)
3584            .and_then(|v| serde_json::from_value(v.clone()).ok())
3585    }
3586
3587    /// A model that ends its turn with `finish_reason`, `text`, and an optional provider error.
3588    struct FinishingLlm {
3589        finish_reason: adk_core::FinishReason,
3590        text: &'static str,
3591        error: Option<(&'static str, &'static str)>,
3592    }
3593
3594    #[async_trait]
3595    impl Llm for FinishingLlm {
3596        fn name(&self) -> &str {
3597            "finishing"
3598        }
3599        async fn generate_content(
3600            &self,
3601            _req: LlmRequest,
3602            _stream: bool,
3603        ) -> adk_core::Result<adk_core::LlmResponseStream> {
3604            let mut response =
3605                adk_core::model::LlmResponse::new(Content::new("model").with_text(self.text));
3606            response.finish_reason = Some(self.finish_reason);
3607            response.error_code = self.error.map(|(code, _)| code.to_string());
3608            response.error_message = self.error.map(|(_, message)| message.to_string());
3609            Ok(Box::pin(futures::stream::once(async move { Ok(response) })))
3610        }
3611    }
3612
3613    /// The first error the loop yields, and how many planned programs no script started.
3614    async fn first_error(model: FinishingLlm) -> (AdkError, usize) {
3615        let runtime = Arc::new(ScriptedRuntime::new(vec![vec![Planned::Complete(
3616            json!({"type": "final_result", "value": "ran anyway"}),
3617        )]]));
3618        let input = base_inputs(Arc::new(model), runtime.clone(), user("go"));
3619        let mut stream = Box::pin(run_codeact(input));
3620        let error = loop {
3621            match stream.next().await.expect("the loop ends with an error") {
3622                Ok(_) => continue,
3623                Err(error) => break error,
3624            }
3625        };
3626        (error, runtime.programs_left())
3627    }
3628
3629    #[tokio::test]
3630    async fn a_refusal_ends_the_run_without_running_a_script() {
3631        let (error, programs_left) = first_error(FinishingLlm {
3632            finish_reason: adk_core::FinishReason::Refusal,
3633            text: "I can't help with that.",
3634            error: None,
3635        })
3636        .await;
3637        assert_eq!(
3638            (error.code, error.category, programs_left),
3639            ("model.refusal", adk_core::ErrorCategory::Forbidden, 1)
3640        );
3641        assert!(error.message.contains("I can't help with that."), "{}", error.message);
3642    }
3643
3644    #[tokio::test]
3645    async fn a_refusal_reported_with_an_error_code_keeps_the_provider_message() {
3646        let (error, programs_left) = first_error(FinishingLlm {
3647            finish_reason: adk_core::FinishReason::Refusal,
3648            text: "",
3649            error: Some(("refusal", "Claude declined the request (category cyber): Declined.")),
3650        })
3651        .await;
3652        assert_eq!((error.code, programs_left), ("model.refusal", 1));
3653        assert!(error.message.contains("category cyber"), "{}", error.message);
3654        assert_eq!(error.details.metadata["provider_error_code"], json!("refusal"));
3655    }
3656
3657    #[tokio::test]
3658    async fn a_malformed_tool_call_ends_the_run_without_running_a_script() {
3659        let (error, programs_left) = first_error(FinishingLlm {
3660            finish_reason: adk_core::FinishReason::MalformedToolCall,
3661            text: "",
3662            error: None,
3663        })
3664        .await;
3665        assert_eq!((error.code, programs_left), ("model.malformed_tool_call", 1));
3666    }
3667
3668    #[tokio::test]
3669    async fn produces_final_result() {
3670        let events = drive(
3671            FakeLlm::new("noop"),
3672            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
3673                json!({"type": "final_result", "value": "answer"}),
3674            )]])),
3675            vec![],
3676            ToolConfirmationPolicy::Never,
3677            HashMap::new(),
3678            user("go"),
3679            None,
3680            true,
3681        )
3682        .await;
3683        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("answer"));
3684    }
3685
3686    #[tokio::test]
3687    async fn inline_tool_brackets_with_before_and_after_checkpoints() {
3688        let events = drive(
3689            FakeLlm::new("noop"),
3690            Arc::new(ScriptedRuntime::with_suspension(vec![vec![
3691                Planned::call("echo", json!({"msg": "x"}), 1),
3692                Planned::Complete(json!({"type": "final_result", "value": "done"})),
3693            ]])),
3694            vec![echo_tool()],
3695            ToolConfirmationPolicy::Never,
3696            HashMap::new(),
3697            user("go"),
3698            None,
3699            true,
3700        )
3701        .await;
3702
3703        // before (PendingResult), after (Resolved), final (cleared).
3704        let dispositions: Vec<_> =
3705            events.iter().filter_map(pending_in).map(|c| c.disposition).collect();
3706        assert!(matches!(dispositions.first(), Some(Disposition::PendingResult)));
3707        assert!(matches!(dispositions.get(1), Some(Disposition::Resolved(_))));
3708        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
3709        // final event clears the pending state
3710        assert_eq!(
3711            events.last().unwrap().actions.state_delta.get(PENDING_STATE_KEY),
3712            Some(&Value::Null)
3713        );
3714    }
3715
3716    #[tokio::test]
3717    async fn no_checkpoints_without_suspension() {
3718        let events = drive(
3719            FakeLlm::new("noop"),
3720            Arc::new(ScriptedRuntime::new(vec![vec![
3721                Planned::call("echo", json!({"msg": "x"}), 1),
3722                Planned::Complete(json!({"type": "final_result", "value": "inline"})),
3723            ]])),
3724            vec![echo_tool()],
3725            ToolConfirmationPolicy::Never,
3726            HashMap::new(),
3727            user("go"),
3728            None,
3729            false,
3730        )
3731        .await;
3732        // Only the final event; no durability checkpoints were written.
3733        assert_eq!(events.len(), 1);
3734        assert_eq!(final_text(&events[0]).as_deref(), Some("inline"));
3735    }
3736
3737    #[tokio::test]
3738    async fn long_running_suspends_then_resumes_from_checkpoint() {
3739        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
3740            Planned::call("slow", json!({}), 1),
3741            Planned::Complete(json!({"type": "final_result", "value": "completed"})),
3742        ]]));
3743
3744        // First invocation: suspends to a checkpoint.
3745        let events = drive(
3746            FakeLlm::new("noop"),
3747            runtime.clone(),
3748            vec![long_running_tool()],
3749            ToolConfirmationPolicy::Never,
3750            HashMap::new(),
3751            user("go"),
3752            None,
3753            true,
3754        )
3755        .await;
3756        let suspend = events.last().unwrap();
3757        assert_eq!(suspend.long_running_tool_ids, vec!["slow".to_string()]);
3758        let cp = pending_in(suspend).expect("checkpoint persisted");
3759        assert!(matches!(cp.disposition, Disposition::AwaitingCompletion { .. }));
3760
3761        // Second invocation: the result arrives as a FunctionResponse.
3762        let completion = Content {
3763            role: "user".to_string(),
3764            parts: vec![Part::FunctionResponse {
3765                function_response: adk_core::FunctionResponseData::new("slow", json!({"ok": true})),
3766                id: None,
3767                annotations: None,
3768            }],
3769        };
3770        let events = drive(
3771            FakeLlm::new("noop"),
3772            runtime,
3773            vec![long_running_tool()],
3774            ToolConfirmationPolicy::Never,
3775            HashMap::new(),
3776            completion,
3777            Some(cp),
3778            true,
3779        )
3780        .await;
3781        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("completed"));
3782    }
3783
3784    #[tokio::test]
3785    async fn stdout_before_a_suspend_is_persisted_in_the_checkpoint() {
3786        // The script prints before calling a long-running tool; that output must
3787        // ride along in the checkpoint transcript so it is not lost across the
3788        // suspend/resume boundary.
3789        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
3790            Planned::call_with_stdout("slow", json!({}), 1, "working...\n"),
3791            Planned::Complete(json!({"type": "final_result", "value": "completed"})),
3792        ]]));
3793
3794        let events = drive(
3795            FakeLlm::new("noop"),
3796            runtime,
3797            vec![long_running_tool()],
3798            ToolConfirmationPolicy::Never,
3799            HashMap::new(),
3800            user("go"),
3801            None,
3802            true,
3803        )
3804        .await;
3805
3806        let cp = pending_in(events.last().unwrap()).expect("checkpoint persisted");
3807        let printed = cp
3808            .transcript
3809            .iter()
3810            .filter_map(|c| c.parts.first().and_then(Part::text))
3811            .any(|t| t.contains("Output (stdout):") && t.contains("working..."));
3812        assert!(printed, "stdout was not persisted in the checkpoint transcript: {cp:?}");
3813    }
3814
3815    #[test]
3816    fn transcript_with_stdout_appends_only_when_non_empty() {
3817        let base = vec![Content::new("user").with_text("hi")];
3818        assert_eq!(transcript_with_stdout(&base, "", 100).len(), 1);
3819        let with = transcript_with_stdout(&base, "printed", 100);
3820        assert_eq!(with.len(), 2);
3821        assert!(
3822            with[1].parts.first().and_then(Part::text).unwrap().contains("printed"),
3823            "appended entry should carry the stdout"
3824        );
3825    }
3826
3827    #[tokio::test]
3828    async fn recovers_from_resolved_checkpoint_without_rerunning_tool() {
3829        // A crafted "after" checkpoint: resume with the stored result.
3830        let snapshot = serde_json::to_vec(&vec![Planned::Complete(
3831            json!({"type": "final_result", "value": "recovered"}),
3832        )])
3833        .unwrap();
3834        let cp = CodeActCheckpoint {
3835            iteration: 1,
3836            transcript: vec![],
3837            snapshot,
3838            call: PendingToolCall { call_id: 1, tool: "echo".into(), args: json!({}) },
3839            disposition: Disposition::Resolved(ResolutionRecord::Value(json!("stored"))),
3840            tool_roster: vec!["echo".to_string()],
3841            run_id: None,
3842        };
3843        let events = drive(
3844            FakeLlm::new("noop"),
3845            Arc::new(ScriptedRuntime::with_suspension(vec![])),
3846            vec![echo_tool()],
3847            ToolConfirmationPolicy::Never,
3848            HashMap::new(),
3849            user("ignored"),
3850            Some(cp),
3851            true,
3852        )
3853        .await;
3854        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("recovered"));
3855    }
3856
3857    #[tokio::test]
3858    async fn tool_failure_raises_into_script() {
3859        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
3860            Planned::call("boom", json!({}), 1),
3861            Planned::Complete(json!({"type": "final_result", "value": "caught"})),
3862        ]]));
3863        let events = drive(
3864            FakeLlm::new("noop"),
3865            rt.clone(),
3866            vec![failing_tool()],
3867            ToolConfirmationPolicy::Never,
3868            HashMap::new(),
3869            user("go"),
3870            None,
3871            true,
3872        )
3873        .await;
3874        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("caught"));
3875        assert!(rt.last_raise().unwrap().contains("not_found"));
3876    }
3877
3878    /// Replaces the history with one notice once asked `compact_on` times or more, recording
3879    /// each trigger it is asked with.
3880    #[derive(Debug, Default)]
3881    struct NoticeCompactor {
3882        compact_on: usize,
3883        triggers: StdMutex<Vec<adk_core::CompactionTrigger>>,
3884    }
3885
3886    #[async_trait]
3887    impl adk_core::HistoryCompactor for NoticeCompactor {
3888        async fn compact(
3889            &self,
3890            _ctx: Arc<dyn InvocationContext>,
3891            _model: Arc<dyn Llm>,
3892            request: adk_core::HistoryCompactionRequest<'_>,
3893        ) -> adk_core::Result<Option<adk_core::CompactedHistory>> {
3894            let mut triggers = self.triggers.lock().unwrap();
3895            triggers.push(request.trigger);
3896            if triggers.len() < self.compact_on {
3897                return Ok(None);
3898            }
3899            let mut event = Event::new("inv-1");
3900            event.actions.compaction = Some(adk_core::EventCompaction {
3901                start_timestamp: chrono::Utc::now(),
3902                end_timestamp: chrono::Utc::now(),
3903                compacted_content: adk_core::history::system_notice("compacted"),
3904            });
3905            Ok(Some(adk_core::CompactedHistory {
3906                history: vec![adk_core::history::system_notice("compacted")],
3907                event: Some(event),
3908            }))
3909        }
3910    }
3911
3912    /// Rejects its first request as too long inside the stream, then answers as `FakeLlm`.
3913    struct RejectsFirst {
3914        inner: Arc<FakeLlm>,
3915        rejected: StdMutex<bool>,
3916    }
3917
3918    #[async_trait]
3919    impl Llm for RejectsFirst {
3920        fn name(&self) -> &str {
3921            "rejects-first"
3922        }
3923        async fn generate_content(
3924            &self,
3925            req: LlmRequest,
3926            stream: bool,
3927        ) -> adk_core::Result<adk_core::LlmResponseStream> {
3928            if !std::mem::replace(&mut *self.rejected.lock().unwrap(), true) {
3929                let error = AdkError::new(
3930                    ErrorComponent::Model,
3931                    ErrorCategory::InvalidInput,
3932                    "model.test.api_error",
3933                    "400: prompt is too long: 1048577 tokens > 1000000 maximum",
3934                );
3935                return Ok(Box::pin(futures::stream::once(async move { Err(error) })));
3936            }
3937            self.inner.generate_content(req, stream).await
3938        }
3939    }
3940
3941    fn with_compactor(input: &mut LoopInputs, compactor: Arc<NoticeCompactor>) {
3942        let config =
3943            adk_core::RunConfig { history_compactor: Some(compactor), ..Default::default() };
3944        input.invocation_ctx =
3945            Arc::new(MockInvocationContext::new(user("go")).with_run_config(config));
3946    }
3947
3948    #[tokio::test]
3949    async fn the_transcript_is_compacted_before_each_model_call() {
3950        let model = FakeLlm::new("noop");
3951        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![
3952            vec![Planned::Raised("the first try failed".to_string())],
3953            vec![Planned::Complete(json!({"type": "final_result", "value": "done"}))],
3954        ]));
3955        let compactor = Arc::new(NoticeCompactor { compact_on: 2, ..Default::default() });
3956        let mut input = base_inputs(model.clone(), rt, user("go"));
3957        with_compactor(&mut input, compactor.clone());
3958
3959        let events = collect(input).await;
3960
3961        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
3962        assert_eq!(
3963            *compactor.triggers.lock().unwrap(),
3964            vec![adk_core::CompactionTrigger::BeforeModelCall; 2]
3965        );
3966        // The system prompt stays; the rest of the transcript is the compactor's.
3967        assert_eq!(
3968            model.seen.lock().unwrap()[1],
3969            vec![user("sys"), adk_core::history::system_notice("compacted")]
3970        );
3971        assert_eq!(events.iter().filter(|event| event.actions.compaction.is_some()).count(), 1);
3972    }
3973
3974    #[tokio::test]
3975    async fn a_script_request_rejected_as_too_long_is_compacted_and_sent_once_more() {
3976        let inner = FakeLlm::new("noop");
3977        let model = Arc::new(RejectsFirst { inner: inner.clone(), rejected: StdMutex::new(false) });
3978        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
3979            json!({"type": "final_result", "value": "done"}),
3980        )]]));
3981        let compactor = Arc::new(NoticeCompactor { compact_on: 2, ..Default::default() });
3982        let mut input = base_inputs(model, rt, user("go"));
3983        with_compactor(&mut input, compactor.clone());
3984
3985        let events = collect(input).await;
3986
3987        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
3988        assert_eq!(
3989            *compactor.triggers.lock().unwrap(),
3990            vec![
3991                adk_core::CompactionTrigger::BeforeModelCall,
3992                adk_core::CompactionTrigger::ContextLimitExceeded
3993            ]
3994        );
3995        assert_eq!(inner.calls(), 1, "the compacted request was sent once more");
3996    }
3997
3998    /// The full Agent path: `run()` reads session state, suspends, and on a
3999    /// second `run()` (with the result in the message) resumes to a final.
4000    #[tokio::test]
4001    async fn run_round_trips_through_session_state() {
4002        let agent = CodeActAgent::builder()
4003            .model(FakeLlm::new("noop"))
4004            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4005                Planned::call("slow", json!({}), 1),
4006                Planned::Complete(json!({"type": "final_result", "value": "completed"})),
4007            ]])))
4008            .tool(long_running_tool())
4009            .build()
4010            .unwrap();
4011
4012        // First run: suspends, persisting the checkpoint to session state.
4013        let ctx1 = Arc::new(MockInvocationContext::new(user("go")));
4014        let mut state = HashMap::new();
4015        let mut stream = agent.run(ctx1).await.unwrap();
4016        while let Some(item) = stream.next().await {
4017            let event = item.unwrap();
4018            for (k, v) in &event.actions.state_delta {
4019                state.insert(k.clone(), v.clone());
4020            }
4021        }
4022        assert!(state.contains_key(PENDING_STATE_KEY));
4023
4024        // Second run: the result arrives as a FunctionResponse; the seeded
4025        // session state carries the checkpoint.
4026        let completion = Content {
4027            role: "user".to_string(),
4028            parts: vec![Part::FunctionResponse {
4029                function_response: FunctionResponseData::new("slow", json!({"ok": true})),
4030                id: None,
4031                annotations: None,
4032            }],
4033        };
4034        let ctx2 = Arc::new(MockInvocationContext::new(completion).with_state(state));
4035        let mut last = None;
4036        let mut stream = agent.run(ctx2).await.unwrap();
4037        while let Some(item) = stream.next().await {
4038            last = Some(item.unwrap());
4039        }
4040        let last = last.unwrap();
4041        assert_eq!(final_text(&last).as_deref(), Some("completed"));
4042        assert_eq!(last.actions.state_delta.get(PENDING_STATE_KEY), Some(&Value::Null));
4043    }
4044
4045    #[tokio::test]
4046    async fn observation_then_final_records_model_turns() {
4047        let model = FakeLlm::new("the script");
4048        let events = drive(
4049            model.clone(),
4050            Arc::new(ScriptedRuntime::with_suspension(vec![
4051                vec![Planned::Complete(json!({"type": "observation", "value": "look"}))],
4052                vec![Planned::Complete(json!({"type": "final_result", "value": "done"}))],
4053            ])),
4054            vec![],
4055            ToolConfirmationPolicy::Never,
4056            HashMap::new(),
4057            user("go"),
4058            None,
4059            true,
4060        )
4061        .await;
4062        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4063        assert_eq!(model.calls(), 2);
4064        let second = &model.seen.lock().unwrap()[1];
4065        assert!(second.iter().any(|c| c.role == "model"));
4066    }
4067
4068    #[tokio::test]
4069    async fn a_steering_message_joins_the_transcript_after_a_script_turn() {
4070        let inbox = adk_core::SteeringInbox::new();
4071        let receipt =
4072            inbox.push(user("use metric units"), user("use metric units"), "user", true).unwrap();
4073        let model = FakeLlm::new("the script");
4074        let mut input = base_inputs(
4075            model.clone(),
4076            Arc::new(ScriptedRuntime::with_suspension(vec![
4077                vec![Planned::Complete(json!({"type": "observation", "value": "look"}))],
4078                vec![Planned::Complete(json!({"type": "final_result", "value": "done"}))],
4079            ])),
4080            user("go"),
4081        );
4082        input.invocation_ctx =
4083            Arc::new(MockInvocationContext::new(user("go")).with_steering_inbox(inbox));
4084        let events = collect(input).await;
4085
4086        let steered: Vec<&Event> =
4087            events.iter().filter(|event| event.actions.steering.is_some()).collect();
4088        assert_eq!(steered.len(), 1);
4089        assert_eq!(
4090            (
4091                steered[0].author.as_str(),
4092                steered[0].llm_response.content.clone(),
4093                steered[0].actions.input_screened,
4094                steered[0].actions.steering.as_ref().map(|marker| marker.steer_id.as_str()),
4095            ),
4096            ("user", Some(user("use metric units")), true, Some(receipt.steer_id()))
4097        );
4098        // The second request carries it after the first turn's observation.
4099        let second = model.seen.lock().unwrap()[1].clone();
4100        assert_eq!(second.last(), Some(&user("use metric units")));
4101        assert!(second[second.len() - 2].parts[0].text().unwrap().starts_with("Observation:"));
4102        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4103    }
4104
4105    #[tokio::test]
4106    async fn a_script_that_answers_directly_never_takes_steering() {
4107        let inbox = adk_core::SteeringInbox::new();
4108        let _receipt =
4109            inbox.push(user("keep it short"), user("keep it short"), "user", false).unwrap();
4110        let mut input = base_inputs(
4111            FakeLlm::new("the script"),
4112            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4113                json!({"type": "final_result", "value": "done"}),
4114            )]])),
4115            user("go"),
4116        );
4117        input.invocation_ctx =
4118            Arc::new(MockInvocationContext::new(user("go")).with_steering_inbox(inbox.clone()));
4119        let events = collect(input).await;
4120
4121        assert!(events.iter().all(|event| event.actions.steering.is_none()));
4122        assert_eq!(
4123            inbox.drain().into_iter().map(|message| message.content).collect::<Vec<_>>(),
4124            vec![user("keep it short")]
4125        );
4126    }
4127
4128    #[test]
4129    fn extract_code_handles_language_tag_and_fallback() {
4130        assert_eq!(extract_code_block("```python\nreturn 42\n```"), "return 42");
4131        assert_eq!(extract_code_block("```js\nx;\n```"), "x;");
4132        assert_eq!(extract_code_block("return 1"), "return 1");
4133    }
4134
4135    #[test]
4136    fn assemble_orders_sections() {
4137        let prompt = assemble_system_prompt(
4138            Some("SKILL"),
4139            Some("LITERAL {window_id}"),
4140            Some("GLOBAL"),
4141            Some("HOUSE"),
4142            "RT-ENV",
4143            "TOOLS",
4144            Some("XFER"),
4145        );
4146        let skill = prompt.find("SKILL").unwrap();
4147        let literal = prompt.find("LITERAL {window_id}").unwrap();
4148        let global = prompt.find("GLOBAL").unwrap();
4149        let user = prompt.find("HOUSE").unwrap();
4150        let base = prompt.find("You act by writing code").unwrap();
4151        let rt = prompt.find("RT-ENV").unwrap();
4152        let tools = prompt.find("TOOLS").unwrap();
4153        let xfer = prompt.find("XFER").unwrap();
4154        assert!(
4155            skill < literal
4156                && literal < global
4157                && global < user
4158                && user < base
4159                && base < rt
4160                && rt < tools
4161                && tools < xfer
4162        );
4163    }
4164
4165    #[test]
4166    fn builder_requires_model_and_runtime() {
4167        assert!(CodeActAgent::builder().build().unwrap_err().message.contains("model"));
4168    }
4169
4170    #[test]
4171    fn builder_rejects_two_tools_with_one_name() {
4172        let builder = || {
4173            CodeActAgent::builder()
4174                .model(FakeLlm::new("noop"))
4175                .runtime(Arc::new(ScriptedRuntime::new(vec![])))
4176                .tool(echo_tool())
4177        };
4178        let err = builder().tool(echo_tool()).build().unwrap_err();
4179        assert_eq!(err.code, adk_core::DUPLICATE_TOOL_NAME_CODE);
4180        assert!(err.message.contains("'echo'"), "{}", err.message);
4181        assert!(builder().build().is_ok());
4182    }
4183
4184    #[tokio::test]
4185    async fn generation_config_is_sent_to_the_model() {
4186        let model = FakeLlm::new("noop");
4187        let mut input = base_inputs(
4188            model.clone(),
4189            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4190                json!({"type": "final_result", "value": "done"}),
4191            )]])),
4192            user("go"),
4193        );
4194        input.generate_content_config =
4195            Some(GenerateContentConfig { temperature: Some(0.5), ..Default::default() });
4196        collect(input).await;
4197        assert_eq!(model.last_config().and_then(|c| c.temperature), Some(0.5));
4198    }
4199
4200    #[tokio::test]
4201    async fn output_key_stores_final_result_in_state() {
4202        let mut input = base_inputs(
4203            FakeLlm::new("noop"),
4204            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4205                json!({"type": "final_result", "value": {"answer": 42}}),
4206            )]])),
4207            user("go"),
4208        );
4209        input.output_key = Some("result".to_string());
4210        let events = collect(input).await;
4211        let last = events.last().unwrap();
4212        assert_eq!(last.actions.state_delta.get("result"), Some(&json!({"answer": 42})));
4213    }
4214
4215    #[tokio::test]
4216    async fn tool_timeout_raises_into_the_script() {
4217        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4218            Planned::call("sleeper", json!({}), 1),
4219            Planned::Complete(json!({"type": "final_result", "value": "recovered"})),
4220        ]]));
4221        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
4222        input.tools = vec![sleeping_tool()];
4223        input.tool_timeout = Duration::from_millis(20);
4224        let events = collect(input).await;
4225        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("recovered"));
4226        assert!(rt.last_raise().unwrap().contains("timed out"));
4227    }
4228
4229    #[tokio::test]
4230    async fn before_agent_callback_short_circuits_the_loop() {
4231        let model = FakeLlm::new("noop");
4232        let before: BeforeAgentCallback = Box::new(|_ctx| {
4233            Box::pin(async { Ok(Some(Content::new("model").with_text("intercepted"))) })
4234        });
4235        let agent = CodeActAgent::builder()
4236            .model(model.clone())
4237            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![])))
4238            .before_callback(before)
4239            .build()
4240            .unwrap();
4241        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4242        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("intercepted"));
4243        // The model was never consulted because the loop was short-circuited.
4244        assert_eq!(model.calls(), 0);
4245    }
4246
4247    #[tokio::test]
4248    async fn after_agent_callback_runs_on_completion() {
4249        let after: AfterAgentCallback = Box::new(|_ctx| {
4250            Box::pin(async { Ok(Some(Content::new("model").with_text("after-done"))) })
4251        });
4252        let agent = CodeActAgent::builder()
4253            .model(FakeLlm::new("noop"))
4254            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4255                json!({"type": "final_result", "value": "answer"}),
4256            )]])))
4257            .after_callback(after)
4258            .build()
4259            .unwrap();
4260        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4261        // The final result is emitted, then the after-agent callback content.
4262        assert!(events.iter().any(|e| final_text(e).as_deref() == Some("answer")));
4263        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("after-done"));
4264    }
4265
4266    #[tokio::test]
4267    async fn after_agent_callback_skipped_on_suspend() {
4268        let after: AfterAgentCallback = Box::new(|_ctx| {
4269            Box::pin(async { Ok(Some(Content::new("model").with_text("after-done"))) })
4270        });
4271        let agent = CodeActAgent::builder()
4272            .model(FakeLlm::new("noop"))
4273            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4274                Planned::call("slow", json!({}), 1),
4275                Planned::Complete(json!({"type": "final_result", "value": "unreached"})),
4276            ]])))
4277            .tool(long_running_tool())
4278            .after_callback(after)
4279            .build()
4280            .unwrap();
4281        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4282        // The run suspended, so the after-agent callback must not have fired.
4283        assert!(events.iter().all(|e| final_text(e).as_deref() != Some("after-done")));
4284    }
4285
4286    /// Concatenated text of the transcript the model saw on its first call.
4287    fn first_transcript_text(model: &FakeLlm) -> String {
4288        model
4289            .seen
4290            .lock()
4291            .unwrap()
4292            .first()
4293            .map(|contents| {
4294                contents
4295                    .iter()
4296                    .flat_map(|c| c.parts.iter())
4297                    .filter_map(|p| p.text())
4298                    .collect::<Vec<_>>()
4299                    .join("\n")
4300            })
4301            .unwrap_or_default()
4302    }
4303
4304    fn final_runtime() -> Arc<ScriptedRuntime> {
4305        Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4306            json!({"type": "final_result", "value": "x"}),
4307        )]]))
4308    }
4309
4310    #[tokio::test]
4311    async fn agent_instruction_precedes_the_contract() {
4312        let model = FakeLlm::new("noop");
4313        let agent = CodeActAgent::builder()
4314            .model(model.clone())
4315            .runtime(final_runtime())
4316            .instruction("HOUSE RULES")
4317            .build()
4318            .unwrap();
4319        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4320        let sys = first_transcript_text(&model);
4321        assert!(sys.find("HOUSE RULES").unwrap() < sys.find("You act by writing code").unwrap());
4322    }
4323
4324    #[tokio::test]
4325    async fn instruction_provider_takes_precedence_over_static() {
4326        let model = FakeLlm::new("noop");
4327        let provider: InstructionProvider =
4328            Box::new(|_ctx| Box::pin(async { Ok("DYNAMIC RULES".to_string()) }));
4329        let agent = CodeActAgent::builder()
4330            .model(model.clone())
4331            .runtime(final_runtime())
4332            .instruction("STATIC RULES")
4333            .instruction_provider(provider)
4334            .build()
4335            .unwrap();
4336        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4337        let sys = first_transcript_text(&model);
4338        assert!(sys.contains("DYNAMIC RULES"));
4339        assert!(!sys.contains("STATIC RULES"));
4340    }
4341
4342    #[tokio::test]
4343    async fn global_instruction_precedes_agent_instruction() {
4344        let model = FakeLlm::new("noop");
4345        let agent = CodeActAgent::builder()
4346            .model(model.clone())
4347            .runtime(final_runtime())
4348            .global_instruction("GLOBAL IDENTITY")
4349            .instruction("AGENT RULES")
4350            .build()
4351            .unwrap();
4352        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4353        let sys = first_transcript_text(&model);
4354        assert!(sys.find("GLOBAL IDENTITY").unwrap() < sys.find("AGENT RULES").unwrap());
4355    }
4356
4357    #[tokio::test]
4358    async fn static_instruction_is_sent_as_written_before_the_global_instruction() {
4359        let model = FakeLlm::new("noop");
4360        let agent = CodeActAgent::builder()
4361            .model(model.clone())
4362            .runtime(final_runtime())
4363            .static_instruction("Call set_target {window_id} first.")
4364            .global_instruction("GLOBAL IDENTITY")
4365            .instruction("AGENT RULES")
4366            .build()
4367            .unwrap();
4368        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4369        let sys = first_transcript_text(&model);
4370        let literal = sys.find("Call set_target {window_id} first.").unwrap();
4371        assert!(literal < sys.find("GLOBAL IDENTITY").unwrap());
4372    }
4373
4374    #[tokio::test]
4375    async fn default_include_contents_seeds_conversation_history() {
4376        let model = FakeLlm::new("noop");
4377        let agent =
4378            CodeActAgent::builder().model(model.clone()).runtime(final_runtime()).build().unwrap();
4379        let ctx = MockInvocationContext::new(user("q2")).with_history(vec![
4380            user("q1"),
4381            Content::new("model").with_text("a1"),
4382            user("q2"),
4383        ]);
4384        run_collect(&agent, Arc::new(ctx)).await;
4385        let transcript = first_transcript_text(&model);
4386        assert!(transcript.contains("q1"));
4387        assert!(transcript.contains("a1"));
4388    }
4389
4390    #[tokio::test]
4391    async fn include_contents_none_excludes_history() {
4392        let model = FakeLlm::new("noop");
4393        let agent = CodeActAgent::builder()
4394            .model(model.clone())
4395            .runtime(final_runtime())
4396            .include_contents(IncludeContents::None)
4397            .build()
4398            .unwrap();
4399        let ctx = MockInvocationContext::new(user("q2")).with_history(vec![
4400            user("q1"),
4401            Content::new("model").with_text("a1"),
4402            user("q2"),
4403        ]);
4404        run_collect(&agent, Arc::new(ctx)).await;
4405        let transcript = first_transcript_text(&model);
4406        assert!(!transcript.contains("a1"));
4407        assert!(transcript.contains("q2"));
4408    }
4409
4410    #[tokio::test]
4411    async fn retry_budget_recovers_a_flaky_tool() {
4412        // `flaky` fails once; a budget of one retry lets the call succeed.
4413        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4414            Planned::call("flaky", json!({}), 1),
4415            Planned::Complete(json!({"type": "final_result", "value": "done"})),
4416        ]]));
4417        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
4418        input.tools = vec![flaky_tool(1)];
4419        input.default_retry_budget = Some(RetryBudget::new(1, Duration::ZERO));
4420        let events = collect(input).await;
4421        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4422        // The retried call ultimately returned a value (not a raised error).
4423        assert_eq!(rt.last_value(), Some(json!({"ok": true})));
4424        assert!(rt.last_raise().is_none());
4425    }
4426
4427    #[tokio::test]
4428    async fn retry_budget_never_repeats_a_non_idempotent_tool() {
4429        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4430            Planned::call("flaky", json!({}), 1),
4431            Planned::Complete(json!({"type": "final_result", "value": "done"})),
4432        ]]));
4433        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
4434        input.tools = vec![flaky_tool_with_effect(1, adk_core::ToolEffect::NonIdempotent)];
4435        input.default_retry_budget = Some(RetryBudget::new(3, Duration::ZERO));
4436        collect(input).await;
4437        // The single failure is raised into the script instead of being retried.
4438        assert!(rt.last_raise().is_some_and(|message| message.contains("transient failure")));
4439        assert_eq!(rt.last_value(), None);
4440    }
4441
4442    #[tokio::test]
4443    async fn on_tool_error_supplies_a_fallback_value() {
4444        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4445            Planned::call("boom", json!({}), 1),
4446            Planned::Complete(json!({"type": "final_result", "value": "done"})),
4447        ]]));
4448        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
4449        input.tools = vec![failing_tool()];
4450        let cb: OnToolErrorCallback = Box::new(|_ctx, _tool, _args, _err| {
4451            Box::pin(async { Ok(Some(json!({"fallback": "used"}))) })
4452        });
4453        input.on_tool_error = Arc::new(vec![cb]);
4454        let events = collect(input).await;
4455        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4456        // The failure was replaced by the fallback value, not raised.
4457        assert_eq!(rt.last_value(), Some(json!({"fallback": "used"})));
4458        assert!(rt.last_raise().is_none());
4459    }
4460
4461    #[tokio::test]
4462    async fn circuit_breaker_opens_after_threshold_failures() {
4463        // Threshold 1: the first failure trips the breaker; the second call is
4464        // short-circuited without executing the tool.
4465        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4466            Planned::call("boom", json!({}), 1),
4467            Planned::call("boom", json!({}), 2),
4468            Planned::Complete(json!({"type": "final_result", "value": "done"})),
4469        ]]));
4470        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
4471        input.tools = vec![failing_tool()];
4472        input.circuit_breaker_threshold = Some(1);
4473        let events = collect(input).await;
4474        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4475        assert!(rt.last_raise().unwrap().contains("temporarily disabled"));
4476    }
4477
4478    fn object_schema() -> Value {
4479        json!({
4480            "type": "object",
4481            "required": ["answer"],
4482            "properties": { "answer": { "type": "string" } },
4483            "additionalProperties": false
4484        })
4485    }
4486
4487    #[tokio::test]
4488    async fn output_schema_accepts_a_conforming_final_result() {
4489        let mut input = base_inputs(
4490            FakeLlm::new("noop"),
4491            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4492                json!({"type": "final_result", "value": {"answer": "hi"}}),
4493            )]])),
4494            user("go"),
4495        );
4496        input.output_schema = Some(object_schema());
4497        let events = collect(input).await;
4498        // A single final event, carrying the conforming value.
4499        assert_eq!(events.len(), 1);
4500        assert!(final_text(events.last().unwrap()).unwrap().contains("hi"));
4501    }
4502
4503    #[tokio::test]
4504    async fn output_schema_correction_retries_then_succeeds() {
4505        let model = FakeLlm::new("noop");
4506        let mut input = base_inputs(
4507            model.clone(),
4508            Arc::new(ScriptedRuntime::with_suspension(vec![
4509                vec![Planned::Complete(json!({"type": "final_result", "value": {"wrong": 1}}))],
4510                vec![Planned::Complete(json!({"type": "final_result", "value": {"answer": "ok"}}))],
4511            ])),
4512            user("go"),
4513        );
4514        input.output_schema = Some(object_schema());
4515        let events = collect(input).await;
4516        assert!(final_text(events.last().unwrap()).unwrap().contains("ok"));
4517        // Two model turns: the first was corrected.
4518        assert_eq!(model.calls(), 2);
4519        let second = &model.seen.lock().unwrap()[1];
4520        assert!(second.iter().any(|c| {
4521            c.parts
4522                .iter()
4523                .any(|p| p.text().is_some_and(|t| t.contains("did not match the required schema")))
4524        }));
4525    }
4526
4527    #[tokio::test]
4528    async fn output_schema_errors_after_max_retries() {
4529        let mut input = base_inputs(
4530            FakeLlm::new("noop"),
4531            Arc::new(ScriptedRuntime::with_suspension(vec![
4532                vec![Planned::Complete(json!({"type": "final_result", "value": {"wrong": 1}}))],
4533                vec![Planned::Complete(json!({"type": "final_result", "value": {"wrong": 2}}))],
4534            ])),
4535            user("go"),
4536        );
4537        input.output_schema = Some(object_schema());
4538        input.output_max_retries = 1;
4539        let mut stream = Box::pin(run_codeact(input));
4540        let mut last_err = None;
4541        while let Some(item) = stream.next().await {
4542            if let Err(e) = item {
4543                last_err = Some(e);
4544            }
4545        }
4546        assert!(last_err.unwrap().message.contains("schema validation"));
4547    }
4548
4549    #[derive(schemars::JsonSchema)]
4550    #[allow(dead_code)]
4551    struct Answer {
4552        answer: String,
4553    }
4554
4555    #[tokio::test]
4556    async fn output_type_enforces_a_derived_schema() {
4557        let agent = CodeActAgent::builder()
4558            .model(FakeLlm::new("noop"))
4559            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4560                json!({"type": "final_result", "value": {"answer": "hi"}}),
4561            )]])))
4562            .output_type::<Answer>()
4563            .build()
4564            .unwrap();
4565        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4566        assert!(final_text(events.last().unwrap()).unwrap().contains("hi"));
4567    }
4568
4569    #[tokio::test]
4570    async fn toolset_tools_are_callable_and_listed_in_the_prompt() {
4571        let model = FakeLlm::new("noop");
4572        let agent = CodeActAgent::builder()
4573            .model(model.clone())
4574            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4575                Planned::call("echo", json!({"msg": "hi"}), 1),
4576                Planned::Complete(json!({"type": "final_result", "value": "done"})),
4577            ]])))
4578            .toolset(fake_toolset("dynamic", vec![echo_tool()]))
4579            .build()
4580            .unwrap();
4581        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4582        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4583        // The toolset-provided tool was both callable and described to the model.
4584        assert!(first_transcript_text(&model).contains("echo"));
4585    }
4586
4587    #[cfg(feature = "skills")]
4588    #[tokio::test]
4589    async fn skill_block_is_injected_for_a_matching_query() {
4590        use std::fs;
4591        let temp = tempfile::tempdir().unwrap();
4592        fs::create_dir_all(temp.path().join(".skills")).unwrap();
4593        fs::write(
4594            temp.path().join(".skills/searcher.md"),
4595            "---\nname: searcher\ndescription: Search rust code with rg\ntags: [search]\n---\nUse rg to grep the codebase.",
4596        )
4597        .unwrap();
4598
4599        let model = FakeLlm::new("noop");
4600        let agent = CodeActAgent::builder()
4601            .model(model.clone())
4602            .runtime(final_runtime())
4603            .with_skills_from_root(temp.path())
4604            .unwrap()
4605            .with_skill_policy(SelectionPolicy { min_score: 0.1, ..SelectionPolicy::default() })
4606            .build()
4607            .unwrap();
4608        run_collect(&agent, Arc::new(MockInvocationContext::new(user("help me search rust code"))))
4609            .await;
4610        // The matched skill's prompt block is present in the system prompt.
4611        assert!(first_transcript_text(&model).contains("rg"));
4612    }
4613
4614    #[cfg(feature = "guardrails")]
4615    #[tokio::test]
4616    async fn input_guardrail_blocks_harmful_content() {
4617        use crate::guardrails::{ContentFilter, GuardrailSet};
4618        let agent = CodeActAgent::builder()
4619            .model(FakeLlm::new("noop"))
4620            .runtime(final_runtime())
4621            .input_guardrails(GuardrailSet::new().with(ContentFilter::harmful_content()))
4622            .build()
4623            .unwrap();
4624        let ctx = MockInvocationContext::new(user("how to deploy malware on a server"));
4625        match agent.run(Arc::new(ctx)).await {
4626            Ok(_) => panic!("harmful input should be blocked"),
4627            Err(e) => assert!(e.message.contains("guardrail")),
4628        }
4629    }
4630
4631    #[cfg(feature = "guardrails")]
4632    #[tokio::test]
4633    async fn output_guardrail_redacts_pii_in_final_result() {
4634        use crate::guardrails::{GuardrailSet, PiiRedactor};
4635        let agent = CodeActAgent::builder()
4636            .model(FakeLlm::new("noop"))
4637            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4638                json!({"type": "final_result", "value": "reach me at alice@example.com"}),
4639            )]])))
4640            .output_guardrails(GuardrailSet::new().with(PiiRedactor::new()))
4641            .build()
4642            .unwrap();
4643        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4644        let text = final_text(events.last().unwrap()).unwrap();
4645        assert!(!text.contains("alice@example.com"));
4646        assert!(text.contains("[EMAIL REDACTED]"));
4647    }
4648
4649    /// Returns a passage and records its source.
4650    #[cfg(feature = "guardrails")]
4651    struct CitedSearch;
4652
4653    #[cfg(feature = "guardrails")]
4654    #[async_trait]
4655    impl Tool for CitedSearch {
4656        fn name(&self) -> &str {
4657            "search"
4658        }
4659        fn description(&self) -> &str {
4660            "Searches the policies."
4661        }
4662        async fn execute(
4663            &self,
4664            ctx: Arc<dyn ToolContext>,
4665            _args: Value,
4666        ) -> adk_core::Result<Value> {
4667            adk_core::record_grounding_sources(
4668                ctx.as_ref(),
4669                [GroundingSource::new("search", "https://example.com/refunds")],
4670            );
4671            Ok(json!("Refunds take 30 days."))
4672        }
4673    }
4674
4675    #[cfg(feature = "guardrails")]
4676    fn cited_agent(answer: &str) -> CodeActAgent {
4677        use crate::guardrails::{CitationRequired, GuardrailSet};
4678        CodeActAgent::builder()
4679            .model(FakeLlm::new("noop"))
4680            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4681                Planned::call("search", json!({}), 1),
4682                Planned::Complete(json!({"type": "final_result", "value": answer})),
4683            ]])))
4684            .tool(Arc::new(CitedSearch))
4685            .output_guardrails(GuardrailSet::new().with(CitationRequired::new()))
4686            .build()
4687            .unwrap()
4688    }
4689
4690    #[cfg(feature = "guardrails")]
4691    #[tokio::test]
4692    async fn a_final_result_citing_a_retrieved_source_carries_the_citation() {
4693        let agent = cited_agent("30 days ([policy](https://example.com/refunds))");
4694        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4695        assert!(
4696            events.iter().any(|event| event.actions.grounding_sources
4697                == [GroundingSource::new("search", "https://example.com/refunds")]),
4698            "the tool's source reaches an event"
4699        );
4700        let citations = events.last().unwrap().llm_response.citation_metadata.clone().unwrap();
4701        let uris: Vec<_> =
4702            citations.citation_sources.iter().filter_map(|c| c.uri.as_deref()).collect();
4703        assert_eq!(uris, ["https://example.com/refunds"]);
4704    }
4705
4706    #[cfg(feature = "guardrails")]
4707    #[tokio::test]
4708    async fn a_final_result_citing_nothing_retrieved_is_blocked() {
4709        let agent = cited_agent("30 days ([policy](https://elsewhere.example/refunds))");
4710        let mut stream = agent.run(Arc::new(MockInvocationContext::new(user("go")))).await.unwrap();
4711        let mut blocked = None;
4712        while let Some(item) = stream.next().await {
4713            if let Err(error) = item {
4714                blocked = Some(error);
4715            }
4716        }
4717        let error = blocked.expect("the final result is blocked");
4718        assert_eq!(error.code, crate::guardrails::OUTPUT_BLOCKED_CODE);
4719    }
4720
4721    #[cfg(feature = "enhanced-plugins")]
4722    struct ToolArgRewriter;
4723    #[cfg(feature = "enhanced-plugins")]
4724    #[async_trait]
4725    impl EnhancedPlugin for ToolArgRewriter {
4726        fn name(&self) -> &str {
4727            "arg-rewriter"
4728        }
4729        async fn before_tool_call(
4730            &self,
4731            _tool: Arc<dyn Tool>,
4732            _args: Value,
4733            _ctx: Arc<dyn CallbackContext>,
4734            _pctx: &adk_plugin::PluginContext,
4735        ) -> adk_core::Result<BeforeToolCallResult> {
4736            Ok(BeforeToolCallResult::Continue(json!({"rewritten": true})))
4737        }
4738    }
4739
4740    #[cfg(feature = "enhanced-plugins")]
4741    struct ToolShortCircuit;
4742    #[cfg(feature = "enhanced-plugins")]
4743    #[async_trait]
4744    impl EnhancedPlugin for ToolShortCircuit {
4745        fn name(&self) -> &str {
4746            "short-circuit"
4747        }
4748        async fn before_tool_call(
4749            &self,
4750            _tool: Arc<dyn Tool>,
4751            _args: Value,
4752            _ctx: Arc<dyn CallbackContext>,
4753            _pctx: &adk_plugin::PluginContext,
4754        ) -> adk_core::Result<BeforeToolCallResult> {
4755            Ok(BeforeToolCallResult::ShortCircuit(json!({"synthetic": true})))
4756        }
4757    }
4758
4759    #[cfg(feature = "enhanced-plugins")]
4760    struct ModelShortCircuit;
4761    #[cfg(feature = "enhanced-plugins")]
4762    #[async_trait]
4763    impl EnhancedPlugin for ModelShortCircuit {
4764        fn name(&self) -> &str {
4765            "model-short-circuit"
4766        }
4767        async fn before_model_call(
4768            &self,
4769            _request: LlmRequest,
4770            _ctx: Arc<dyn CallbackContext>,
4771            _pctx: &adk_plugin::PluginContext,
4772        ) -> adk_core::Result<BeforeModelCallResult> {
4773            let response = LlmResponse {
4774                content: Some(Content::new("model").with_text("noop")),
4775                ..Default::default()
4776            };
4777            Ok(BeforeModelCallResult::ShortCircuit(response))
4778        }
4779    }
4780
4781    #[cfg(feature = "enhanced-plugins")]
4782    #[tokio::test]
4783    async fn enhanced_plugin_rewrites_tool_args() {
4784        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4785            Planned::call("echo", json!({"orig": true}), 1),
4786            Planned::Complete(json!({"type": "final_result", "value": "done"})),
4787        ]]));
4788        let agent = CodeActAgent::builder()
4789            .model(FakeLlm::new("noop"))
4790            .runtime(rt.clone())
4791            .tool(echo_tool())
4792            .enhanced_plugin(Arc::new(ToolArgRewriter))
4793            .build()
4794            .unwrap();
4795        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4796        // echo received the plugin-rewritten args and returned them.
4797        assert_eq!(rt.last_value(), Some(json!({"rewritten": true})));
4798    }
4799
4800    #[cfg(feature = "enhanced-plugins")]
4801    #[tokio::test]
4802    async fn enhanced_plugin_short_circuits_tool() {
4803        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
4804            Planned::call("boom", json!({}), 1),
4805            Planned::Complete(json!({"type": "final_result", "value": "done"})),
4806        ]]));
4807        let agent = CodeActAgent::builder()
4808            .model(FakeLlm::new("noop"))
4809            .runtime(rt.clone())
4810            .tool(failing_tool())
4811            .enhanced_plugin(Arc::new(ToolShortCircuit))
4812            .build()
4813            .unwrap();
4814        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4815        // The failing tool never ran; the synthetic result was fed back.
4816        assert_eq!(rt.last_value(), Some(json!({"synthetic": true})));
4817        assert!(rt.last_raise().is_none());
4818    }
4819
4820    #[cfg(feature = "enhanced-plugins")]
4821    #[tokio::test]
4822    async fn enhanced_plugin_short_circuits_model() {
4823        let model = FakeLlm::new("noop");
4824        let agent = CodeActAgent::builder()
4825            .model(model.clone())
4826            .runtime(final_runtime())
4827            .enhanced_plugin(Arc::new(ModelShortCircuit))
4828            .build()
4829            .unwrap();
4830        run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
4831        // The model was short-circuited by the plugin, never invoked.
4832        assert_eq!(model.calls(), 0);
4833    }
4834
4835    #[tokio::test]
4836    async fn toolset_name_conflict_is_rejected() {
4837        let agent = CodeActAgent::builder()
4838            .model(FakeLlm::new("noop"))
4839            .runtime(Arc::new(ScriptedRuntime::new(vec![])))
4840            .tool(echo_tool())
4841            .toolset(fake_toolset("dup", vec![echo_tool()]))
4842            .build()
4843            .unwrap();
4844        let err = match agent.run(Arc::new(MockInvocationContext::new(user("go")))).await {
4845            Ok(_) => panic!("toolset name conflict should error"),
4846            Err(e) => e,
4847        };
4848        assert!(err.message.contains("duplicate tool name 'echo'"));
4849    }
4850
4851    #[test]
4852    fn input_schema_is_exposed_for_introspection() {
4853        let schema = json!({"type": "object"});
4854        let agent = CodeActAgent::builder()
4855            .model(FakeLlm::new("noop"))
4856            .runtime(Arc::new(ScriptedRuntime::new(vec![])))
4857            .input_schema(schema.clone())
4858            .build()
4859            .unwrap();
4860        assert_eq!(agent.input_schema(), Some(&schema));
4861    }
4862
4863    #[test]
4864    fn require_confirmation_for_all_sets_always_policy() {
4865        let agent = CodeActAgent::builder()
4866            .model(FakeLlm::new("noop"))
4867            .runtime(Arc::new(ScriptedRuntime::new(vec![])))
4868            .require_tool_confirmation_for_all()
4869            .build()
4870            .unwrap();
4871        assert!(agent.policy.requires_confirmation("anything"));
4872    }
4873
4874    fn transfer_target(event: &Event) -> Option<&str> {
4875        event.actions.transfer_to_agent.as_deref()
4876    }
4877
4878    #[tokio::test]
4879    async fn transfer_to_valid_target_ends_loop_with_transfer_event() {
4880        let events = drive_targets(
4881            FakeLlm::new("noop"),
4882            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4883                json!({"type": "transfer_to_agent", "agent_name": "billing"}),
4884            )]])),
4885            vec!["billing".to_string(), "support".to_string()],
4886            user("go"),
4887        )
4888        .await;
4889        let last = events.last().unwrap();
4890        assert_eq!(transfer_target(last), Some("billing"));
4891        // The pending checkpoint is cleared on transfer, like a final result.
4892        assert_eq!(last.actions.state_delta.get(PENDING_STATE_KEY), Some(&Value::Null));
4893    }
4894
4895    #[tokio::test]
4896    async fn unknown_transfer_target_feeds_error_then_model_retries() {
4897        // First script transfers to an unknown agent; the model then finishes.
4898        let model = FakeLlm::new("noop");
4899        let events = drive_targets(
4900            model.clone(),
4901            Arc::new(ScriptedRuntime::with_suspension(vec![
4902                vec![Planned::Complete(
4903                    json!({"type": "transfer_to_agent", "agent_name": "ghost"}),
4904                )],
4905                vec![Planned::Complete(json!({"type": "final_result", "value": "done"}))],
4906            ])),
4907            vec!["billing".to_string()],
4908            user("go"),
4909        )
4910        .await;
4911        // No transfer happened; the loop reached a final result instead.
4912        assert!(events.iter().all(|e| transfer_target(e).is_none()));
4913        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
4914        // The model got a second turn whose transcript carries the error.
4915        assert_eq!(model.calls(), 2);
4916        let second = &model.seen.lock().unwrap()[1];
4917        assert!(second.iter().any(|c| {
4918            c.parts
4919                .iter()
4920                .any(|p| p.text().is_some_and(|t| t.contains("cannot transfer to 'ghost'")))
4921        }));
4922    }
4923
4924    #[tokio::test]
4925    async fn transfer_section_revealed_only_when_targets_present() {
4926        // With targets: the first prompt the model sees lists the transfer option.
4927        let with_model = FakeLlm::new("noop");
4928        drive_targets(
4929            with_model.clone(),
4930            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4931                json!({"type": "final_result", "value": "x"}),
4932            )]])),
4933            vec!["billing".to_string()],
4934            user("go"),
4935        )
4936        .await;
4937        let with_sys = with_model.seen.lock().unwrap()[0][0].parts[0].text().unwrap().to_string();
4938        assert!(with_sys.contains("transfer_to_agent"));
4939        assert!(with_sys.contains("billing"));
4940
4941        // Without targets: no transfer section is injected.
4942        let without_model = FakeLlm::new("noop");
4943        drive(
4944            without_model.clone(),
4945            Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4946                json!({"type": "final_result", "value": "x"}),
4947            )]])),
4948            vec![],
4949            ToolConfirmationPolicy::Never,
4950            HashMap::new(),
4951            user("go"),
4952            None,
4953            true,
4954        )
4955        .await;
4956        let without_sys =
4957            without_model.seen.lock().unwrap()[0][0].parts[0].text().unwrap().to_string();
4958        assert!(!without_sys.contains("transfer_to_agent"));
4959    }
4960
4961    #[tokio::test]
4962    async fn run_merges_sub_agents_and_runner_targets() {
4963        // A sub-agent (build time) plus a runner-provided peer (run time) are
4964        // both offered; the script transfers to the runner-provided one.
4965        let agent = CodeActAgent::builder()
4966            .model(FakeLlm::new("noop"))
4967            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
4968                json!({"type": "transfer_to_agent", "agent_name": "peer"}),
4969            )]])))
4970            .sub_agent(fake_agent("child"))
4971            .build()
4972            .unwrap();
4973
4974        let ctx = Arc::new(
4975            MockInvocationContext::new(user("go")).with_transfer_targets(vec!["peer".to_string()]),
4976        );
4977        let mut last = None;
4978        let mut stream = agent.run(ctx).await.unwrap();
4979        while let Some(item) = stream.next().await {
4980            last = Some(item.unwrap());
4981        }
4982        assert_eq!(transfer_target(last.as_ref().unwrap()), Some("peer"));
4983    }
4984
4985    /// Build an agent that, across two turns, first tries `first` then `second`
4986    /// as transfer targets, configured with the given disallow flags.
4987    fn two_transfer_agent(
4988        first: &str,
4989        second: &str,
4990        disallow_parent: bool,
4991        disallow_peers: bool,
4992        sub_agents: Vec<Arc<dyn Agent>>,
4993    ) -> CodeActAgent {
4994        let mut builder = CodeActAgent::builder()
4995            .model(FakeLlm::new("noop"))
4996            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![
4997                vec![Planned::Complete(json!({"type": "transfer_to_agent", "agent_name": first}))],
4998                vec![Planned::Complete(json!({"type": "transfer_to_agent", "agent_name": second}))],
4999            ])))
5000            .disallow_transfer_to_parent(disallow_parent)
5001            .disallow_transfer_to_peers(disallow_peers);
5002        for agent in sub_agents {
5003            builder = builder.sub_agent(agent);
5004        }
5005        builder.build().unwrap()
5006    }
5007
5008    async fn run_collect(agent: &CodeActAgent, ctx: Arc<dyn InvocationContext>) -> Vec<Event> {
5009        let mut events = Vec::new();
5010        let mut stream = agent.run(ctx).await.unwrap();
5011        while let Some(item) = stream.next().await {
5012            events.push(item.unwrap());
5013        }
5014        events
5015    }
5016
5017    #[tokio::test]
5018    async fn disallow_transfer_to_parent_filters_only_the_parent() {
5019        // First turn transfers to the parent (filtered out) -> error; second
5020        // turn transfers to a peer, which is still allowed.
5021        let agent = two_transfer_agent("boss", "peer", true, false, vec![]);
5022        let ctx = Arc::new(
5023            MockInvocationContext::new(user("go"))
5024                .with_parent_agent("boss")
5025                .with_transfer_targets(vec!["boss".to_string(), "peer".to_string()]),
5026        );
5027        let events = run_collect(&agent, ctx).await;
5028        assert_eq!(transfer_target(events.last().unwrap()), Some("peer"));
5029    }
5030
5031    #[tokio::test]
5032    async fn disallow_transfer_to_peers_filters_peers_but_keeps_parent() {
5033        // First turn transfers to a peer (filtered out) -> error; second turn
5034        // transfers to the parent, which is still allowed.
5035        let agent = two_transfer_agent("peer", "boss", false, true, vec![]);
5036        let ctx = Arc::new(
5037            MockInvocationContext::new(user("go"))
5038                .with_parent_agent("boss")
5039                .with_transfer_targets(vec!["boss".to_string(), "peer".to_string()]),
5040        );
5041        let events = run_collect(&agent, ctx).await;
5042        assert_eq!(transfer_target(events.last().unwrap()), Some("boss"));
5043    }
5044
5045    fn state_delta_in(event: &Event, key: &str) -> Option<Value> {
5046        event.actions.state_delta.get(key).cloned()
5047    }
5048
5049    #[tokio::test]
5050    async fn inline_tool_state_delta_is_persisted_on_a_checkpoint() {
5051        // A tool that writes session state has its delta merged onto the
5052        // after-checkpoint event, so the Runner persists it — like LlmAgent.
5053        let events = drive(
5054            FakeLlm::new("noop"),
5055            Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5056                Planned::call("remember", json!({}), 1),
5057                Planned::Complete(json!({"type": "final_result", "value": "done"})),
5058            ]])),
5059            vec![state_tool()],
5060            ToolConfirmationPolicy::Never,
5061            HashMap::new(),
5062            user("go"),
5063            None,
5064            true,
5065        )
5066        .await;
5067        // Some persisted event carries the tool's state delta.
5068        assert!(events.iter().any(|e| state_delta_in(e, "note") == Some(json!("kept"))));
5069        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5070    }
5071
5072    #[tokio::test]
5073    async fn non_suspending_tool_state_delta_persists_on_final() {
5074        // Without suspension there are no checkpoints, so the delta rides on the
5075        // final event instead.
5076        let events = drive(
5077            FakeLlm::new("noop"),
5078            Arc::new(ScriptedRuntime::new(vec![vec![
5079                Planned::call("remember", json!({}), 1),
5080                Planned::Complete(json!({"type": "final_result", "value": "done"})),
5081            ]])),
5082            vec![state_tool()],
5083            ToolConfirmationPolicy::Never,
5084            HashMap::new(),
5085            user("go"),
5086            None,
5087            false,
5088        )
5089        .await;
5090        let last = events.last().unwrap();
5091        assert_eq!(state_delta_in(last, "note"), Some(json!("kept")));
5092        assert_eq!(final_text(last).as_deref(), Some("done"));
5093    }
5094
5095    #[tokio::test]
5096    async fn escalating_tool_ends_the_run() {
5097        // A tool that escalates stops the loop before the script continues.
5098        let events = drive(
5099            FakeLlm::new("noop"),
5100            Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5101                Planned::call("panic_button", json!({}), 1),
5102                Planned::Complete(json!({"type": "final_result", "value": "unreached"})),
5103            ]])),
5104            vec![escalating_tool()],
5105            ToolConfirmationPolicy::Never,
5106            HashMap::new(),
5107            user("go"),
5108            None,
5109            true,
5110        )
5111        .await;
5112        let last = events.last().unwrap();
5113        assert!(last.actions.escalate);
5114        // The pending checkpoint is cleared and no final result was produced.
5115        assert_eq!(last.actions.state_delta.get(PENDING_STATE_KEY), Some(&Value::Null));
5116        assert!(events.iter().all(|e| final_text(e).as_deref() != Some("unreached")));
5117    }
5118
5119    #[tokio::test]
5120    async fn agent_tool_runs_as_a_regular_callable_tool() {
5121        // An AgentTool wrapping a sub-agent is just a Tool: it is not built-in
5122        // and not long-running, so the loop calls it inline and hands its
5123        // output back into the script as the call's return value.
5124        use adk_tool::AgentTool;
5125        let tool: Arc<dyn Tool> = Arc::new(AgentTool::new(text_agent("researcher", "the answer")));
5126        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5127            Planned::call("researcher", json!({"request": "find it"}), 1),
5128            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5129        ]]));
5130        let events = drive(
5131            FakeLlm::new("noop"),
5132            rt.clone(),
5133            vec![tool],
5134            ToolConfirmationPolicy::Never,
5135            HashMap::new(),
5136            user("go"),
5137            None,
5138            true,
5139        )
5140        .await;
5141        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5142        // The sub-agent ran and its response was the value returned into the script.
5143        assert_eq!(rt.last_value(), Some(json!({"response": "the answer"})));
5144    }
5145
5146    #[tokio::test]
5147    async fn disallow_flags_do_not_filter_sub_agents() {
5148        // A child sub-agent stays available even with peers disallowed.
5149        let agent = two_transfer_agent("child", "child", false, true, vec![fake_agent("child")]);
5150        let ctx = Arc::new(MockInvocationContext::new(user("go")));
5151        let events = run_collect(&agent, ctx).await;
5152        assert_eq!(transfer_target(events.last().unwrap()), Some("child"));
5153    }
5154
5155    #[tokio::test]
5156    async fn before_model_callback_can_skip_the_model() {
5157        // A before-model callback returns a synthetic response, so the model is
5158        // never called; its content drives the loop to a final result.
5159        let model = FakeLlm::new("noop");
5160        let before: BeforeModelCallback = Box::new(|_ctx, _req| {
5161            Box::pin(async {
5162                Ok(BeforeModelResult::Skip(LlmResponse::new(
5163                    Content::new("model").with_text("```\nreturn final_result\n```"),
5164                )))
5165            })
5166        });
5167        let agent = CodeActAgent::builder()
5168            .model(model.clone())
5169            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
5170                json!({"type": "final_result", "value": "done"}),
5171            )]])))
5172            .before_model_callback(before)
5173            .build()
5174            .unwrap();
5175        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
5176        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5177        assert_eq!(model.calls(), 0);
5178    }
5179
5180    #[tokio::test]
5181    async fn after_model_callback_rewrites_the_script() {
5182        // The model emits one script; the after-model callback swaps the response
5183        // for a different one. The swapped script is what the runtime executes —
5184        // here the scripted runtime ignores the text, so we just confirm the
5185        // callback ran and the loop completed.
5186        let model = FakeLlm::new("noop");
5187        let seen = Arc::new(StdMutex::new(false));
5188        let seen_cb = seen.clone();
5189        let after: AfterModelCallback = Box::new(move |_ctx, _resp| {
5190            let seen = seen_cb.clone();
5191            Box::pin(async move {
5192                *seen.lock().unwrap() = true;
5193                Ok(Some(LlmResponse::new(Content::new("model").with_text("```\nx\n```"))))
5194            })
5195        });
5196        let agent = CodeActAgent::builder()
5197            .model(model)
5198            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
5199                json!({"type": "final_result", "value": "done"}),
5200            )]])))
5201            .after_model_callback(after)
5202            .build()
5203            .unwrap();
5204        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
5205        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5206        assert!(*seen.lock().unwrap());
5207    }
5208
5209    #[tokio::test]
5210    async fn before_tool_callback_short_circuits_the_tool() {
5211        // The before-tool callback returns content, so the tool never runs; the
5212        // content's text becomes the value fed back into the script.
5213        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5214            Planned::call("boom", json!({}), 1),
5215            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5216        ]]));
5217        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
5218        input.tools = vec![failing_tool()];
5219        let cb: BeforeToolCallback = Box::new(|_ctx| {
5220            Box::pin(async { Ok(Some(Content::new("function").with_text("intercepted"))) })
5221        });
5222        input.before_tool_callbacks = Arc::new(vec![cb]);
5223        let events = collect(input).await;
5224        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5225        // The failing tool never ran; the callback's text was fed back.
5226        assert_eq!(rt.last_value(), Some(json!("intercepted")));
5227        assert!(rt.last_raise().is_none());
5228    }
5229
5230    /// Skips the model with a final-result script and short-circuits every tool call.
5231    #[derive(Debug)]
5232    struct PolicyHooks;
5233
5234    #[async_trait]
5235    impl adk_core::InvocationHooks for PolicyHooks {
5236        async fn before_model(
5237            &self,
5238            _ctx: Arc<dyn CallbackContext>,
5239            _request: LlmRequest,
5240        ) -> adk_core::Result<BeforeModelResult> {
5241            Ok(BeforeModelResult::Skip(LlmResponse::new(
5242                Content::new("model").with_text("```\nreturn final_result\n```"),
5243            )))
5244        }
5245
5246        async fn before_tool(
5247            &self,
5248            _ctx: Arc<dyn CallbackContext>,
5249        ) -> adk_core::Result<Option<Content>> {
5250            Ok(Some(Content::new("function").with_text("blocked by policy")))
5251        }
5252    }
5253
5254    #[tokio::test]
5255    async fn invocation_hooks_skip_the_model_ahead_of_agent_callbacks() {
5256        let model = FakeLlm::new("noop");
5257        let agent_callback_ran = Arc::new(StdMutex::new(false));
5258        let ran = agent_callback_ran.clone();
5259        let before: BeforeModelCallback = Box::new(move |_ctx, request| {
5260            *ran.lock().unwrap() = true;
5261            Box::pin(async move { Ok(BeforeModelResult::Continue(request)) })
5262        });
5263        let agent = CodeActAgent::builder()
5264            .model(model.clone())
5265            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
5266                json!({"type": "final_result", "value": "done"}),
5267            )]])))
5268            .before_model_callback(before)
5269            .build()
5270            .unwrap();
5271        let ctx =
5272            MockInvocationContext::new(user("go")).with_invocation_hook(Arc::new(PolicyHooks));
5273
5274        let events = run_collect(&agent, Arc::new(ctx)).await;
5275
5276        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5277        assert_eq!(model.calls(), 0, "the hook's response replaces the model call");
5278        assert!(!*agent_callback_ran.lock().unwrap(), "a hook's value short-circuits callbacks");
5279    }
5280
5281    #[tokio::test]
5282    async fn invocation_hooks_short_circuit_a_tool_call() {
5283        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5284            Planned::call("boom", json!({}), 1),
5285            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5286        ]]));
5287        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
5288        input.tools = vec![failing_tool()];
5289        input.invocation_ctx = Arc::new(
5290            MockInvocationContext::new(user("go")).with_invocation_hook(Arc::new(PolicyHooks)),
5291        );
5292
5293        let events = collect(input).await;
5294
5295        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5296        assert_eq!(rt.last_value(), Some(json!("blocked by policy")));
5297        assert!(rt.last_raise().is_none());
5298    }
5299
5300    #[tokio::test]
5301    async fn after_tool_callback_full_rewrites_the_result() {
5302        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5303            Planned::call("echo", json!({"orig": true}), 1),
5304            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5305        ]]));
5306        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
5307        input.tools = vec![echo_tool()];
5308        let cb: AfterToolCallbackFull = Box::new(|_ctx, _tool, _args, _resp| {
5309            Box::pin(async { Ok(Some(json!({"rewritten": true}))) })
5310        });
5311        input.after_tool_callbacks_full = Arc::new(vec![cb]);
5312        let events = collect(input).await;
5313        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5314        assert_eq!(rt.last_value(), Some(json!({"rewritten": true})));
5315    }
5316
5317    #[tokio::test]
5318    async fn tool_call_id_is_visible_to_the_tool() {
5319        // The per-call tool context carries the interpreter call id, not a fixed
5320        // placeholder, so tools can correlate their invocation.
5321        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5322            Planned::call("whoami", json!({}), 42),
5323            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5324        ]]));
5325        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
5326        input.tools = vec![call_id_tool()];
5327        collect(input).await;
5328        assert_eq!(rt.last_value(), Some(json!({"call_id": "42"})));
5329    }
5330
5331    #[tokio::test]
5332    async fn skip_summarization_tool_ends_the_run() {
5333        // A tool that sets skip_summarization ends the loop, like escalate.
5334        let events = drive(
5335            FakeLlm::new("noop"),
5336            Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5337                Planned::call("wrap_up", json!({}), 1),
5338                Planned::Complete(json!({"type": "final_result", "value": "unreached"})),
5339            ]])),
5340            vec![skip_summarization_tool()],
5341            ToolConfirmationPolicy::Never,
5342            HashMap::new(),
5343            user("go"),
5344            None,
5345            true,
5346        )
5347        .await;
5348        let last = events.last().unwrap();
5349        assert!(last.actions.skip_summarization);
5350        assert_eq!(last.actions.state_delta.get(PENDING_STATE_KEY), Some(&Value::Null));
5351        assert!(events.iter().all(|e| final_text(e).as_deref() != Some("unreached")));
5352    }
5353
5354    #[tokio::test]
5355    async fn max_iterations_exceeded_is_an_error() {
5356        // The model keeps emitting observations; with a 1-turn budget the loop
5357        // errors instead of silently terminating.
5358        let mut input = base_inputs(
5359            FakeLlm::new("noop"),
5360            Arc::new(ScriptedRuntime::with_suspension(vec![
5361                vec![Planned::Complete(json!({"type": "observation", "value": "again"}))],
5362                vec![Planned::Complete(json!({"type": "observation", "value": "again"}))],
5363            ])),
5364            user("go"),
5365        );
5366        input.max_iterations = 1;
5367        let mut stream = Box::pin(run_codeact(input));
5368        let mut last_err = None;
5369        while let Some(item) = stream.next().await {
5370            if let Err(e) = item {
5371                last_err = Some(e);
5372            }
5373        }
5374        assert!(last_err.unwrap().message.contains("max iterations"));
5375    }
5376
5377    #[tokio::test]
5378    async fn confirmation_suspend_marks_the_turn_interrupted() {
5379        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5380            Planned::call("echo", json!({}), 1),
5381            Planned::Complete(json!({"type": "final_result", "value": "unreached"})),
5382        ]]));
5383        let mut input = base_inputs(FakeLlm::new("noop"), rt, user("go"));
5384        input.tools = vec![echo_tool()];
5385        input.policy = ToolConfirmationPolicy::Always;
5386        let events = collect(input).await;
5387        let last = events.last().unwrap();
5388        assert!(last.actions.tool_confirmation.is_some());
5389        assert!(last.llm_response.interrupted);
5390        assert!(last.llm_response.turn_complete);
5391    }
5392
5393    #[tokio::test]
5394    async fn the_run_policy_refuses_a_script_tool_call() {
5395        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5396            Planned::call("echo", json!({"msg": "x"}), 1),
5397            Planned::Complete(json!({"type": "final_result", "value": "after"})),
5398        ]]));
5399        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
5400        input.tools = vec![echo_tool()];
5401        let deny_all = adk_core::DeclarativePolicy::builder().build();
5402        input.invocation_ctx = Arc::new(MockInvocationContext::new(user("go")).with_run_config(
5403            adk_core::RunConfig::builder().tool_policy(Arc::new(deny_all)).build(),
5404        ));
5405
5406        let events = collect(input).await;
5407
5408        let raised = rt.last_raise().expect("the refusal is raised into the script");
5409        assert!(raised.contains("denied by policy"), "{raised}");
5410        assert_eq!(rt.last_value(), None, "the tool must not run");
5411        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("after"));
5412    }
5413
5414    #[tokio::test]
5415    async fn an_approval_by_fingerprint_resumes_a_held_call() {
5416        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5417            Planned::call("echo", json!({"msg": "x"}), 7),
5418            Planned::Complete(json!({"type": "final_result", "value": "after"})),
5419        ]]));
5420        let mut input = base_inputs(FakeLlm::new("noop"), rt, user("go"));
5421        input.tools = vec![echo_tool()];
5422        input.policy = ToolConfirmationPolicy::Always;
5423        let held = collect(input).await;
5424        let last = held.last().unwrap();
5425        let request = last.actions.tool_confirmation.clone().expect("held for confirmation");
5426        let cp = pending_in(last).expect("checkpoint persisted");
5427        assert!(matches!(cp.disposition, Disposition::AwaitingConfirmation));
5428
5429        let resumed_rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
5430        let resume = Content::new("user");
5431        let mut input = base_inputs(FakeLlm::new("noop"), resumed_rt.clone(), resume.clone());
5432        input.tools = vec![echo_tool()];
5433        input.policy = ToolConfirmationPolicy::Always;
5434        input.pending = Some(cp);
5435        input.invocation_ctx = Arc::new(
5436            MockInvocationContext::new(resume).with_run_config(
5437                adk_core::RunConfig::builder()
5438                    .tool_approval(request.fingerprint(), adk_core::ToolApproval::approve())
5439                    .build(),
5440            ),
5441        );
5442        let events = collect(input).await;
5443
5444        assert_eq!(resumed_rt.last_value(), Some(json!({"msg": "x"})), "the approved call ran");
5445        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("after"));
5446    }
5447
5448    /// The request a held call carries names the acting agent, so its fingerprint does too
5449    /// (#1210).
5450    #[tokio::test]
5451    async fn a_held_call_names_the_acting_agent() {
5452        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5453            Planned::call("echo", json!({"msg": "x"}), 7),
5454            Planned::Complete(json!({"type": "final_result", "value": "after"})),
5455        ]]));
5456        let mut input = base_inputs(FakeLlm::new("noop"), rt, user("go"));
5457        input.tools = vec![echo_tool()];
5458        input.policy = ToolConfirmationPolicy::Always;
5459        let held = collect(input).await;
5460        let request = held.last().unwrap().actions.tool_confirmation.clone().expect("held");
5461
5462        let agent = "urn:adk:agent:app/code-agent";
5463        assert_eq!(request.acting.as_ref().map(|acting| acting.agent.id.as_str()), Some(agent));
5464        assert_eq!(
5465            adk_core::ToolConfirmationRequest::fingerprint_agent(&request.fingerprint()),
5466            Some(agent)
5467        );
5468    }
5469
5470    #[tokio::test]
5471    async fn a_frozen_run_stops_before_the_model_call() {
5472        let model = FakeLlm::new("noop");
5473        let control = adk_core::GovernanceControl::new();
5474        control.freeze("drill");
5475        let mut input = base_inputs(
5476            model.clone(),
5477            Arc::new(ScriptedRuntime::with_suspension(vec![])),
5478            user("go"),
5479        );
5480        input.invocation_ctx = Arc::new(
5481            MockInvocationContext::new(user("go"))
5482                .with_run_config(adk_core::RunConfig::builder().governance(control).build()),
5483        );
5484        let mut stream = Box::pin(run_codeact(input));
5485        let error = stream.next().await.expect("an item").expect_err("the run must fail");
5486        assert_eq!(error.code, "governance.frozen");
5487        assert_eq!(*model.calls.lock().unwrap(), 0, "the model must not be called");
5488    }
5489
5490    #[tokio::test]
5491    async fn transfer_skips_after_agent_callbacks() {
5492        // A transfer hands control elsewhere, so after-agent callbacks must not
5493        // run (mirrors LlmAgent's early return on transfer).
5494        let after: AfterAgentCallback = Box::new(|_ctx| {
5495            Box::pin(async { Ok(Some(Content::new("model").with_text("after-done"))) })
5496        });
5497        let agent = CodeActAgent::builder()
5498            .model(FakeLlm::new("noop"))
5499            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
5500                json!({"type": "transfer_to_agent", "agent_name": "child"}),
5501            )]])))
5502            .sub_agent(fake_agent("child"))
5503            .after_callback(after)
5504            .build()
5505            .unwrap();
5506        let events = run_collect(&agent, Arc::new(MockInvocationContext::new(user("go")))).await;
5507        assert_eq!(transfer_target(events.last().unwrap()), Some("child"));
5508        assert!(events.iter().all(|e| final_text(e).as_deref() != Some("after-done")));
5509    }
5510
5511    #[tokio::test]
5512    async fn resume_from_pending_result_persists_a_resolved_checkpoint() {
5513        // Recovering from a SAVE-BEFORE (PendingResult) checkpoint re-runs the
5514        // tool, but must persist a SAVE-AFTER (Resolved) checkpoint before
5515        // resuming so a second crash never re-runs the tool again.
5516        let snapshot = serde_json::to_vec(&vec![Planned::Complete(
5517            json!({"type": "final_result", "value": "recovered"}),
5518        )])
5519        .unwrap();
5520        let cp = CodeActCheckpoint {
5521            iteration: 1,
5522            transcript: vec![],
5523            snapshot,
5524            call: PendingToolCall { call_id: 1, tool: "echo".into(), args: json!({"v": 1}) },
5525            disposition: Disposition::PendingResult,
5526            tool_roster: vec!["echo".to_string()],
5527            run_id: None,
5528        };
5529        let events = drive(
5530            FakeLlm::new("noop"),
5531            Arc::new(ScriptedRuntime::with_suspension(vec![])),
5532            vec![echo_tool()],
5533            ToolConfirmationPolicy::Never,
5534            HashMap::new(),
5535            user("ignored"),
5536            Some(cp),
5537            true,
5538        )
5539        .await;
5540        // A Resolved checkpoint is persisted before the final result.
5541        let dispositions: Vec<_> =
5542            events.iter().filter_map(pending_in).map(|c| c.disposition).collect();
5543        assert!(dispositions.iter().any(|d| matches!(d, Disposition::Resolved(_))));
5544        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("recovered"));
5545    }
5546
5547    #[tokio::test]
5548    async fn tool_route_is_propagated_onto_a_persisted_event() {
5549        // A tool that sets `actions.route` has it merged onto a persisted event,
5550        // so the Runner sees it — like `state_delta`/`artifact_delta`.
5551        let events = drive(
5552            FakeLlm::new("noop"),
5553            Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5554                Planned::call("set_route", json!({}), 1),
5555                Planned::Complete(json!({"type": "final_result", "value": "done"})),
5556            ]])),
5557            vec![route_tool()],
5558            ToolConfirmationPolicy::Never,
5559            HashMap::new(),
5560            user("go"),
5561            None,
5562            true,
5563        )
5564        .await;
5565        assert!(
5566            events.iter().any(|e| e.actions.route.as_deref() == Some(&["next".to_string()][..]))
5567        );
5568        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5569    }
5570
5571    #[tokio::test]
5572    async fn escalation_on_resume_ends_the_run_without_resuming() {
5573        // Recovering a SAVE-BEFORE (PendingResult) checkpoint re-runs the tool;
5574        // if that tool escalates, the run ends now (no SAVE-AFTER, no resume),
5575        // matching the inline path.
5576        let snapshot = serde_json::to_vec(&vec![Planned::Complete(
5577            json!({"type": "final_result", "value": "unreached"}),
5578        )])
5579        .unwrap();
5580        let cp = CodeActCheckpoint {
5581            iteration: 1,
5582            transcript: vec![],
5583            snapshot,
5584            call: PendingToolCall { call_id: 1, tool: "panic_button".into(), args: json!({}) },
5585            disposition: Disposition::PendingResult,
5586            tool_roster: vec!["panic_button".to_string()],
5587            run_id: None,
5588        };
5589        let events = drive(
5590            FakeLlm::new("noop"),
5591            Arc::new(ScriptedRuntime::with_suspension(vec![])),
5592            vec![escalating_tool()],
5593            ToolConfirmationPolicy::Never,
5594            HashMap::new(),
5595            user("ignored"),
5596            Some(cp),
5597            true,
5598        )
5599        .await;
5600        let last = events.last().unwrap();
5601        assert!(last.actions.escalate);
5602        assert_eq!(last.actions.state_delta.get(PENDING_STATE_KEY), Some(&Value::Null));
5603        // The run ended before resuming, so no Resolved checkpoint was persisted
5604        // and the script's final result was never reached.
5605        let dispositions: Vec<_> =
5606            events.iter().filter_map(pending_in).map(|c| c.disposition).collect();
5607        assert!(!dispositions.iter().any(|d| matches!(d, Disposition::Resolved(_))));
5608        assert!(events.iter().all(|e| final_text(e).as_deref() != Some("unreached")));
5609    }
5610
5611    #[tokio::test]
5612    async fn escalation_on_long_running_ends_the_run_before_suspending() {
5613        // A long-running tool that escalates ends the run instead of suspending
5614        // to an AwaitingCompletion checkpoint.
5615        let events = drive(
5616            FakeLlm::new("noop"),
5617            Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5618                Planned::call("slow_escalate", json!({}), 1),
5619                Planned::Complete(json!({"type": "final_result", "value": "unreached"})),
5620            ]])),
5621            vec![escalating_long_running_tool()],
5622            ToolConfirmationPolicy::Never,
5623            HashMap::new(),
5624            user("go"),
5625            None,
5626            true,
5627        )
5628        .await;
5629        let last = events.last().unwrap();
5630        assert!(last.actions.escalate);
5631        assert!(last.long_running_tool_ids.is_empty());
5632        assert_eq!(last.actions.state_delta.get(PENDING_STATE_KEY), Some(&Value::Null));
5633        assert!(events.iter().all(|e| final_text(e).as_deref() != Some("unreached")));
5634    }
5635
5636    #[tokio::test]
5637    async fn after_tool_callback_sees_the_tool_outcome() {
5638        // After-tool callbacks receive structured `ToolOutcome` metadata via
5639        // `CallbackContext::tool_outcome()`, matching LlmAgent.
5640        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5641            Planned::call("echo", json!({"v": 1}), 1),
5642            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5643        ]]));
5644        let mut input = base_inputs(FakeLlm::new("noop"), rt, user("go"));
5645        input.tools = vec![echo_tool()];
5646        let seen: Arc<StdMutex<Option<adk_core::ToolOutcome>>> = Arc::new(StdMutex::new(None));
5647        let seen_cb = seen.clone();
5648        let cb: AfterToolCallback = Box::new(move |ctx| {
5649            let seen = seen_cb.clone();
5650            Box::pin(async move {
5651                *seen.lock().unwrap() = ctx.tool_outcome();
5652                Ok(None)
5653            })
5654        });
5655        input.after_tool_callbacks = Arc::new(vec![cb]);
5656        let events = collect(input).await;
5657        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5658        let outcome = seen.lock().unwrap().clone().expect("tool outcome available");
5659        assert_eq!(outcome.tool_name, "echo");
5660        assert!(outcome.success);
5661        assert_eq!(outcome.attempt, 0);
5662        assert!(outcome.error_message.is_none());
5663    }
5664
5665    #[tokio::test]
5666    async fn after_tool_callback_sees_failed_tool_outcome() {
5667        // Match LlmAgent: after-tool callbacks still run for failed tools and see
5668        // `success = false` with the final error message.
5669        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
5670            Planned::call("boom", json!({}), 1),
5671            Planned::Complete(json!({"type": "final_result", "value": "done"})),
5672        ]]));
5673        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
5674        input.tools = vec![failing_tool()];
5675        let seen: Arc<StdMutex<Option<adk_core::ToolOutcome>>> = Arc::new(StdMutex::new(None));
5676        let seen_cb = seen.clone();
5677        let cb: AfterToolCallback = Box::new(move |ctx| {
5678            let seen = seen_cb.clone();
5679            Box::pin(async move {
5680                *seen.lock().unwrap() = ctx.tool_outcome();
5681                Ok(None)
5682            })
5683        });
5684        input.after_tool_callbacks = Arc::new(vec![cb]);
5685        let events = collect(input).await;
5686        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("done"));
5687        assert!(rt.last_raise().unwrap().contains("not_found"));
5688        let outcome = seen.lock().unwrap().clone().expect("tool outcome available");
5689        assert_eq!(outcome.tool_name, "boom");
5690        assert!(!outcome.success);
5691        assert_eq!(outcome.attempt, 0);
5692        assert!(outcome.error_message.unwrap().contains("not_found"));
5693    }
5694
5695    // ----- action ledger -----
5696
5697    /// A `charge` tool that records the idempotency key of every execution. With a
5698    /// delay it records the key first, so a call that times out has taken effect.
5699    struct ChargeTool {
5700        effect: adk_core::ToolEffect,
5701        delay: Option<Duration>,
5702        keys: Arc<StdMutex<Vec<String>>>,
5703    }
5704
5705    fn charge_tool(
5706        effect: adk_core::ToolEffect,
5707        delay: Option<Duration>,
5708    ) -> (Arc<dyn Tool>, Arc<StdMutex<Vec<String>>>) {
5709        let keys = Arc::new(StdMutex::new(Vec::new()));
5710        (Arc::new(ChargeTool { effect, delay, keys: keys.clone() }), keys)
5711    }
5712
5713    #[async_trait]
5714    impl Tool for ChargeTool {
5715        fn name(&self) -> &str {
5716            "charge"
5717        }
5718        fn description(&self) -> &str {
5719            "charges a card"
5720        }
5721        fn effect(&self) -> adk_core::ToolEffect {
5722            self.effect
5723        }
5724        async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
5725            self.keys.lock().unwrap().push(ctx.idempotency_key());
5726            if let Some(delay) = self.delay {
5727                tokio::time::sleep(delay).await;
5728            }
5729            Ok(json!({ "charged": args["amount"] }))
5730        }
5731    }
5732
5733    /// An in-memory ledger that also records every key it begins.
5734    #[derive(Debug, Default)]
5735    struct RecordingLedger {
5736        inner: adk_core::InMemoryActionLedger,
5737        begun: StdMutex<Vec<String>>,
5738    }
5739
5740    #[async_trait]
5741    impl adk_core::ActionLedger for RecordingLedger {
5742        async fn begin(&self, record: &adk_core::ActionRecord) -> adk_core::Result<()> {
5743            self.begun.lock().unwrap().push(record.key.clone());
5744            self.inner.begin(record).await
5745        }
5746        async fn complete(
5747            &self,
5748            key: &str,
5749            outcome: adk_core::ActionOutcome,
5750        ) -> adk_core::Result<()> {
5751            self.inner.complete(key, outcome).await
5752        }
5753        async fn get(&self, key: &str) -> adk_core::Result<Option<adk_core::ActionRecord>> {
5754            self.inner.get(key).await
5755        }
5756    }
5757
5758    /// Loop inputs for one invocation `invocation` whose run config carries `ledger`.
5759    fn ledgered_inputs(
5760        runtime: Arc<dyn CodeRuntime>,
5761        tools: Vec<Arc<dyn Tool>>,
5762        ledger: Arc<RecordingLedger>,
5763        invocation: &str,
5764        decisions: HashMap<String, ToolConfirmationDecision>,
5765    ) -> LoopInputs {
5766        let incoming = user("pay");
5767        let mut input = base_inputs(FakeLlm::new("noop"), runtime, incoming.clone());
5768        input.invocation_ctx = Arc::new(
5769            MockInvocationContext::new(incoming)
5770                .with_invocation_id(invocation)
5771                .with_run_config(adk_core::RunConfig::builder().action_ledger(ledger).build())
5772                .with_confirmation_decisions(decisions),
5773        );
5774        input.tools = tools;
5775        input
5776    }
5777
5778    fn charge_program(call_ids: &[u64]) -> Vec<Planned> {
5779        call_ids
5780            .iter()
5781            .map(|id| Planned::call("charge", json!({"amount": 5}), *id))
5782            .chain(std::iter::once(Planned::Complete(
5783                json!({"type": "final_result", "value": "paid"}),
5784            )))
5785            .collect()
5786    }
5787
5788    fn checkpoints(events: &[Event]) -> Vec<CodeActCheckpoint> {
5789        events.iter().filter_map(pending_in).collect()
5790    }
5791
5792    #[tokio::test]
5793    async fn a_non_idempotent_call_executes_once_when_its_step_is_replayed() {
5794        let ledger = Arc::new(RecordingLedger::default());
5795        let (charge, executions) = charge_tool(adk_core::ToolEffect::NonIdempotent, None);
5796        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[0])]));
5797        let input =
5798            ledgered_inputs(runtime, vec![charge.clone()], ledger.clone(), "inv-1", HashMap::new());
5799        let events = collect(input).await;
5800        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("paid"));
5801        assert_eq!(executions.lock().unwrap().len(), 1);
5802
5803        // The process crashed after the charge but before SAVE-AFTER landed: a later
5804        // invocation recovers from the SAVE-BEFORE checkpoint.
5805        let save_before = checkpoints(&events)
5806            .into_iter()
5807            .find(|cp| cp.disposition == Disposition::PendingResult)
5808            .expect("a SAVE-BEFORE checkpoint");
5809        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![]));
5810        let mut input =
5811            ledgered_inputs(runtime.clone(), vec![charge], ledger.clone(), "inv-2", HashMap::new());
5812        input.pending = Some(save_before);
5813        let events = collect(input).await;
5814
5815        assert_eq!(executions.lock().unwrap().len(), 1, "the replayed call does not execute");
5816        let raised: Value = serde_json::from_str(&runtime.last_raise().unwrap()).unwrap();
5817        assert_eq!(raised["status"], "already_succeeded");
5818        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("paid"));
5819        assert_eq!(ledger.begun.lock().unwrap().len(), 1);
5820    }
5821
5822    #[tokio::test]
5823    async fn a_recorded_call_is_answered_from_the_ledger_without_executing() {
5824        use adk_core::ActionLedger as _;
5825        let ledger = Arc::new(RecordingLedger::default());
5826        let key = "app/user/sess-test/codeact/run-1/3/7";
5827        let record = adk_core::ActionRecord::new(
5828            key,
5829            "charge",
5830            &json!({"amount": 5}),
5831            adk_core::ToolEffect::NonIdempotent,
5832        );
5833        ledger.inner.begin(&record).await.unwrap();
5834        ledger
5835            .inner
5836            .complete(key, adk_core::ActionOutcome::Failed { error: "card declined".into() })
5837            .await
5838            .unwrap();
5839        let (charge, executions) = charge_tool(adk_core::ToolEffect::NonIdempotent, None);
5840        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![]));
5841        let mut input =
5842            ledgered_inputs(runtime.clone(), vec![charge], ledger.clone(), "inv-2", HashMap::new());
5843        input.pending = Some(CodeActCheckpoint {
5844            iteration: 3,
5845            transcript: vec![],
5846            snapshot: serde_json::to_vec(&vec![Planned::Complete(
5847                json!({"type": "final_result", "value": "recovered"}),
5848            )])
5849            .unwrap(),
5850            call: PendingToolCall { call_id: 7, tool: "charge".into(), args: json!({"amount": 5}) },
5851            disposition: Disposition::PendingResult,
5852            tool_roster: vec!["charge".to_string()],
5853            run_id: Some("run-1".to_string()),
5854        });
5855        collect(input).await;
5856
5857        assert!(executions.lock().unwrap().is_empty());
5858        let raised: Value = serde_json::from_str(&runtime.last_raise().unwrap()).unwrap();
5859        assert_eq!(
5860            raised,
5861            json!({
5862                "status": "already_failed",
5863                "error": "card declined",
5864                "detail": "this call to 'charge' already failed; it was not executed again",
5865            })
5866        );
5867        assert!(ledger.begun.lock().unwrap().is_empty());
5868    }
5869
5870    /// A freeze that arrives while the ledger records the call: the call never starts, and
5871    /// its begun record is completed with the not-run text.
5872    #[tokio::test]
5873    async fn a_freeze_during_the_ledger_write_keeps_the_call_from_starting() {
5874        #[derive(Debug)]
5875        struct FreezingLedger {
5876            inner: adk_core::InMemoryActionLedger,
5877            control: adk_core::GovernanceControl,
5878            begun: StdMutex<Vec<String>>,
5879        }
5880
5881        #[async_trait]
5882        impl adk_core::ActionLedger for FreezingLedger {
5883            async fn begin(&self, record: &adk_core::ActionRecord) -> adk_core::Result<()> {
5884                self.inner.begin(record).await?;
5885                self.begun.lock().unwrap().push(record.key.clone());
5886                self.control.freeze("incident 7");
5887                Ok(())
5888            }
5889            async fn complete(
5890                &self,
5891                key: &str,
5892                outcome: adk_core::ActionOutcome,
5893            ) -> adk_core::Result<()> {
5894                self.inner.complete(key, outcome).await
5895            }
5896            async fn get(&self, key: &str) -> adk_core::Result<Option<adk_core::ActionRecord>> {
5897                self.inner.get(key).await
5898            }
5899        }
5900
5901        use adk_core::ActionLedger as _;
5902        let control = adk_core::GovernanceControl::new();
5903        let ledger = Arc::new(FreezingLedger {
5904            inner: adk_core::InMemoryActionLedger::new(),
5905            control: control.clone(),
5906            begun: StdMutex::new(Vec::new()),
5907        });
5908        let (charge, executions) = charge_tool(adk_core::ToolEffect::NonIdempotent, None);
5909        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[0])]));
5910        let incoming = user("pay");
5911        let mut input = base_inputs(FakeLlm::new("noop"), runtime, incoming.clone());
5912        input.invocation_ctx = Arc::new(
5913            MockInvocationContext::new(incoming).with_invocation_id("inv-1").with_run_config(
5914                adk_core::RunConfig::builder()
5915                    .action_ledger(ledger.clone())
5916                    .governance(control)
5917                    .build(),
5918            ),
5919        );
5920        input.tools = vec![charge];
5921
5922        let mut stream = Box::pin(run_codeact(input));
5923        let mut ended = None;
5924        while let Some(item) = stream.next().await {
5925            if let Err(error) = item {
5926                ended = Some(error);
5927                break;
5928            }
5929        }
5930
5931        assert!(executions.lock().unwrap().is_empty(), "the tool never started");
5932        let error = ended.expect("the run stops at the freeze");
5933        assert_eq!(error.code, adk_core::GOVERNANCE_FROZEN_CODE);
5934        let key = ledger.begun.lock().unwrap().first().cloned().expect("the call was begun");
5935        let record = ledger.get(&key).await.unwrap().expect("a record");
5936        assert_eq!(
5937            record.outcome,
5938            Some(adk_core::ActionOutcome::Failed { error: adk_core::not_run_text(&error) })
5939        );
5940    }
5941
5942    #[tokio::test]
5943    async fn a_timed_out_non_idempotent_call_is_outcome_unknown_and_stays_begun() {
5944        use adk_core::ActionLedger as _;
5945        let ledger = Arc::new(RecordingLedger::default());
5946        let (charge, executions) =
5947            charge_tool(adk_core::ToolEffect::NonIdempotent, Some(Duration::from_secs(3600)));
5948        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[0])]));
5949        let mut input = ledgered_inputs(
5950            runtime.clone(),
5951            vec![charge.clone()],
5952            ledger.clone(),
5953            "inv-1",
5954            HashMap::new(),
5955        );
5956        input.tool_timeout = Duration::from_millis(20);
5957        // A retry budget never applies to a non-idempotent call.
5958        input.default_retry_budget = Some(RetryBudget::new(3, Duration::from_millis(1)));
5959        let events = collect(input).await;
5960
5961        assert_eq!(executions.lock().unwrap().len(), 1);
5962        let raised: Value = serde_json::from_str(&runtime.last_raise().unwrap()).unwrap();
5963        assert_eq!(
5964            raised,
5965            adk_core::outcome_unknown_response(
5966                "tool timed out after 20ms. The call may have taken effect; check its result before calling it again."
5967            )
5968        );
5969        let key = ledger.begun.lock().unwrap()[0].clone();
5970        let record = ledger.get(&key).await.unwrap().expect("a begun record");
5971        assert!(!record.is_completed(), "a timed-out call keeps its begun record");
5972
5973        // A replay of the step is answered as unknown without executing.
5974        let save_before = checkpoints(&events)
5975            .into_iter()
5976            .find(|cp| cp.disposition == Disposition::PendingResult)
5977            .unwrap();
5978        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![]));
5979        let mut input =
5980            ledgered_inputs(runtime.clone(), vec![charge], ledger.clone(), "inv-2", HashMap::new());
5981        input.pending = Some(save_before);
5982        collect(input).await;
5983        assert_eq!(executions.lock().unwrap().len(), 1);
5984        let raised: Value = serde_json::from_str(&runtime.last_raise().unwrap()).unwrap();
5985        assert!(adk_core::is_outcome_unknown(&raised), "{raised}");
5986    }
5987
5988    #[tokio::test]
5989    async fn a_timed_out_non_idempotent_call_is_outcome_unknown_without_a_ledger() {
5990        let (charge, _) =
5991            charge_tool(adk_core::ToolEffect::NonIdempotent, Some(Duration::from_secs(3600)));
5992        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[0])]));
5993        let mut input = base_inputs(FakeLlm::new("noop"), runtime.clone(), user("pay"));
5994        input.tools = vec![charge];
5995        input.tool_timeout = Duration::from_millis(20);
5996        collect(input).await;
5997        let raised: Value = serde_json::from_str(&runtime.last_raise().unwrap()).unwrap();
5998        assert!(adk_core::is_outcome_unknown(&raised), "{raised}");
5999    }
6000
6001    #[tokio::test]
6002    async fn identical_calls_in_one_program_and_across_programs_each_execute() {
6003        let ledger = Arc::new(RecordingLedger::default());
6004        let (charge, executions) = charge_tool(adk_core::ToolEffect::NonIdempotent, None);
6005        let mut first = charge_program(&[0, 1]);
6006        *first.last_mut().unwrap() = Planned::Complete(json!({"type": "observation", "value": 1}));
6007        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![first, charge_program(&[0])]));
6008        let input = ledgered_inputs(runtime, vec![charge], ledger.clone(), "inv-1", HashMap::new());
6009        let events = collect(input).await;
6010
6011        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("paid"));
6012        let keys = executions.lock().unwrap().clone();
6013        assert_eq!(keys.len(), 3, "every call executes: {keys:?}");
6014        let distinct: std::collections::HashSet<_> = keys.iter().collect();
6015        assert_eq!(distinct.len(), 3, "every call has its own key: {keys:?}");
6016        assert_eq!(*ledger.begun.lock().unwrap(), keys);
6017        let run_id = checkpoints(&events)[0].run_id.clone().unwrap();
6018        assert_eq!(
6019            keys,
6020            vec![
6021                format!("app/user/sess-test/codeact/{run_id}/1/0"),
6022                format!("app/user/sess-test/codeact/{run_id}/1/1"),
6023                format!("app/user/sess-test/codeact/{run_id}/2/0"),
6024            ]
6025        );
6026    }
6027
6028    #[tokio::test]
6029    async fn read_only_and_idempotent_calls_are_not_ledgered() {
6030        for effect in [adk_core::ToolEffect::ReadOnly, adk_core::ToolEffect::Idempotent] {
6031            let ledger = Arc::new(RecordingLedger::default());
6032            let (charge, executions) = charge_tool(effect, None);
6033            let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[0])]));
6034            let input =
6035                ledgered_inputs(runtime, vec![charge], ledger.clone(), "inv-1", HashMap::new());
6036            collect(input).await;
6037            assert_eq!(executions.lock().unwrap().len(), 1);
6038            assert!(ledger.begun.lock().unwrap().is_empty(), "{effect:?} is not ledgered");
6039        }
6040    }
6041
6042    #[tokio::test]
6043    async fn a_confirmed_call_executes_once_when_its_resume_is_replayed() {
6044        let ledger = Arc::new(RecordingLedger::default());
6045        let (charge, executions) = charge_tool(adk_core::ToolEffect::NonIdempotent, None);
6046        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[1])]));
6047        let mut input =
6048            ledgered_inputs(runtime, vec![charge.clone()], ledger.clone(), "inv-1", HashMap::new());
6049        input.policy = ToolConfirmationPolicy::Always;
6050        let events = collect(input).await;
6051        let held = checkpoints(&events).pop().expect("a held checkpoint");
6052        assert_eq!(held.disposition, Disposition::AwaitingConfirmation);
6053        assert!(executions.lock().unwrap().is_empty());
6054        assert!(ledger.begun.lock().unwrap().is_empty(), "a held call never begins");
6055
6056        let approve = HashMap::from([("1".to_string(), ToolConfirmationDecision::Approve)]);
6057        // The approved resume, then a replay of it after a crash before SAVE-AFTER landed.
6058        for invocation in ["inv-2", "inv-3"] {
6059            let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6060            let mut input = ledgered_inputs(
6061                runtime,
6062                vec![charge.clone()],
6063                ledger.clone(),
6064                invocation,
6065                approve.clone(),
6066            );
6067            input.policy = ToolConfirmationPolicy::Always;
6068            input.pending = Some(held.clone());
6069            let events = collect(input).await;
6070            assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("paid"));
6071        }
6072        assert_eq!(executions.lock().unwrap().len(), 1);
6073        assert_eq!(ledger.begun.lock().unwrap().len(), 1);
6074    }
6075
6076    /// Never answers, and counts how often it is asked.
6077    #[derive(Debug, Default)]
6078    struct NeverAnswers(std::sync::atomic::AtomicUsize);
6079
6080    #[async_trait]
6081    impl adk_core::ToolConfirmationHandler for NeverAnswers {
6082        async fn decide(
6083            &self,
6084            _request: &ToolConfirmationRequest,
6085        ) -> adk_core::Result<ToolConfirmationDecision> {
6086            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
6087            std::future::pending().await
6088        }
6089    }
6090
6091    /// The review of #1005: a freeze that lands while the handler decides ends the wait, and
6092    /// the run ends with the freeze before the tool starts, as `LlmAgent`'s call is refused.
6093    #[tokio::test]
6094    async fn a_freeze_ends_the_wait_for_the_confirmation_handler() {
6095        let control = adk_core::GovernanceControl::new();
6096        let handler = Arc::new(NeverAnswers::default());
6097        let (charge, executions) = charge_tool(adk_core::ToolEffect::NonIdempotent, None);
6098        let runtime = Arc::new(ScriptedRuntime::with_suspension(vec![charge_program(&[0])]));
6099        let incoming = user("pay");
6100        let mut input = base_inputs(FakeLlm::new("noop"), runtime, incoming.clone());
6101        input.invocation_ctx = Arc::new(
6102            MockInvocationContext::new(incoming).with_run_config(
6103                adk_core::RunConfig::builder()
6104                    .tool_confirmation_handler(handler.clone())
6105                    .governance(control.clone())
6106                    .build(),
6107            ),
6108        );
6109        input.tools = vec![charge];
6110        input.policy = ToolConfirmationPolicy::Always;
6111        tokio::spawn(async move {
6112            tokio::time::sleep(Duration::from_millis(50)).await;
6113            control.freeze("incident 4016");
6114        });
6115
6116        let ended = tokio::time::timeout(Duration::from_secs(5), async {
6117            let mut stream = Box::pin(run_codeact(input));
6118            while let Some(item) = stream.next().await {
6119                if let Err(error) = item {
6120                    return Some(error);
6121                }
6122            }
6123            None
6124        })
6125        .await
6126        .expect("the freeze ends the wait");
6127
6128        let error = ended.expect("the run ends with the freeze");
6129        assert_eq!(error.code, adk_core::GOVERNANCE_FROZEN_CODE);
6130        assert!(error.message.contains("incident 4016"), "{error}");
6131        assert_eq!(handler.0.load(std::sync::atomic::Ordering::SeqCst), 1, "it was asked");
6132        assert!(executions.lock().unwrap().is_empty(), "the tool never started");
6133    }
6134
6135    /// The checkpoint `event` writes to session state, as stored; `None` leaves state as it is.
6136    fn kept(event: &Event) -> Option<Value> {
6137        event.actions.state_delta.get(PENDING_STATE_KEY).cloned()
6138    }
6139
6140    /// Loop inputs for a run of `echo` under a handler that never answers within 20 ms and
6141    /// an approval store, so a call it is asked about waits in the store.
6142    fn waiting_inputs(
6143        model: Arc<dyn Llm>,
6144        runtime: Arc<dyn CodeRuntime>,
6145        incoming: Content,
6146        handler: Arc<NeverAnswers>,
6147        store: Arc<adk_core::InMemoryApprovalStore>,
6148    ) -> LoopInputs {
6149        let mut input = base_inputs(model, runtime, incoming.clone());
6150        input.tools = vec![echo_tool()];
6151        input.policy = ToolConfirmationPolicy::Always;
6152        input.invocation_ctx = Arc::new(
6153            MockInvocationContext::new(incoming).with_run_config(
6154                adk_core::RunConfig::builder()
6155                    .tool_confirmation_handler(handler)
6156                    .tool_confirmation_timeout(Duration::from_millis(20))
6157                    .approval_store(store)
6158                    .build(),
6159            ),
6160        );
6161        input
6162    }
6163
6164    /// Review finding 1 of #1044 (spec 3.3 §7.3, §7.4): a call that timed out waits in the
6165    /// store; later runs do not ask the handler about it again, a new message is answered
6166    /// while it waits, and a decision recorded for it resumes it once.
6167    #[tokio::test]
6168    async fn a_waiting_call_is_not_asked_again_and_a_new_message_is_answered() {
6169        use adk_core::ApprovalStore as _;
6170        let handler = Arc::new(NeverAnswers::default());
6171        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6172        let program = vec![
6173            Planned::call("echo", json!({"msg": "x"}), 7),
6174            Planned::Complete(json!({"type": "final_result", "value": "after"})),
6175        ];
6176        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![program]));
6177        let input =
6178            waiting_inputs(FakeLlm::new("noop"), rt, user("go"), handler.clone(), store.clone());
6179        let events = collect(input).await;
6180        let held = events.last().unwrap();
6181        let request = held.actions.tool_confirmation.clone().expect("the call waits");
6182        let cp = pending_in(held).expect("its checkpoint is kept");
6183        assert_eq!(handler.0.load(std::sync::atomic::Ordering::SeqCst), 1);
6184        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6185        assert_eq!(store.pending(&scope).await.unwrap().len(), 1, "it waits in the store");
6186
6187        // A new message: the model answers it, the handler is not asked, the call waits on.
6188        let model = FakeLlm::new("noop");
6189        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
6190            json!({"type": "final_result", "value": "hello"}),
6191        )]]));
6192        let mut input = waiting_inputs(
6193            model.clone(),
6194            rt.clone(),
6195            user("never mind, just say hello"),
6196            handler.clone(),
6197            store.clone(),
6198        );
6199        input.pending = Some(cp.clone());
6200        let events = collect(input).await;
6201        let last = events.last().unwrap();
6202        assert_eq!(final_text(last).as_deref(), Some("hello"));
6203        assert_eq!(kept(last), None, "the turn leaves the waiting call's checkpoint in state");
6204        assert_eq!(*model.calls.lock().unwrap(), 1);
6205        assert_eq!(rt.last_value(), None, "the waiting call has not run");
6206        assert_eq!(handler.0.load(std::sync::atomic::Ordering::SeqCst), 1, "not asked again");
6207
6208        // A run without a message keeps it waiting, unasked and without a model call.
6209        let model = FakeLlm::new("noop");
6210        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6211        let mut input =
6212            waiting_inputs(model.clone(), rt, Content::new("user"), handler.clone(), store.clone());
6213        input.pending = Some(cp.clone());
6214        let events = collect(input).await;
6215        let last = events.last().unwrap();
6216        assert_eq!(last.actions.tool_confirmation.as_ref(), Some(&request));
6217        assert_eq!(kept(last), Some(json!(cp)));
6218        assert_eq!(*model.calls.lock().unwrap(), 0);
6219        assert_eq!(handler.0.load(std::sync::atomic::Ordering::SeqCst), 1, "not asked again");
6220
6221        // A decision recorded for it resumes it once.
6222        store
6223            .decide(&scope, &request.fingerprint(), adk_core::ToolApproval::approve())
6224            .await
6225            .unwrap();
6226        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6227        let mut input = waiting_inputs(
6228            FakeLlm::new("noop"),
6229            rt.clone(),
6230            Content::new("user"),
6231            handler.clone(),
6232            store.clone(),
6233        );
6234        input.pending = Some(cp);
6235        let events = collect(input).await;
6236        assert_eq!(rt.last_value(), Some(json!({"msg": "x"})), "the approved call ran");
6237        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("after"));
6238        assert_eq!(handler.0.load(std::sync::atomic::Ordering::SeqCst), 1);
6239    }
6240
6241    /// The turn that answers a message while a call waits cannot wait for a second
6242    /// decision: a call it makes that needs one is not run, and is not left waiting.
6243    #[tokio::test]
6244    async fn a_turn_beside_a_waiting_call_does_not_leave_a_second_call_waiting() {
6245        use adk_core::ApprovalStore as _;
6246        let handler = Arc::new(NeverAnswers::default());
6247        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6248        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6249            Planned::call("echo", json!({"msg": "x"}), 7),
6250            Planned::Complete(json!({"type": "final_result", "value": "after"})),
6251        ]]));
6252        let input =
6253            waiting_inputs(FakeLlm::new("noop"), rt, user("go"), handler.clone(), store.clone());
6254        let cp = pending_in(collect(input).await.last().unwrap()).unwrap();
6255
6256        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6257            Planned::call("echo", json!({"msg": "y"}), 1),
6258            Planned::Complete(json!({"type": "final_result", "value": "later"})),
6259        ]]));
6260        let mut input = waiting_inputs(
6261            FakeLlm::new("noop"),
6262            rt.clone(),
6263            user("also echo y"),
6264            handler.clone(),
6265            store.clone(),
6266        );
6267        input.pending = Some(cp.clone());
6268        let events = collect(input).await;
6269        let raised = rt.last_raise().expect("the second call is refused in the script");
6270        assert!(raised.contains("already waiting"), "{raised}");
6271        assert_eq!(kept(events.last().unwrap()), None, "the waiting call keeps its checkpoint");
6272        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6273        let pending = store.pending(&scope).await.unwrap();
6274        assert_eq!(pending.len(), 1, "only the first call waits");
6275        assert_eq!(pending[0].request.args, json!({"msg": "x"}));
6276    }
6277
6278    /// Adds a default `cc` field to every call's arguments.
6279    #[cfg(feature = "enhanced-plugins")]
6280    struct AddsDefault;
6281    #[cfg(feature = "enhanced-plugins")]
6282    #[async_trait]
6283    impl EnhancedPlugin for AddsDefault {
6284        fn name(&self) -> &str {
6285            "adds-default"
6286        }
6287        async fn before_tool_call(
6288            &self,
6289            _tool: Arc<dyn Tool>,
6290            mut args: Value,
6291            _ctx: Arc<dyn CallbackContext>,
6292            _pctx: &adk_plugin::PluginContext,
6293        ) -> adk_core::Result<BeforeToolCallResult> {
6294            args["cc"] = json!([]);
6295            Ok(BeforeToolCallResult::Continue(args))
6296        }
6297    }
6298
6299    /// Wave 2 review findings 1, 2 and 7 (spec 3.3 §7.3): a plugin rewrote the call's
6300    /// arguments before it was held, so its decision is recorded under the rewritten ones.
6301    /// The waiting call is checked under those: an identical call in a turn beside it is the
6302    /// waiting call, and its decision resumes it.
6303    #[cfg(feature = "enhanced-plugins")]
6304    #[tokio::test]
6305    async fn a_waiting_call_whose_arguments_a_plugin_rewrote_resumes_on_its_decision() {
6306        use adk_core::ApprovalStore as _;
6307        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6308        let plugins = Some(Arc::new(EnhancedPluginManager::new(vec![
6309            Arc::new(AddsDefault) as Arc<dyn EnhancedPlugin>
6310        ])));
6311        let inputs = |rt: Arc<ScriptedRuntime>, incoming: Content, events: Vec<Event>| {
6312            let mut input = base_inputs(FakeLlm::new("noop"), rt, incoming.clone());
6313            input.tools = vec![echo_tool()];
6314            input.policy = ToolConfirmationPolicy::Always;
6315            input.enhanced_plugin_manager = plugins.clone();
6316            input.invocation_ctx = Arc::new(
6317                MockInvocationContext::new(incoming)
6318                    .with_run_config(
6319                        adk_core::RunConfig::builder().approval_store(store.clone()).build(),
6320                    )
6321                    .with_events(events),
6322            );
6323            input
6324        };
6325        let program = vec![
6326            Planned::call("echo", json!({"msg": "x"}), 7),
6327            Planned::Complete(json!({"type": "final_result", "value": "after"})),
6328        ];
6329        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![program]));
6330        let held = collect(inputs(rt, user("go"), vec![])).await.pop().unwrap();
6331        let request = held.actions.tool_confirmation.clone().expect("the call waits");
6332        assert_eq!(request.args, json!({"msg": "x", "cc": []}), "held as the plugin rewrote it");
6333        let cp = pending_in(&held).unwrap();
6334        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6335
6336        // An identical call in a turn beside it is the waiting call, which keeps waiting.
6337        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6338            Planned::call("echo", json!({"msg": "x"}), 1),
6339            Planned::Complete(json!({"type": "final_result", "value": "later"})),
6340        ]]));
6341        let mut input = inputs(rt.clone(), user("echo x again"), vec![held.clone()]);
6342        input.pending = Some(cp.clone());
6343        collect(input).await;
6344        let raised = rt.last_raise().expect("the identical call is refused in the script");
6345        assert!(raised.starts_with("this call to 'echo' is already waiting"), "{raised}");
6346        assert_eq!(store.pending(&scope).await.unwrap().len(), 1, "the call still waits");
6347
6348        // Its decision, recorded under the rewritten arguments, resumes it.
6349        store
6350            .decide(&scope, &request.fingerprint(), adk_core::ToolApproval::approve())
6351            .await
6352            .unwrap();
6353        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6354        let mut input = inputs(rt.clone(), Content::new("user"), vec![held]);
6355        input.pending = Some(cp);
6356        let events = collect(input).await;
6357        assert_eq!(rt.last_value(), Some(json!({"msg": "x", "cc": []})), "the approved call ran");
6358        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("after"));
6359    }
6360
6361    /// Approves every call at once.
6362    #[derive(Debug)]
6363    struct ApprovesAll;
6364
6365    #[async_trait]
6366    impl adk_core::ToolConfirmationHandler for ApprovesAll {
6367        async fn decide(
6368            &self,
6369            _request: &ToolConfirmationRequest,
6370        ) -> adk_core::Result<ToolConfirmationDecision> {
6371            Ok(ToolConfirmationDecision::Approve)
6372        }
6373    }
6374
6375    /// Wave 2 review finding 8 (spec 3.3 §7.3): a turn beside a waiting call that runs an
6376    /// identical call on the handler's approval answers the waiting call, so the call's
6377    /// checkpoint is cleared and no later run asks about it or runs it again.
6378    #[tokio::test]
6379    async fn a_turn_that_runs_the_waiting_call_answers_it() {
6380        use adk_core::ApprovalStore as _;
6381        let never = Arc::new(NeverAnswers::default());
6382        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6383        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6384            Planned::call("echo", json!({"msg": "x"}), 7),
6385            Planned::Complete(json!({"type": "final_result", "value": "after"})),
6386        ]]));
6387        let input = waiting_inputs(FakeLlm::new("noop"), rt, user("go"), never, store.clone());
6388        let mut session = collect(input).await;
6389        let cp = pending_in(session.last().unwrap()).unwrap();
6390
6391        let incoming = user("go ahead and echo it");
6392        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6393            Planned::call("echo", json!({"msg": "x"}), 1),
6394            Planned::Complete(json!({"type": "final_result", "value": "done"})),
6395        ]]));
6396        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), incoming.clone());
6397        input.tools = vec![echo_tool()];
6398        input.policy = ToolConfirmationPolicy::Always;
6399        input.invocation_ctx = Arc::new(
6400            MockInvocationContext::new(incoming).with_run_config(
6401                adk_core::RunConfig::builder()
6402                    .tool_confirmation_handler(Arc::new(ApprovesAll))
6403                    .approval_store(store.clone())
6404                    .build(),
6405            ),
6406        );
6407        input.pending = Some(cp);
6408        let events = collect(input).await;
6409        let last = events.last().unwrap();
6410        assert_eq!(final_text(last).as_deref(), Some("done"));
6411        assert_eq!(rt.last_value(), Some(json!({"msg": "x"})), "the identical call ran");
6412        assert_eq!(kept(last), Some(Value::Null), "the answered call's checkpoint is cleared");
6413        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6414        assert!(store.pending(&scope).await.unwrap().is_empty());
6415        // Wave 2 gate, core item a: the session holds the call no longer.
6416        // The waiting call never ran: the identical call ran in its place.
6417        let mut answered = Part::FunctionResponse {
6418            function_response: adk_core::FunctionResponseData::new(
6419                "echo",
6420                json!({
6421                    "status": "decided",
6422                    "detail": "an identical call in a later turn took this call's decision",
6423                }),
6424            ),
6425            id: Some("7".to_string()),
6426            annotations: None,
6427        };
6428        answered.set_tool_result_status(ToolResultStatus::NotRun, None);
6429        let answers: Vec<_> = events
6430            .iter()
6431            .flat_map(|event| event.llm_response.content.iter())
6432            .flat_map(|content| content.parts.iter())
6433            .filter(|part| matches!(part, Part::FunctionResponse { .. }))
6434            .cloned()
6435            .collect();
6436        assert_eq!(answers, vec![answered]);
6437        session.extend(events);
6438        assert!(adk_core::held_tool_calls(&session, "code-agent", "").is_empty());
6439    }
6440
6441    /// Wave 2 gate, core item a (spec 3.3 §7.3): a held call a decision resumes, approved or
6442    /// denied, is answered in the session as LlmAgent answers it, so nothing holds it
6443    /// afterwards and compaction may pass it.
6444    #[tokio::test]
6445    async fn a_decided_call_is_answered_and_no_longer_held() {
6446        use adk_core::ApprovalStore as _;
6447        for (approval, response) in [
6448            (adk_core::ToolApproval::approve(), json!({"msg": "x"})),
6449            (adk_core::ToolApproval::deny(), Value::Null),
6450        ] {
6451            let handler = Arc::new(NeverAnswers::default());
6452            let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6453            let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6454                Planned::call("echo", json!({"msg": "x"}), 7),
6455                Planned::Complete(json!({"type": "final_result", "value": "after"})),
6456            ]]));
6457            let input = waiting_inputs(
6458                FakeLlm::new("noop"),
6459                rt,
6460                user("go"),
6461                handler.clone(),
6462                store.clone(),
6463            );
6464            let mut session = collect(input).await;
6465            let held = session.last().unwrap().clone();
6466            let request = held.actions.tool_confirmation.clone().expect("the call waits");
6467            assert_eq!(adk_core::held_tool_calls(&session, "code-agent", "").len(), 1);
6468
6469            let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6470            store.decide(&scope, &request.fingerprint(), approval).await.unwrap();
6471            let rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6472            let mut input =
6473                waiting_inputs(FakeLlm::new("noop"), rt, Content::new("user"), handler, store);
6474            input.pending = pending_in(&held);
6475            let resumed = collect(input).await;
6476            assert_eq!(final_text(resumed.last().unwrap()).as_deref(), Some("after"));
6477            let answers: Vec<_> = resumed
6478                .iter()
6479                .flat_map(|event| event.llm_response.content.iter())
6480                .flat_map(|content| content.parts.iter())
6481                .filter_map(|part| match part {
6482                    Part::FunctionResponse { function_response, id, .. } => Some((
6483                        function_response.name.clone(),
6484                        id.clone(),
6485                        function_response.response.clone(),
6486                    )),
6487                    _ => None,
6488                })
6489                .collect();
6490            assert_eq!(answers.len(), 1, "{answers:?}");
6491            assert_eq!((answers[0].0.as_str(), answers[0].1.as_deref()), ("echo", Some("7")));
6492            if !response.is_null() {
6493                assert_eq!(answers[0].2, response);
6494            } else {
6495                assert!(answers[0].2.get("error").is_some(), "a denial answers with its error");
6496            }
6497            session.extend(resumed);
6498            assert!(adk_core::held_tool_calls(&session, "code-agent", "").is_empty());
6499            assert_eq!(
6500                adk_core::held_call_compaction_limit(&session, session.len()),
6501                session.len(),
6502                "compaction may pass the answered call"
6503            );
6504        }
6505    }
6506
6507    /// The answer to a held call carries the status of how its decision resolved it: none for
6508    /// the tool's own result, `refused` for a denial, `failed` for a tool that failed.
6509    #[tokio::test]
6510    async fn a_held_calls_answer_carries_the_status_of_its_resolution() {
6511        use adk_core::ApprovalStore as _;
6512        let echoed = Part::FunctionResponse {
6513            function_response: adk_core::FunctionResponseData::new("echo", json!({"msg": "x"})),
6514            id: Some("7".to_string()),
6515            annotations: None,
6516        };
6517        let mut denied = Part::FunctionResponse {
6518            function_response: adk_core::FunctionResponseData::new(
6519                "echo",
6520                json!({ "error": denied_message("echo") }),
6521            ),
6522            id: Some("7".to_string()),
6523            annotations: None,
6524        };
6525        denied.set_tool_result_status(ToolResultStatus::Refused, None);
6526        for (tool, approval, expected) in [
6527            ("echo", adk_core::ToolApproval::approve(), Some(echoed)),
6528            ("echo", adk_core::ToolApproval::deny(), Some(denied)),
6529            ("boom", adk_core::ToolApproval::approve(), None),
6530        ] {
6531            let handler = Arc::new(NeverAnswers::default());
6532            let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6533            let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6534                Planned::call(tool, json!({"msg": "x"}), 7),
6535                Planned::Complete(json!({"type": "final_result", "value": "after"})),
6536            ]]));
6537            let mut input = waiting_inputs(
6538                FakeLlm::new("noop"),
6539                rt,
6540                user("go"),
6541                handler.clone(),
6542                store.clone(),
6543            );
6544            input.tools.push(failing_tool());
6545            let held = collect(input).await.last().unwrap().clone();
6546            let request = held.actions.tool_confirmation.clone().expect("the call waits");
6547
6548            let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6549            store.decide(&scope, &request.fingerprint(), approval).await.unwrap();
6550            let rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6551            let mut input =
6552                waiting_inputs(FakeLlm::new("noop"), rt, Content::new("user"), handler, store);
6553            input.tools.push(failing_tool());
6554            input.pending = pending_in(&held);
6555            let answer = collect(input)
6556                .await
6557                .iter()
6558                .flat_map(|event| event.llm_response.content.iter())
6559                .flat_map(|content| content.parts.iter())
6560                .find(|part| matches!(part, Part::FunctionResponse { .. }))
6561                .cloned()
6562                .expect("the held call is answered");
6563            let expected = expected.unwrap_or_else(|| {
6564                // The failure's text is the tool's; its status is what this test is about.
6565                let Part::FunctionResponse { function_response, .. } = &answer else {
6566                    unreachable!()
6567                };
6568                let mut failed = Part::FunctionResponse {
6569                    function_response: function_response.clone(),
6570                    id: Some("7".to_string()),
6571                    annotations: None,
6572                };
6573                failed.set_tool_result_status(ToolResultStatus::Failed, None);
6574                failed
6575            });
6576            assert_eq!(answer, expected, "{tool}");
6577        }
6578    }
6579
6580    /// Wave 2 review finding 9 (spec 3.3 §7.4): a turn beside a waiting call that ends
6581    /// with a result completes, so the after-agent callbacks run for it.
6582    #[tokio::test]
6583    async fn after_agent_callbacks_run_for_a_turn_beside_a_waiting_call() {
6584        let handler = Arc::new(NeverAnswers::default());
6585        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6586        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6587            Planned::call("echo", json!({"msg": "x"}), 7),
6588            Planned::Complete(json!({"type": "final_result", "value": "after"})),
6589        ]]));
6590        let input =
6591            waiting_inputs(FakeLlm::new("noop"), rt, user("go"), handler.clone(), store.clone());
6592        let cp = pending_in(collect(input).await.last().unwrap()).unwrap();
6593
6594        let after: AfterAgentCallback = Box::new(|_ctx| {
6595            Box::pin(async { Ok(Some(Content::new("model").with_text("after-done"))) })
6596        });
6597        let agent = CodeActAgent::builder()
6598            .name("code-agent")
6599            .model(FakeLlm::new("noop"))
6600            .runtime(Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
6601                json!({"type": "final_result", "value": "hello"}),
6602            )]])))
6603            .tool(echo_tool())
6604            .require_tool_confirmation_for_all()
6605            .after_callback(after)
6606            .build()
6607            .unwrap();
6608        let ctx = MockInvocationContext::new(user("never mind, just say hello"))
6609            .with_state(HashMap::from([(PENDING_STATE_KEY.to_string(), json!(cp))]))
6610            .with_run_config(
6611                adk_core::RunConfig::builder()
6612                    .tool_confirmation_handler(handler.clone())
6613                    .tool_confirmation_timeout(Duration::from_millis(20))
6614                    .approval_store(store)
6615                    .build(),
6616            );
6617        let events = run_collect(&agent, Arc::new(ctx)).await;
6618        assert!(events.iter().any(|e| final_text(e).as_deref() == Some("hello")));
6619        assert!(events.iter().all(|e| kept(e).is_none()), "the waiting call keeps its checkpoint");
6620        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("after-done"));
6621        assert_eq!(handler.0.load(std::sync::atomic::Ordering::SeqCst), 1, "not asked again");
6622    }
6623
6624    /// Wave 2 review finding 10 (spec 3.3 §12): a run that resumes a decided call and brings
6625    /// a message gives the message to the model, also when the resumed script finishes first.
6626    #[tokio::test]
6627    async fn a_resumed_call_keeps_the_message_its_run_brought() {
6628        use adk_core::ApprovalStore as _;
6629        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6630        let inputs = |model: Arc<FakeLlm>, rt: Arc<ScriptedRuntime>, incoming: Content| {
6631            let mut input = base_inputs(model, rt, incoming.clone());
6632            input.tools = vec![echo_tool()];
6633            input.policy = ToolConfirmationPolicy::Always;
6634            input.invocation_ctx = Arc::new(MockInvocationContext::new(incoming).with_run_config(
6635                adk_core::RunConfig::builder().approval_store(store.clone()).build(),
6636            ));
6637            input
6638        };
6639        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6640            Planned::call("echo", json!({"msg": "x"}), 7),
6641            Planned::Complete(json!({"type": "final_result", "value": "sent"})),
6642        ]]));
6643        let held = collect(inputs(FakeLlm::new("noop"), rt, user("go"))).await.pop().unwrap();
6644        let request = held.actions.tool_confirmation.clone().expect("the call waits");
6645        let cp = pending_in(&held).unwrap();
6646        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6647        store
6648            .decide(&scope, &request.fingerprint(), adk_core::ToolApproval::approve())
6649            .await
6650            .unwrap();
6651
6652        let model = FakeLlm::new("noop");
6653        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
6654            json!({"type": "final_result", "value": "sent, and the receipt is on its way"}),
6655        )]]));
6656        let mut input = inputs(model.clone(), rt.clone(), user("and email me the receipt"));
6657        input.pending = Some(cp);
6658        let events = collect(input).await;
6659        assert_eq!(rt.last_value(), Some(json!({"msg": "x"})), "the approved call ran");
6660        assert_eq!(model.calls(), 1, "the model answers the message");
6661        let seen = model.seen.lock().unwrap().last().cloned().unwrap();
6662        let texts: Vec<&str> =
6663            seen.iter().flat_map(|c| c.parts.iter()).filter_map(|p| p.text()).collect();
6664        let message = texts.iter().position(|t| *t == "and email me the receipt");
6665        let result = texts.iter().position(|t| t.starts_with("Observation:") && t.contains("sent"));
6666        assert!(
6667            message.is_some() && result.is_some(),
6668            "the message and the resumed result are in view: {texts:?}"
6669        );
6670        assert_eq!(
6671            final_text(events.last().unwrap()).as_deref(),
6672            Some("sent, and the receipt is on its way")
6673        );
6674    }
6675
6676    /// Wave 2 review finding 10 (spec 3.3 §12): a message brought by a run whose resumed
6677    /// script stops at a second call that needs a decision stays in the checkpoint, so the
6678    /// run that resumes the second call gives it to the model.
6679    #[tokio::test]
6680    async fn a_message_survives_a_second_held_call() {
6681        use adk_core::ApprovalStore as _;
6682        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6683        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6684        let inputs = |model: Arc<FakeLlm>, rt: Arc<ScriptedRuntime>, incoming: Content| {
6685            let mut input = base_inputs(model, rt, incoming.clone());
6686            input.tools = vec![echo_tool()];
6687            input.policy = ToolConfirmationPolicy::Always;
6688            input.invocation_ctx = Arc::new(MockInvocationContext::new(incoming).with_run_config(
6689                adk_core::RunConfig::builder().approval_store(store.clone()).build(),
6690            ));
6691            input
6692        };
6693        let approve = |event: &Event| {
6694            let fingerprint = event.actions.tool_confirmation.as_ref().unwrap().fingerprint();
6695            let store = store.clone();
6696            let scope = scope.clone();
6697            async move {
6698                store.decide(&scope, &fingerprint, adk_core::ToolApproval::approve()).await.unwrap()
6699            }
6700        };
6701        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![
6702            Planned::call("echo", json!({"msg": "x"}), 7),
6703            Planned::call("echo", json!({"msg": "y"}), 8),
6704            Planned::Complete(json!({"type": "final_result", "value": "sent"})),
6705        ]]));
6706        let first = collect(inputs(FakeLlm::new("noop"), rt, user("go"))).await.pop().unwrap();
6707        approve(&first).await;
6708
6709        let model = FakeLlm::new("noop");
6710        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![]));
6711        let mut input = inputs(model.clone(), rt.clone(), user("and email me the receipt"));
6712        input.pending = pending_in(&first);
6713        let second = collect(input).await.pop().unwrap();
6714        assert_eq!(rt.last_value(), Some(json!({"msg": "x"})), "the first call ran");
6715        assert_eq!(model.calls(), 0, "the script stopped at the second call");
6716        approve(&second).await;
6717
6718        let rt = Arc::new(ScriptedRuntime::with_suspension(vec![vec![Planned::Complete(
6719            json!({"type": "final_result", "value": "sent, and the receipt is on its way"}),
6720        )]]));
6721        let mut input = inputs(model.clone(), rt.clone(), Content::new("user"));
6722        input.pending = pending_in(&second);
6723        let events = collect(input).await;
6724        assert_eq!(rt.last_value(), Some(json!({"msg": "y"})), "the second call ran");
6725        assert_eq!(model.calls(), 1, "the model answers the message");
6726        let seen = model.seen.lock().unwrap().last().cloned().unwrap();
6727        let texts: Vec<&str> =
6728            seen.iter().flat_map(|c| c.parts.iter()).filter_map(|p| p.text()).collect();
6729        assert_eq!(
6730            texts.iter().filter(|t| **t == "and email me the receipt").count(),
6731            1,
6732            "the message is in view once: {texts:?}"
6733        );
6734        assert_eq!(
6735            final_text(events.last().unwrap()).as_deref(),
6736            Some("sent, and the receipt is on its way")
6737        );
6738    }
6739
6740    /// Wave 2 review finding 11 (spec 3.3 §7.3): on a runtime that cannot pause, a call that
6741    /// needs a decision is refused into the script and leaves nothing waiting that a later
6742    /// decision could use to authorize an identical call.
6743    #[tokio::test]
6744    async fn a_runtime_that_cannot_pause_leaves_no_call_waiting() {
6745        use adk_core::ApprovalStore as _;
6746        let store = Arc::new(adk_core::InMemoryApprovalStore::new());
6747        let rt = Arc::new(ScriptedRuntime::new(vec![vec![
6748            Planned::call("echo", json!({"msg": "x"}), 1),
6749            Planned::Complete(json!({"type": "final_result", "value": "could not"})),
6750        ]]));
6751        let mut input = base_inputs(FakeLlm::new("noop"), rt.clone(), user("go"));
6752        input.tools = vec![echo_tool()];
6753        input.policy = ToolConfirmationPolicy::Always;
6754        input.supports_suspension = false;
6755        input.invocation_ctx =
6756            Arc::new(MockInvocationContext::new(user("go")).with_run_config(
6757                adk_core::RunConfig::builder().approval_store(store.clone()).build(),
6758            ));
6759        let events = collect(input).await;
6760        assert_eq!(final_text(events.last().unwrap()).as_deref(), Some("could not"));
6761        let raised = rt.last_raise().expect("the call is refused in the script");
6762        assert!(raised.contains("cannot pause"), "{raised}");
6763        let scope = adk_core::ApprovalScope::new("app", "user", "sess-test");
6764        assert!(store.pending(&scope).await.unwrap().is_empty(), "nothing waits");
6765    }
6766}