use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use adk_core::{
ActionOutcome, ActionRecord, ApprovalScope, GovernedCall, RunConfig, ToolAuthorization,
ToolConfirmationRequest, ToolEffect, ToolGate, ToolOrigin,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
use crate::checkpoint::Checkpointer;
use crate::error::{GraphError, Result};
use crate::graph::CompiledGraph;
use crate::interrupt::GraphToolConfirmationPause;
use crate::node::{Node, NodeContext, NodeOutput};
use crate::record::NodeStatus;
use crate::state::{Checkpoint, State};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GovernedNode {
pub requires_approval: bool,
pub spends_money: bool,
}
impl GovernedNode {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_approval(mut self) -> Self {
self.requires_approval = true;
self
}
#[must_use]
pub fn spending_money(mut self) -> Self {
self.spends_money = true;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum GovernedError {
#[error(
"graph.not_run: governed node '{node}' was not run: the run has no approval gate. Run \
the graph as a GraphAgent under a Runner, or with invoke_with_run_config"
)]
NotRun {
node: String,
},
#[error("graph.frozen: governed node '{node}' was not run: {reason}")]
Frozen {
node: String,
reason: String,
},
#[error("graph.refused: governed node '{node}' was not run: {reason}")]
Refused {
node: String,
reason: String,
},
#[error(
"graph.recorded_failure: governed node '{node}' already ran this call and it failed: \
{error}. It is not run again; fork with changed state to make a new call"
)]
RecordedFailure {
node: String,
error: String,
},
#[error(
"graph.outcome_unknown: governed node '{node}' began this call before and recorded no \
outcome, so it may have taken effect. It is not run again; check the effect, then \
fork with changed state to make a new call (ledger key '{key}')"
)]
OutcomeUnknown {
node: String,
key: String,
},
#[error(
"graph.effect_unavailable: governed node '{node}' already completed this call, but \
its writes are not in the effect log. It is not run again (ledger key '{key}')"
)]
EffectUnavailable {
node: String,
key: String,
},
#[error(
"graph.edit_unsupported: governed node '{node}' cannot run an edited call, so it was \
not run. Approve the call as shown, or deny it"
)]
EditUnsupported {
node: String,
},
#[error("graph.unavailable: governed node '{node}' was not run: {detail}")]
Unavailable {
node: String,
detail: String,
},
}
impl GovernedError {
pub const CODES: [&'static str; 8] = [
"graph.not_run",
"graph.frozen",
"graph.refused",
"graph.recorded_failure",
"graph.outcome_unknown",
"graph.effect_unavailable",
"graph.edit_unsupported",
"graph.unavailable",
];
pub fn code(&self) -> &'static str {
match self {
Self::NotRun { .. } => Self::CODES[0],
Self::Frozen { .. } => Self::CODES[1],
Self::Refused { .. } => Self::CODES[2],
Self::RecordedFailure { .. } => Self::CODES[3],
Self::OutcomeUnknown { .. } => Self::CODES[4],
Self::EffectUnavailable { .. } => Self::CODES[5],
Self::EditUnsupported { .. } => Self::CODES[6],
Self::Unavailable { .. } => Self::CODES[7],
}
}
pub fn code_of(error: &GraphError) -> Option<&'static str> {
let GraphError::NodeExecutionFailed { message, .. } = error else { return None };
Self::CODES
.into_iter()
.find(|code| message.strip_prefix(code).is_some_and(|rest| rest.starts_with(':')))
}
fn node(&self) -> &str {
match self {
Self::NotRun { node }
| Self::Frozen { node, .. }
| Self::Refused { node, .. }
| Self::RecordedFailure { node, .. }
| Self::OutcomeUnknown { node, .. }
| Self::EffectUnavailable { node, .. }
| Self::EditUnsupported { node }
| Self::Unavailable { node, .. } => node,
}
}
fn status(&self) -> NodeStatus {
match self {
Self::NotRun { .. } => NodeStatus::NotRun,
Self::Frozen { .. } | Self::Refused { .. } | Self::EditUnsupported { .. } => {
NodeStatus::Refused
}
Self::RecordedFailure { .. }
| Self::OutcomeUnknown { .. }
| Self::EffectUnavailable { .. }
| Self::Unavailable { .. } => NodeStatus::Failed,
}
}
}
impl From<GovernedError> for GraphError {
fn from(error: GovernedError) -> Self {
GraphError::NodeExecutionFailed {
node: error.node().to_string(),
message: error.to_string(),
}
}
}
pub const EFFECT_METADATA_KEY: &str = "adk.graph.effect";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EffectRecord {
pub key: String,
pub node: String,
pub writes: BTreeMap<String, Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goto: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub goto_parent: Option<Vec<String>>,
pub thread: String,
pub checkpoint: String,
pub at: DateTime<Utc>,
}
pub fn effect_log_thread(root: &str) -> String {
format!("{root}:effects")
}
pub async fn effect_log(checkpointer: &dyn Checkpointer, root: &str) -> Result<Vec<EffectRecord>> {
let entries = checkpointer.list(&effect_log_thread(root)).await?;
entries
.iter()
.filter_map(|checkpoint| checkpoint.metadata.get(EFFECT_METADATA_KEY))
.map(|value| {
serde_json::from_value(value.clone()).map_err(|error| {
GraphError::SerializationError(format!("effect log entry is malformed: {error}"))
})
})
.collect()
}
async fn append_effect(
checkpointer: &dyn Checkpointer,
root: &str,
entry: &EffectRecord,
) -> Result<()> {
let thread = effect_log_thread(root);
let value = serde_json::to_value(entry)?;
for _ in 0..16 {
let (version, index) = checkpointer
.load(&thread)
.await?
.map_or((1, 0), |newest| (newest.version + 1, newest.step + 1));
let checkpoint = Checkpoint::new(&thread, State::new(), index, Vec::new())
.with_version(version)
.with_metadata(EFFECT_METADATA_KEY, value.clone());
match checkpointer.save(&checkpoint).await {
Ok(_) => return Ok(()),
Err(GraphError::CheckpointConflict { .. }) => continue,
Err(error) => return Err(error),
}
}
Err(GraphError::CheckpointError(format!(
"the effect log '{thread}' kept changing while an entry was appended"
)))
}
pub(crate) const STANDALONE_AGENT_NAME: &str = "graph";
const MAX_SLOTS: u32 = 16;
pub(crate) struct GovernedDispatch {
pub(crate) node_name: String,
pub(crate) node: Arc<dyn Node>,
pub(crate) governed: GovernedNode,
pub(crate) effect: ToolEffect,
pub(crate) declaration: Value,
pub(crate) root: String,
pub(crate) run_id: String,
pub(crate) occurrence: u32,
pub(crate) held: Option<ToolConfirmationRequest>,
pub(crate) checkpointer: Option<Arc<dyn Checkpointer>>,
pub(crate) thread_id: String,
pub(crate) checkpoint_id: String,
pub(crate) run_timeout: Option<Duration>,
}
pub(crate) struct GovernedRun {
pub(crate) output: Result<NodeOutput>,
pub(crate) status: NodeStatus,
pub(crate) effect_key: Option<String>,
pub(crate) held: Option<ToolConfirmationRequest>,
}
impl GovernedRun {
fn failed(error: GovernedError, effect_key: Option<String>) -> Self {
let status = error.status();
Self { output: Err(error.into()), status, effect_key, held: None }
}
}
impl CompiledGraph {
#[must_use]
pub fn with_governed_node(mut self, node: &str, governed: GovernedNode) -> Self {
self.governed_nodes.insert(node.to_string(), governed);
self
}
pub(crate) fn is_governed(&self, node: &str) -> bool {
self.governed_nodes.contains_key(node)
}
pub(crate) fn check_governed_nodes(&self) -> Result<()> {
let mut unknown: Vec<&String> =
self.governed_nodes.keys().filter(|name| !self.nodes.contains_key(*name)).collect();
unknown.sort();
match unknown.first() {
Some(name) => Err(GraphError::InvalidGraph(format!(
"governed node '{name}' is not a node of this graph, so the node it names \
would run ungoverned. Govern a node by the name it was added under"
))),
None => Ok(()),
}
}
}
pub(crate) async fn dispatch(dispatch: GovernedDispatch, ctx: &NodeContext) -> GovernedRun {
debug_assert!(ctx.governed_call(), "a governed node's context is marked as its call");
let node = dispatch.node_name.clone();
let parent = ctx.config.parent_context.clone();
let explicit = ctx.run_config();
let run_config: &RunConfig = match (&explicit, &parent) {
(Some(config), _) => config,
(None, Some(parent)) => parent.run_config(),
(None, None) => {
tracing::warn!(node = %node, "governed node not run: the run has no approval gate");
return GovernedRun::failed(GovernedError::NotRun { node }, None);
}
};
let gate = match (&explicit, &parent) {
(None, Some(parent)) => ToolGate::for_context(parent.as_ref()),
(_, Some(parent)) => ToolGate::new(
run_config,
parent.agent_name(),
parent.invocation_id(),
ApprovalScope::new(parent.app_name(), parent.user_id(), parent.session_id()),
),
(_, None) => ToolGate::new(
run_config,
STANDALONE_AGENT_NAME,
&dispatch.run_id,
ApprovalScope::new(
crate::node::STANDALONE_APP_NAME,
crate::node::STANDALONE_USER_ID,
&dispatch.thread_id,
),
),
};
let agent_name = parent.as_ref().map_or(STANDALONE_AGENT_NAME, |parent| parent.agent_name());
if let Err(frozen) = run_config.check_governance() {
return GovernedRun::failed(GovernedError::Frozen { node, reason: frozen.message }, None);
}
match dispatch.node.will_act(ctx) {
Ok(true) => {}
Ok(false) => {
tracing::debug!(node = %node, "governed node does nothing here; no decision");
if let Some(held) = dispatch.held.as_ref() {
withdraw(&gate, held, &node).await;
}
return GovernedRun {
output: Ok(NodeOutput::new()),
status: NodeStatus::Done,
effect_key: None,
held: None,
};
}
Err(error) => {
if let Some(held) = dispatch.held.as_ref() {
withdraw(&gate, held, &node).await;
}
return GovernedRun {
output: Err(error),
status: NodeStatus::Failed,
effect_key: None,
held: None,
};
}
}
let Some(ledger) = run_config.action_ledger.clone() else {
return GovernedRun::failed(
GovernedError::Unavailable {
node,
detail: "the run has no action ledger, so its call could not be kept to once. \
Set RunConfig::action_ledger"
.to_string(),
},
None,
);
};
if dispatch.checkpointer.is_none() {
return GovernedRun::failed(
GovernedError::Unavailable {
node,
detail: "the graph has no checkpointer, so its call could not be kept to once \
in its lineage. Add one with with_checkpointer"
.to_string(),
},
None,
);
}
let call_args = dispatch.node.call_args(ctx).unwrap_or_else(|| state_args(&ctx.state));
let base_key = format!(
"graph/{}/{}/{node}/{}/{}",
gate.acting_context().agent.id,
dispatch.root,
dispatch.occurrence,
adk_core::json_digest(&call_args)
);
let answered = match lookup(ledger.as_ref(), &node, &base_key).await {
Lookup::Free(key) => Ok(key),
Lookup::Done(key) => Err(replay(&dispatch, key).await),
Lookup::Failed(run) => Err(*run),
};
let key = match answered {
Ok(key) => key,
Err(run) => {
let unread = matches!(
&run.output,
Err(error) if GovernedError::code_of(error) == Some("graph.unavailable")
);
if let Some(held) = dispatch.held.as_ref().filter(|_| !unread) {
withdraw(&gate, held, &node).await;
}
return run;
}
};
let mut resuming = None;
if let Some(held) = dispatch.held.clone() {
if held.args == call_args {
match adk_core::confirmation_decision_available(&gate, &held).await {
Ok(false) => {
tracing::debug!(node = %node, "governed node still waits for its decision");
let interrupt =
GraphToolConfirmationPause::pending_interrupt(node, held.clone());
return GovernedRun {
output: Ok(NodeOutput::new().with_interrupt(interrupt)),
status: NodeStatus::Paused,
effect_key: Some(key),
held: Some(held),
};
}
Ok(true) => resuming = Some(held),
Err(error) => {
return GovernedRun::failed(
GovernedError::Unavailable {
node,
detail: format!(
"the approval store could not be read: {}",
error.redacted()
),
},
Some(key),
);
}
}
} else {
withdraw(&gate, &held, &node).await;
}
}
let mut call = GovernedCall::new(
node.clone(),
format!("{}/{node}/{}", dispatch.run_id, dispatch.occurrence),
call_args.clone(),
)
.with_effect(dispatch.effect)
.requiring_confirmation(dispatch.governed.requires_approval);
call.origin = Some(ToolOrigin::new(format!("graph:{agent_name}"), &dispatch.declaration, None));
if let Some(held) = resuming {
call = call.resuming(held);
}
let args = match adk_core::authorize_tool_call(&gate, call).await {
Ok(ToolAuthorization::Execute { args, .. }) => args,
Ok(ToolAuthorization::Pending { request, reason }) => {
tracing::info!(node = %node, reason = %reason, "governed node waits for a decision");
let interrupt = GraphToolConfirmationPause::pending_interrupt(node, request.clone());
return GovernedRun {
output: Ok(NodeOutput::new().with_interrupt(interrupt)),
status: NodeStatus::Paused,
effect_key: Some(key),
held: Some(request),
};
}
Ok(ToolAuthorization::Refuse { reason, .. }) => {
tracing::info!(node = %node, "governed node refused");
return GovernedRun::failed(GovernedError::Refused { node, reason }, Some(key));
}
Err(error) if error.code.starts_with("governance.") => {
return GovernedRun::failed(
GovernedError::Frozen { node, reason: error.message },
None,
);
}
Err(error) => {
return GovernedRun::failed(
GovernedError::Unavailable {
node,
detail: format!("the approval gate failed: {}", error.redacted()),
},
Some(key),
);
}
};
let edited = (args != call_args).then_some(args);
let record = ActionRecord::new(
key.clone(),
node.clone(),
edited.as_ref().unwrap_or(&call_args),
dispatch.effect,
);
let begun = match ledger.begin(&record).await {
Ok(()) => Some(ledger.as_ref()),
Err(error) if error.code == "tool.action_ledger.duplicate_key" => {
return GovernedRun::failed(
GovernedError::OutcomeUnknown { node, key: key.clone() },
Some(key),
);
}
Err(error) => {
return GovernedRun::failed(
GovernedError::Unavailable {
node,
detail: format!(
"the action ledger could not record the call: {}",
error.redacted()
),
},
Some(key),
);
}
};
if let Err(frozen) = run_config.check_governance() {
complete(
begun,
&node,
&key,
ActionOutcome::Failed { error: adk_core::not_run_text(&frozen) },
)
.await;
return GovernedRun::failed(
GovernedError::Frozen { node, reason: frozen.message },
Some(key),
);
}
crate::executor::begin_attempt(ctx);
let ran = run_with_timeout(&node, dispatch.run_timeout, async {
match edited {
Some(args) => dispatch.node.run_call(ctx, args).await,
None => dispatch.node.execute(ctx).await,
}
})
.await;
match ran {
Ok(output) if output.interrupt.is_some() => {
let note = adk_core::not_run_text(&adk_core::AdkError::agent(
"the node paused before it acted",
));
complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
GovernedRun {
output: Ok(output),
status: NodeStatus::Paused,
effect_key: Some(key),
held: None,
}
}
Ok(output) => {
let writes: BTreeMap<String, Value> =
output.updates.iter().map(|(key, value)| (key.clone(), value.clone())).collect();
let digest = adk_core::json_digest(&serde_json::to_value(&writes).unwrap_or_default());
complete(begun, &node, &key, ActionOutcome::Succeeded { result_digest: digest }).await;
if let Some(checkpointer) = &dispatch.checkpointer {
let entry = EffectRecord {
key: key.clone(),
node: node.clone(),
writes,
goto: output.goto.clone(),
goto_parent: output.goto_parent.clone(),
thread: dispatch.thread_id.clone(),
checkpoint: dispatch.checkpoint_id.clone(),
at: crate::record::now(),
};
if let Err(error) =
append_effect(checkpointer.as_ref(), &dispatch.root, &entry).await
{
tracing::error!(
node = %node,
error = %error,
"the effect log could not record a governed call's writes"
);
}
}
GovernedRun {
output: Ok(output),
status: NodeStatus::Done,
effect_key: Some(key),
held: None,
}
}
Err(error) if GovernedError::code_of(&error) == Some("graph.refused") => {
let note =
adk_core::not_run_text(&adk_core::AdkError::agent("the node refused the call"));
complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
GovernedRun {
output: Err(error),
status: NodeStatus::Refused,
effect_key: Some(key),
held: None,
}
}
Err(error) if GovernedError::code_of(&error) == Some("graph.edit_unsupported") => {
let note = adk_core::not_run_text(&adk_core::AdkError::agent(
"the node cannot run an edited call",
));
complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
GovernedRun::failed(GovernedError::EditUnsupported { node }, Some(key))
}
Err(error)
if matches!(error, GraphError::NodeTimedOut { .. })
|| GovernedError::code_of(&error) == Some("graph.outcome_unknown") =>
{
tracing::warn!(node = %node, "governed node's outcome is unknown");
GovernedRun {
output: Err(error),
status: NodeStatus::Failed,
effect_key: Some(key),
held: None,
}
}
Err(error) => {
complete(begun, &node, &key, ActionOutcome::Failed { error: error.to_string() }).await;
GovernedRun {
output: Err(error),
status: NodeStatus::Failed,
effect_key: Some(key),
held: None,
}
}
}
}
enum Lookup {
Free(String),
Done(String),
Failed(Box<GovernedRun>),
}
async fn lookup(ledger: &dyn adk_core::ActionLedger, node: &str, base: &str) -> Lookup {
for slot in 1..=MAX_SLOTS {
let key = if slot == 1 { base.to_string() } else { format!("{base}#{slot}") };
let record = match ledger.get(&key).await {
Ok(record) => record,
Err(error) => {
return Lookup::Failed(Box::new(GovernedRun::failed(
GovernedError::Unavailable {
node: node.to_string(),
detail: format!(
"the action ledger could not be read: {}",
error.redacted()
),
},
Some(key),
)));
}
};
let Some(record) = record else { return Lookup::Free(key) };
match record.outcome {
Some(ActionOutcome::Succeeded { .. }) => return Lookup::Done(key),
Some(ActionOutcome::Failed { error }) if adk_core::is_not_run(&error) => continue,
Some(ActionOutcome::Failed { error }) => {
return Lookup::Failed(Box::new(GovernedRun::failed(
GovernedError::RecordedFailure { node: node.to_string(), error },
Some(key),
)));
}
_ => {
return Lookup::Failed(Box::new(GovernedRun::failed(
GovernedError::OutcomeUnknown { node: node.to_string(), key: key.clone() },
Some(key),
)));
}
}
}
Lookup::Failed(Box::new(GovernedRun::failed(
GovernedError::Unavailable {
node: node.to_string(),
detail: format!("the call was refused {MAX_SLOTS} times; fork to make a new call"),
},
Some(base.to_string()),
)))
}
async fn replay(dispatch: &GovernedDispatch, key: String) -> GovernedRun {
let node = dispatch.node_name.clone();
let Some(checkpointer) = &dispatch.checkpointer else {
return GovernedRun::failed(
GovernedError::EffectUnavailable { node, key: key.clone() },
Some(key),
);
};
let effect = match effect_log(checkpointer.as_ref(), &dispatch.root).await {
Ok(entries) => entries.into_iter().rev().find(|entry| entry.key == key),
Err(error) => {
return GovernedRun::failed(
GovernedError::Unavailable {
node,
detail: format!("the effect log could not be read: {error}"),
},
Some(key),
);
}
};
let Some(effect) = effect else {
return GovernedRun::failed(
GovernedError::EffectUnavailable { node, key: key.clone() },
Some(key),
);
};
tracing::info!(node = %node, effect.key = %key, "governed call answered from its record");
let mut output = NodeOutput::new().with_updates(effect.writes.into_iter().collect());
output.goto = effect.goto;
output.goto_parent = effect.goto_parent;
GovernedRun {
output: Ok(output),
status: NodeStatus::Recorded,
effect_key: Some(key),
held: None,
}
}
async fn withdraw(gate: &ToolGate<'_>, held: &ToolConfirmationRequest, node: &str) {
if let Err(error) = adk_core::withdraw_held_call(gate, held).await {
tracing::warn!(node = %node, error = %error, "a governed node's waiting decision could not be withdrawn");
}
}
async fn complete(
ledger: Option<&dyn adk_core::ActionLedger>,
node: &str,
key: &str,
outcome: ActionOutcome,
) {
let Some(ledger) = ledger else { return };
if let Err(error) = ledger.complete(key, outcome).await {
tracing::error!(
node = %node,
effect.key = %key,
error = %error,
"the action ledger could not record a governed call's outcome"
);
}
}
async fn run_with_timeout(
node: &str,
timeout: Option<Duration>,
call: impl std::future::Future<Output = Result<NodeOutput>>,
) -> Result<NodeOutput> {
match timeout {
Some(limit) => tokio::time::timeout(limit, call).await.unwrap_or_else(|_| {
Err(GraphError::NodeTimedOut { node: node.to_string(), elapsed: limit })
}),
None => call.await,
}
}
fn state_args(state: &State) -> Value {
let sorted: BTreeMap<&String, &Value> =
state.iter().filter(|(key, _)| key.as_str() != SESSION_ID_KEY).collect();
serde_json::to_value(sorted).unwrap_or(Value::Null)
}
const SESSION_ID_KEY: &str = "session_id";
#[cfg(feature = "action-http")]
pub(crate) fn sent_without_outcome(node: &str, detail: &str) -> GraphError {
GraphError::NodeExecutionFailed {
node: node.to_string(),
message: format!(
"graph.outcome_unknown: governed node '{node}' sent its call and {detail}, so it may \
have taken effect. It is not run again; check the effect, then fork with changed \
state to make a new call"
),
}
}