Skip to main content

adk_core/
context.rs

1use crate::identity::{AdkIdentity, AppName, ExecutionIdentity, InvocationId, SessionId, UserId};
2use crate::{AdkError, Agent, Result, ToolApproval, Toolset, types::Content};
3use async_trait::async_trait;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use std::collections::{BTreeSet, HashMap};
7use std::sync::Arc;
8
9/// Policy for handling excess tool calls when the concurrency limit is reached.
10///
11/// Determines whether tool calls that exceed the configured concurrency limit
12/// should wait in a queue or fail immediately.
13///
14/// # Example
15///
16/// ```rust
17/// use adk_core::BackpressurePolicy;
18///
19/// // Default is Queue
20/// let policy = BackpressurePolicy::default();
21/// assert!(matches!(policy, BackpressurePolicy::Queue));
22/// ```
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
24pub enum BackpressurePolicy {
25    /// Queue excess calls until a permit becomes available.
26    ///
27    /// This is the default policy. Tool calls will await until a semaphore
28    /// permit is released by a completing tool execution.
29    #[default]
30    Queue,
31
32    /// Fail immediately with a concurrency limit error when no permit is available.
33    ///
34    /// Use this when latency is more important than throughput — callers receive
35    /// an immediate error rather than waiting indefinitely.
36    Fail,
37}
38
39/// Configuration for tool execution concurrency.
40///
41/// Controls how many tool calls can execute simultaneously, with support for
42/// global limits, per-tool overrides, and configurable backpressure behavior.
43///
44/// # Example
45///
46/// ```rust
47/// use adk_core::{BackpressurePolicy, ToolConcurrencyConfig};
48/// use std::collections::HashMap;
49///
50/// let config = ToolConcurrencyConfig {
51///     max_concurrency: Some(10),
52///     per_tool: HashMap::from([
53///         ("web_scraper".to_string(), 2),
54///         ("calculator".to_string(), 8),
55///     ]),
56///     backpressure: BackpressurePolicy::Fail,
57/// };
58///
59/// assert_eq!(config.max_concurrency, Some(10));
60/// assert_eq!(config.per_tool.get("web_scraper"), Some(&2));
61/// ```
62#[derive(Debug, Clone, Default)]
63pub struct ToolConcurrencyConfig {
64    /// Global maximum concurrent tool calls. `None` means unlimited.
65    pub max_concurrency: Option<usize>,
66
67    /// Per-tool concurrency overrides. When a tool name is present in this map,
68    /// its individual limit takes precedence over the global `max_concurrency`.
69    pub per_tool: HashMap<String, usize>,
70
71    /// What to do when the concurrency limit is reached.
72    pub backpressure: BackpressurePolicy,
73}
74
75/// Read-only access to invocation metadata.
76///
77/// Provides identity information (user, app, session, invocation) and the
78/// current user content. Implemented by all context types.
79#[async_trait]
80pub trait ReadonlyContext: Send + Sync {
81    /// Returns the current invocation identifier.
82    fn invocation_id(&self) -> &str;
83    /// Returns the name of the currently executing agent.
84    fn agent_name(&self) -> &str;
85    /// Returns the user identifier for this session.
86    fn user_id(&self) -> &str;
87    /// Returns the application name for this session.
88    fn app_name(&self) -> &str;
89    /// Returns the session identifier.
90    fn session_id(&self) -> &str;
91    /// Returns the current conversation branch.
92    fn branch(&self) -> &str;
93    /// Returns the user's input content for this invocation.
94    fn user_content(&self) -> &Content;
95
96    /// Returns who the running agent is and on whose behalf it acts.
97    ///
98    /// The runtime's contexts answer from the run's [`RunConfig::acting`] for the agent
99    /// that is executing, and wrapper contexts must forward this to the context they
100    /// wrap. The default is the identity ADK-Rust derives when none is configured:
101    /// [`ActingContext::derived`](crate::ActingContext::derived) from the app name, the
102    /// agent name, and the user as a human. The invocation the agent acts in is
103    /// [`invocation_id`](Self::invocation_id).
104    fn acting_context(&self) -> crate::ActingContext {
105        crate::ActingContext::derived(
106            self.app_name(),
107            self.agent_name(),
108            self.user_id(),
109            crate::SubjectKind::Human,
110        )
111    }
112
113    /// Returns whether [`user_id`](Self::user_id) comes from an authenticated
114    /// [`RequestContext`](crate::RequestContext) rather than from the caller's request body.
115    ///
116    /// The runner's invocation context answers `true` when the run carries a
117    /// `RequestContext`, which `adk-server` sets only from a request its
118    /// `RequestContextExtractor` authenticated. A wrapper context should forward it to the
119    /// context it wraps. The default is `false`, so a context that cannot tell treats the
120    /// identity as unauthenticated. Implements spec 3.1 §10 F5.
121    ///
122    /// # Example
123    ///
124    /// ```rust
125    /// use adk_core::ReadonlyContext;
126    ///
127    /// /// Standing approvals apply only to a user the server authenticated.
128    /// fn standing_rules_apply(ctx: &dyn ReadonlyContext) -> bool {
129    ///     ctx.is_authenticated()
130    /// }
131    /// ```
132    fn is_authenticated(&self) -> bool {
133        false
134    }
135
136    /// Returns the session state when the runtime exposes it to dynamic toolsets.
137    ///
138    /// The default keeps lightweight contexts and third-party implementations
139    /// source-compatible. Consumers must gracefully handle contexts without
140    /// session state. Dynamic [`Toolset`] implementations use
141    /// this to determine their context-specific tool surface without requiring
142    /// mutable access to the session.
143    fn state(&self) -> Option<&dyn State> {
144        None
145    }
146
147    /// Returns the application name as a typed [`AppName`].
148    ///
149    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
150    /// error if the raw string fails validation (empty, null bytes, or exceeds
151    /// the maximum length).
152    ///
153    /// # Errors
154    ///
155    /// Returns an error when the
156    /// underlying string is not a valid identifier.
157    fn try_app_name(&self) -> Result<AppName> {
158        Ok(AppName::try_from(self.app_name())?)
159    }
160
161    /// Returns the user identifier as a typed [`UserId`].
162    ///
163    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
164    /// error if the raw string fails validation.
165    ///
166    /// # Errors
167    ///
168    /// Returns an error when the
169    /// underlying string is not a valid identifier.
170    fn try_user_id(&self) -> Result<UserId> {
171        Ok(UserId::try_from(self.user_id())?)
172    }
173
174    /// Returns the session identifier as a typed [`SessionId`].
175    ///
176    /// Parses the value returned by [`session_id()`](Self::session_id).
177    /// Returns an error if the raw string fails validation.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error when the
182    /// underlying string is not a valid identifier.
183    fn try_session_id(&self) -> Result<SessionId> {
184        Ok(SessionId::try_from(self.session_id())?)
185    }
186
187    /// Returns the invocation identifier as a typed [`InvocationId`].
188    ///
189    /// Parses the value returned by [`invocation_id()`](Self::invocation_id).
190    /// Returns an error if the raw string fails validation.
191    ///
192    /// # Errors
193    ///
194    /// Returns an error when the
195    /// underlying string is not a valid identifier.
196    fn try_invocation_id(&self) -> Result<InvocationId> {
197        Ok(InvocationId::try_from(self.invocation_id())?)
198    }
199
200    /// Returns the stable session-scoped [`AdkIdentity`] triple.
201    ///
202    /// Combines [`try_app_name()`](Self::try_app_name),
203    /// [`try_user_id()`](Self::try_user_id), and
204    /// [`try_session_id()`](Self::try_session_id) into a single composite
205    /// identity value.
206    ///
207    /// # Errors
208    ///
209    /// Returns an error if any of the three constituent identifiers fail
210    /// validation.
211    fn try_identity(&self) -> Result<AdkIdentity> {
212        Ok(AdkIdentity {
213            app_name: self.try_app_name()?,
214            user_id: self.try_user_id()?,
215            session_id: self.try_session_id()?,
216        })
217    }
218
219    /// Returns the full per-invocation [`ExecutionIdentity`].
220    ///
221    /// Combines [`try_identity()`](Self::try_identity) with the invocation,
222    /// branch, and agent name from this context.
223    ///
224    /// # Errors
225    ///
226    /// Returns an error if any of the four typed identifiers fail validation.
227    fn try_execution_identity(&self) -> Result<ExecutionIdentity> {
228        Ok(ExecutionIdentity {
229            adk: self.try_identity()?,
230            invocation_id: self.try_invocation_id()?,
231            branch: self.branch().to_string(),
232            agent_name: self.agent_name().to_string(),
233        })
234    }
235}
236
237// State management traits
238
239/// Maximum allowed length for state keys (256 bytes).
240pub const MAX_STATE_KEY_LEN: usize = 256;
241
242/// Validates a state key. Returns `Ok(())` if the key is safe, or an error message.
243///
244/// Rules:
245/// - Must not be empty
246/// - Must not exceed [`MAX_STATE_KEY_LEN`] bytes
247/// - Must not contain path separators (`/`, `\`) or `..`
248/// - Must not contain null bytes
249pub fn validate_state_key(key: &str) -> std::result::Result<(), &'static str> {
250    if key.is_empty() {
251        return Err("state key must not be empty");
252    }
253    if key.len() > MAX_STATE_KEY_LEN {
254        return Err("state key exceeds maximum length of 256 bytes");
255    }
256    if key.contains('/') || key.contains('\\') || key.contains("..") {
257        return Err("state key must not contain path separators or '..'");
258    }
259    if key.contains('\0') {
260        return Err("state key must not contain null bytes");
261    }
262    Ok(())
263}
264
265/// Mutable session state with key-value storage.
266///
267/// Implementations persist state across turns within a session.
268pub trait State: Send + Sync {
269    /// Returns the value for the given key, or `None` if not present.
270    fn get(&self, key: &str) -> Option<Value>;
271    /// Set a state value. Implementations should call [`validate_state_key`] and
272    /// reject invalid keys (e.g., by logging a warning or panicking).
273    fn set(&mut self, key: String, value: Value);
274    /// Returns all key-value pairs in the state.
275    fn all(&self) -> HashMap<String, Value>;
276}
277
278/// Read-only view of session state.
279pub trait ReadonlyState: Send + Sync {
280    /// Returns the value for the given key, or `None` if not present.
281    fn get(&self, key: &str) -> Option<Value>;
282    /// Returns all key-value pairs in the state.
283    fn all(&self) -> HashMap<String, Value>;
284}
285
286// Session trait
287/// Represents an active conversation session with identity and state.
288pub trait Session: Send + Sync {
289    /// Returns the session identifier.
290    fn id(&self) -> &str;
291    /// Returns the application name this session belongs to.
292    fn app_name(&self) -> &str;
293    /// Returns the user identifier for this session.
294    fn user_id(&self) -> &str;
295    /// Returns the mutable state associated with this session.
296    fn state(&self) -> &dyn State;
297    /// Returns the conversation history from this session as Content items
298    fn conversation_history(&self) -> Vec<Content>;
299    /// Returns conversation history filtered for a specific agent.
300    ///
301    /// When provided, events authored by other agents (not "user", not the
302    /// named agent, and not function/tool responses) are excluded. This
303    /// prevents a transferred sub-agent from seeing the parent's tool calls
304    /// mapped as "model" role, which would cause the LLM to think work is
305    /// already done.
306    ///
307    /// Default implementation delegates to [`conversation_history`](Self::conversation_history).
308    fn conversation_history_for_agent(&self, _agent_name: &str) -> Vec<Content> {
309        self.conversation_history()
310    }
311    /// Returns conversation history scoped to an agent and a conversation branch.
312    ///
313    /// `branch` is the invocation branch of the agent asking for history. An
314    /// event is visible when its branch equals that branch or is an *ancestor*
315    /// of it, so a sub-agent sees the conversation that led to it but not what
316    /// its siblings produced. `ParallelAgent` relies on this to keep concurrent
317    /// branches from contaminating each other's context, mirroring ADK Python's
318    /// `_is_event_belongs_to_branch` and ADK Go's `eventBelongsToBranch`.
319    ///
320    /// An empty `branch` on either side means "unscoped" and matches everything,
321    /// so implementations that never set [`crate::Event::branch`] are unaffected.
322    ///
323    /// Default implementation ignores `branch` and preserves the agent-name
324    /// filtering behaviour, so existing [`Session`] implementations keep working.
325    fn conversation_history_scoped(&self, agent_name: Option<&str>, _branch: &str) -> Vec<Content> {
326        match agent_name {
327            Some(name) => self.conversation_history_for_agent(name),
328            None => self.conversation_history(),
329        }
330    }
331    /// Returns the history `agent_name` sends its model on `branch`.
332    ///
333    /// The agent's own events and the user's keep their turns. What another agent said,
334    /// called and got back becomes user-role context
335    /// ([`other_agent_context`](crate::history::other_agent_context)), so a workflow
336    /// sub-agent never replays an earlier agent's turns as its own, and a request that would
337    /// end on another agent's answer ends on a user turn. A system notice
338    /// ([`system_notice_event`](crate::history::system_notice_event)) keeps its user-role
339    /// turn. Branch scoping is that of
340    /// [`conversation_history_scoped`](Self::conversation_history_scoped).
341    ///
342    /// The default cannot tell authors apart and returns
343    /// `conversation_history_scoped(None, branch)`. Implementations backed by an event log
344    /// override it.
345    fn conversation_history_with_context(&self, _agent_name: &str, branch: &str) -> Vec<Content> {
346        self.conversation_history_scoped(None, branch)
347    }
348    /// Whether this session's history already holds every event of the current invocation
349    /// once the agent that produced it has yielded it.
350    ///
351    /// The runner's session records each event before it asks the agent for the next one, so
352    /// a workflow agent reads its sub-agents' history from it instead of tracking their
353    /// events itself. The default is `false`.
354    fn records_invocation_events(&self) -> bool {
355        false
356    }
357    /// Returns the tool calls `agent_name` holds for confirmation on `branch`.
358    ///
359    /// An agent resumes these at the start of a run once a decision exists for them.
360    /// Implementations backed by an event log return
361    /// [`held_tool_calls`](crate::held_tool_calls) over it. The default returns none,
362    /// so a session without an event log never resumes a held call.
363    fn held_tool_calls(&self, _agent_name: &str, _branch: &str) -> Vec<crate::HeldToolCall> {
364        Vec::new()
365    }
366    /// Returns where the workflow agent `workflow` on `branch` resumes: the positions it
367    /// recorded on the holds that stopped its last run, while those calls are still held.
368    ///
369    /// Implementations backed by an event log return
370    /// [`workflow_resume_positions`](crate::workflow_resume_positions) over it. The default
371    /// returns none, so a workflow over a session without an event log starts over.
372    fn workflow_resume_positions(
373        &self,
374        _workflow: &str,
375        _branch: &str,
376    ) -> Vec<crate::WorkflowPosition> {
377        Vec::new()
378    }
379    /// Append content to conversation history (for sequential agent support)
380    fn append_to_history(&self, _content: Content) {
381        // Default no-op - implementations can override to track history
382    }
383
384    /// Returns the application name as a typed [`AppName`].
385    ///
386    /// Parses the value returned by [`app_name()`](Self::app_name). Returns an
387    /// error if the raw string fails validation (empty, null bytes, or exceeds
388    /// the maximum length).
389    ///
390    /// # Errors
391    ///
392    /// Returns an error when the
393    /// underlying string is not a valid identifier.
394    fn try_app_name(&self) -> Result<AppName> {
395        Ok(AppName::try_from(self.app_name())?)
396    }
397
398    /// Returns the user identifier as a typed [`UserId`].
399    ///
400    /// Parses the value returned by [`user_id()`](Self::user_id). Returns an
401    /// error if the raw string fails validation.
402    ///
403    /// # Errors
404    ///
405    /// Returns an error when the
406    /// underlying string is not a valid identifier.
407    fn try_user_id(&self) -> Result<UserId> {
408        Ok(UserId::try_from(self.user_id())?)
409    }
410
411    /// Returns the session identifier as a typed [`SessionId`].
412    ///
413    /// Parses the value returned by [`id()`](Self::id). Returns an error if
414    /// the raw string fails validation.
415    ///
416    /// # Errors
417    ///
418    /// Returns an error when the
419    /// underlying string is not a valid identifier.
420    fn try_session_id(&self) -> Result<SessionId> {
421        Ok(SessionId::try_from(self.id())?)
422    }
423
424    /// Returns the stable session-scoped [`AdkIdentity`] triple.
425    ///
426    /// Combines [`try_app_name()`](Self::try_app_name),
427    /// [`try_user_id()`](Self::try_user_id), and
428    /// [`try_session_id()`](Self::try_session_id) into a single composite
429    /// identity value.
430    ///
431    /// # Errors
432    ///
433    /// Returns an error if any of the three constituent identifiers fail
434    /// validation.
435    fn try_identity(&self) -> Result<AdkIdentity> {
436        Ok(AdkIdentity {
437            app_name: self.try_app_name()?,
438            user_id: self.try_user_id()?,
439            session_id: self.try_session_id()?,
440        })
441    }
442}
443
444/// Structured metadata about a completed tool execution.
445///
446/// Available via [`CallbackContext::tool_outcome()`] in after-tool callbacks,
447/// plugins, and telemetry hooks. Provides structured access to execution
448/// results without requiring JSON error parsing.
449///
450/// # Fields
451///
452/// - `tool_name` — Name of the tool that was executed.
453/// - `tool_args` — Arguments passed to the tool as a JSON value.
454/// - `success` — Whether the tool execution succeeded. Derived from the
455///   Rust `Result` / timeout path, never from JSON content inspection.
456/// - `duration` — Wall-clock duration of the tool execution.
457/// - `error_message` — Error message if the tool failed; `None` on success.
458/// - `error` — The structured error if the tool failed; `None` on success.
459/// - `attempt` — Retry attempt number (0 = first attempt, 1 = first retry, etc.).
460///   Always 0 when retries are not configured.
461#[derive(Debug, Clone)]
462pub struct ToolOutcome {
463    /// Name of the tool that was executed.
464    pub tool_name: String,
465    /// Arguments passed to the tool (JSON value).
466    pub tool_args: serde_json::Value,
467    /// Whether the tool execution succeeded.
468    pub success: bool,
469    /// Wall-clock duration of the tool execution.
470    pub duration: std::time::Duration,
471    /// Error message if the tool failed. `None` on success.
472    ///
473    /// This is the full message, which the model does not see by default; see
474    /// [`tool_error_response`](crate::tool_error_response).
475    pub error_message: Option<String>,
476    /// The structured error if the tool failed. `None` on success.
477    ///
478    /// A timeout is an [`ErrorCategory::Timeout`](crate::ErrorCategory::Timeout) error with code
479    /// `tool.timeout`, and a panic an internal error with code `tool.panicked`.
480    pub error: Option<Arc<crate::AdkError>>,
481    /// Retry attempt number (0 = first attempt, 1 = first retry, etc.).
482    /// Always 0 when retries are not configured.
483    pub attempt: u32,
484}
485
486/// Context available to agent lifecycle callbacks.
487///
488/// Extends [`ReadonlyContext`] with access to artifacts and tool execution metadata.
489#[async_trait]
490pub trait CallbackContext: ReadonlyContext {
491    /// Returns the artifact store, if one is configured.
492    fn artifacts(&self) -> Option<Arc<dyn Artifacts>>;
493
494    /// Returns structured metadata about the most recent tool execution.
495    /// Available in after-tool callbacks and plugin hooks.
496    /// Returns `None` when not in a tool execution context.
497    fn tool_outcome(&self) -> Option<ToolOutcome> {
498        None // default for backward compatibility
499    }
500
501    /// Returns the name of the tool about to be executed.
502    /// Available in before-tool and after-tool callback contexts.
503    fn tool_name(&self) -> Option<&str> {
504        None
505    }
506
507    /// Returns the input arguments for the tool about to be executed.
508    /// Available in before-tool and after-tool callback contexts.
509    fn tool_input(&self) -> Option<&serde_json::Value> {
510        None
511    }
512
513    /// Returns the shared state for parallel agent coordination.
514    /// Returns `None` when not running inside a `ParallelAgent` with shared state enabled.
515    fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
516        None
517    }
518}
519
520/// Wraps a [`CallbackContext`] to inject tool name and input for before-tool
521/// and after-tool callbacks.
522///
523/// Used by the agent runtime to provide tool context to `BeforeToolCallback`
524/// and `AfterToolCallback` invocations.
525///
526/// # Example
527///
528/// ```rust,ignore
529/// let tool_ctx = Arc::new(ToolCallbackContext::new(
530///     ctx.clone(),
531///     "search".to_string(),
532///     serde_json::json!({"query": "hello"}),
533/// ));
534/// callback(tool_ctx as Arc<dyn CallbackContext>).await;
535/// ```
536pub struct ToolCallbackContext {
537    /// The inner callback context to delegate to.
538    pub inner: Arc<dyn CallbackContext>,
539    /// The name of the tool being executed.
540    pub tool_name: String,
541    /// The input arguments for the tool being executed.
542    pub tool_input: serde_json::Value,
543}
544
545impl ToolCallbackContext {
546    /// Creates a new `ToolCallbackContext` wrapping the given inner context.
547    pub fn new(
548        inner: Arc<dyn CallbackContext>,
549        tool_name: String,
550        tool_input: serde_json::Value,
551    ) -> Self {
552        Self { inner, tool_name, tool_input }
553    }
554}
555
556#[async_trait]
557impl ReadonlyContext for ToolCallbackContext {
558    fn invocation_id(&self) -> &str {
559        self.inner.invocation_id()
560    }
561
562    fn agent_name(&self) -> &str {
563        self.inner.agent_name()
564    }
565
566    fn user_id(&self) -> &str {
567        self.inner.user_id()
568    }
569
570    fn app_name(&self) -> &str {
571        self.inner.app_name()
572    }
573
574    fn session_id(&self) -> &str {
575        self.inner.session_id()
576    }
577
578    fn branch(&self) -> &str {
579        self.inner.branch()
580    }
581
582    fn user_content(&self) -> &Content {
583        self.inner.user_content()
584    }
585
586    fn acting_context(&self) -> crate::ActingContext {
587        self.inner.acting_context()
588    }
589
590    fn is_authenticated(&self) -> bool {
591        self.inner.is_authenticated()
592    }
593}
594
595#[async_trait]
596impl CallbackContext for ToolCallbackContext {
597    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
598        self.inner.artifacts()
599    }
600
601    fn tool_outcome(&self) -> Option<ToolOutcome> {
602        self.inner.tool_outcome()
603    }
604
605    fn tool_name(&self) -> Option<&str> {
606        Some(&self.tool_name)
607    }
608
609    fn tool_input(&self) -> Option<&serde_json::Value> {
610        Some(&self.tool_input)
611    }
612
613    fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
614        self.inner.shared_state()
615    }
616}
617
618/// Full invocation context available to agents during execution.
619///
620/// Extends [`CallbackContext`] with access to the agent itself, memory,
621/// session, and run configuration.
622#[async_trait]
623pub trait InvocationContext: CallbackContext {
624    /// Returns the agent being executed.
625    fn agent(&self) -> Arc<dyn Agent>;
626    /// Returns the memory service, if one is configured.
627    fn memory(&self) -> Option<Arc<dyn Memory>>;
628    /// Returns the current session.
629    fn session(&self) -> &dyn Session;
630    /// Returns the run configuration for this invocation.
631    fn run_config(&self) -> &RunConfig;
632    /// Signals that this invocation should end after the current turn.
633    fn end_invocation(&self);
634    /// Returns whether the invocation has been ended.
635    fn ended(&self) -> bool;
636
637    /// Returns `true` if this invocation has been cancelled.
638    ///
639    /// Agents and tools can poll this during long-running work (LLM streaming,
640    /// HTTP I/O, tool execution) to detect an external cancellation request —
641    /// for example, a user pressing "Stop" or a call to
642    /// [`Runner::interrupt`](https://docs.rs/adk-runner). Checking it at chunk
643    /// or tool boundaries lets an agent exit promptly and perform any graceful
644    /// cleanup instead of running to natural completion.
645    ///
646    /// The default returns `false`. The runtime sets the underlying token when
647    /// `Runner::interrupt()` is called or `RunConfig::cancellation_token` fires.
648    fn is_cancelled(&self) -> bool {
649        false
650    }
651
652    /// Returns the scopes granted to the current user for this invocation.
653    ///
654    /// When a [`RequestContext`](crate::RequestContext) is present (set by the
655    /// server's auth middleware bridge), this returns the scopes from that
656    /// context. The default returns an empty vec (no scopes granted).
657    fn user_scopes(&self) -> Vec<String> {
658        vec![]
659    }
660
661    /// Returns the run's request metadata: the run's unauthenticated
662    /// [`RunConfig::request_metadata`] overlaid with the metadata of its
663    /// [`RequestContext`](crate::RequestContext), whose values win on a shared key.
664    ///
665    /// Only the request context's entries come from a request the server authenticated;
666    /// [`is_authenticated`](ReadonlyContext::is_authenticated) says whether there is one.
667    fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
668        HashMap::new()
669    }
670
671    /// Whether the run's transfer target list replaces static sub-agent targets.
672    fn authoritative_transfer_targets(&self) -> bool {
673        false
674    }
675
676    /// Current nested agent-as-tool delegation depth.
677    fn delegation_depth(&self) -> u32 {
678        0
679    }
680
681    /// Maximum nested agent-as-tool delegation depth.
682    fn max_delegation_depth(&self) -> Option<u32> {
683        None
684    }
685
686    /// Returns the root invocation that owns this orchestration tree.
687    ///
688    /// Nested agent runs use this stable identifier to aggregate budgets,
689    /// traces, and execution receipts without conflating unrelated runs.
690    fn orchestration_root_invocation_id(&self) -> &str {
691        self.invocation_id()
692    }
693
694    /// Returns the causal relationship execution that started this run.
695    fn orchestration_edge_id(&self) -> Option<&str> {
696        None
697    }
698
699    /// Returns whether a runtime-injected tool requires confirmation.
700    ///
701    /// This additive hook lets composition layers protect relationship tools
702    /// without mutating the concrete agent that receives them.
703    fn requires_tool_confirmation(&self, _tool_name: &str) -> bool {
704        false
705    }
706
707    /// Returns the inbox of user messages sent to this run while it runs, through
708    /// `Runner::steer`.
709    ///
710    /// An agent takes the queued messages at a safe point of its loop, after a tool step's
711    /// results are in its history and before its next model request, and yields each as
712    /// [`SteeringMessage::to_event`](crate::SteeringMessage::to_event). A wrapper context
713    /// forwards it. A context whose agent must not take steering returns `None`: a
714    /// `ParallelAgent` branch, whose message waits for the first safe point after the join.
715    /// The default returns `None`.
716    fn steering_inbox(&self) -> Option<crate::SteeringInbox> {
717        None
718    }
719
720    /// Retrieve a secret by name from the configured secret provider.
721    ///
722    /// Returns `Ok(Some(value))` when a provider is configured and the secret
723    /// exists, `Ok(None)` when no provider is configured, or an error on
724    /// provider failure. The default returns `Ok(None)`.
725    async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
726        Ok(None)
727    }
728
729    /// Resolves a secret for a described access.
730    ///
731    /// A wrapper context must forward this, and a tool context builds the request from
732    /// the identity the framework gave it. The default drops the description and calls
733    /// [`InvocationContext::get_secret`], which keeps a context that predates the
734    /// request object working.
735    async fn get_secret_for(&self, request: &SecretRequest) -> Result<Option<String>> {
736        self.get_secret(&request.name).await
737    }
738}
739
740// Placeholder service traits
741/// Binary artifact storage for agents.
742#[async_trait]
743pub trait Artifacts: Send + Sync {
744    /// Saves a binary artifact and returns its version number.
745    async fn save(&self, name: &str, data: &crate::Part) -> Result<i64>;
746    /// Loads a binary artifact by name.
747    async fn load(&self, name: &str) -> Result<crate::Part>;
748    /// Lists all artifact names.
749    async fn list(&self) -> Result<Vec<String>>;
750}
751
752/// Semantic memory search for agents.
753#[async_trait]
754pub trait Memory: Send + Sync {
755    /// Searches memory for entries matching the query.
756    async fn search(&self, query: &str) -> Result<Vec<MemoryEntry>>;
757
758    /// Verify backend connectivity.
759    ///
760    /// The default implementation succeeds, which is suitable for in-memory
761    /// implementations and adapters without an external dependency.
762    async fn health_check(&self) -> Result<()> {
763        Ok(())
764    }
765
766    /// Add a single memory entry.
767    ///
768    /// The default implementation returns an "not implemented" error, which is
769    /// suitable for read-only memory backends.
770    async fn add(&self, entry: MemoryEntry) -> Result<()> {
771        let _ = entry;
772        Err(AdkError::memory("add not implemented"))
773    }
774
775    /// Delete entries matching a query. Returns count of deleted entries.
776    ///
777    /// The default implementation returns an "not implemented" error, which is
778    /// suitable for read-only memory backends.
779    async fn delete(&self, query: &str) -> Result<u64> {
780        let _ = query;
781        Err(AdkError::memory("delete not implemented"))
782    }
783
784    /// Whether this memory keeps project-scoped entries isolated.
785    ///
786    /// Returns `false` by default, so a caller can tell real isolation apart from a
787    /// memory that has no project support instead of inferring it from data.
788    fn supports_project_scoping(&self) -> bool {
789        false
790    }
791
792    /// Searches memories within a specific project.
793    ///
794    /// # Errors
795    ///
796    /// The default implementation returns an error. Delegating to the global search
797    /// would return entries the project boundary is meant to exclude, and nothing in
798    /// the result would say the boundary was ignored.
799    async fn search_in_project(&self, query: &str, project_id: &str) -> Result<Vec<MemoryEntry>> {
800        let _ = (query, project_id);
801        Err(AdkError::memory(
802            "this memory does not implement project scoping, so `search_in_project` cannot \
803             honour the project boundary; check `supports_project_scoping` first, or call \
804             `search` if global scope is intended",
805        ))
806    }
807
808    /// Adds a memory entry scoped to a specific project.
809    ///
810    /// # Errors
811    ///
812    /// Returns an error by default. Writing the entry globally would make data
813    /// intended for one project visible everywhere under the same app and user.
814    async fn add_to_project(&self, entry: MemoryEntry, project_id: &str) -> Result<()> {
815        let _ = (entry, project_id);
816        Err(AdkError::memory(
817            "this memory does not implement project scoping, so `add_to_project` cannot honour \
818             the project boundary; check `supports_project_scoping` first, or call `add` if \
819             global scope is intended",
820        ))
821    }
822}
823
824/// Trait for retrieving secrets at runtime.
825///
826/// This is the core-level abstraction used by `ToolContext::get_secret` and
827/// `InvocationContext::get_secret`. Concrete implementations (e.g., AWS
828/// Secrets Manager, Azure Key Vault, GCP Secret Manager) live in `adk-auth`
829/// behind feature flags and implement this trait via the `SecretProvider`
830/// adapter.
831///
832/// # Example
833///
834/// ```rust,ignore
835/// use adk_core::SecretService;
836///
837/// struct EnvSecretService;
838///
839/// #[async_trait::async_trait]
840/// impl SecretService for EnvSecretService {
841///     async fn get_secret(&self, name: &str) -> adk_core::Result<String> {
842///         std::env::var(name).map_err(|_| adk_core::AdkError::not_found(
843///             format!("secret '{name}' not found in environment"),
844///         ))
845///     }
846/// }
847/// ```
848#[async_trait]
849pub trait SecretService: Send + Sync {
850    /// Retrieve a secret value by name.
851    ///
852    /// Returns the secret string on success, or an [`AdkError`] on failure.
853    async fn get_secret(&self, name: &str) -> Result<String>;
854
855    /// Retrieve a secret for a described access.
856    ///
857    /// This is the form an authorizing service implements: the request carries who is
858    /// asking and why, so a decision can be made before the value is fetched. The
859    /// default implementation ignores the context and calls
860    /// [`SecretService::get_secret`], which is correct for a service that has no
861    /// policy of its own.
862    ///
863    /// Every field on [`SecretRequest`] is set by the framework at the call site, not
864    /// supplied by the tool, so a tool cannot present another tool's identity.
865    async fn get_secret_for(&self, request: &SecretRequest) -> Result<String> {
866        self.get_secret(&request.name).await
867    }
868}
869
870/// A described secret access.
871///
872/// Carries the requested name plus the identity the framework observed at the call
873/// site, so a [`SecretService`] can authorize and audit rather than being handed a
874/// bare name with no context.
875///
876/// # Example
877///
878/// ```rust
879/// use adk_core::SecretRequest;
880///
881/// let request = SecretRequest::new("payments-api-key")
882///     .with_tool_name("charge_card")
883///     .with_purpose("authorize a customer payment");
884///
885/// assert_eq!(request.tool_name.as_deref(), Some("charge_card"));
886/// ```
887#[derive(Debug, Clone, Default, PartialEq, Eq)]
888pub struct SecretRequest {
889    /// Name of the requested secret.
890    pub name: String,
891    /// The tool making the request, when the access came from a tool.
892    ///
893    /// Set by the framework from the tool it dispatched, never from a value the tool
894    /// provided.
895    pub tool_name: Option<String>,
896    /// Application the run belongs to.
897    pub app_name: Option<String>,
898    /// Authenticated user the run belongs to.
899    pub user_id: Option<String>,
900    /// Session the run belongs to.
901    pub session_id: Option<String>,
902    /// Invocation the access happened in, for correlating audit records.
903    pub invocation_id: Option<String>,
904    /// Why the secret is needed, when the caller states it.
905    pub purpose: Option<String>,
906}
907
908impl SecretRequest {
909    /// Creates a request for `name` with no identity attached.
910    pub fn new(name: impl Into<String>) -> Self {
911        Self { name: name.into(), ..Default::default() }
912    }
913
914    /// Attaches the requesting tool's name.
915    #[must_use]
916    pub fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
917        self.tool_name = Some(tool_name.into());
918        self
919    }
920
921    /// Attaches the run's identity.
922    #[must_use]
923    pub fn with_identity(
924        mut self,
925        app_name: impl Into<String>,
926        user_id: impl Into<String>,
927        session_id: impl Into<String>,
928    ) -> Self {
929        self.app_name = Some(app_name.into());
930        self.user_id = Some(user_id.into());
931        self.session_id = Some(session_id.into());
932        self
933    }
934
935    /// Attaches the invocation the access happened in.
936    #[must_use]
937    pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
938        self.invocation_id = Some(invocation_id.into());
939        self
940    }
941
942    /// Attaches a stated purpose.
943    #[must_use]
944    pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
945        self.purpose = Some(purpose.into());
946        self
947    }
948}
949
950/// A single entry returned from memory search.
951#[derive(Debug, Clone)]
952pub struct MemoryEntry {
953    /// The content of this memory entry.
954    pub content: Content,
955    /// The author who created this memory entry.
956    pub author: String,
957}
958
959/// Streaming mode for agent responses.
960/// Matches ADK Python/Go specification.
961#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
962pub enum StreamingMode {
963    /// No streaming; responses delivered as complete units.
964    /// Agent collects all chunks internally and yields a single final event.
965    None,
966    /// Server-Sent Events streaming; one-way streaming from server to client.
967    /// Agent yields each chunk as it arrives with stable event ID.
968    #[default]
969    SSE,
970    /// Bidirectional streaming; simultaneous communication in both directions.
971    /// Used for realtime audio/video agents.
972    Bidi,
973}
974
975/// Controls what parts of prior conversation history is received by llmagent
976#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
977pub enum IncludeContents {
978    /// The llmagent operates solely on its current turn (latest user input + any following agent events)
979    None,
980    /// Default - The llmagent receives the relevant conversation history
981    #[default]
982    Default,
983}
984
985/// Decision applied when a tool execution requires human confirmation.
986#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
987#[serde(rename_all = "snake_case")]
988pub enum ToolConfirmationDecision {
989    /// Approve the tool execution.
990    Approve,
991    /// Deny the tool execution.
992    Deny,
993}
994
995/// Produces a canonical fingerprint of a tool call's name and arguments.
996///
997/// The fingerprint is the tool name followed by its arguments in canonical JSON
998/// form, with object keys sorted at every level so that two structurally equal
999/// argument sets always produce the same string. It is deliberately readable
1000/// rather than hashed, so a mismatch can be diagnosed by inspection.
1001///
1002/// It identifies a call, not a decision: approvals are keyed by
1003/// [`ToolConfirmationRequest::fingerprint`], which adds the acting agent and the
1004/// tool's [`ToolOrigin`] in front of this string.
1005///
1006/// # Example
1007///
1008/// ```rust
1009/// use adk_core::tool_call_fingerprint;
1010/// use serde_json::json;
1011///
1012/// // Key order does not change the fingerprint.
1013/// let a = tool_call_fingerprint("delete_file", &json!({ "path": "/tmp/a", "force": true }));
1014/// let b = tool_call_fingerprint("delete_file", &json!({ "force": true, "path": "/tmp/a" }));
1015/// assert_eq!(a, b);
1016///
1017/// // A different path does not.
1018/// let c = tool_call_fingerprint("delete_file", &json!({ "path": "/etc/passwd", "force": true }));
1019/// assert_ne!(a, c);
1020/// ```
1021pub fn tool_call_fingerprint(tool_name: &str, args: &Value) -> String {
1022    let mut out = String::with_capacity(tool_name.len() + 32);
1023    out.push_str(tool_name);
1024    out.push('\u{1f}');
1025    write_canonical(args, &mut out);
1026    out
1027}
1028
1029/// Writes `value` as canonical JSON, with object keys sorted at every level.
1030pub(crate) fn write_canonical(value: &Value, out: &mut String) {
1031    match value {
1032        Value::Object(map) => {
1033            let mut keys: Vec<&String> = map.keys().collect();
1034            keys.sort();
1035            out.push('{');
1036            for (i, key) in keys.iter().enumerate() {
1037                if i > 0 {
1038                    out.push(',');
1039                }
1040                out.push_str(&Value::String((*key).clone()).to_string());
1041                out.push(':');
1042                write_canonical(&map[*key], out);
1043            }
1044            out.push('}');
1045        }
1046        Value::Array(items) => {
1047            out.push('[');
1048            for (i, item) in items.iter().enumerate() {
1049                if i > 0 {
1050                    out.push(',');
1051                }
1052                write_canonical(item, out);
1053            }
1054            out.push(']');
1055        }
1056        other => out.push_str(&other.to_string()),
1057    }
1058}
1059
1060/// Policy defining which tools require human confirmation before execution.
1061#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1062#[serde(rename_all = "snake_case")]
1063pub enum ToolConfirmationPolicy {
1064    /// No tool confirmation is required.
1065    #[default]
1066    Never,
1067    /// Every tool call requires confirmation.
1068    Always,
1069    /// Only the listed tool names require confirmation.
1070    PerTool(BTreeSet<String>),
1071}
1072
1073impl ToolConfirmationPolicy {
1074    /// Returns true when the given tool name must be confirmed before execution.
1075    pub fn requires_confirmation(&self, tool_name: &str) -> bool {
1076        match self {
1077            Self::Never => false,
1078            Self::Always => true,
1079            Self::PerTool(tools) => tools.contains(tool_name),
1080        }
1081    }
1082
1083    /// Add one tool name to the confirmation policy (converts `Never` to `PerTool`).
1084    pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self {
1085        let tool_name = tool_name.into();
1086        match &mut self {
1087            Self::Never => {
1088                let mut tools = BTreeSet::new();
1089                tools.insert(tool_name);
1090                Self::PerTool(tools)
1091            }
1092            Self::Always => Self::Always,
1093            Self::PerTool(tools) => {
1094                tools.insert(tool_name);
1095                self
1096            }
1097        }
1098    }
1099}
1100
1101/// [`Tool::origin`](crate::Tool::origin) of a tool attached to an agent directly rather than
1102/// published by a toolset or server.
1103pub const STATIC_TOOL_ORIGIN: &str = "static";
1104
1105/// [`ToolOrigin::source`] of a provider-executed built-in tool the agent declares without a
1106/// [`Tool`](crate::Tool) of its own.
1107pub const BUILTIN_TOOL_ORIGIN: &str = "builtin";
1108
1109/// Who published a tool and what it declared, as recorded on a call held for approval.
1110///
1111/// The origin is part of the call's [fingerprint](ToolConfirmationRequest::fingerprint), so
1112/// an approval granted for a tool one MCP server publishes never authorizes the same name
1113/// published by another, and a tool whose description or parameters changed after the
1114/// approval needs a new one.
1115///
1116/// # Example
1117///
1118/// ```rust
1119/// use adk_core::ToolOrigin;
1120/// use serde_json::json;
1121///
1122/// let wire = json!({ "name": "wire", "parameters": { "type": "object" } });
1123/// let a = ToolOrigin::new("mcp:bank_a", &wire, None);
1124/// let b = ToolOrigin::new("mcp:bank_b", &wire, None);
1125/// assert_eq!(a.declaration_digest, b.declaration_digest);
1126/// assert_ne!(a, b);
1127///
1128/// let redefined = json!({ "name": "wire", "parameters": { "type": "object", "required": ["memo"] } });
1129/// assert_ne!(a.declaration_digest, ToolOrigin::new("mcp:bank_a", &redefined, None).declaration_digest);
1130/// ```
1131#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1132#[serde(rename_all = "camelCase")]
1133pub struct ToolOrigin {
1134    /// Who publishes the tool, as [`Tool::origin`](crate::Tool::origin) reports it:
1135    /// [`STATIC_TOOL_ORIGIN`] for a tool attached to the agent, `mcp:{toolset}` for a tool an
1136    /// MCP server publishes. Calls that have no [`Tool`](crate::Tool) name their publisher
1137    /// too: [`BUILTIN_TOOL_ORIGIN`] for a provider-executed built-in tool, `graph:{agent}`
1138    /// for a governed graph node, and `realtime` for a native handler registered on an
1139    /// `adk-realtime` `RealtimeRunner`.
1140    pub source: String,
1141    /// `sha256:` followed by the hex SHA-256 of the tool's declaration and annotations in
1142    /// canonical JSON.
1143    pub declaration_digest: String,
1144}
1145
1146impl ToolOrigin {
1147    /// The origin of a tool `source` publishes with `declaration` and `annotations`.
1148    pub fn new(
1149        source: impl Into<String>,
1150        declaration: &Value,
1151        annotations: Option<&Value>,
1152    ) -> Self {
1153        use sha2::{Digest, Sha256};
1154        use std::fmt::Write as _;
1155
1156        let declared =
1157            serde_json::json!({ "declaration": declaration, "annotations": annotations });
1158        let mut canonical = String::new();
1159        write_canonical(&declared, &mut canonical);
1160        let mut digest = String::with_capacity(7 + 64);
1161        digest.push_str("sha256:");
1162        for byte in Sha256::digest(canonical.as_bytes()) {
1163            let _ = write!(digest, "{byte:02x}");
1164        }
1165        Self { source: source.into(), declaration_digest: digest }
1166    }
1167
1168    /// The origin of `tool`: its [`Tool::origin`](crate::Tool::origin) and a digest of its
1169    /// [`declaration`](crate::Tool::declaration) and [`annotations`](crate::Tool::annotations).
1170    ///
1171    /// # Example
1172    ///
1173    /// ```rust
1174    /// use adk_core::{Result, STATIC_TOOL_ORIGIN, Tool, ToolContext, ToolOrigin};
1175    /// use serde_json::Value;
1176    /// use std::sync::Arc;
1177    ///
1178    /// struct Ping;
1179    ///
1180    /// #[async_trait::async_trait]
1181    /// impl Tool for Ping {
1182    ///     fn name(&self) -> &str {
1183    ///         "ping"
1184    ///     }
1185    ///     fn description(&self) -> &str {
1186    ///         "Checks the service is up"
1187    ///     }
1188    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
1189    ///         Ok(Value::Null)
1190    ///     }
1191    /// }
1192    ///
1193    /// assert_eq!(ToolOrigin::of(&Ping).source, STATIC_TOOL_ORIGIN);
1194    /// ```
1195    pub fn of(tool: &dyn crate::Tool) -> Self {
1196        Self::new(tool.origin(), &tool.declaration(), tool.annotations())
1197    }
1198}
1199
1200/// Payload describing a tool call awaiting human confirmation.
1201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1202#[serde(rename_all = "camelCase")]
1203pub struct ToolConfirmationRequest {
1204    /// Name of the tool awaiting confirmation.
1205    pub tool_name: String,
1206    /// The function call ID from the LLM, if available.
1207    #[serde(skip_serializing_if = "Option::is_none")]
1208    pub function_call_id: Option<String>,
1209    /// Arguments the tool would be called with.
1210    pub args: Value,
1211    /// The agent that made the call and the subject it acted for.
1212    ///
1213    /// Recorded for the approver and the audit trail. The agent's id is part of the
1214    /// [`fingerprint`](Self::fingerprint), so a decision for this call never authorizes
1215    /// another agent's call.
1216    #[serde(default, skip_serializing_if = "Option::is_none")]
1217    pub acting: Option<Box<crate::ActingContext>>,
1218    /// Who published the tool and what it declared when the call was held.
1219    ///
1220    /// Part of the [`fingerprint`](Self::fingerprint). `None` in requests recorded before
1221    /// origins were, and in requests for calls the governed path saw without their tool.
1222    #[serde(default, skip_serializing_if = "Option::is_none")]
1223    pub origin: Option<ToolOrigin>,
1224    /// What the approver sees with the call, such as the exact image it would send
1225    /// ([`Tool::approval_evidence`](crate::Tool::approval_evidence)).
1226    ///
1227    /// The digests are part of the [`fingerprint`](Self::fingerprint), so a decision binds
1228    /// to these images. Empty for a call held without evidence, and in requests recorded
1229    /// before evidence was.
1230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1231    pub evidence: Vec<crate::Evidence>,
1232}
1233
1234impl ToolConfirmationRequest {
1235    /// A request for a call to `tool_name` with `args`.
1236    ///
1237    /// # Example
1238    ///
1239    /// ```rust
1240    /// use adk_core::ToolConfirmationRequest;
1241    /// use serde_json::json;
1242    ///
1243    /// let request = ToolConfirmationRequest::new("transfer", json!({ "amount": 5 }))
1244    ///     .with_function_call_id("call-1");
1245    /// assert_eq!(request.function_call_id.as_deref(), Some("call-1"));
1246    /// ```
1247    pub fn new(tool_name: impl Into<String>, args: Value) -> Self {
1248        Self {
1249            tool_name: tool_name.into(),
1250            function_call_id: None,
1251            args,
1252            acting: None,
1253            origin: None,
1254            evidence: Vec::new(),
1255        }
1256    }
1257
1258    /// A request for a call to `tool` with `args`, carrying the tool's [`ToolOrigin`].
1259    ///
1260    /// With the acting agent set, its [`fingerprint`](Self::fingerprint) is the key the
1261    /// governed path looks a decision up under for that agent's call, so a deployment can
1262    /// approve a call before any run makes it.
1263    ///
1264    /// # Example
1265    ///
1266    /// ```rust
1267    /// use adk_core::principal::{ActingContext, AgentPrincipal};
1268    /// use adk_core::{Result, Tool, ToolApproval, ToolConfirmationRequest, ToolContext, RunConfig};
1269    /// use serde_json::{Value, json};
1270    /// use std::sync::Arc;
1271    ///
1272    /// struct Transfer;
1273    ///
1274    /// #[async_trait::async_trait]
1275    /// impl Tool for Transfer {
1276    ///     fn name(&self) -> &str {
1277    ///         "transfer"
1278    ///     }
1279    ///     fn description(&self) -> &str {
1280    ///         "Moves money out of the treasury"
1281    ///     }
1282    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
1283    ///         Ok(args)
1284    ///     }
1285    /// }
1286    ///
1287    /// // The agent `treasurer` of app `ops` acts as `urn:adk:agent:ops/treasurer` by default.
1288    /// let treasurer = ActingContext::new(AgentPrincipal::derived("ops", "treasurer"));
1289    /// let key = ToolConfirmationRequest::for_tool(&Transfer, json!({ "amount": 40 }))
1290    ///     .with_acting_context(treasurer)
1291    ///     .fingerprint();
1292    /// let config = RunConfig::builder().tool_approval(key, ToolApproval::approve()).build();
1293    /// assert_eq!(config.tool_approvals.len(), 1);
1294    /// ```
1295    pub fn for_tool(tool: &dyn crate::Tool, args: Value) -> Self {
1296        Self::new(tool.name(), args).with_origin(ToolOrigin::of(tool))
1297    }
1298
1299    /// Records the origin of the tool the call was made to.
1300    #[must_use]
1301    pub fn with_origin(mut self, origin: ToolOrigin) -> Self {
1302        self.origin = Some(origin);
1303        self
1304    }
1305
1306    /// Sets the function call ID.
1307    #[must_use]
1308    pub fn with_function_call_id(mut self, id: impl Into<String>) -> Self {
1309        self.function_call_id = Some(id.into());
1310        self
1311    }
1312
1313    /// Records the acting context of the agent that made the call.
1314    #[must_use]
1315    pub fn with_acting_context(mut self, acting: crate::ActingContext) -> Self {
1316        self.acting = Some(Box::new(acting));
1317        self
1318    }
1319
1320    /// Holds the call with `evidence`, whose digests become part of its
1321    /// [`fingerprint`](Self::fingerprint).
1322    ///
1323    /// # Example
1324    ///
1325    /// ```rust
1326    /// use adk_core::{ArtifactLocator, Evidence, ImageEvidence, ToolConfirmationRequest};
1327    /// use serde_json::json;
1328    ///
1329    /// let image = |digest: &str| {
1330    ///     Evidence::from(ImageEvidence::new(
1331    ///         digest,
1332    ///         ArtifactLocator::new("desk", "ana", "s1", "egress/crop.png", 1),
1333    ///         "image/png",
1334    ///         320,
1335    ///         200,
1336    ///     ))
1337    /// };
1338    /// let call = ToolConfirmationRequest::new("vision_describe", json!({ "question": "Total?" }));
1339    /// let held = call.clone().with_evidence([image("sha256:aa")]);
1340    /// let swapped = call.clone().with_evidence([image("sha256:bb")]);
1341    /// assert_ne!(held.fingerprint(), call.fingerprint());
1342    /// assert_ne!(held.fingerprint(), swapped.fingerprint());
1343    /// ```
1344    #[must_use]
1345    pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
1346        self.evidence.extend(evidence);
1347        self
1348    }
1349
1350    /// The call's fingerprint: the acting agent's id, the tool's [`ToolOrigin`], the tool
1351    /// name, and the canonical arguments.
1352    ///
1353    /// This is the key a decision is recorded under in [`RunConfig::tool_approvals`], in
1354    /// [`RunConfig::tool_confirmation_fingerprints`], and in an
1355    /// [`ApprovalStore`](crate::ApprovalStore), so the decision applies to the same call
1356    /// re-issued under a new call ID by the same agent to the same tool. It never applies to
1357    /// another agent's call, to a tool of the same name another publisher answers, to a
1358    /// tool whose declaration changed, or to a call held with different evidence. The parts
1359    /// are separated by U+001F; a missing agent or origin leaves its part empty.
1360    ///
1361    /// A call held with [`evidence`](Self::evidence) adds the evidence digests, in order, to
1362    /// the declaration part: U+001E, `evidence:`, then the digests as a JSON array. The five
1363    /// parts and their order stay as they are, and a call without evidence keeps the
1364    /// fingerprint it had before evidence existed.
1365    ///
1366    /// The governed path records the acting agent on every request it builds, so a
1367    /// fingerprint without one never matches a governed call.
1368    /// [`RunConfigBuilder::tool_approval`] refuses one; see
1369    /// [`fingerprint_agent`](Self::fingerprint_agent).
1370    ///
1371    /// # Example
1372    ///
1373    /// ```rust
1374    /// use adk_core::principal::{ActingContext, AgentPrincipal};
1375    /// use adk_core::ToolConfirmationRequest;
1376    /// use serde_json::json;
1377    ///
1378    /// let call = |agent: &str| {
1379    ///     ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }))
1380    ///         .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", agent)))
1381    /// };
1382    /// assert_eq!(call("treasurer").fingerprint(), call("treasurer").fingerprint());
1383    /// assert_ne!(call("treasurer").fingerprint(), call("intern").fingerprint());
1384    /// ```
1385    pub fn fingerprint(&self) -> String {
1386        // Control characters would forge a separator; agent ids already exclude them.
1387        let push_clean = |out: &mut String, part: &str| {
1388            out.extend(part.chars().map(|c| if c.is_control() { '\u{fffd}' } else { c }));
1389        };
1390        let call = tool_call_fingerprint(&self.tool_name, &self.args);
1391        let mut out = String::with_capacity(call.len() + 160);
1392        if let Some(acting) = &self.acting {
1393            push_clean(&mut out, acting.agent.id.as_str());
1394        }
1395        out.push('\u{1f}');
1396        if let Some(origin) = &self.origin {
1397            push_clean(&mut out, &origin.source);
1398            out.push('\u{1f}');
1399            push_clean(&mut out, &origin.declaration_digest);
1400        } else {
1401            out.push('\u{1f}');
1402        }
1403        if !self.evidence.is_empty() {
1404            // JSON escapes every control character, so no digest can forge a separator.
1405            let digests: Vec<&str> = self.evidence.iter().map(crate::Evidence::digest).collect();
1406            out.push('\u{1e}');
1407            out.push_str("evidence:");
1408            out.push_str(&serde_json::to_string(&digests).unwrap_or_default());
1409        }
1410        out.push('\u{1f}');
1411        out.push_str(&call);
1412        out
1413    }
1414
1415    /// The id of the acting agent `fingerprint` names, or `None` when it names none.
1416    ///
1417    /// `None` for the [`fingerprint`](Self::fingerprint) of a request without an acting
1418    /// agent, and for a string that is no request fingerprint at all, such as a
1419    /// [`tool_call_fingerprint`]. A decision keyed by such a string never authorizes a call
1420    /// on the governed path, which keys every call by its acting agent.
1421    ///
1422    /// # Example
1423    ///
1424    /// ```rust
1425    /// use adk_core::principal::{ActingContext, AgentPrincipal};
1426    /// use adk_core::{ToolConfirmationRequest, tool_call_fingerprint};
1427    /// use serde_json::json;
1428    ///
1429    /// let call = ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }));
1430    /// let owned = call
1431    ///     .clone()
1432    ///     .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
1433    ///
1434    /// assert_eq!(
1435    ///     ToolConfirmationRequest::fingerprint_agent(&owned.fingerprint()),
1436    ///     Some("urn:adk:agent:ops/treasurer")
1437    /// );
1438    /// assert_eq!(ToolConfirmationRequest::fingerprint_agent(&call.fingerprint()), None);
1439    /// let bare = tool_call_fingerprint("transfer", &json!({ "amount": 40 }));
1440    /// assert_eq!(ToolConfirmationRequest::fingerprint_agent(&bare), None);
1441    /// ```
1442    pub fn fingerprint_agent(fingerprint: &str) -> Option<&str> {
1443        // Five parts: agent, origin source, declaration digest, tool name, arguments.
1444        let mut parts = fingerprint.splitn(5, '\u{1f}');
1445        let agent = parts.next().filter(|agent| !agent.is_empty())?;
1446        (parts.count() == 4).then_some(agent)
1447    }
1448}
1449
1450/// One call of a model turn's batch, as [`ToolConfirmationHandler::batch_started`] sees
1451/// it (spec 3.1 §10 C6).
1452///
1453/// # Example
1454///
1455/// ```rust
1456/// use adk_core::BatchCall;
1457/// use serde_json::json;
1458///
1459/// let args = json!({ "path": "src/lib.rs" });
1460/// let call = BatchCall::new("edit_file", &args).with_function_call_id("call-1");
1461/// assert_eq!(call.function_call_id, Some("call-1"));
1462/// ```
1463#[derive(Clone, Copy, Debug)]
1464#[non_exhaustive]
1465pub struct BatchCall<'a> {
1466    /// The tool's name.
1467    pub name: &'a str,
1468    /// The call's ID.
1469    pub function_call_id: Option<&'a str>,
1470    /// The call's arguments as the model sent them.
1471    pub args: &'a Value,
1472    /// Who publishes the tool, when the agent knows it.
1473    pub origin: Option<&'a crate::ToolOrigin>,
1474}
1475
1476impl<'a> BatchCall<'a> {
1477    /// A call to `name` with `args`.
1478    pub fn new(name: &'a str, args: &'a Value) -> Self {
1479        Self { name, function_call_id: None, args, origin: None }
1480    }
1481
1482    /// Sets the call's ID.
1483    #[must_use]
1484    pub fn with_function_call_id(mut self, id: &'a str) -> Self {
1485        self.function_call_id = Some(id);
1486        self
1487    }
1488
1489    /// Sets the tool's origin.
1490    #[must_use]
1491    pub fn with_origin(mut self, origin: &'a crate::ToolOrigin) -> Self {
1492        self.origin = Some(origin);
1493        self
1494    }
1495}
1496
1497/// Asynchronous decision source for tool calls that require confirmation.
1498///
1499/// Front ends and protocol adapters can implement this trait to pause an
1500/// invocation while a person or an external policy service reviews the exact
1501/// tool call. When no handler is configured, agents preserve the existing
1502/// behavior and emit an interrupted confirmation event for a later run.
1503///
1504/// Agents ask for each call as it is dispatched, with the call's final arguments,
1505/// while calls that need no approval keep running. Calls in one batch are decided
1506/// concurrently, so a handler that prompts on a shared device such as a terminal
1507/// serializes its own prompts. The governed path asks through
1508/// [`decide_approval`](Self::decide_approval), which calls `decide` unless overridden. A
1509/// decision that takes longer than [`RunConfig::tool_confirmation_timeout`] denies the call.
1510/// An error ends the turn after running tools finish; decisions still waiting in the same
1511/// batch are dropped.
1512///
1513/// The timeout denies only in a run without an [`approval_store`](RunConfig::approval_store)
1514/// to read a later decision from. With one, a call the handler does not decide in time is
1515/// held there (and submitted to the run's
1516/// [`approval_service`](RunConfig::approval_service), if any), the run ends with it waiting,
1517/// and only a decision recorded for it resumes it; the handler is not asked about it again
1518/// (spec 3.3 §7.3). [`RunConfig::deny_on_confirmation_timeout`] restores the denial.
1519///
1520/// A freeze of one of the run's [`governance`](RunConfig::governance) controls ends the
1521/// wait at once, whatever the timeout: the handler's future is dropped, the call is refused
1522/// with the freeze error, and an inbox request opened for it is withdrawn, so an answer
1523/// given later — during the freeze or after an unfreeze — does not run it.
1524#[async_trait]
1525pub trait ToolConfirmationHandler: std::fmt::Debug + Send + Sync {
1526    /// Approve or deny one pending tool call.
1527    async fn decide(&self, request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision>;
1528
1529    /// Decides one pending tool call, optionally with arguments that replace the call's own
1530    /// and a message.
1531    ///
1532    /// The governed path calls this method, not [`decide`](Self::decide). The default
1533    /// returns [`ToolApproval::approve`](crate::ToolApproval::approve) or
1534    /// [`ToolApproval::deny`](crate::ToolApproval::deny) for `decide`'s answer, so a
1535    /// handler that does not override it decides exactly as before.
1536    ///
1537    /// An approval with [`edited_args`](crate::ToolApproval::edited_args) executes the call
1538    /// with them only after they pass the run's [`ToolPolicy`](crate::ToolPolicy) and the
1539    /// agent's tool screen again; a denial's [`message`](crate::ToolApproval::message) is
1540    /// reported to the model. The approval's expiry is ignored, since it decides this call
1541    /// only.
1542    ///
1543    /// Spec 3.1 §10, C3.
1544    ///
1545    /// # Errors
1546    ///
1547    /// An error ends the turn, as an error from `decide` does.
1548    ///
1549    /// # Example
1550    ///
1551    /// ```rust
1552    /// use adk_core::{
1553    ///     Result, ToolApproval, ToolConfirmationDecision, ToolConfirmationHandler,
1554    ///     ToolConfirmationRequest, async_trait,
1555    /// };
1556    /// use serde_json::json;
1557    ///
1558    /// /// Approves transfers, capping the amount at 100.
1559    /// #[derive(Debug)]
1560    /// struct CapTransfers;
1561    ///
1562    /// #[async_trait]
1563    /// impl ToolConfirmationHandler for CapTransfers {
1564    ///     async fn decide(&self, _request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision> {
1565    ///         Ok(ToolConfirmationDecision::Approve)
1566    ///     }
1567    ///
1568    ///     async fn decide_approval(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
1569    ///         let amount = request.args["amount"].as_f64().unwrap_or(0.0);
1570    ///         Ok(if amount > 100.0 {
1571    ///             ToolApproval::approve().with_edited_args(json!({ "amount": 100 }))
1572    ///         } else {
1573    ///             ToolApproval::approve()
1574    ///         })
1575    ///     }
1576    /// }
1577    ///
1578    /// # futures::executor::block_on(async {
1579    /// let request = ToolConfirmationRequest::new("transfer", json!({ "amount": 250 }));
1580    /// let approval = CapTransfers.decide_approval(&request).await?;
1581    /// assert_eq!(approval.edited_args, Some(json!({ "amount": 100 })));
1582    /// # Ok::<(), adk_core::AdkError>(())
1583    /// # }).unwrap();
1584    /// ```
1585    async fn decide_approval(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
1586        Ok(match self.decide(request).await? {
1587            ToolConfirmationDecision::Approve => ToolApproval::approve(),
1588            ToolConfirmationDecision::Deny => ToolApproval::deny(),
1589        })
1590    }
1591
1592    /// Tells the handler the calls one model turn made, once per turn, before any of them
1593    /// is dispatched and after the turn's run budget is reserved (spec 3.1 §10 C6, A2).
1594    ///
1595    /// A handler that reviews several held calls as one — a change set of edits — keeps
1596    /// the batch and answers each call's [`decide_approval`](Self::decide_approval) from
1597    /// one decision, whichever order the calls are dispatched in. The default does nothing,
1598    /// so every call is decided on its own.
1599    ///
1600    /// # Example
1601    ///
1602    /// ```rust
1603    /// use std::sync::Mutex;
1604    ///
1605    /// use adk_core::{
1606    ///     BatchCall, Result, ToolConfirmationDecision, ToolConfirmationHandler,
1607    ///     ToolConfirmationRequest, async_trait,
1608    /// };
1609    ///
1610    /// /// Remembers how many calls the last turn made.
1611    /// #[derive(Debug, Default)]
1612    /// struct Counting(Mutex<usize>);
1613    ///
1614    /// #[async_trait]
1615    /// impl ToolConfirmationHandler for Counting {
1616    ///     async fn decide(&self, _request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision> {
1617    ///         Ok(ToolConfirmationDecision::Approve)
1618    ///     }
1619    ///
1620    ///     async fn batch_started(&self, calls: &[BatchCall<'_>]) {
1621    ///         *self.0.lock().unwrap() = calls.len();
1622    ///     }
1623    /// }
1624    ///
1625    /// # futures::executor::block_on(async {
1626    /// let handler = Counting::default();
1627    /// let args = serde_json::json!({});
1628    /// handler.batch_started(&[BatchCall::new("a", &args), BatchCall::new("b", &args)]).await;
1629    /// assert_eq!(*handler.0.lock().unwrap(), 2);
1630    /// # });
1631    /// ```
1632    async fn batch_started(&self, calls: &[BatchCall<'_>]) {
1633        let _ = calls;
1634    }
1635}
1636
1637/// A toolset attached to one runner invocation rather than compiled into the
1638/// agent definition.
1639///
1640/// Protocol adapters use this wrapper for session-scoped capabilities such as
1641/// MCP servers supplied by an ACP client. The wrapper keeps [`RunConfig`]
1642/// debuggable without requiring every toolset implementation to implement
1643/// [`std::fmt::Debug`].
1644#[derive(Clone)]
1645pub struct RuntimeToolset(Arc<dyn Toolset>);
1646
1647impl RuntimeToolset {
1648    /// Wrap a toolset for use during one runner invocation.
1649    pub fn new(toolset: Arc<dyn Toolset>) -> Self {
1650        Self(toolset)
1651    }
1652
1653    /// Borrow the wrapped toolset.
1654    pub fn toolset(&self) -> &Arc<dyn Toolset> {
1655        &self.0
1656    }
1657}
1658
1659impl std::fmt::Debug for RuntimeToolset {
1660    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1661        formatter.debug_tuple("RuntimeToolset").field(&self.0.name()).finish()
1662    }
1663}
1664
1665/// Configuration for a single agent run.
1666///
1667/// Controls streaming behavior, tool confirmation, caching, transfer targets,
1668/// and concurrency settings. Use [`RunConfig::builder()`] to construct from
1669#[derive(Debug, Clone)]
1670pub struct RunConfig {
1671    /// The streaming mode for agent responses.
1672    pub streaming_mode: StreamingMode,
1673    /// Static confirmation decisions for the current run, keyed by **function
1674    /// call ID**.
1675    ///
1676    /// The ID is the one reported on
1677    /// [`ToolConfirmationRequest::function_call_id`], so a decision authorizes the
1678    /// exact call it was requested for. A decision under a tool *name* is not
1679    /// consulted, because one name can cover materially different calls — a
1680    /// `delete_file` approval for a scratch path must not authorize a call that
1681    /// targets a different path.
1682    ///
1683    /// A call ID alone does not name the agent: a provider that reuses call IDs gives
1684    /// another agent's call the same one. Bind each decision with
1685    /// [`tool_confirmation_fingerprints`](Self::tool_confirmation_fingerprints) to the
1686    /// agent, tool, and arguments it was granted for. For name-wide or policy-driven
1687    /// decisions, supply a [`tool_confirmation_handler`](Self::tool_confirmation_handler)
1688    /// instead.
1689    pub tool_confirmation_decisions: HashMap<String, ToolConfirmationDecision>,
1690    /// Binding for entries in
1691    /// [`tool_confirmation_decisions`](Self::tool_confirmation_decisions), keyed by
1692    /// the same function call ID.
1693    ///
1694    /// The value is the [`ToolConfirmationRequest::fingerprint`] of the request the
1695    /// decision was granted for: the acting agent, the tool's origin, the tool name, and
1696    /// the arguments. When an entry is present and the actual call does not match it, the
1697    /// decision is ignored and the call is treated as unconfirmed — the safe direction.
1698    /// Use this whenever a decision travels through a round trip, such as a browser or an
1699    /// editor, where the arguments could be changed or another agent's call could carry
1700    /// the replayed call ID.
1701    ///
1702    /// Every governed call names its acting agent, so a binding whose fingerprint names
1703    /// none ([`ToolConfirmationRequest::fingerprint_agent`]) matches no call and the
1704    /// decision it binds is never applied.
1705    pub tool_confirmation_fingerprints: HashMap<String, String>,
1706    /// Optional live decision source for confirmations that have no static
1707    /// entry in [`tool_confirmation_decisions`](Self::tool_confirmation_decisions).
1708    pub tool_confirmation_handler: Option<Arc<dyn ToolConfirmationHandler>>,
1709    /// The reviewer asked about a call the [`tool_policy`](Self::tool_policy) holds for
1710    /// approval, before the confirmation handler and the approval inbox: it approves,
1711    /// denies, or escalates the call to a person. `None` (the default) asks a person about
1712    /// every held call. See [`ToolReviewer`](crate::ToolReviewer).
1713    pub tool_reviewer: Option<Arc<dyn crate::ToolReviewer>>,
1714    /// Checks each requested call (one a person asked for through something an agent drew)
1715    /// against the seal made when the person approved it, right before it runs; `None`
1716    /// checks nothing beyond the approval itself. See
1717    /// [`RequestedCallSeal`](crate::RequestedCallSeal).
1718    pub requested_call_seal: Option<Arc<dyn crate::RequestedCallSeal>>,
1719    /// Toolsets made available only for this invocation.
1720    pub runtime_toolsets: Vec<RuntimeToolset>,
1721    /// Optional cached content name for automatic prompt caching.
1722    /// When set by the runner's cache lifecycle manager, agents should attach
1723    /// this name to their `GenerateContentConfig` so the LLM provider can
1724    /// reuse cached system instructions and tool definitions.
1725    pub cached_content: Option<String>,
1726    /// Valid agent names this agent can transfer to (parent, peers, children).
1727    /// Set by the runner when invoking agents in a multi-agent tree.
1728    /// When non-empty, the `transfer_to_agent` tool is injected and validation
1729    /// uses this list instead of only checking `sub_agents`.
1730    pub transfer_targets: Vec<String>,
1731    /// The description of each agent in
1732    /// [`transfer_targets`](Self::transfer_targets), by name, set by the runner from the
1733    /// agent tree. An agent tells its model what each target does, so the model can choose
1734    /// where to transfer.
1735    pub transfer_target_descriptions: HashMap<String, String>,
1736    /// The name of the parent agent, if this agent was invoked via transfer.
1737    /// Used by the agent to apply `disallow_transfer_to_parent` filtering.
1738    pub parent_agent: Option<String>,
1739    /// Enable automatic prompt caching for all providers that support it.
1740    ///
1741    /// When `true` (the default), the runner enables provider-level caching:
1742    /// - Anthropic: sets `prompt_caching = true` on the config
1743    /// - Bedrock: sets `prompt_caching = Some(BedrockCacheConfig::default())`
1744    /// - OpenAI / DeepSeek: no action needed (caching is automatic)
1745    /// - Gemini: handled separately via `ContextCacheConfig`
1746    pub auto_cache: bool,
1747    /// Maximum number of recent persisted events to load at the start of a run.
1748    ///
1749    /// `None` preserves the previous behavior and loads the full session
1750    /// history. Set this for chat surfaces that already summarize older turns
1751    /// and need predictable startup latency.
1752    pub history_max_events: Option<usize>,
1753    /// Tool concurrency configuration controlling parallel tool dispatch limits,
1754    /// per-tool overrides, and backpressure behavior.
1755    ///
1756    /// The default (`ToolConcurrencyConfig::default()`) imposes no limits,
1757    /// preserving backward compatibility with the previous `max_tool_concurrency: None`.
1758    pub tool_concurrency: ToolConcurrencyConfig,
1759    /// Whether tracing spans and the `llm_request` debug copy on model events
1760    /// may include the full request, response, and tool payloads when the
1761    /// `record-payloads` crate feature is enabled.
1762    pub record_payloads: bool,
1763    /// Maximum serialized bytes recorded for tracing payload fields, and for the
1764    /// `llm_request` debug copy on model events, when full payload recording is
1765    /// disabled.
1766    pub trace_payload_max_bytes: usize,
1767    /// Maximum number of agent-to-agent transfers allowed in a single run.
1768    ///
1769    /// Prevents infinite transfer loops when agents transfer back and forth.
1770    /// Defaults to 10 when `None`.
1771    pub max_transfer_depth: Option<u32>,
1772    /// Hooks applied to every model and tool call in the invocation, ahead of each agent's own
1773    /// callbacks.
1774    ///
1775    /// The runner prepends its plugin manager here at the start of each run. Because the
1776    /// `RunConfig` travels with the invocation, transfer targets and agents behind an agent tool
1777    /// run these hooks too. See [`InvocationHooks`](crate::InvocationHooks).
1778    pub invocation_hooks: Vec<Arc<dyn crate::InvocationHooks>>,
1779    /// Resource limits for the run. `Runner` creates a fresh
1780    /// [`budget_tracker`](Self::budget_tracker) from it for every run.
1781    pub budget: Option<crate::RunBudget>,
1782    /// Shared counters enforcing a budget across the invocation.
1783    ///
1784    /// `Runner` sets this from [`budget`](Self::budget) at the start of each run
1785    /// when it is `None`; a tracker that is already set is kept, so callers can
1786    /// share one tracker across runs. See [`crate::budget`].
1787    pub budget_tracker: Option<Arc<crate::BudgetTracker>>,
1788    /// Ledger that records non-idempotent tool calls so a replayed call never
1789    /// executes twice. `None` disables ledgering. See
1790    /// [`ActionLedger`](crate::ActionLedger).
1791    pub action_ledger: Option<Arc<dyn crate::ActionLedger>>,
1792    /// Policy evaluated for every tool call on its final arguments.
1793    ///
1794    /// `None` allows every call the agent's own confirmation settings allow. See
1795    /// [`ToolPolicy`](crate::ToolPolicy) and [`authorize_tool_call`](crate::authorize_tool_call).
1796    pub tool_policy: Option<Arc<dyn crate::ToolPolicy>>,
1797    /// The operator's network egress ceiling for tool calls.
1798    ///
1799    /// When set, [`authorize_tool_call`](crate::authorize_tool_call) refuses a call whose
1800    /// [`Tool::egress`](crate::Tool::egress) declaration the policy does not admit, and tools
1801    /// that open their own connections read it through
1802    /// [`ToolContext::egress_policy`](crate::ToolContext::egress_policy). `None` checks no
1803    /// declaration. Set it with [`RunConfigBuilder::egress_policy`] or the runner's builder,
1804    /// which narrow a policy already set rather than replace it. See
1805    /// [`egress`](crate::egress).
1806    pub egress_policy: Option<crate::egress::EgressPolicy>,
1807    /// Kill switches checked at run start, before each model call, and before each tool
1808    /// call, and watched while a call waits for a confirmation decision. The run stops when
1809    /// any of them is frozen.
1810    pub governance: Vec<crate::GovernanceControl>,
1811    /// Confirmation decisions keyed by tool-call fingerprint
1812    /// ([`ToolConfirmationRequest::fingerprint`]).
1813    ///
1814    /// A decision applies to every call in the run by the agent the fingerprint names, to
1815    /// a tool with the origin it names, with those canonical arguments, whatever its call
1816    /// ID, until it expires. Take the fingerprint from the request a held call surfaced, or
1817    /// build it with [`ToolConfirmationRequest::for_tool`] and
1818    /// [`with_acting_context`](ToolConfirmationRequest::with_acting_context). Record a
1819    /// decision in an [`approval_store`](Self::approval_store) instead for one that is
1820    /// consumed by the call it authorizes.
1821    ///
1822    /// A key that names no acting agent ([`ToolConfirmationRequest::fingerprint_agent`])
1823    /// matches no governed call. [`RunConfigBuilder::tool_approval`] refuses one.
1824    pub tool_approvals: HashMap<String, crate::ToolApproval>,
1825    /// Where calls held for approval are recorded, and decisions taken from, between runs.
1826    pub approval_store: Option<Arc<dyn crate::ApprovalStore>>,
1827    /// The approval inbox a call held for approval is submitted to, as an
1828    /// [`ApprovalRequest`](crate::ApprovalRequest) under the service's routing policy.
1829    ///
1830    /// Set it with [`RunConfigBuilder::approval_service`], which also installs the
1831    /// service's store as the [`approval_store`](Self::approval_store) the decisions are
1832    /// taken from.
1833    pub approval_service: Option<Arc<dyn crate::ApprovalService>>,
1834    /// The [`DurableRunStore`](crate::DurableRunStore) run this invocation executes, if
1835    /// any. Approval requests submitted during the run carry it, so a decision wakes the
1836    /// run instead of waiting for the next one.
1837    pub durable_run_id: Option<String>,
1838    /// The identity a server authenticated for this run, which replaces the runner's
1839    /// `request_context` for it (spec 3.1 §9.2 I6). The run's contexts then answer
1840    /// [`is_authenticated`](crate::ReadonlyContext::is_authenticated) with `true` and
1841    /// `user_scopes` with its scopes. Its `user_id` must be the run's user; the runner
1842    /// refuses a run whose request context names anyone else. `DurableWorker` sets it for
1843    /// a run enqueued by an authenticated caller ([`NewRun::authenticated`](crate::NewRun::authenticated)).
1844    pub request_context: Option<crate::RequestContext>,
1845    /// Request metadata the run carries without authenticating anyone, such as the thread
1846    /// or channel an anonymous visitor wrote in.
1847    ///
1848    /// Tools read it through `request_metadata()`, where the
1849    /// [`request_context`](Self::request_context)'s own metadata wins on a shared key.
1850    /// Unlike a request context, it never makes
1851    /// [`is_authenticated`](crate::ReadonlyContext::is_authenticated) answer `true`, sets
1852    /// no scopes, and names no user.
1853    pub request_metadata: HashMap<String, String>,
1854    /// The consent gate the run's tool calls and the runner read: a tool the gate names is
1855    /// refused without consent for its purpose, the runner refuses a run for a subject being
1856    /// erased, and the run's spans carry the user id only with consent for analytics.
1857    /// `None` gates nothing.
1858    pub consent_gate: Option<crate::subject::ConsentGate>,
1859    /// How long the [`tool_confirmation_handler`](Self::tool_confirmation_handler) may take
1860    /// to decide one call. A call it does not decide in time waits in the
1861    /// [`approval_store`](Self::approval_store) when the run has one, and is denied
1862    /// otherwise or under [`deny_on_confirmation_timeout`](Self::deny_on_confirmation_timeout).
1863    /// A freeze of the run's [`governance`](Self::governance) ends the wait sooner and
1864    /// refuses the call. Defaults to
1865    /// [`DEFAULT_TOOL_CONFIRMATION_TIMEOUT`](crate::DEFAULT_TOOL_CONFIRMATION_TIMEOUT).
1866    pub tool_confirmation_timeout: std::time::Duration,
1867    /// Ledger that model calls and payment tools reserve budget against.
1868    ///
1869    /// When set, every model call of the run reserves its upper-bound cost
1870    /// ([`Llm::max_cost_micro_usd`](crate::Llm::max_cost_micro_usd)) through a
1871    /// [`ModelCallScope`](crate::ModelCallScope) built from this config and commits its
1872    /// reported cost, and payment tools reserve checkout totals. See [`crate::SpendLedger`].
1873    pub spend_ledger: Option<Arc<dyn crate::SpendLedger>>,
1874    /// What a call to an unpriced model commits in the [`spend_ledger`](Self::spend_ledger)
1875    /// when its response reports no cost.
1876    ///
1877    /// `None` uses the runner's estimate (`Runner::with_llm_spend_estimate`), which the
1878    /// runner writes here at the start of each run, or
1879    /// [`LlmSpendEstimate::default`](crate::LlmSpendEstimate::default) outside a runner.
1880    pub llm_spend_estimate: Option<crate::LlmSpendEstimate>,
1881    /// Where the run writes audit records, and what happens when a record cannot be
1882    /// written.
1883    ///
1884    /// When set, the governed path records every tool decision (allowed, denied, held
1885    /// for approval) and every approval decision it applies, payment tools record each
1886    /// payment, and agents record calls answered with an unknown outcome. Records carry
1887    /// argument digests, never arguments. Under
1888    /// [`AuditFailureMode::Block`](crate::audit_log::AuditFailureMode::Block) an action
1889    /// whose record cannot be written does not happen. See
1890    /// [`AuditTrail`](crate::audit_log::AuditTrail).
1891    pub audit: Option<crate::audit_log::AuditTrail>,
1892    /// Who the run's agents act as, and for whom.
1893    ///
1894    /// Each agent acts as its entry in [`ActingConfig::principals`](crate::ActingConfig),
1895    /// or as `urn:adk:agent:{app}/{agent}`, on behalf of the session's user as
1896    /// [`ActingConfig::subject_kind`](crate::ActingConfig). At the start of each run the
1897    /// runner adds the principals its [`IdentitySource`](crate::IdentitySource) gives the
1898    /// root agent and the agents it maps, and refuses a run whose
1899    /// [`on_behalf_of`](crate::ActingConfig::on_behalf_of) names a subject other than the
1900    /// session's user unless a [`SubjectDelegationPolicy`](crate::SubjectDelegationPolicy)
1901    /// allows it. An agent tool delegating to another agent sets the delegate's principal
1902    /// and appends the delegating agent to the delegation chain.
1903    /// See [`acting_context_for`](Self::acting_context_for).
1904    pub acting: crate::ActingConfig,
1905    /// Deny a call whose [`tool_confirmation_handler`](Self::tool_confirmation_handler) does
1906    /// not decide within [`tool_confirmation_timeout`](Self::tool_confirmation_timeout), even
1907    /// when the run has an [`approval_store`](Self::approval_store).
1908    ///
1909    /// `false` (the default) holds such a call in the store instead: it is recorded as
1910    /// pending and submitted to the [`approval_service`](Self::approval_service), if any, the
1911    /// run ends with it waiting, and a decision recorded for it later resumes it, so nothing
1912    /// is decided by silence (spec 3.3 §7.3, §10 C2). A run without a store — including one
1913    /// with only an approval service, whose decisions it cannot read — denies the call
1914    /// either way.
1915    pub deny_on_confirmation_timeout: bool,
1916    /// A tool call a person asked for through something an agent drew, which this run
1917    /// holds for their decision before any model call (spec 3.3 §7.4 rule 5).
1918    ///
1919    /// The run's root `LlmAgent` takes it once, after resuming held calls: it refuses a tool
1920    /// outside its own toolset, a `kernel_*` tool or a tool that draws, checks the arguments
1921    /// against the tool's parameters, runs the before-tool stages a model's call passes, and
1922    /// authorizes the call as [`GovernedCall::requested`](crate::GovernedCall::requested), so
1923    /// an earlier approval or the confirmation handler never answers it. The call is held as
1924    /// the agent, or refused, and the run ends without a model call. A run that is not
1925    /// authenticated, or whose user is not the person who asked, has it refused. A root that
1926    /// cannot hold a call refuses it before anything else runs: `CodeActAgent`, the workflow
1927    /// agents, teams and `GraphAgent` do; another [`Agent`] answers it with
1928    /// [`RequestedCall::refusal_events`](crate::RequestedCall::refusal_events).
1929    pub requested_call: Option<crate::RequestedCall>,
1930    /// When the run's agents compact their history before a model call.
1931    ///
1932    /// `None` uses the runner's setting, which is on by default
1933    /// ([`IntraCompactionConfig::default`](crate::IntraCompactionConfig)): a request is
1934    /// compacted once it nears the model's context window.
1935    /// `Some(IntraCompactionConfig::disabled())` turns it off for this run.
1936    pub intra_compaction: Option<crate::IntraCompactionConfig>,
1937    /// The compactor the run's agents call before each model call, and once after a model
1938    /// rejects a request as longer than its context window.
1939    ///
1940    /// At the start of each run the runner installs its own, built from
1941    /// [`intra_compaction`](Self::intra_compaction) or the runner's setting, when this is
1942    /// `None` and compaction is enabled. A compactor already set is kept, so a caller can
1943    /// supply its own. Transfer targets, workflow sub-agents and agent tools inherit it with
1944    /// the config. See [`HistoryCompactor`](crate::HistoryCompactor).
1945    pub history_compactor: Option<Arc<dyn crate::HistoryCompactor>>,
1946}
1947
1948impl Default for RunConfig {
1949    fn default() -> Self {
1950        Self {
1951            streaming_mode: StreamingMode::SSE,
1952            tool_confirmation_decisions: HashMap::new(),
1953            tool_confirmation_fingerprints: HashMap::new(),
1954            tool_confirmation_handler: None,
1955            tool_reviewer: None,
1956            requested_call_seal: None,
1957            runtime_toolsets: Vec::new(),
1958            cached_content: None,
1959            transfer_targets: Vec::new(),
1960            transfer_target_descriptions: HashMap::new(),
1961            parent_agent: None,
1962            auto_cache: true,
1963            history_max_events: None,
1964            tool_concurrency: ToolConcurrencyConfig::default(),
1965            record_payloads: false,
1966            trace_payload_max_bytes: 2048,
1967            max_transfer_depth: None,
1968            invocation_hooks: Vec::new(),
1969            budget: None,
1970            budget_tracker: None,
1971            action_ledger: None,
1972            tool_policy: None,
1973            egress_policy: None,
1974            governance: Vec::new(),
1975            tool_approvals: HashMap::new(),
1976            approval_store: None,
1977            approval_service: None,
1978            durable_run_id: None,
1979            request_context: None,
1980            request_metadata: HashMap::new(),
1981            consent_gate: None,
1982            tool_confirmation_timeout: crate::DEFAULT_TOOL_CONFIRMATION_TIMEOUT,
1983            spend_ledger: None,
1984            llm_spend_estimate: None,
1985            audit: None,
1986            acting: crate::ActingConfig::default(),
1987            deny_on_confirmation_timeout: false,
1988            requested_call: None,
1989            intra_compaction: None,
1990            history_compactor: None,
1991        }
1992    }
1993}
1994
1995impl RunConfig {
1996    /// Creates a new [`RunConfigBuilder`] initialized with default values.
1997    ///
1998    /// Use the builder to construct a `RunConfig` when struct literal syntax
1999    ///
2000    /// # Example
2001    ///
2002    /// ```rust
2003    /// use adk_core::{RunConfig, StreamingMode};
2004    ///
2005    /// let config = RunConfig::builder()
2006    ///     .streaming_mode(StreamingMode::None)
2007    ///     .auto_cache(false)
2008    ///     .build();
2009    ///
2010    /// assert_eq!(config.streaming_mode, StreamingMode::None);
2011    /// assert!(!config.auto_cache);
2012    /// ```
2013    pub fn builder() -> RunConfigBuilder {
2014        RunConfigBuilder::default()
2015    }
2016
2017    /// Returns an error when any of the run's [`governance`](Self::governance) controls
2018    /// is frozen.
2019    ///
2020    /// # Errors
2021    ///
2022    /// Returns the frozen control's `governance.frozen` error.
2023    pub fn check_governance(&self) -> Result<()> {
2024        self.governance.iter().try_for_each(crate::GovernanceControl::check)
2025    }
2026
2027    /// Waits until any of the run's [`governance`](Self::governance) controls refuses work,
2028    /// and returns its error, as [`check_governance`](Self::check_governance) would give it.
2029    ///
2030    /// Never resolves for a run without a control. See
2031    /// [`GovernanceControl::refused`](crate::GovernanceControl::refused).
2032    ///
2033    /// # Example
2034    ///
2035    /// ```rust
2036    /// use adk_core::{GOVERNANCE_FROZEN_CODE, GovernanceControl, RunConfig};
2037    ///
2038    /// # #[tokio::main(flavor = "current_thread")]
2039    /// # async fn main() {
2040    /// let control = GovernanceControl::new();
2041    /// let config = RunConfig::builder().governance(control.clone()).build();
2042    /// control.freeze("incident 4012");
2043    /// assert_eq!(config.governance_refused().await.code, GOVERNANCE_FROZEN_CODE);
2044    /// # }
2045    /// ```
2046    pub async fn governance_refused(&self) -> crate::AdkError {
2047        if self.governance.is_empty() {
2048            return std::future::pending().await;
2049        }
2050        let waits = self.governance.iter().map(|control| Box::pin(control.refused()));
2051        futures::future::select_all(waits).await.0
2052    }
2053
2054    /// The acting context of the agent named `agent_name` running for `user_id`.
2055    ///
2056    /// See [`ActingConfig::acting_context_for`](crate::ActingConfig::acting_context_for).
2057    ///
2058    /// # Example
2059    ///
2060    /// ```rust
2061    /// use adk_core::{AgentId, AgentPrincipal, RunConfig, SubjectRef};
2062    ///
2063    /// let derived = RunConfig::default().acting_context_for("shop", "cashier", "alice");
2064    /// assert_eq!(derived.agent.id.as_str(), "urn:adk:agent:shop/cashier");
2065    ///
2066    /// let config = RunConfig::builder()
2067    ///     .agent_principal("cashier", AgentPrincipal::new(AgentId::new("spiffe://shop/cashier")?))
2068    ///     .build();
2069    /// let configured = config.acting_context_for("shop", "cashier", "alice");
2070    /// assert_eq!(configured.agent.id.as_str(), "spiffe://shop/cashier");
2071    /// assert_eq!(configured.on_behalf_of, Some(SubjectRef::human("alice")));
2072    /// assert_eq!(
2073    ///     config.acting_context_for("shop", "stocker", "alice").agent.id.as_str(),
2074    ///     "urn:adk:agent:shop/stocker"
2075    /// );
2076    /// # Ok::<(), adk_core::AdkError>(())
2077    /// ```
2078    pub fn acting_context_for(
2079        &self,
2080        app_name: &str,
2081        agent_name: &str,
2082        user_id: &str,
2083    ) -> crate::ActingContext {
2084        self.acting.acting_context_for(app_name, agent_name, user_id)
2085    }
2086}
2087
2088/// Builder for [`RunConfig`].
2089///
2090/// Provides a fluent API for constructing `RunConfig` instances. All fields
2091/// start with their default values and can be overridden individually.
2092///
2093/// # Example
2094///
2095/// ```rust
2096/// use adk_core::{RunConfig, RunConfigBuilder, StreamingMode, ToolConcurrencyConfig};
2097///
2098/// let config = RunConfigBuilder::default()
2099///     .streaming_mode(StreamingMode::Bidi)
2100///     .history_max_events(Some(50))
2101///     .build();
2102/// ```
2103#[derive(Debug, Clone, Default)]
2104pub struct RunConfigBuilder {
2105    config: RunConfig,
2106}
2107
2108impl RunConfigBuilder {
2109    /// Sets the streaming mode for the run.
2110    pub fn streaming_mode(mut self, mode: StreamingMode) -> Self {
2111        self.config.streaming_mode = mode;
2112        self
2113    }
2114
2115    /// Sets static confirmation decisions for the current run, keyed by function
2116    /// call ID.
2117    ///
2118    /// The ID is the one carried on `ToolConfirmationRequest::function_call_id`.
2119    pub fn tool_confirmation_decisions(
2120        mut self,
2121        decisions: HashMap<String, ToolConfirmationDecision>,
2122    ) -> Self {
2123        self.config.tool_confirmation_decisions = decisions;
2124        self
2125    }
2126
2127    /// Binds confirmation decisions to the agent, tool, and arguments they were granted for.
2128    ///
2129    /// Keys are function call IDs and values are the [`ToolConfirmationRequest::fingerprint`]
2130    /// of the request each decision answers. A decision whose fingerprint does not match
2131    /// the actual call is ignored and the call is treated as unconfirmed.
2132    ///
2133    /// A binding whose fingerprint names no acting agent
2134    /// ([`ToolConfirmationRequest::fingerprint_agent`]) matches no governed call, so the
2135    /// decision it binds is never applied; each one is logged with `tracing::warn!`.
2136    pub fn tool_confirmation_fingerprints(mut self, fingerprints: HashMap<String, String>) -> Self {
2137        for (call_id, fingerprint) in &fingerprints {
2138            if ToolConfirmationRequest::fingerprint_agent(fingerprint).is_none() {
2139                tracing::warn!(
2140                    function_call.id = %call_id,
2141                    "confirmation decision bound to a fingerprint that names no acting agent; \
2142                     it never applies. Bind it to the fingerprint of the request the call \
2143                     surfaced"
2144                );
2145            }
2146        }
2147        self.config.tool_confirmation_fingerprints = fingerprints;
2148        self
2149    }
2150
2151    /// Sets an asynchronous tool confirmation handler for the current run.
2152    pub fn tool_confirmation_handler(mut self, handler: Arc<dyn ToolConfirmationHandler>) -> Self {
2153        self.config.tool_confirmation_handler = Some(handler);
2154        self
2155    }
2156
2157    /// Sets the reviewer that decides held calls before a person is asked. See
2158    /// [`RunConfig::tool_reviewer`].
2159    ///
2160    /// # Example
2161    ///
2162    /// ```rust
2163    /// use std::sync::Arc;
2164    /// use adk_core::principal::SubjectRef;
2165    /// use adk_core::{Result, ReviewVerdict, RunConfig, ToolReview, ToolReviewer, async_trait};
2166    ///
2167    /// #[derive(Debug)]
2168    /// struct Escalates;
2169    ///
2170    /// #[async_trait]
2171    /// impl ToolReviewer for Escalates {
2172    ///     fn reviewer(&self) -> SubjectRef {
2173    ///         SubjectRef::service("rules:escalate")
2174    ///     }
2175    ///     async fn review(&self, _review: &ToolReview) -> Result<ReviewVerdict> {
2176    ///         Ok(ReviewVerdict::escalate("a person decides"))
2177    ///     }
2178    /// }
2179    ///
2180    /// let config = RunConfig::builder().tool_reviewer(Arc::new(Escalates)).build();
2181    /// assert!(config.tool_reviewer.is_some());
2182    /// ```
2183    pub fn tool_reviewer(mut self, reviewer: Arc<dyn crate::ToolReviewer>) -> Self {
2184        self.config.tool_reviewer = Some(reviewer);
2185        self
2186    }
2187
2188    /// Adds a toolset that is resolved only for this runner invocation.
2189    pub fn runtime_toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
2190        self.config.runtime_toolsets.push(RuntimeToolset::new(toolset));
2191        self
2192    }
2193
2194    /// Adds several toolsets that are resolved only for this runner invocation.
2195    pub fn runtime_toolsets(
2196        mut self,
2197        toolsets: impl IntoIterator<Item = Arc<dyn Toolset>>,
2198    ) -> Self {
2199        self.config.runtime_toolsets.extend(toolsets.into_iter().map(RuntimeToolset::new));
2200        self
2201    }
2202
2203    /// Sets the cached content name for automatic prompt caching.
2204    pub fn cached_content(mut self, name: impl Into<String>) -> Self {
2205        self.config.cached_content = Some(name.into());
2206        self
2207    }
2208
2209    /// Sets the valid agent names this agent can transfer to.
2210    pub fn transfer_targets(mut self, targets: Vec<String>) -> Self {
2211        self.config.transfer_targets = targets;
2212        self
2213    }
2214
2215    /// Sets the parent agent name.
2216    pub fn parent_agent(mut self, name: impl Into<String>) -> Self {
2217        self.config.parent_agent = Some(name.into());
2218        self
2219    }
2220
2221    /// Enables or disables automatic prompt caching for supported providers.
2222    pub fn auto_cache(mut self, enabled: bool) -> Self {
2223        self.config.auto_cache = enabled;
2224        self
2225    }
2226
2227    /// Sets the maximum number of recent persisted events to load at run start.
2228    pub fn history_max_events(mut self, max: Option<usize>) -> Self {
2229        self.config.history_max_events = max;
2230        self
2231    }
2232
2233    /// Sets the tool concurrency configuration.
2234    pub fn tool_concurrency(mut self, config: ToolConcurrencyConfig) -> Self {
2235        self.config.tool_concurrency = config;
2236        self
2237    }
2238
2239    /// Enables or disables full payload recording in tracing spans.
2240    pub fn record_payloads(mut self, enabled: bool) -> Self {
2241        self.config.record_payloads = enabled;
2242        self
2243    }
2244
2245    /// Sets the maximum serialized bytes for tracing payload fields.
2246    pub fn trace_payload_max_bytes(mut self, max: usize) -> Self {
2247        self.config.trace_payload_max_bytes = max;
2248        self
2249    }
2250
2251    /// Sets the maximum number of agent-to-agent transfers allowed in a single run.
2252    ///
2253    /// Prevents infinite transfer loops. Defaults to 10 when `None`.
2254    pub fn max_transfer_depth(mut self, depth: u32) -> Self {
2255        self.config.max_transfer_depth = Some(depth);
2256        self
2257    }
2258
2259    /// Sets when the run's agents compact their history, in place of the runner's setting.
2260    ///
2261    /// See [`RunConfig::intra_compaction`].
2262    ///
2263    /// # Example
2264    ///
2265    /// ```rust
2266    /// use adk_core::{IntraCompactionConfig, RunConfig};
2267    ///
2268    /// let config = RunConfig::builder().intra_compaction(IntraCompactionConfig::disabled()).build();
2269    /// assert_eq!(config.intra_compaction, Some(IntraCompactionConfig::disabled()));
2270    /// ```
2271    pub fn intra_compaction(mut self, config: crate::IntraCompactionConfig) -> Self {
2272        self.config.intra_compaction = Some(config);
2273        self
2274    }
2275
2276    /// Sets the compactor the run's agents call before each model call.
2277    ///
2278    /// See [`RunConfig::history_compactor`].
2279    pub fn history_compactor(mut self, compactor: Arc<dyn crate::HistoryCompactor>) -> Self {
2280        self.config.history_compactor = Some(compactor);
2281        self
2282    }
2283
2284    /// Appends a hook applied to every model and tool call in the invocation.
2285    ///
2286    /// See [`RunConfig::invocation_hooks`].
2287    pub fn invocation_hook(mut self, hook: Arc<dyn crate::InvocationHooks>) -> Self {
2288        self.config.invocation_hooks.push(hook);
2289        self
2290    }
2291
2292    /// Sets the resource limits for the run.
2293    ///
2294    /// See [`RunConfig::budget`] and [`crate::budget`].
2295    pub fn budget(mut self, budget: crate::RunBudget) -> Self {
2296        self.config.budget = Some(budget);
2297        self
2298    }
2299
2300    /// Sets the ledger that records non-idempotent tool calls.
2301    ///
2302    /// See [`RunConfig::action_ledger`].
2303    pub fn action_ledger(mut self, ledger: Arc<dyn crate::ActionLedger>) -> Self {
2304        self.config.action_ledger = Some(ledger);
2305        self
2306    }
2307
2308    /// Sets the policy evaluated for every tool call. See [`RunConfig::tool_policy`].
2309    pub fn tool_policy(mut self, policy: Arc<dyn crate::ToolPolicy>) -> Self {
2310        self.config.tool_policy = Some(policy);
2311        self
2312    }
2313
2314    /// Sets the run's egress policy, or narrows the one already set to the intersection of
2315    /// both. See [`RunConfig::egress_policy`].
2316    ///
2317    /// # Example
2318    ///
2319    /// ```rust
2320    /// use adk_core::RunConfig;
2321    /// use adk_core::egress::EgressPolicy;
2322    ///
2323    /// let config = RunConfig::builder()
2324    ///     .egress_policy(EgressPolicy::allowlist(["*.example.com:443"]).unwrap())
2325    ///     .egress_policy(EgressPolicy::allowlist(["api.example.com"]).unwrap())
2326    ///     .build();
2327    /// let policy = config.egress_policy.unwrap();
2328    /// assert!(policy.check_url("https://api.example.com/").is_ok());
2329    /// assert!(policy.check_url("https://www.example.com/").is_err());
2330    /// ```
2331    pub fn egress_policy(mut self, policy: crate::egress::EgressPolicy) -> Self {
2332        self.config.egress_policy = Some(match self.config.egress_policy.take() {
2333            Some(existing) => existing.narrow(&policy),
2334            None => policy,
2335        });
2336        self
2337    }
2338
2339    /// Adds a kill switch the run checks. See [`RunConfig::governance`].
2340    pub fn governance(mut self, control: crate::GovernanceControl) -> Self {
2341        if !self.config.governance.iter().any(|existing| existing.same_as(&control)) {
2342            self.config.governance.push(control);
2343        }
2344        self
2345    }
2346
2347    /// Records a decision for the call with `fingerprint`. See [`RunConfig::tool_approvals`].
2348    ///
2349    /// A fingerprint that names no acting agent
2350    /// ([`ToolConfirmationRequest::fingerprint_agent`]) is refused: it could never authorize
2351    /// a governed call, so the decision is not recorded and the refusal is logged with
2352    /// `tracing::warn!`.
2353    ///
2354    /// # Example
2355    ///
2356    /// ```rust
2357    /// use adk_core::principal::{ActingContext, AgentPrincipal};
2358    /// use adk_core::{RunConfig, ToolApproval, ToolConfirmationRequest};
2359    /// use serde_json::json;
2360    ///
2361    /// let call = ToolConfirmationRequest::new("transfer", json!({ "amount": 40 }));
2362    /// let owned = call
2363    ///     .clone()
2364    ///     .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
2365    ///
2366    /// let config = RunConfig::builder()
2367    ///     .tool_approval(owned.fingerprint(), ToolApproval::approve())
2368    ///     .tool_approval(call.fingerprint(), ToolApproval::approve())
2369    ///     .build();
2370    /// assert_eq!(config.tool_approvals.keys().collect::<Vec<_>>(), [&owned.fingerprint()]);
2371    /// ```
2372    pub fn tool_approval(
2373        mut self,
2374        fingerprint: impl Into<String>,
2375        approval: crate::ToolApproval,
2376    ) -> Self {
2377        let fingerprint = fingerprint.into();
2378        if ToolConfirmationRequest::fingerprint_agent(&fingerprint).is_none() {
2379            tracing::warn!(
2380                "tool approval refused: its fingerprint names no acting agent, so it could \
2381                 never authorize a governed call. Build it from the request the call surfaced, \
2382                 or with ToolConfirmationRequest::with_acting_context"
2383            );
2384            return self;
2385        }
2386        self.config.tool_approvals.insert(fingerprint, approval);
2387        self
2388    }
2389
2390    /// Sets where held calls and their decisions are kept between runs.
2391    pub fn approval_store(mut self, store: Arc<dyn crate::ApprovalStore>) -> Self {
2392        self.config.approval_store = Some(store);
2393        self
2394    }
2395
2396    /// Sets the call a person asked for, which the run holds for their decision before any
2397    /// model call. See [`RunConfig::requested_call`] (spec 3.3 §7.4 rule 5).
2398    ///
2399    /// # Example
2400    ///
2401    /// ```rust
2402    /// use adk_core::{RequestedCall, RequestedVia, RunConfig, SubjectRef};
2403    /// use serde_json::json;
2404    ///
2405    /// let call = RequestedCall::new(
2406    ///     "send_invoice",
2407    ///     json!({ "to": "ana@example.com" }),
2408    ///     SubjectRef::human("ana"),
2409    ///     RequestedVia::form("invoice-10", 1, "send"),
2410    /// );
2411    /// let config = RunConfig::builder().requested_call(call.clone()).build();
2412    /// assert_eq!(config.requested_call, Some(call));
2413    /// ```
2414    pub fn requested_call(mut self, call: crate::RequestedCall) -> Self {
2415        self.config.requested_call = Some(call);
2416        self
2417    }
2418
2419    /// Submits calls held for approval to `service`, and takes their decisions from the
2420    /// service's store unless an [`approval_store`](Self::approval_store) is already set.
2421    ///
2422    /// See [`RunConfig::approval_service`].
2423    pub fn approval_service(mut self, service: Arc<dyn crate::ApprovalService>) -> Self {
2424        if self.config.approval_store.is_none() {
2425            self.config.approval_store = service.approval_store();
2426        }
2427        self.config.approval_service = Some(service);
2428        self
2429    }
2430
2431    /// Records the durable run this invocation executes. See [`RunConfig::durable_run_id`].
2432    pub fn durable_run_id(mut self, run_id: impl Into<String>) -> Self {
2433        self.config.durable_run_id = Some(run_id.into());
2434        self
2435    }
2436
2437    /// Runs as the identity a server authenticated. See [`RunConfig::request_context`].
2438    ///
2439    /// # Example
2440    ///
2441    /// ```rust
2442    /// use adk_core::{RequestContext, RunConfig};
2443    ///
2444    /// let config = RunConfig::builder()
2445    ///     .request_context(RequestContext {
2446    ///         user_id: "alice".to_string(),
2447    ///         scopes: vec![],
2448    ///         metadata: Default::default(),
2449    ///     })
2450    ///     .build();
2451    /// assert_eq!(config.request_context.map(|context| context.user_id).as_deref(), Some("alice"));
2452    /// ```
2453    pub fn request_context(mut self, request_context: crate::RequestContext) -> Self {
2454        self.config.request_context = Some(request_context);
2455        self
2456    }
2457
2458    /// Adds one entry of request metadata that authenticates no one. See
2459    /// [`RunConfig::request_metadata`].
2460    ///
2461    /// # Example
2462    ///
2463    /// ```rust
2464    /// use adk_core::RunConfig;
2465    ///
2466    /// let config = RunConfig::builder().request_metadata("thread", "chat-7").build();
2467    /// assert_eq!(config.request_metadata.get("thread").map(String::as_str), Some("chat-7"));
2468    /// assert!(config.request_context.is_none());
2469    /// ```
2470    pub fn request_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
2471        self.config.request_metadata.insert(key.into(), value.into());
2472        self
2473    }
2474
2475    /// Sets the consent gate. See [`RunConfig::consent_gate`].
2476    ///
2477    /// # Example
2478    ///
2479    /// ```rust
2480    /// use std::sync::Arc;
2481    /// use adk_core::RunConfig;
2482    /// use adk_core::subject::{ConsentGate, ConsentPurpose, InMemoryConsentStore};
2483    ///
2484    /// let gate = ConsentGate::new(Arc::new(InMemoryConsentStore::new()))
2485    ///     .with_tool("subscribe", ConsentPurpose::Newsletter);
2486    /// let config = RunConfig::builder().consent_gate(gate).build();
2487    /// assert!(config.consent_gate.is_some());
2488    /// ```
2489    pub fn consent_gate(mut self, gate: crate::subject::ConsentGate) -> Self {
2490        self.config.consent_gate = Some(gate);
2491        self
2492    }
2493
2494    /// Sets how long the confirmation handler may take to decide one call.
2495    pub fn tool_confirmation_timeout(mut self, timeout: std::time::Duration) -> Self {
2496        self.config.tool_confirmation_timeout = timeout;
2497        self
2498    }
2499
2500    /// Denies a call the confirmation handler does not decide in time, instead of holding
2501    /// it in the run's approval store (spec 3.3 §10 C2).
2502    ///
2503    /// See [`RunConfig::deny_on_confirmation_timeout`].
2504    ///
2505    /// # Example
2506    ///
2507    /// ```rust
2508    /// use adk_core::RunConfig;
2509    ///
2510    /// assert!(!RunConfig::default().deny_on_confirmation_timeout);
2511    /// let config = RunConfig::builder().deny_on_confirmation_timeout(true).build();
2512    /// assert!(config.deny_on_confirmation_timeout);
2513    /// ```
2514    pub fn deny_on_confirmation_timeout(mut self, deny: bool) -> Self {
2515        self.config.deny_on_confirmation_timeout = deny;
2516        self
2517    }
2518
2519    /// Sets the ledger that model calls and payment tools reserve budget against.
2520    ///
2521    /// See [`RunConfig::spend_ledger`].
2522    pub fn spend_ledger(mut self, ledger: Arc<dyn crate::SpendLedger>) -> Self {
2523        self.config.spend_ledger = Some(ledger);
2524        self
2525    }
2526
2527    /// Records the run's governed actions through `audit`. See [`RunConfig::audit`].
2528    pub fn audit(mut self, audit: crate::audit_log::AuditTrail) -> Self {
2529        self.config.audit = Some(audit);
2530        self
2531    }
2532
2533    /// Sets the hold reserved in the spend ledger before each model call.
2534    ///
2535    /// See [`RunConfig::llm_spend_estimate`].
2536    pub fn llm_spend_estimate(mut self, estimate: crate::LlmSpendEstimate) -> Self {
2537        self.config.llm_spend_estimate = Some(estimate);
2538        self
2539    }
2540
2541    /// Sets who the run's agents act as, and for whom. See [`RunConfig::acting`].
2542    pub fn acting(mut self, acting: crate::ActingConfig) -> Self {
2543        self.config.acting = acting;
2544        self
2545    }
2546
2547    /// Sets the principal the agent named `agent_name` acts as. See [`RunConfig::acting`].
2548    pub fn agent_principal(
2549        mut self,
2550        agent_name: impl Into<String>,
2551        principal: crate::AgentPrincipal,
2552    ) -> Self {
2553        self.config.acting.principals.insert(agent_name.into(), principal);
2554        self
2555    }
2556
2557    /// Sets what kind of subject the session's user is. See [`RunConfig::acting`].
2558    pub fn subject_kind(mut self, kind: crate::SubjectKind) -> Self {
2559        self.config.acting.subject_kind = kind;
2560        self
2561    }
2562
2563    /// Asks the run to act for `subject`; the runner refuses the run unless `subject` is
2564    /// the session's user or a [`SubjectDelegationPolicy`](crate::SubjectDelegationPolicy)
2565    /// allows it. See [`RunConfig::acting`].
2566    pub fn on_behalf_of(mut self, subject: crate::SubjectRef) -> Self {
2567        self.config.acting.on_behalf_of = Some(subject);
2568        self
2569    }
2570
2571    /// Consumes the builder and returns the configured [`RunConfig`].
2572    pub fn build(self) -> RunConfig {
2573        self.config
2574    }
2575}
2576
2577#[cfg(test)]
2578mod tests {
2579    use super::*;
2580
2581    #[test]
2582    fn test_run_config_default() {
2583        let config = RunConfig::default();
2584        assert_eq!(config.streaming_mode, StreamingMode::SSE);
2585        assert_eq!(config.history_max_events, None);
2586        assert_eq!(config.tool_concurrency.max_concurrency, None);
2587        assert!(config.tool_concurrency.per_tool.is_empty());
2588        assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Queue);
2589        assert!(!config.record_payloads);
2590        assert_eq!(config.trace_payload_max_bytes, 2048);
2591        assert!(config.tool_confirmation_decisions.is_empty());
2592        assert_eq!(config.max_transfer_depth, None);
2593        assert!(config.invocation_hooks.is_empty());
2594        assert!(config.action_ledger.is_none());
2595    }
2596
2597    #[test]
2598    fn test_streaming_mode() {
2599        assert_eq!(StreamingMode::SSE, StreamingMode::SSE);
2600        assert_ne!(StreamingMode::SSE, StreamingMode::None);
2601        assert_ne!(StreamingMode::None, StreamingMode::Bidi);
2602    }
2603
2604    #[test]
2605    fn test_tool_confirmation_policy() {
2606        let policy = ToolConfirmationPolicy::default();
2607        assert!(!policy.requires_confirmation("search"));
2608
2609        let policy = policy.with_tool("search");
2610        assert!(policy.requires_confirmation("search"));
2611        assert!(!policy.requires_confirmation("write_file"));
2612
2613        assert!(ToolConfirmationPolicy::Always.requires_confirmation("any_tool"));
2614    }
2615
2616    #[test]
2617    fn test_validate_state_key_valid() {
2618        assert!(validate_state_key("user_name").is_ok());
2619        assert!(validate_state_key("app:config").is_ok());
2620        assert!(validate_state_key("temp:data").is_ok());
2621        assert!(validate_state_key("a").is_ok());
2622    }
2623
2624    #[test]
2625    fn test_validate_state_key_empty() {
2626        assert_eq!(validate_state_key(""), Err("state key must not be empty"));
2627    }
2628
2629    #[test]
2630    fn test_validate_state_key_too_long() {
2631        let long_key = "a".repeat(MAX_STATE_KEY_LEN + 1);
2632        assert!(validate_state_key(&long_key).is_err());
2633    }
2634
2635    #[test]
2636    fn test_validate_state_key_path_traversal() {
2637        assert!(validate_state_key("../etc/passwd").is_err());
2638        assert!(validate_state_key("foo/bar").is_err());
2639        assert!(validate_state_key("foo\\bar").is_err());
2640        assert!(validate_state_key("..").is_err());
2641    }
2642
2643    #[test]
2644    fn test_validate_state_key_null_byte() {
2645        assert!(validate_state_key("foo\0bar").is_err());
2646    }
2647
2648    #[test]
2649    fn fingerprint_agent_reads_the_acting_agent_of_a_request_fingerprint() {
2650        use crate::principal::{ActingContext, AgentPrincipal};
2651        let args = serde_json::json!({ "amount": 40 });
2652        let call = ToolConfirmationRequest::new("pay", args.clone());
2653        let owned = call
2654            .clone()
2655            .with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
2656        let published =
2657            owned.clone().with_origin(ToolOrigin::new("mcp:bank", &serde_json::json!({}), None));
2658
2659        let agent = ToolConfirmationRequest::fingerprint_agent;
2660        assert_eq!(agent(&owned.fingerprint()), Some("urn:adk:agent:ops/treasurer"));
2661        assert_eq!(agent(&published.fingerprint()), Some("urn:adk:agent:ops/treasurer"));
2662        assert_eq!(agent(&call.fingerprint()), None);
2663        assert_eq!(agent(&call.with_origin(published.origin.unwrap()).fingerprint()), None);
2664        assert_eq!(agent(&tool_call_fingerprint("pay", &args)), None);
2665        assert_eq!(agent(""), None);
2666    }
2667
2668    #[test]
2669    fn test_run_config_builder_defaults() {
2670        let config = RunConfig::builder().build();
2671        let default = RunConfig::default();
2672        assert_eq!(config.streaming_mode, default.streaming_mode);
2673        assert_eq!(config.auto_cache, default.auto_cache);
2674        assert_eq!(config.history_max_events, default.history_max_events);
2675        assert_eq!(config.record_payloads, default.record_payloads);
2676        assert_eq!(config.trace_payload_max_bytes, default.trace_payload_max_bytes);
2677        assert!(config.tool_confirmation_decisions.is_empty());
2678        assert!(config.transfer_targets.is_empty());
2679        assert!(config.cached_content.is_none());
2680        assert!(config.parent_agent.is_none());
2681    }
2682
2683    #[test]
2684    fn test_run_config_builder_all_fields() {
2685        let mut decisions = HashMap::new();
2686        decisions.insert("delete".to_string(), ToolConfirmationDecision::Approve);
2687
2688        let config = RunConfig::builder()
2689            .streaming_mode(StreamingMode::None)
2690            .tool_confirmation_decisions(decisions.clone())
2691            .cached_content("my-cache")
2692            .transfer_targets(vec!["agent_a".to_string(), "agent_b".to_string()])
2693            .parent_agent("parent")
2694            .auto_cache(false)
2695            .history_max_events(Some(50))
2696            .tool_concurrency(ToolConcurrencyConfig {
2697                max_concurrency: Some(4),
2698                per_tool: HashMap::new(),
2699                backpressure: BackpressurePolicy::Fail,
2700            })
2701            .record_payloads(true)
2702            .trace_payload_max_bytes(4096)
2703            .build();
2704
2705        assert_eq!(config.streaming_mode, StreamingMode::None);
2706        assert_eq!(config.tool_confirmation_decisions, decisions);
2707        assert_eq!(config.cached_content.as_deref(), Some("my-cache"));
2708        assert_eq!(config.transfer_targets, vec!["agent_a", "agent_b"]);
2709        assert_eq!(config.parent_agent.as_deref(), Some("parent"));
2710        assert!(!config.auto_cache);
2711        assert_eq!(config.history_max_events, Some(50));
2712        assert_eq!(config.tool_concurrency.max_concurrency, Some(4));
2713        assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Fail);
2714        assert!(config.record_payloads);
2715        assert_eq!(config.trace_payload_max_bytes, 4096);
2716    }
2717}