use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, RwLock};
use adk_core::{
AdkError, ErrorCategory, ErrorComponent, PolicyCall, PolicyDecision, Tool,
ToolConfirmationRequest, ToolContext, ToolEffect, ToolOrigin, ToolPolicy, ToolPolicyRequest,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{PartitionId, Partitions};
pub const CROSSING_PARTITION_ARG: &str = "partition";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CrossingResource {
Memory,
Driver,
Session,
}
impl CrossingResource {
pub fn as_str(self) -> &'static str {
match self {
Self::Memory => "memory",
Self::Driver => "driver",
Self::Session => "session",
}
}
}
impl fmt::Display for CrossingResource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CrossingAccess {
Read,
Write,
}
impl CrossingAccess {
pub fn as_str(self) -> &'static str {
match self {
Self::Read => "read",
Self::Write => "write",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Crossing {
pub from: PartitionId,
pub to: PartitionId,
pub resource: CrossingResource,
pub name: String,
pub access: CrossingAccess,
}
impl Crossing {
pub fn new(
from: impl Into<PartitionId>,
to: impl Into<PartitionId>,
resource: CrossingResource,
name: impl Into<String>,
access: CrossingAccess,
) -> Self {
Self { from: from.into(), to: to.into(), resource, name: name.into(), access }
}
pub fn label(&self) -> String {
format!("{} › {}", self.to, self.name)
}
pub fn fingerprint(&self, request: &ToolConfirmationRequest) -> String {
let mut out = request.fingerprint();
for part in [self.to.as_str(), self.resource.as_str()] {
out.push('\u{1f}');
out.extend(part.chars().map(|c| if c.is_control() { '\u{fffd}' } else { c }));
}
out
}
pub fn answers(&self) -> [String; 3] {
let allow = match self.access {
CrossingAccess::Read => format!("allow this read of {} for this run", self.label()),
CrossingAccess::Write => format!("allow this change to {} once", self.label()),
};
[
allow,
"deny".to_string(),
format!("deny and block crossings to {} from this partition", self.to),
]
}
pub fn approval_reason(&self) -> String {
let [allow, deny, block] = self.answers();
format!(
"partition crossing from `{}` into {}: needs a person's approval, which no standing \
rule can give ({allow} / {deny} / {block})",
self.from,
self.label()
)
}
}
pub(crate) fn digest(fingerprint: &str) -> String {
use sha2::{Digest, Sha256};
use std::fmt::Write as _;
let mut out = String::with_capacity(7 + 64);
out.push_str("sha256:");
for byte in Sha256::digest(fingerprint.as_bytes()) {
let _ = write!(out, "{byte:02x}");
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CrossingOutcome {
Denied,
Held,
Approved,
RunGrant,
}
impl CrossingOutcome {
pub fn as_str(self) -> &'static str {
match self {
Self::Denied => "denied",
Self::Held => "held",
Self::Approved => "approved",
Self::RunGrant => "runGrant",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CrossingRecord {
pub id: String,
pub at: DateTime<Utc>,
pub run: String,
pub agent: String,
pub from: PartitionId,
pub to: PartitionId,
pub resource: CrossingResource,
pub name: String,
pub access: CrossingAccess,
pub tool: String,
pub fingerprint: String,
pub outcome: CrossingOutcome,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CrossingFilter {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<PartitionId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub to: Option<PartitionId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fingerprint: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub outcomes: Vec<CrossingOutcome>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub since: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub limit: Option<usize>,
}
impl CrossingFilter {
#[must_use]
pub fn from(mut self, from: impl Into<PartitionId>) -> Self {
self.from = Some(from.into());
self
}
#[must_use]
pub fn to(mut self, to: impl Into<PartitionId>) -> Self {
self.to = Some(to.into());
self
}
#[must_use]
pub fn run(mut self, run: impl Into<String>) -> Self {
self.run = Some(run.into());
self
}
#[must_use]
pub fn fingerprint(mut self, digest: impl Into<String>) -> Self {
self.fingerprint = Some(digest.into());
self
}
#[must_use]
pub fn outcomes(mut self, outcomes: impl IntoIterator<Item = CrossingOutcome>) -> Self {
self.outcomes = outcomes.into_iter().collect();
self
}
#[must_use]
pub fn since(mut self, since: DateTime<Utc>) -> Self {
self.since = Some(since);
self
}
#[must_use]
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn matches(&self, record: &CrossingRecord) -> bool {
self.from.as_ref().is_none_or(|from| *from == record.from)
&& self.to.as_ref().is_none_or(|to| *to == record.to)
&& self.run.as_ref().is_none_or(|run| *run == record.run)
&& self.fingerprint.as_ref().is_none_or(|digest| *digest == record.fingerprint)
&& (self.outcomes.is_empty() || self.outcomes.contains(&record.outcome))
&& self.since.is_none_or(|since| record.at >= since)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CrossingRoute {
Argument {
resource: CrossingResource,
access: CrossingAccess,
name: String,
},
Fixed {
to: PartitionId,
resource: CrossingResource,
access: CrossingAccess,
name: String,
},
}
impl CrossingRoute {
pub fn argument(
resource: CrossingResource,
access: CrossingAccess,
name: impl Into<String>,
) -> Self {
Self::Argument { resource, access, name: name.into() }
}
pub fn fixed(
to: impl Into<PartitionId>,
resource: CrossingResource,
access: CrossingAccess,
name: impl Into<String>,
) -> Self {
Self::Fixed { to: to.into(), resource, access, name: name.into() }
}
pub fn crossing(&self, from: &PartitionId, args: &Value) -> Result<Crossing, String> {
match self {
Self::Argument { resource, access, name } => {
let to = args
.get(CROSSING_PARTITION_ARG)
.and_then(Value::as_str)
.map(str::trim)
.filter(|to| !to.is_empty())
.ok_or_else(|| {
format!("the call names no `{CROSSING_PARTITION_ARG}` to reach")
})?;
Ok(Crossing::new(from.clone(), to, *resource, name.clone(), *access))
}
Self::Fixed { to, resource, access, name } => {
Ok(Crossing::new(from.clone(), to.clone(), *resource, name.clone(), *access))
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CrossingRun {
Durable(String),
Invocation(String),
}
impl CrossingRun {
pub fn of(durable_run_id: Option<&str>, invocation_id: &str) -> Self {
match durable_run_id {
Some(run) => Self::Durable(run.to_string()),
None => Self::Invocation(invocation_id.to_string()),
}
}
pub fn as_str(&self) -> &str {
match self {
Self::Durable(id) | Self::Invocation(id) => id,
}
}
}
#[derive(Clone)]
pub struct PartitionPolicy {
partitions: Partitions,
home: PartitionId,
coordinator: Option<String>,
routes: Arc<RwLock<BTreeMap<String, CrossingRoute>>>,
}
impl fmt::Debug for PartitionPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PartitionPolicy")
.field("home", &self.home)
.field("coordinator", &self.coordinator)
.field("routes", &self.routes.read().unwrap_or_else(|e| e.into_inner()).len())
.finish()
}
}
impl PartitionPolicy {
pub(super) fn new(partitions: Partitions, home: PartitionId) -> Self {
Self { partitions, home, coordinator: None, routes: Arc::default() }
}
#[must_use]
pub fn with_coordinator(mut self, agent_name: impl Into<String>) -> Self {
self.coordinator = Some(agent_name.into());
self
}
#[must_use]
pub fn with_crossing_tool(self, name: impl Into<String>, route: CrossingRoute) -> Self {
self.register(name, route);
self
}
pub fn register(&self, name: impl Into<String>, route: CrossingRoute) {
self.routes.write().unwrap_or_else(|e| e.into_inner()).insert(name.into(), route);
}
pub fn home(&self) -> &PartitionId {
&self.home
}
pub fn coordinator(&self) -> Option<&str> {
self.coordinator.as_deref()
}
pub fn partitions(&self) -> &Partitions {
&self.partitions
}
pub fn route(&self, name: &str) -> Option<CrossingRoute> {
self.routes.read().unwrap_or_else(|e| e.into_inner()).get(name).cloned()
}
fn is_coordinator(&self, agent_name: &str) -> bool {
self.coordinator.as_deref() == Some(agent_name)
}
pub async fn run_crossing<F, Fut>(
&self,
ctx: &dyn ToolContext,
tool: &dyn Tool,
args: &Value,
body: F,
) -> adk_core::Result<Value>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = adk_core::Result<Value>>,
{
let route = self.route(tool.name()).ok_or_else(|| {
AdkError::tool(format!(
"{} is not registered as a crossing tool of partition `{}`",
tool.name(),
self.home
))
})?;
let crossing = route.crossing(&self.home, args).map_err(refused)?;
if crossing.to == self.home {
return body().await;
}
self.partitions
.admit(&crossing, self.is_coordinator(ctx.agent_name()))
.await
.map_err(refused)?;
let acting = ctx.acting_context();
let request = ToolConfirmationRequest::new(tool.name(), args.clone())
.with_acting_context(acting.clone())
.with_origin(ToolOrigin::of(tool));
let fingerprint = crossing.fingerprint(&request);
let durable = ctx.run_config().and_then(|config| config.durable_run_id.clone());
let run = CrossingRun::of(durable.as_deref(), ctx.invocation_id());
let value = body().await?;
if let Err(error) = self
.partitions
.executed(&crossing, &fingerprint, &run, acting.agent.id.as_str(), tool.name())
.await
{
tracing::warn!(error = %error, crossing = %crossing.label(), "a crossing ran but could not be recorded");
}
Ok(value)
}
}
fn refused(reason: String) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Forbidden,
crate::error::CROSSING_DENIED_CODE,
reason,
)
}
#[async_trait]
impl ToolPolicy for PartitionPolicy {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
self.evaluate_call(request, &PolicyCall::new()).await
}
async fn evaluate_call(
&self,
request: &ToolPolicyRequest,
call: &PolicyCall<'_>,
) -> PolicyDecision {
let Some(route) = self.route(&request.tool_name) else {
return PolicyDecision::Allow;
};
let crossing = match route.crossing(&self.home, &request.args) {
Ok(crossing) => crossing,
Err(reason) => return PolicyDecision::deny(reason),
};
if crossing.to == self.home {
return PolicyDecision::Allow;
}
let mut confirmation =
ToolConfirmationRequest::new(&request.tool_name, request.args.clone());
if let Some(acting) = &request.acting {
confirmation = confirmation.with_acting_context(acting.clone());
}
if let Some(origin) = call.origin {
confirmation = confirmation.with_origin(origin.clone());
}
let fingerprint = crossing.fingerprint(&confirmation);
let run = CrossingRun::of(call.durable_run_id, &request.invocation_id);
let agent = request
.acting
.as_ref()
.map(|acting| acting.agent.id.as_str().to_string())
.unwrap_or_else(|| request.agent_name.clone());
let recorded = super::CrossingCall {
crossing: &crossing,
fingerprint: &fingerprint,
run: run.as_str(),
agent: &agent,
tool: &request.tool_name,
};
let decided = |outcome, reason: Option<String>| {
self.partitions.decided(&recorded, call.function_call_id, outcome, reason)
};
if let Err(reason) =
self.partitions.admit(&crossing, self.is_coordinator(&request.agent_name)).await
{
tracing::info!(crossing = %crossing.label(), agent.name = %request.agent_name, reason = %reason, "partition crossing denied");
decided(CrossingOutcome::Denied, Some(reason.clone())).await;
return PolicyDecision::deny(format!("partition crossing denied: {reason}"));
}
if crossing.access == CrossingAccess::Read
&& self.partitions.granted(&run, &fingerprint).await
{
decided(CrossingOutcome::RunGrant, None).await;
return PolicyDecision::Allow;
}
decided(CrossingOutcome::Held, None).await;
PolicyDecision::require_approval(crossing.approval_reason())
}
fn policy_ref(&self) -> Option<String> {
Some(format!("adk-kernel.partition:{}", self.home))
}
}
const TOOL_NAME_MAX: usize = 64;
pub struct CrossingTool {
inner: Arc<dyn Tool>,
name: String,
description: String,
policy: PartitionPolicy,
}
impl fmt::Debug for CrossingTool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CrossingTool").field("name", &self.name).finish_non_exhaustive()
}
}
impl CrossingTool {
pub fn new(
inner: Arc<dyn Tool>,
policy: &PartitionPolicy,
to: impl Into<PartitionId>,
resource: CrossingResource,
access: CrossingAccess,
name: impl Into<String>,
) -> Self {
let to = to.into();
let access = match (access, inner.effect()) {
(CrossingAccess::Read, ToolEffect::ReadOnly) => CrossingAccess::Read,
_ => CrossingAccess::Write,
};
let route = CrossingRoute::fixed(to.clone(), resource, access, name);
let label = match &route {
CrossingRoute::Fixed { name, .. } => format!("{to} › {name}"),
CrossingRoute::Argument { .. } => to.to_string(),
};
let tool_name: String = format!("{to}__{}", inner.name())
.chars()
.map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '-') { c } else { '_' })
.take(TOOL_NAME_MAX)
.collect();
let description = format!(
"[Reaches partition `{to}` ({label}): every call needs the user's approval.] {}",
inner.description()
);
policy.register(tool_name.clone(), route);
Self { inner, name: tool_name, description, policy: policy.clone() }
}
pub fn inner(&self) -> &Arc<dyn Tool> {
&self.inner
}
}
#[async_trait]
impl Tool for CrossingTool {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
&self.description
}
fn declaration(&self) -> Value {
let mut declaration = self.inner.declaration();
if let Value::Object(fields) = &mut declaration {
fields.insert("name".into(), Value::String(self.name.clone()));
fields.insert("description".into(), Value::String(self.description.clone()));
}
declaration
}
fn parameters_schema(&self) -> Option<Value> {
self.inner.parameters_schema()
}
fn response_schema(&self) -> Option<Value> {
self.inner.response_schema()
}
fn is_long_running(&self) -> bool {
self.inner.is_long_running()
}
fn annotations(&self) -> Option<&Value> {
self.inner.annotations()
}
fn origin(&self) -> &str {
self.inner.origin()
}
fn required_scopes(&self) -> &[&str] {
self.inner.required_scopes()
}
fn is_read_only(&self) -> bool {
self.inner.is_read_only()
}
fn effect(&self) -> ToolEffect {
self.inner.effect()
}
fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
self.inner.egress(args)
}
fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
self.inner.approval_evidence(args)
}
fn batch_group(&self) -> Option<adk_core::BatchGroup> {
self.inner.batch_group()
}
fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
self.inner.timeout_override()
}
fn is_concurrency_safe(&self) -> bool {
self.inner.is_concurrency_safe()
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
let inner = Arc::clone(&self.inner);
let call_ctx = Arc::clone(&ctx);
let call_args = args.clone();
self.policy
.run_crossing(ctx.as_ref(), self, &args, move || async move {
inner.execute(call_ctx, call_args).await
})
.await
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RecurringCrossing {
pub from: PartitionId,
pub to: PartitionId,
pub resource: CrossingResource,
pub name: String,
pub count: usize,
}
impl RecurringCrossing {
pub fn new(
from: impl Into<PartitionId>,
to: impl Into<PartitionId>,
resource: CrossingResource,
name: impl Into<String>,
count: usize,
) -> Self {
Self { from: from.into(), to: to.into(), resource, name: name.into(), count }
}
pub fn remedy(&self) -> String {
format!(
"partition {} crossed into {} › {} {} times; if it needs it this often, move {} into \
{}, or merge {} and {} (`adk-rust partitions`); a crossing is never waived",
self.from, self.to, self.name, self.count, self.name, self.from, self.from, self.to
)
}
}