use crate::identity::{AdkIdentity, AppName, ExecutionIdentity, InvocationId, SessionId, UserId};
use crate::{AdkError, Agent, Result, ToolApproval, Toolset, types::Content};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum BackpressurePolicy {
#[default]
Queue,
Fail,
}
#[derive(Debug, Clone, Default)]
pub struct ToolConcurrencyConfig {
pub max_concurrency: Option<usize>,
pub per_tool: HashMap<String, usize>,
pub backpressure: BackpressurePolicy,
}
#[async_trait]
pub trait ReadonlyContext: Send + Sync {
fn invocation_id(&self) -> &str;
fn agent_name(&self) -> &str;
fn user_id(&self) -> &str;
fn app_name(&self) -> &str;
fn session_id(&self) -> &str;
fn branch(&self) -> &str;
fn user_content(&self) -> &Content;
fn acting_context(&self) -> crate::ActingContext {
crate::ActingContext::derived(
self.app_name(),
self.agent_name(),
self.user_id(),
crate::SubjectKind::Human,
)
}
fn is_authenticated(&self) -> bool {
false
}
fn state(&self) -> Option<&dyn State> {
None
}
fn try_app_name(&self) -> Result<AppName> {
Ok(AppName::try_from(self.app_name())?)
}
fn try_user_id(&self) -> Result<UserId> {
Ok(UserId::try_from(self.user_id())?)
}
fn try_session_id(&self) -> Result<SessionId> {
Ok(SessionId::try_from(self.session_id())?)
}
fn try_invocation_id(&self) -> Result<InvocationId> {
Ok(InvocationId::try_from(self.invocation_id())?)
}
fn try_identity(&self) -> Result<AdkIdentity> {
Ok(AdkIdentity {
app_name: self.try_app_name()?,
user_id: self.try_user_id()?,
session_id: self.try_session_id()?,
})
}
fn try_execution_identity(&self) -> Result<ExecutionIdentity> {
Ok(ExecutionIdentity {
adk: self.try_identity()?,
invocation_id: self.try_invocation_id()?,
branch: self.branch().to_string(),
agent_name: self.agent_name().to_string(),
})
}
}
pub const MAX_STATE_KEY_LEN: usize = 256;
pub fn validate_state_key(key: &str) -> std::result::Result<(), &'static str> {
if key.is_empty() {
return Err("state key must not be empty");
}
if key.len() > MAX_STATE_KEY_LEN {
return Err("state key exceeds maximum length of 256 bytes");
}
if key.contains('/') || key.contains('\\') || key.contains("..") {
return Err("state key must not contain path separators or '..'");
}
if key.contains('\0') {
return Err("state key must not contain null bytes");
}
Ok(())
}
pub trait State: Send + Sync {
fn get(&self, key: &str) -> Option<Value>;
fn set(&mut self, key: String, value: Value);
fn all(&self) -> HashMap<String, Value>;
}
pub trait ReadonlyState: Send + Sync {
fn get(&self, key: &str) -> Option<Value>;
fn all(&self) -> HashMap<String, Value>;
}
pub trait Session: Send + Sync {
fn id(&self) -> &str;
fn app_name(&self) -> &str;
fn user_id(&self) -> &str;
fn state(&self) -> &dyn State;
fn conversation_history(&self) -> Vec<Content>;
fn conversation_history_for_agent(&self, _agent_name: &str) -> Vec<Content> {
self.conversation_history()
}
fn conversation_history_scoped(&self, agent_name: Option<&str>, _branch: &str) -> Vec<Content> {
match agent_name {
Some(name) => self.conversation_history_for_agent(name),
None => self.conversation_history(),
}
}
fn conversation_history_with_context(&self, _agent_name: &str, branch: &str) -> Vec<Content> {
self.conversation_history_scoped(None, branch)
}
fn records_invocation_events(&self) -> bool {
false
}
fn held_tool_calls(&self, _agent_name: &str, _branch: &str) -> Vec<crate::HeldToolCall> {
Vec::new()
}
fn workflow_resume_positions(
&self,
_workflow: &str,
_branch: &str,
) -> Vec<crate::WorkflowPosition> {
Vec::new()
}
fn append_to_history(&self, _content: Content) {
}
fn try_app_name(&self) -> Result<AppName> {
Ok(AppName::try_from(self.app_name())?)
}
fn try_user_id(&self) -> Result<UserId> {
Ok(UserId::try_from(self.user_id())?)
}
fn try_session_id(&self) -> Result<SessionId> {
Ok(SessionId::try_from(self.id())?)
}
fn try_identity(&self) -> Result<AdkIdentity> {
Ok(AdkIdentity {
app_name: self.try_app_name()?,
user_id: self.try_user_id()?,
session_id: self.try_session_id()?,
})
}
}
#[derive(Debug, Clone)]
pub struct ToolOutcome {
pub tool_name: String,
pub tool_args: serde_json::Value,
pub success: bool,
pub duration: std::time::Duration,
pub error_message: Option<String>,
pub error: Option<Arc<crate::AdkError>>,
pub attempt: u32,
}
#[async_trait]
pub trait CallbackContext: ReadonlyContext {
fn artifacts(&self) -> Option<Arc<dyn Artifacts>>;
fn tool_outcome(&self) -> Option<ToolOutcome> {
None }
fn tool_name(&self) -> Option<&str> {
None
}
fn tool_input(&self) -> Option<&serde_json::Value> {
None
}
fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
None
}
}
pub struct ToolCallbackContext {
pub inner: Arc<dyn CallbackContext>,
pub tool_name: String,
pub tool_input: serde_json::Value,
}
impl ToolCallbackContext {
pub fn new(
inner: Arc<dyn CallbackContext>,
tool_name: String,
tool_input: serde_json::Value,
) -> Self {
Self { inner, tool_name, tool_input }
}
}
#[async_trait]
impl ReadonlyContext for ToolCallbackContext {
fn invocation_id(&self) -> &str {
self.inner.invocation_id()
}
fn agent_name(&self) -> &str {
self.inner.agent_name()
}
fn user_id(&self) -> &str {
self.inner.user_id()
}
fn app_name(&self) -> &str {
self.inner.app_name()
}
fn session_id(&self) -> &str {
self.inner.session_id()
}
fn branch(&self) -> &str {
self.inner.branch()
}
fn user_content(&self) -> &Content {
self.inner.user_content()
}
fn acting_context(&self) -> crate::ActingContext {
self.inner.acting_context()
}
fn is_authenticated(&self) -> bool {
self.inner.is_authenticated()
}
}
#[async_trait]
impl CallbackContext for ToolCallbackContext {
fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
self.inner.artifacts()
}
fn tool_outcome(&self) -> Option<ToolOutcome> {
self.inner.tool_outcome()
}
fn tool_name(&self) -> Option<&str> {
Some(&self.tool_name)
}
fn tool_input(&self) -> Option<&serde_json::Value> {
Some(&self.tool_input)
}
fn shared_state(&self) -> Option<Arc<crate::SharedState>> {
self.inner.shared_state()
}
}
#[async_trait]
pub trait InvocationContext: CallbackContext {
fn agent(&self) -> Arc<dyn Agent>;
fn memory(&self) -> Option<Arc<dyn Memory>>;
fn session(&self) -> &dyn Session;
fn run_config(&self) -> &RunConfig;
fn end_invocation(&self);
fn ended(&self) -> bool;
fn is_cancelled(&self) -> bool {
false
}
fn user_scopes(&self) -> Vec<String> {
vec![]
}
fn request_metadata(&self) -> HashMap<String, serde_json::Value> {
HashMap::new()
}
fn authoritative_transfer_targets(&self) -> bool {
false
}
fn delegation_depth(&self) -> u32 {
0
}
fn max_delegation_depth(&self) -> Option<u32> {
None
}
fn orchestration_root_invocation_id(&self) -> &str {
self.invocation_id()
}
fn orchestration_edge_id(&self) -> Option<&str> {
None
}
fn requires_tool_confirmation(&self, _tool_name: &str) -> bool {
false
}
fn steering_inbox(&self) -> Option<crate::SteeringInbox> {
None
}
async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
Ok(None)
}
async fn get_secret_for(&self, request: &SecretRequest) -> Result<Option<String>> {
self.get_secret(&request.name).await
}
}
#[async_trait]
pub trait Artifacts: Send + Sync {
async fn save(&self, name: &str, data: &crate::Part) -> Result<i64>;
async fn load(&self, name: &str) -> Result<crate::Part>;
async fn list(&self) -> Result<Vec<String>>;
}
#[async_trait]
pub trait Memory: Send + Sync {
async fn search(&self, query: &str) -> Result<Vec<MemoryEntry>>;
async fn health_check(&self) -> Result<()> {
Ok(())
}
async fn add(&self, entry: MemoryEntry) -> Result<()> {
let _ = entry;
Err(AdkError::memory("add not implemented"))
}
async fn delete(&self, query: &str) -> Result<u64> {
let _ = query;
Err(AdkError::memory("delete not implemented"))
}
fn supports_project_scoping(&self) -> bool {
false
}
async fn search_in_project(&self, query: &str, project_id: &str) -> Result<Vec<MemoryEntry>> {
let _ = (query, project_id);
Err(AdkError::memory(
"this memory does not implement project scoping, so `search_in_project` cannot \
honour the project boundary; check `supports_project_scoping` first, or call \
`search` if global scope is intended",
))
}
async fn add_to_project(&self, entry: MemoryEntry, project_id: &str) -> Result<()> {
let _ = (entry, project_id);
Err(AdkError::memory(
"this memory does not implement project scoping, so `add_to_project` cannot honour \
the project boundary; check `supports_project_scoping` first, or call `add` if \
global scope is intended",
))
}
}
#[async_trait]
pub trait SecretService: Send + Sync {
async fn get_secret(&self, name: &str) -> Result<String>;
async fn get_secret_for(&self, request: &SecretRequest) -> Result<String> {
self.get_secret(&request.name).await
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SecretRequest {
pub name: String,
pub tool_name: Option<String>,
pub app_name: Option<String>,
pub user_id: Option<String>,
pub session_id: Option<String>,
pub invocation_id: Option<String>,
pub purpose: Option<String>,
}
impl SecretRequest {
pub fn new(name: impl Into<String>) -> Self {
Self { name: name.into(), ..Default::default() }
}
#[must_use]
pub fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
self.tool_name = Some(tool_name.into());
self
}
#[must_use]
pub fn with_identity(
mut self,
app_name: impl Into<String>,
user_id: impl Into<String>,
session_id: impl Into<String>,
) -> Self {
self.app_name = Some(app_name.into());
self.user_id = Some(user_id.into());
self.session_id = Some(session_id.into());
self
}
#[must_use]
pub fn with_invocation_id(mut self, invocation_id: impl Into<String>) -> Self {
self.invocation_id = Some(invocation_id.into());
self
}
#[must_use]
pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
self.purpose = Some(purpose.into());
self
}
}
#[derive(Debug, Clone)]
pub struct MemoryEntry {
pub content: Content,
pub author: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StreamingMode {
None,
#[default]
SSE,
Bidi,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum IncludeContents {
None,
#[default]
Default,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolConfirmationDecision {
Approve,
Deny,
}
pub fn tool_call_fingerprint(tool_name: &str, args: &Value) -> String {
let mut out = String::with_capacity(tool_name.len() + 32);
out.push_str(tool_name);
out.push('\u{1f}');
write_canonical(args, &mut out);
out
}
pub(crate) fn write_canonical(value: &Value, out: &mut String) {
match value {
Value::Object(map) => {
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
out.push('{');
for (i, key) in keys.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&Value::String((*key).clone()).to_string());
out.push(':');
write_canonical(&map[*key], out);
}
out.push('}');
}
Value::Array(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
write_canonical(item, out);
}
out.push(']');
}
other => out.push_str(&other.to_string()),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ToolConfirmationPolicy {
#[default]
Never,
Always,
PerTool(BTreeSet<String>),
}
impl ToolConfirmationPolicy {
pub fn requires_confirmation(&self, tool_name: &str) -> bool {
match self {
Self::Never => false,
Self::Always => true,
Self::PerTool(tools) => tools.contains(tool_name),
}
}
pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self {
let tool_name = tool_name.into();
match &mut self {
Self::Never => {
let mut tools = BTreeSet::new();
tools.insert(tool_name);
Self::PerTool(tools)
}
Self::Always => Self::Always,
Self::PerTool(tools) => {
tools.insert(tool_name);
self
}
}
}
}
pub const STATIC_TOOL_ORIGIN: &str = "static";
pub const BUILTIN_TOOL_ORIGIN: &str = "builtin";
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolOrigin {
pub source: String,
pub declaration_digest: String,
}
impl ToolOrigin {
pub fn new(
source: impl Into<String>,
declaration: &Value,
annotations: Option<&Value>,
) -> Self {
use sha2::{Digest, Sha256};
use std::fmt::Write as _;
let declared =
serde_json::json!({ "declaration": declaration, "annotations": annotations });
let mut canonical = String::new();
write_canonical(&declared, &mut canonical);
let mut digest = String::with_capacity(7 + 64);
digest.push_str("sha256:");
for byte in Sha256::digest(canonical.as_bytes()) {
let _ = write!(digest, "{byte:02x}");
}
Self { source: source.into(), declaration_digest: digest }
}
pub fn of(tool: &dyn crate::Tool) -> Self {
Self::new(tool.origin(), &tool.declaration(), tool.annotations())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolConfirmationRequest {
pub tool_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub function_call_id: Option<String>,
pub args: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub acting: Option<Box<crate::ActingContext>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub origin: Option<ToolOrigin>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub evidence: Vec<crate::Evidence>,
}
impl ToolConfirmationRequest {
pub fn new(tool_name: impl Into<String>, args: Value) -> Self {
Self {
tool_name: tool_name.into(),
function_call_id: None,
args,
acting: None,
origin: None,
evidence: Vec::new(),
}
}
pub fn for_tool(tool: &dyn crate::Tool, args: Value) -> Self {
Self::new(tool.name(), args).with_origin(ToolOrigin::of(tool))
}
#[must_use]
pub fn with_origin(mut self, origin: ToolOrigin) -> Self {
self.origin = Some(origin);
self
}
#[must_use]
pub fn with_function_call_id(mut self, id: impl Into<String>) -> Self {
self.function_call_id = Some(id.into());
self
}
#[must_use]
pub fn with_acting_context(mut self, acting: crate::ActingContext) -> Self {
self.acting = Some(Box::new(acting));
self
}
#[must_use]
pub fn with_evidence(mut self, evidence: impl IntoIterator<Item = crate::Evidence>) -> Self {
self.evidence.extend(evidence);
self
}
pub fn fingerprint(&self) -> String {
let push_clean = |out: &mut String, part: &str| {
out.extend(part.chars().map(|c| if c.is_control() { '\u{fffd}' } else { c }));
};
let call = tool_call_fingerprint(&self.tool_name, &self.args);
let mut out = String::with_capacity(call.len() + 160);
if let Some(acting) = &self.acting {
push_clean(&mut out, acting.agent.id.as_str());
}
out.push('\u{1f}');
if let Some(origin) = &self.origin {
push_clean(&mut out, &origin.source);
out.push('\u{1f}');
push_clean(&mut out, &origin.declaration_digest);
} else {
out.push('\u{1f}');
}
if !self.evidence.is_empty() {
let digests: Vec<&str> = self.evidence.iter().map(crate::Evidence::digest).collect();
out.push('\u{1e}');
out.push_str("evidence:");
out.push_str(&serde_json::to_string(&digests).unwrap_or_default());
}
out.push('\u{1f}');
out.push_str(&call);
out
}
pub fn fingerprint_agent(fingerprint: &str) -> Option<&str> {
let mut parts = fingerprint.splitn(5, '\u{1f}');
let agent = parts.next().filter(|agent| !agent.is_empty())?;
(parts.count() == 4).then_some(agent)
}
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct BatchCall<'a> {
pub name: &'a str,
pub function_call_id: Option<&'a str>,
pub args: &'a Value,
pub origin: Option<&'a crate::ToolOrigin>,
}
impl<'a> BatchCall<'a> {
pub fn new(name: &'a str, args: &'a Value) -> Self {
Self { name, function_call_id: None, args, origin: None }
}
#[must_use]
pub fn with_function_call_id(mut self, id: &'a str) -> Self {
self.function_call_id = Some(id);
self
}
#[must_use]
pub fn with_origin(mut self, origin: &'a crate::ToolOrigin) -> Self {
self.origin = Some(origin);
self
}
}
#[async_trait]
pub trait ToolConfirmationHandler: std::fmt::Debug + Send + Sync {
async fn decide(&self, request: &ToolConfirmationRequest) -> Result<ToolConfirmationDecision>;
async fn decide_approval(&self, request: &ToolConfirmationRequest) -> Result<ToolApproval> {
Ok(match self.decide(request).await? {
ToolConfirmationDecision::Approve => ToolApproval::approve(),
ToolConfirmationDecision::Deny => ToolApproval::deny(),
})
}
async fn batch_started(&self, calls: &[BatchCall<'_>]) {
let _ = calls;
}
}
#[derive(Clone)]
pub struct RuntimeToolset(Arc<dyn Toolset>);
impl RuntimeToolset {
pub fn new(toolset: Arc<dyn Toolset>) -> Self {
Self(toolset)
}
pub fn toolset(&self) -> &Arc<dyn Toolset> {
&self.0
}
}
impl std::fmt::Debug for RuntimeToolset {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_tuple("RuntimeToolset").field(&self.0.name()).finish()
}
}
#[derive(Debug, Clone)]
pub struct RunConfig {
pub streaming_mode: StreamingMode,
pub tool_confirmation_decisions: HashMap<String, ToolConfirmationDecision>,
pub tool_confirmation_fingerprints: HashMap<String, String>,
pub tool_confirmation_handler: Option<Arc<dyn ToolConfirmationHandler>>,
pub tool_reviewer: Option<Arc<dyn crate::ToolReviewer>>,
pub requested_call_seal: Option<Arc<dyn crate::RequestedCallSeal>>,
pub runtime_toolsets: Vec<RuntimeToolset>,
pub cached_content: Option<String>,
pub transfer_targets: Vec<String>,
pub transfer_target_descriptions: HashMap<String, String>,
pub parent_agent: Option<String>,
pub auto_cache: bool,
pub history_max_events: Option<usize>,
pub tool_concurrency: ToolConcurrencyConfig,
pub record_payloads: bool,
pub trace_payload_max_bytes: usize,
pub max_transfer_depth: Option<u32>,
pub invocation_hooks: Vec<Arc<dyn crate::InvocationHooks>>,
pub budget: Option<crate::RunBudget>,
pub budget_tracker: Option<Arc<crate::BudgetTracker>>,
pub action_ledger: Option<Arc<dyn crate::ActionLedger>>,
pub tool_policy: Option<Arc<dyn crate::ToolPolicy>>,
pub egress_policy: Option<crate::egress::EgressPolicy>,
pub governance: Vec<crate::GovernanceControl>,
pub tool_approvals: HashMap<String, crate::ToolApproval>,
pub approval_store: Option<Arc<dyn crate::ApprovalStore>>,
pub approval_service: Option<Arc<dyn crate::ApprovalService>>,
pub durable_run_id: Option<String>,
pub request_context: Option<crate::RequestContext>,
pub request_metadata: HashMap<String, String>,
pub consent_gate: Option<crate::subject::ConsentGate>,
pub tool_confirmation_timeout: std::time::Duration,
pub spend_ledger: Option<Arc<dyn crate::SpendLedger>>,
pub llm_spend_estimate: Option<crate::LlmSpendEstimate>,
pub audit: Option<crate::audit_log::AuditTrail>,
pub acting: crate::ActingConfig,
pub deny_on_confirmation_timeout: bool,
pub requested_call: Option<crate::RequestedCall>,
pub intra_compaction: Option<crate::IntraCompactionConfig>,
pub history_compactor: Option<Arc<dyn crate::HistoryCompactor>>,
}
impl Default for RunConfig {
fn default() -> Self {
Self {
streaming_mode: StreamingMode::SSE,
tool_confirmation_decisions: HashMap::new(),
tool_confirmation_fingerprints: HashMap::new(),
tool_confirmation_handler: None,
tool_reviewer: None,
requested_call_seal: None,
runtime_toolsets: Vec::new(),
cached_content: None,
transfer_targets: Vec::new(),
transfer_target_descriptions: HashMap::new(),
parent_agent: None,
auto_cache: true,
history_max_events: None,
tool_concurrency: ToolConcurrencyConfig::default(),
record_payloads: false,
trace_payload_max_bytes: 2048,
max_transfer_depth: None,
invocation_hooks: Vec::new(),
budget: None,
budget_tracker: None,
action_ledger: None,
tool_policy: None,
egress_policy: None,
governance: Vec::new(),
tool_approvals: HashMap::new(),
approval_store: None,
approval_service: None,
durable_run_id: None,
request_context: None,
request_metadata: HashMap::new(),
consent_gate: None,
tool_confirmation_timeout: crate::DEFAULT_TOOL_CONFIRMATION_TIMEOUT,
spend_ledger: None,
llm_spend_estimate: None,
audit: None,
acting: crate::ActingConfig::default(),
deny_on_confirmation_timeout: false,
requested_call: None,
intra_compaction: None,
history_compactor: None,
}
}
}
impl RunConfig {
pub fn builder() -> RunConfigBuilder {
RunConfigBuilder::default()
}
pub fn check_governance(&self) -> Result<()> {
self.governance.iter().try_for_each(crate::GovernanceControl::check)
}
pub async fn governance_refused(&self) -> crate::AdkError {
if self.governance.is_empty() {
return std::future::pending().await;
}
let waits = self.governance.iter().map(|control| Box::pin(control.refused()));
futures::future::select_all(waits).await.0
}
pub fn acting_context_for(
&self,
app_name: &str,
agent_name: &str,
user_id: &str,
) -> crate::ActingContext {
self.acting.acting_context_for(app_name, agent_name, user_id)
}
}
#[derive(Debug, Clone, Default)]
pub struct RunConfigBuilder {
config: RunConfig,
}
impl RunConfigBuilder {
pub fn streaming_mode(mut self, mode: StreamingMode) -> Self {
self.config.streaming_mode = mode;
self
}
pub fn tool_confirmation_decisions(
mut self,
decisions: HashMap<String, ToolConfirmationDecision>,
) -> Self {
self.config.tool_confirmation_decisions = decisions;
self
}
pub fn tool_confirmation_fingerprints(mut self, fingerprints: HashMap<String, String>) -> Self {
for (call_id, fingerprint) in &fingerprints {
if ToolConfirmationRequest::fingerprint_agent(fingerprint).is_none() {
tracing::warn!(
function_call.id = %call_id,
"confirmation decision bound to a fingerprint that names no acting agent; \
it never applies. Bind it to the fingerprint of the request the call \
surfaced"
);
}
}
self.config.tool_confirmation_fingerprints = fingerprints;
self
}
pub fn tool_confirmation_handler(mut self, handler: Arc<dyn ToolConfirmationHandler>) -> Self {
self.config.tool_confirmation_handler = Some(handler);
self
}
pub fn tool_reviewer(mut self, reviewer: Arc<dyn crate::ToolReviewer>) -> Self {
self.config.tool_reviewer = Some(reviewer);
self
}
pub fn runtime_toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
self.config.runtime_toolsets.push(RuntimeToolset::new(toolset));
self
}
pub fn runtime_toolsets(
mut self,
toolsets: impl IntoIterator<Item = Arc<dyn Toolset>>,
) -> Self {
self.config.runtime_toolsets.extend(toolsets.into_iter().map(RuntimeToolset::new));
self
}
pub fn cached_content(mut self, name: impl Into<String>) -> Self {
self.config.cached_content = Some(name.into());
self
}
pub fn transfer_targets(mut self, targets: Vec<String>) -> Self {
self.config.transfer_targets = targets;
self
}
pub fn parent_agent(mut self, name: impl Into<String>) -> Self {
self.config.parent_agent = Some(name.into());
self
}
pub fn auto_cache(mut self, enabled: bool) -> Self {
self.config.auto_cache = enabled;
self
}
pub fn history_max_events(mut self, max: Option<usize>) -> Self {
self.config.history_max_events = max;
self
}
pub fn tool_concurrency(mut self, config: ToolConcurrencyConfig) -> Self {
self.config.tool_concurrency = config;
self
}
pub fn record_payloads(mut self, enabled: bool) -> Self {
self.config.record_payloads = enabled;
self
}
pub fn trace_payload_max_bytes(mut self, max: usize) -> Self {
self.config.trace_payload_max_bytes = max;
self
}
pub fn max_transfer_depth(mut self, depth: u32) -> Self {
self.config.max_transfer_depth = Some(depth);
self
}
pub fn intra_compaction(mut self, config: crate::IntraCompactionConfig) -> Self {
self.config.intra_compaction = Some(config);
self
}
pub fn history_compactor(mut self, compactor: Arc<dyn crate::HistoryCompactor>) -> Self {
self.config.history_compactor = Some(compactor);
self
}
pub fn invocation_hook(mut self, hook: Arc<dyn crate::InvocationHooks>) -> Self {
self.config.invocation_hooks.push(hook);
self
}
pub fn budget(mut self, budget: crate::RunBudget) -> Self {
self.config.budget = Some(budget);
self
}
pub fn action_ledger(mut self, ledger: Arc<dyn crate::ActionLedger>) -> Self {
self.config.action_ledger = Some(ledger);
self
}
pub fn tool_policy(mut self, policy: Arc<dyn crate::ToolPolicy>) -> Self {
self.config.tool_policy = Some(policy);
self
}
pub fn egress_policy(mut self, policy: crate::egress::EgressPolicy) -> Self {
self.config.egress_policy = Some(match self.config.egress_policy.take() {
Some(existing) => existing.narrow(&policy),
None => policy,
});
self
}
pub fn governance(mut self, control: crate::GovernanceControl) -> Self {
if !self.config.governance.iter().any(|existing| existing.same_as(&control)) {
self.config.governance.push(control);
}
self
}
pub fn tool_approval(
mut self,
fingerprint: impl Into<String>,
approval: crate::ToolApproval,
) -> Self {
let fingerprint = fingerprint.into();
if ToolConfirmationRequest::fingerprint_agent(&fingerprint).is_none() {
tracing::warn!(
"tool approval refused: its fingerprint names no acting agent, so it could \
never authorize a governed call. Build it from the request the call surfaced, \
or with ToolConfirmationRequest::with_acting_context"
);
return self;
}
self.config.tool_approvals.insert(fingerprint, approval);
self
}
pub fn approval_store(mut self, store: Arc<dyn crate::ApprovalStore>) -> Self {
self.config.approval_store = Some(store);
self
}
pub fn requested_call(mut self, call: crate::RequestedCall) -> Self {
self.config.requested_call = Some(call);
self
}
pub fn approval_service(mut self, service: Arc<dyn crate::ApprovalService>) -> Self {
if self.config.approval_store.is_none() {
self.config.approval_store = service.approval_store();
}
self.config.approval_service = Some(service);
self
}
pub fn durable_run_id(mut self, run_id: impl Into<String>) -> Self {
self.config.durable_run_id = Some(run_id.into());
self
}
pub fn request_context(mut self, request_context: crate::RequestContext) -> Self {
self.config.request_context = Some(request_context);
self
}
pub fn request_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.config.request_metadata.insert(key.into(), value.into());
self
}
pub fn consent_gate(mut self, gate: crate::subject::ConsentGate) -> Self {
self.config.consent_gate = Some(gate);
self
}
pub fn tool_confirmation_timeout(mut self, timeout: std::time::Duration) -> Self {
self.config.tool_confirmation_timeout = timeout;
self
}
pub fn deny_on_confirmation_timeout(mut self, deny: bool) -> Self {
self.config.deny_on_confirmation_timeout = deny;
self
}
pub fn spend_ledger(mut self, ledger: Arc<dyn crate::SpendLedger>) -> Self {
self.config.spend_ledger = Some(ledger);
self
}
pub fn audit(mut self, audit: crate::audit_log::AuditTrail) -> Self {
self.config.audit = Some(audit);
self
}
pub fn llm_spend_estimate(mut self, estimate: crate::LlmSpendEstimate) -> Self {
self.config.llm_spend_estimate = Some(estimate);
self
}
pub fn acting(mut self, acting: crate::ActingConfig) -> Self {
self.config.acting = acting;
self
}
pub fn agent_principal(
mut self,
agent_name: impl Into<String>,
principal: crate::AgentPrincipal,
) -> Self {
self.config.acting.principals.insert(agent_name.into(), principal);
self
}
pub fn subject_kind(mut self, kind: crate::SubjectKind) -> Self {
self.config.acting.subject_kind = kind;
self
}
pub fn on_behalf_of(mut self, subject: crate::SubjectRef) -> Self {
self.config.acting.on_behalf_of = Some(subject);
self
}
pub fn build(self) -> RunConfig {
self.config
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_run_config_default() {
let config = RunConfig::default();
assert_eq!(config.streaming_mode, StreamingMode::SSE);
assert_eq!(config.history_max_events, None);
assert_eq!(config.tool_concurrency.max_concurrency, None);
assert!(config.tool_concurrency.per_tool.is_empty());
assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Queue);
assert!(!config.record_payloads);
assert_eq!(config.trace_payload_max_bytes, 2048);
assert!(config.tool_confirmation_decisions.is_empty());
assert_eq!(config.max_transfer_depth, None);
assert!(config.invocation_hooks.is_empty());
assert!(config.action_ledger.is_none());
}
#[test]
fn test_streaming_mode() {
assert_eq!(StreamingMode::SSE, StreamingMode::SSE);
assert_ne!(StreamingMode::SSE, StreamingMode::None);
assert_ne!(StreamingMode::None, StreamingMode::Bidi);
}
#[test]
fn test_tool_confirmation_policy() {
let policy = ToolConfirmationPolicy::default();
assert!(!policy.requires_confirmation("search"));
let policy = policy.with_tool("search");
assert!(policy.requires_confirmation("search"));
assert!(!policy.requires_confirmation("write_file"));
assert!(ToolConfirmationPolicy::Always.requires_confirmation("any_tool"));
}
#[test]
fn test_validate_state_key_valid() {
assert!(validate_state_key("user_name").is_ok());
assert!(validate_state_key("app:config").is_ok());
assert!(validate_state_key("temp:data").is_ok());
assert!(validate_state_key("a").is_ok());
}
#[test]
fn test_validate_state_key_empty() {
assert_eq!(validate_state_key(""), Err("state key must not be empty"));
}
#[test]
fn test_validate_state_key_too_long() {
let long_key = "a".repeat(MAX_STATE_KEY_LEN + 1);
assert!(validate_state_key(&long_key).is_err());
}
#[test]
fn test_validate_state_key_path_traversal() {
assert!(validate_state_key("../etc/passwd").is_err());
assert!(validate_state_key("foo/bar").is_err());
assert!(validate_state_key("foo\\bar").is_err());
assert!(validate_state_key("..").is_err());
}
#[test]
fn test_validate_state_key_null_byte() {
assert!(validate_state_key("foo\0bar").is_err());
}
#[test]
fn fingerprint_agent_reads_the_acting_agent_of_a_request_fingerprint() {
use crate::principal::{ActingContext, AgentPrincipal};
let args = serde_json::json!({ "amount": 40 });
let call = ToolConfirmationRequest::new("pay", args.clone());
let owned = call
.clone()
.with_acting_context(ActingContext::new(AgentPrincipal::derived("ops", "treasurer")));
let published =
owned.clone().with_origin(ToolOrigin::new("mcp:bank", &serde_json::json!({}), None));
let agent = ToolConfirmationRequest::fingerprint_agent;
assert_eq!(agent(&owned.fingerprint()), Some("urn:adk:agent:ops/treasurer"));
assert_eq!(agent(&published.fingerprint()), Some("urn:adk:agent:ops/treasurer"));
assert_eq!(agent(&call.fingerprint()), None);
assert_eq!(agent(&call.with_origin(published.origin.unwrap()).fingerprint()), None);
assert_eq!(agent(&tool_call_fingerprint("pay", &args)), None);
assert_eq!(agent(""), None);
}
#[test]
fn test_run_config_builder_defaults() {
let config = RunConfig::builder().build();
let default = RunConfig::default();
assert_eq!(config.streaming_mode, default.streaming_mode);
assert_eq!(config.auto_cache, default.auto_cache);
assert_eq!(config.history_max_events, default.history_max_events);
assert_eq!(config.record_payloads, default.record_payloads);
assert_eq!(config.trace_payload_max_bytes, default.trace_payload_max_bytes);
assert!(config.tool_confirmation_decisions.is_empty());
assert!(config.transfer_targets.is_empty());
assert!(config.cached_content.is_none());
assert!(config.parent_agent.is_none());
}
#[test]
fn test_run_config_builder_all_fields() {
let mut decisions = HashMap::new();
decisions.insert("delete".to_string(), ToolConfirmationDecision::Approve);
let config = RunConfig::builder()
.streaming_mode(StreamingMode::None)
.tool_confirmation_decisions(decisions.clone())
.cached_content("my-cache")
.transfer_targets(vec!["agent_a".to_string(), "agent_b".to_string()])
.parent_agent("parent")
.auto_cache(false)
.history_max_events(Some(50))
.tool_concurrency(ToolConcurrencyConfig {
max_concurrency: Some(4),
per_tool: HashMap::new(),
backpressure: BackpressurePolicy::Fail,
})
.record_payloads(true)
.trace_payload_max_bytes(4096)
.build();
assert_eq!(config.streaming_mode, StreamingMode::None);
assert_eq!(config.tool_confirmation_decisions, decisions);
assert_eq!(config.cached_content.as_deref(), Some("my-cache"));
assert_eq!(config.transfer_targets, vec!["agent_a", "agent_b"]);
assert_eq!(config.parent_agent.as_deref(), Some("parent"));
assert!(!config.auto_cache);
assert_eq!(config.history_max_events, Some(50));
assert_eq!(config.tool_concurrency.max_concurrency, Some(4));
assert_eq!(config.tool_concurrency.backpressure, BackpressurePolicy::Fail);
assert!(config.record_payloads);
assert_eq!(config.trace_payload_max_bytes, 4096);
}
}