1use std::collections::BTreeMap;
63use std::sync::Arc;
64use std::time::Duration;
65
66use adk_core::{
67 ActionOutcome, ActionRecord, ApprovalScope, GovernedCall, RunConfig, ToolAuthorization,
68 ToolConfirmationRequest, ToolEffect, ToolGate, ToolOrigin,
69};
70use chrono::{DateTime, Utc};
71use serde::{Deserialize, Serialize};
72use serde_json::Value;
73use thiserror::Error;
74
75use crate::checkpoint::Checkpointer;
76use crate::error::{GraphError, Result};
77use crate::graph::CompiledGraph;
78use crate::interrupt::GraphToolConfirmationPause;
79use crate::node::{Node, NodeContext, NodeOutput};
80use crate::record::NodeStatus;
81use crate::state::{Checkpoint, State};
82
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct GovernedNode {
101 pub requires_approval: bool,
103 pub spends_money: bool,
105}
106
107impl GovernedNode {
108 pub fn new() -> Self {
110 Self::default()
111 }
112
113 #[must_use]
115 pub fn with_approval(mut self) -> Self {
116 self.requires_approval = true;
117 self
118 }
119
120 #[must_use]
122 pub fn spending_money(mut self) -> Self {
123 self.spends_money = true;
124 self
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Error)]
143#[non_exhaustive]
144pub enum GovernedError {
145 #[error(
147 "graph.not_run: governed node '{node}' was not run: the run has no approval gate. Run \
148 the graph as a GraphAgent under a Runner, or with invoke_with_run_config"
149 )]
150 NotRun {
151 node: String,
153 },
154 #[error("graph.frozen: governed node '{node}' was not run: {reason}")]
156 Frozen {
157 node: String,
159 reason: String,
161 },
162 #[error("graph.refused: governed node '{node}' was not run: {reason}")]
164 Refused {
165 node: String,
167 reason: String,
169 },
170 #[error(
172 "graph.recorded_failure: governed node '{node}' already ran this call and it failed: \
173 {error}. It is not run again; fork with changed state to make a new call"
174 )]
175 RecordedFailure {
176 node: String,
178 error: String,
180 },
181 #[error(
183 "graph.outcome_unknown: governed node '{node}' began this call before and recorded no \
184 outcome, so it may have taken effect. It is not run again; check the effect, then \
185 fork with changed state to make a new call (ledger key '{key}')"
186 )]
187 OutcomeUnknown {
188 node: String,
190 key: String,
192 },
193 #[error(
195 "graph.effect_unavailable: governed node '{node}' already completed this call, but \
196 its writes are not in the effect log. It is not run again (ledger key '{key}')"
197 )]
198 EffectUnavailable {
199 node: String,
201 key: String,
203 },
204 #[error(
206 "graph.edit_unsupported: governed node '{node}' cannot run an edited call, so it was \
207 not run. Approve the call as shown, or deny it"
208 )]
209 EditUnsupported {
210 node: String,
212 },
213 #[error("graph.unavailable: governed node '{node}' was not run: {detail}")]
216 Unavailable {
217 node: String,
219 detail: String,
221 },
222}
223
224impl GovernedError {
225 pub const CODES: [&'static str; 8] = [
227 "graph.not_run",
228 "graph.frozen",
229 "graph.refused",
230 "graph.recorded_failure",
231 "graph.outcome_unknown",
232 "graph.effect_unavailable",
233 "graph.edit_unsupported",
234 "graph.unavailable",
235 ];
236
237 pub fn code(&self) -> &'static str {
249 match self {
250 Self::NotRun { .. } => Self::CODES[0],
251 Self::Frozen { .. } => Self::CODES[1],
252 Self::Refused { .. } => Self::CODES[2],
253 Self::RecordedFailure { .. } => Self::CODES[3],
254 Self::OutcomeUnknown { .. } => Self::CODES[4],
255 Self::EffectUnavailable { .. } => Self::CODES[5],
256 Self::EditUnsupported { .. } => Self::CODES[6],
257 Self::Unavailable { .. } => Self::CODES[7],
258 }
259 }
260
261 pub fn code_of(error: &GraphError) -> Option<&'static str> {
273 let GraphError::NodeExecutionFailed { message, .. } = error else { return None };
274 Self::CODES
275 .into_iter()
276 .find(|code| message.strip_prefix(code).is_some_and(|rest| rest.starts_with(':')))
277 }
278
279 fn node(&self) -> &str {
281 match self {
282 Self::NotRun { node }
283 | Self::Frozen { node, .. }
284 | Self::Refused { node, .. }
285 | Self::RecordedFailure { node, .. }
286 | Self::OutcomeUnknown { node, .. }
287 | Self::EffectUnavailable { node, .. }
288 | Self::EditUnsupported { node }
289 | Self::Unavailable { node, .. } => node,
290 }
291 }
292
293 fn status(&self) -> NodeStatus {
295 match self {
296 Self::NotRun { .. } => NodeStatus::NotRun,
297 Self::Frozen { .. } | Self::Refused { .. } | Self::EditUnsupported { .. } => {
298 NodeStatus::Refused
299 }
300 Self::RecordedFailure { .. }
301 | Self::OutcomeUnknown { .. }
302 | Self::EffectUnavailable { .. }
303 | Self::Unavailable { .. } => NodeStatus::Failed,
304 }
305 }
306}
307
308impl From<GovernedError> for GraphError {
309 fn from(error: GovernedError) -> Self {
310 GraphError::NodeExecutionFailed {
311 node: error.node().to_string(),
312 message: error.to_string(),
313 }
314 }
315}
316
317pub const EFFECT_METADATA_KEY: &str = "adk.graph.effect";
319
320#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
341#[serde(rename_all = "camelCase")]
342pub struct EffectRecord {
343 pub key: String,
345 pub node: String,
347 pub writes: BTreeMap<String, Value>,
349 #[serde(default, skip_serializing_if = "Option::is_none")]
351 pub goto: Option<Vec<String>>,
352 #[serde(default, skip_serializing_if = "Option::is_none")]
355 pub goto_parent: Option<Vec<String>>,
356 pub thread: String,
358 pub checkpoint: String,
360 pub at: DateTime<Utc>,
362}
363
364pub fn effect_log_thread(root: &str) -> String {
372 format!("{root}:effects")
373}
374
375pub async fn effect_log(checkpointer: &dyn Checkpointer, root: &str) -> Result<Vec<EffectRecord>> {
396 let entries = checkpointer.list(&effect_log_thread(root)).await?;
397 entries
398 .iter()
399 .filter_map(|checkpoint| checkpoint.metadata.get(EFFECT_METADATA_KEY))
400 .map(|value| {
401 serde_json::from_value(value.clone()).map_err(|error| {
402 GraphError::SerializationError(format!("effect log entry is malformed: {error}"))
403 })
404 })
405 .collect()
406}
407
408async fn append_effect(
410 checkpointer: &dyn Checkpointer,
411 root: &str,
412 entry: &EffectRecord,
413) -> Result<()> {
414 let thread = effect_log_thread(root);
415 let value = serde_json::to_value(entry)?;
416 for _ in 0..16 {
418 let (version, index) = checkpointer
419 .load(&thread)
420 .await?
421 .map_or((1, 0), |newest| (newest.version + 1, newest.step + 1));
422 let checkpoint = Checkpoint::new(&thread, State::new(), index, Vec::new())
423 .with_version(version)
424 .with_metadata(EFFECT_METADATA_KEY, value.clone());
425 match checkpointer.save(&checkpoint).await {
426 Ok(_) => return Ok(()),
427 Err(GraphError::CheckpointConflict { .. }) => continue,
428 Err(error) => return Err(error),
429 }
430 }
431 Err(GraphError::CheckpointError(format!(
432 "the effect log '{thread}' kept changing while an entry was appended"
433 )))
434}
435
436pub(crate) const STANDALONE_AGENT_NAME: &str = "graph";
438
439const MAX_SLOTS: u32 = 16;
441
442pub(crate) struct GovernedDispatch {
445 pub(crate) node_name: String,
446 pub(crate) node: Arc<dyn Node>,
447 pub(crate) governed: GovernedNode,
448 pub(crate) effect: ToolEffect,
449 pub(crate) declaration: Value,
451 pub(crate) root: String,
452 pub(crate) run_id: String,
453 pub(crate) occurrence: u32,
454 pub(crate) held: Option<ToolConfirmationRequest>,
456 pub(crate) checkpointer: Option<Arc<dyn Checkpointer>>,
457 pub(crate) thread_id: String,
458 pub(crate) checkpoint_id: String,
460 pub(crate) run_timeout: Option<Duration>,
461}
462
463pub(crate) struct GovernedRun {
465 pub(crate) output: Result<NodeOutput>,
466 pub(crate) status: NodeStatus,
467 pub(crate) effect_key: Option<String>,
468 pub(crate) held: Option<ToolConfirmationRequest>,
470}
471
472impl GovernedRun {
473 fn failed(error: GovernedError, effect_key: Option<String>) -> Self {
474 let status = error.status();
475 Self { output: Err(error.into()), status, effect_key, held: None }
476 }
477}
478
479impl CompiledGraph {
480 #[must_use]
504 pub fn with_governed_node(mut self, node: &str, governed: GovernedNode) -> Self {
505 self.governed_nodes.insert(node.to_string(), governed);
506 self
507 }
508
509 pub(crate) fn is_governed(&self, node: &str) -> bool {
511 self.governed_nodes.contains_key(node)
512 }
513
514 pub(crate) fn check_governed_nodes(&self) -> Result<()> {
517 let mut unknown: Vec<&String> =
518 self.governed_nodes.keys().filter(|name| !self.nodes.contains_key(*name)).collect();
519 unknown.sort();
520 match unknown.first() {
521 Some(name) => Err(GraphError::InvalidGraph(format!(
522 "governed node '{name}' is not a node of this graph, so the node it names \
523 would run ungoverned. Govern a node by the name it was added under"
524 ))),
525 None => Ok(()),
526 }
527 }
528}
529
530pub(crate) async fn dispatch(dispatch: GovernedDispatch, ctx: &NodeContext) -> GovernedRun {
533 debug_assert!(ctx.governed_call(), "a governed node's context is marked as its call");
534 let node = dispatch.node_name.clone();
535 let parent = ctx.config.parent_context.clone();
536 let explicit = ctx.run_config();
537
538 let run_config: &RunConfig = match (&explicit, &parent) {
540 (Some(config), _) => config,
541 (None, Some(parent)) => parent.run_config(),
542 (None, None) => {
543 tracing::warn!(node = %node, "governed node not run: the run has no approval gate");
544 return GovernedRun::failed(GovernedError::NotRun { node }, None);
545 }
546 };
547 let gate = match (&explicit, &parent) {
548 (None, Some(parent)) => ToolGate::for_context(parent.as_ref()),
549 (_, Some(parent)) => ToolGate::new(
550 run_config,
551 parent.agent_name(),
552 parent.invocation_id(),
553 ApprovalScope::new(parent.app_name(), parent.user_id(), parent.session_id()),
554 ),
555 (_, None) => ToolGate::new(
556 run_config,
557 STANDALONE_AGENT_NAME,
558 &dispatch.run_id,
559 ApprovalScope::new(
560 crate::node::STANDALONE_APP_NAME,
561 crate::node::STANDALONE_USER_ID,
562 &dispatch.thread_id,
563 ),
564 ),
565 };
566 let agent_name = parent.as_ref().map_or(STANDALONE_AGENT_NAME, |parent| parent.agent_name());
567
568 if let Err(frozen) = run_config.check_governance() {
570 return GovernedRun::failed(GovernedError::Frozen { node, reason: frozen.message }, None);
571 }
572
573 match dispatch.node.will_act(ctx) {
576 Ok(true) => {}
577 Ok(false) => {
578 tracing::debug!(node = %node, "governed node does nothing here; no decision");
579 if let Some(held) = dispatch.held.as_ref() {
580 withdraw(&gate, held, &node).await;
581 }
582 return GovernedRun {
583 output: Ok(NodeOutput::new()),
584 status: NodeStatus::Done,
585 effect_key: None,
586 held: None,
587 };
588 }
589 Err(error) => {
590 if let Some(held) = dispatch.held.as_ref() {
591 withdraw(&gate, held, &node).await;
592 }
593 return GovernedRun {
594 output: Err(error),
595 status: NodeStatus::Failed,
596 effect_key: None,
597 held: None,
598 };
599 }
600 }
601
602 let Some(ledger) = run_config.action_ledger.clone() else {
604 return GovernedRun::failed(
605 GovernedError::Unavailable {
606 node,
607 detail: "the run has no action ledger, so its call could not be kept to once. \
608 Set RunConfig::action_ledger"
609 .to_string(),
610 },
611 None,
612 );
613 };
614 if dispatch.checkpointer.is_none() {
615 return GovernedRun::failed(
616 GovernedError::Unavailable {
617 node,
618 detail: "the graph has no checkpointer, so its call could not be kept to once \
619 in its lineage. Add one with with_checkpointer"
620 .to_string(),
621 },
622 None,
623 );
624 }
625
626 let call_args = dispatch.node.call_args(ctx).unwrap_or_else(|| state_args(&ctx.state));
627 let base_key = format!(
628 "graph/{}/{}/{node}/{}/{}",
629 gate.acting_context().agent.id,
630 dispatch.root,
631 dispatch.occurrence,
632 adk_core::json_digest(&call_args)
633 );
634
635 let answered = match lookup(ledger.as_ref(), &node, &base_key).await {
638 Lookup::Free(key) => Ok(key),
639 Lookup::Done(key) => Err(replay(&dispatch, key).await),
640 Lookup::Failed(run) => Err(*run),
641 };
642 let key = match answered {
643 Ok(key) => key,
644 Err(run) => {
645 let unread = matches!(
648 &run.output,
649 Err(error) if GovernedError::code_of(error) == Some("graph.unavailable")
650 );
651 if let Some(held) = dispatch.held.as_ref().filter(|_| !unread) {
652 withdraw(&gate, held, &node).await;
653 }
654 return run;
655 }
656 };
657
658 let mut resuming = None;
662 if let Some(held) = dispatch.held.clone() {
663 if held.args == call_args {
664 match adk_core::confirmation_decision_available(&gate, &held).await {
665 Ok(false) => {
666 tracing::debug!(node = %node, "governed node still waits for its decision");
667 let interrupt =
668 GraphToolConfirmationPause::pending_interrupt(node, held.clone());
669 return GovernedRun {
670 output: Ok(NodeOutput::new().with_interrupt(interrupt)),
671 status: NodeStatus::Paused,
672 effect_key: Some(key),
673 held: Some(held),
674 };
675 }
676 Ok(true) => resuming = Some(held),
677 Err(error) => {
678 return GovernedRun::failed(
679 GovernedError::Unavailable {
680 node,
681 detail: format!(
682 "the approval store could not be read: {}",
683 error.redacted()
684 ),
685 },
686 Some(key),
687 );
688 }
689 }
690 } else {
691 withdraw(&gate, &held, &node).await;
692 }
693 }
694
695 let mut call = GovernedCall::new(
697 node.clone(),
698 format!("{}/{node}/{}", dispatch.run_id, dispatch.occurrence),
699 call_args.clone(),
700 )
701 .with_effect(dispatch.effect)
702 .requiring_confirmation(dispatch.governed.requires_approval);
703 call.origin = Some(ToolOrigin::new(format!("graph:{agent_name}"), &dispatch.declaration, None));
704 if let Some(held) = resuming {
705 call = call.resuming(held);
706 }
707 let args = match adk_core::authorize_tool_call(&gate, call).await {
708 Ok(ToolAuthorization::Execute { args, .. }) => args,
709 Ok(ToolAuthorization::Pending { request, reason }) => {
710 tracing::info!(node = %node, reason = %reason, "governed node waits for a decision");
711 let interrupt = GraphToolConfirmationPause::pending_interrupt(node, request.clone());
712 return GovernedRun {
713 output: Ok(NodeOutput::new().with_interrupt(interrupt)),
714 status: NodeStatus::Paused,
715 effect_key: Some(key),
716 held: Some(request),
717 };
718 }
719 Ok(ToolAuthorization::Refuse { reason, .. }) => {
720 tracing::info!(node = %node, "governed node refused");
721 return GovernedRun::failed(GovernedError::Refused { node, reason }, Some(key));
722 }
723 Err(error) if error.code.starts_with("governance.") => {
724 return GovernedRun::failed(
725 GovernedError::Frozen { node, reason: error.message },
726 None,
727 );
728 }
729 Err(error) => {
730 return GovernedRun::failed(
731 GovernedError::Unavailable {
732 node,
733 detail: format!("the approval gate failed: {}", error.redacted()),
734 },
735 Some(key),
736 );
737 }
738 };
739 let edited = (args != call_args).then_some(args);
740
741 let record = ActionRecord::new(
743 key.clone(),
744 node.clone(),
745 edited.as_ref().unwrap_or(&call_args),
746 dispatch.effect,
747 );
748 let begun = match ledger.begin(&record).await {
749 Ok(()) => Some(ledger.as_ref()),
750 Err(error) if error.code == "tool.action_ledger.duplicate_key" => {
751 return GovernedRun::failed(
753 GovernedError::OutcomeUnknown { node, key: key.clone() },
754 Some(key),
755 );
756 }
757 Err(error) => {
758 return GovernedRun::failed(
759 GovernedError::Unavailable {
760 node,
761 detail: format!(
762 "the action ledger could not record the call: {}",
763 error.redacted()
764 ),
765 },
766 Some(key),
767 );
768 }
769 };
770 if let Err(frozen) = run_config.check_governance() {
772 complete(
773 begun,
774 &node,
775 &key,
776 ActionOutcome::Failed { error: adk_core::not_run_text(&frozen) },
777 )
778 .await;
779 return GovernedRun::failed(
780 GovernedError::Frozen { node, reason: frozen.message },
781 Some(key),
782 );
783 }
784
785 crate::executor::begin_attempt(ctx);
786 let ran = run_with_timeout(&node, dispatch.run_timeout, async {
787 match edited {
788 Some(args) => dispatch.node.run_call(ctx, args).await,
789 None => dispatch.node.execute(ctx).await,
790 }
791 })
792 .await;
793
794 match ran {
795 Ok(output) if output.interrupt.is_some() => {
796 let note = adk_core::not_run_text(&adk_core::AdkError::agent(
798 "the node paused before it acted",
799 ));
800 complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
801 GovernedRun {
802 output: Ok(output),
803 status: NodeStatus::Paused,
804 effect_key: Some(key),
805 held: None,
806 }
807 }
808 Ok(output) => {
809 let writes: BTreeMap<String, Value> =
810 output.updates.iter().map(|(key, value)| (key.clone(), value.clone())).collect();
811 let digest = adk_core::json_digest(&serde_json::to_value(&writes).unwrap_or_default());
812 complete(begun, &node, &key, ActionOutcome::Succeeded { result_digest: digest }).await;
813 if let Some(checkpointer) = &dispatch.checkpointer {
814 let entry = EffectRecord {
815 key: key.clone(),
816 node: node.clone(),
817 writes,
818 goto: output.goto.clone(),
819 goto_parent: output.goto_parent.clone(),
820 thread: dispatch.thread_id.clone(),
821 checkpoint: dispatch.checkpoint_id.clone(),
822 at: crate::record::now(),
823 };
824 if let Err(error) =
825 append_effect(checkpointer.as_ref(), &dispatch.root, &entry).await
826 {
827 tracing::error!(
829 node = %node,
830 error = %error,
831 "the effect log could not record a governed call's writes"
832 );
833 }
834 }
835 GovernedRun {
836 output: Ok(output),
837 status: NodeStatus::Done,
838 effect_key: Some(key),
839 held: None,
840 }
841 }
842 Err(error) if GovernedError::code_of(&error) == Some("graph.refused") => {
843 let note =
845 adk_core::not_run_text(&adk_core::AdkError::agent("the node refused the call"));
846 complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
847 GovernedRun {
848 output: Err(error),
849 status: NodeStatus::Refused,
850 effect_key: Some(key),
851 held: None,
852 }
853 }
854 Err(error) if GovernedError::code_of(&error) == Some("graph.edit_unsupported") => {
855 let note = adk_core::not_run_text(&adk_core::AdkError::agent(
856 "the node cannot run an edited call",
857 ));
858 complete(begun, &node, &key, ActionOutcome::Failed { error: note }).await;
859 GovernedRun::failed(GovernedError::EditUnsupported { node }, Some(key))
860 }
861 Err(error)
862 if matches!(error, GraphError::NodeTimedOut { .. })
863 || GovernedError::code_of(&error) == Some("graph.outcome_unknown") =>
864 {
865 tracing::warn!(node = %node, "governed node's outcome is unknown");
868 GovernedRun {
869 output: Err(error),
870 status: NodeStatus::Failed,
871 effect_key: Some(key),
872 held: None,
873 }
874 }
875 Err(error) => {
876 complete(begun, &node, &key, ActionOutcome::Failed { error: error.to_string() }).await;
877 GovernedRun {
878 output: Err(error),
879 status: NodeStatus::Failed,
880 effect_key: Some(key),
881 held: None,
882 }
883 }
884 }
885}
886
887enum Lookup {
889 Free(String),
891 Done(String),
893 Failed(Box<GovernedRun>),
895}
896
897async fn lookup(ledger: &dyn adk_core::ActionLedger, node: &str, base: &str) -> Lookup {
900 for slot in 1..=MAX_SLOTS {
901 let key = if slot == 1 { base.to_string() } else { format!("{base}#{slot}") };
902 let record = match ledger.get(&key).await {
903 Ok(record) => record,
904 Err(error) => {
905 return Lookup::Failed(Box::new(GovernedRun::failed(
906 GovernedError::Unavailable {
907 node: node.to_string(),
908 detail: format!(
909 "the action ledger could not be read: {}",
910 error.redacted()
911 ),
912 },
913 Some(key),
914 )));
915 }
916 };
917 let Some(record) = record else { return Lookup::Free(key) };
918 match record.outcome {
919 Some(ActionOutcome::Succeeded { .. }) => return Lookup::Done(key),
920 Some(ActionOutcome::Failed { error }) if adk_core::is_not_run(&error) => continue,
921 Some(ActionOutcome::Failed { error }) => {
922 return Lookup::Failed(Box::new(GovernedRun::failed(
923 GovernedError::RecordedFailure { node: node.to_string(), error },
924 Some(key),
925 )));
926 }
927 _ => {
929 return Lookup::Failed(Box::new(GovernedRun::failed(
930 GovernedError::OutcomeUnknown { node: node.to_string(), key: key.clone() },
931 Some(key),
932 )));
933 }
934 }
935 }
936 Lookup::Failed(Box::new(GovernedRun::failed(
937 GovernedError::Unavailable {
938 node: node.to_string(),
939 detail: format!("the call was refused {MAX_SLOTS} times; fork to make a new call"),
940 },
941 Some(base.to_string()),
942 )))
943}
944
945async fn replay(dispatch: &GovernedDispatch, key: String) -> GovernedRun {
947 let node = dispatch.node_name.clone();
948 let Some(checkpointer) = &dispatch.checkpointer else {
949 return GovernedRun::failed(
950 GovernedError::EffectUnavailable { node, key: key.clone() },
951 Some(key),
952 );
953 };
954 let effect = match effect_log(checkpointer.as_ref(), &dispatch.root).await {
955 Ok(entries) => entries.into_iter().rev().find(|entry| entry.key == key),
956 Err(error) => {
957 return GovernedRun::failed(
958 GovernedError::Unavailable {
959 node,
960 detail: format!("the effect log could not be read: {error}"),
961 },
962 Some(key),
963 );
964 }
965 };
966 let Some(effect) = effect else {
967 return GovernedRun::failed(
968 GovernedError::EffectUnavailable { node, key: key.clone() },
969 Some(key),
970 );
971 };
972 tracing::info!(node = %node, effect.key = %key, "governed call answered from its record");
973 let mut output = NodeOutput::new().with_updates(effect.writes.into_iter().collect());
974 output.goto = effect.goto;
975 output.goto_parent = effect.goto_parent;
976 GovernedRun {
977 output: Ok(output),
978 status: NodeStatus::Recorded,
979 effect_key: Some(key),
980 held: None,
981 }
982}
983
984async fn withdraw(gate: &ToolGate<'_>, held: &ToolConfirmationRequest, node: &str) {
986 if let Err(error) = adk_core::withdraw_held_call(gate, held).await {
987 tracing::warn!(node = %node, error = %error, "a governed node's waiting decision could not be withdrawn");
988 }
989}
990
991async fn complete(
994 ledger: Option<&dyn adk_core::ActionLedger>,
995 node: &str,
996 key: &str,
997 outcome: ActionOutcome,
998) {
999 let Some(ledger) = ledger else { return };
1000 if let Err(error) = ledger.complete(key, outcome).await {
1001 tracing::error!(
1002 node = %node,
1003 effect.key = %key,
1004 error = %error,
1005 "the action ledger could not record a governed call's outcome"
1006 );
1007 }
1008}
1009
1010async fn run_with_timeout(
1013 node: &str,
1014 timeout: Option<Duration>,
1015 call: impl std::future::Future<Output = Result<NodeOutput>>,
1016) -> Result<NodeOutput> {
1017 match timeout {
1018 Some(limit) => tokio::time::timeout(limit, call).await.unwrap_or_else(|_| {
1019 Err(GraphError::NodeTimedOut { node: node.to_string(), elapsed: limit })
1020 }),
1021 None => call.await,
1022 }
1023}
1024
1025fn state_args(state: &State) -> Value {
1029 let sorted: BTreeMap<&String, &Value> =
1030 state.iter().filter(|(key, _)| key.as_str() != SESSION_ID_KEY).collect();
1031 serde_json::to_value(sorted).unwrap_or(Value::Null)
1032}
1033
1034const SESSION_ID_KEY: &str = "session_id";
1036
1037#[cfg(feature = "action-http")]
1038pub(crate) fn sent_without_outcome(node: &str, detail: &str) -> GraphError {
1041 GraphError::NodeExecutionFailed {
1042 node: node.to_string(),
1043 message: format!(
1044 "graph.outcome_unknown: governed node '{node}' sent its call and {detail}, so it may \
1045 have taken effect. It is not run again; check the effect, then fork with changed \
1046 state to make a new call"
1047 ),
1048 }
1049}