Skip to main content

lellm_graph/node/
barrier_node.rs

1//! Human-in-the-loop 审批节点。
2//!
3//! v0.4+: 泛型化 `BarrierNode<S: WorkflowState>`。
4//!
5//! # 限制
6//!
7//! `BarrierNode` 要求 `S: WorkflowState<Mutation = StateMutation>`,
8//! 因为 `apply_decision_to_ctx()` 使用 key/value 操作(`Put`/`Delete`)。
9//! 对于 `AgentState` 等类型化状态,请实现自定义 Barrier 节点
10//! 或使用 `BarrierDecision` 枚举配合自定义逻辑。
11
12use async_trait::async_trait;
13
14use super::node_context::{LeafContext, NodeContext};
15#[allow(deprecated)]
16use super::{FlowNode, LeafNode};
17use crate::error::GraphError;
18use crate::event::{BarrierDecision, BarrierId};
19use crate::state::workflow_state::WorkflowState;
20use crate::state::{State, StateMutation};
21
22/// Barrier 超时后的默认行为。
23#[derive(Debug, Clone, Default)]
24pub enum BarrierDefaultAction {
25    #[default]
26    Reject,
27    Approve,
28    Skip,
29}
30
31/// Human-in-the-loop 审批节点。
32#[derive(Debug, Clone)]
33pub struct BarrierNode<S: WorkflowState = State> {
34    pub name: String,
35    pub timeout: Option<std::time::Duration>,
36    pub default_action: BarrierDefaultAction,
37    pub reject_key: String,
38    pub approve_key: String,
39    /// 拒绝(或超时 default_action=Reject)后的跳转目标节点。
40    /// 配置后 → goto 该节点处理拒绝;未配置 → 结束执行。
41    pub reject_target: Option<String>,
42    /// 每次 execute() 递增,生成唯一的 BarrierId::occurrence。
43    /// Arc 包裹确保 clone 后共享同一计数器。
44    occurrence_counter: std::sync::Arc<std::sync::atomic::AtomicU32>,
45    /// Phantom 用于标记泛型类型
46    _phantom: std::marker::PhantomData<S>,
47}
48
49impl<S: WorkflowState<Mutation = StateMutation>> BarrierNode<S> {
50    pub fn new(name: impl Into<String>) -> Self {
51        let name = name.into();
52        Self {
53            name: name.clone(),
54            timeout: None,
55            default_action: BarrierDefaultAction::default(),
56            reject_key: format!("{name}.reject_reason"),
57            approve_key: format!("{name}.approved"),
58            reject_target: None,
59            occurrence_counter: std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)),
60            _phantom: std::marker::PhantomData,
61        }
62    }
63
64    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
65        self.timeout = Some(timeout);
66        self
67    }
68
69    pub fn default_action(mut self, action: BarrierDefaultAction) -> Self {
70        self.default_action = action;
71        self
72    }
73
74    pub fn reject_key(mut self, key: impl Into<String>) -> Self {
75        self.reject_key = key.into();
76        self
77    }
78
79    pub fn approve_key(mut self, key: impl Into<String>) -> Self {
80        self.approve_key = key.into();
81        self
82    }
83
84    /// 设置拒绝(或超时 default_action=Reject)后的跳转目标节点。
85    pub fn reject_target(mut self, target: impl Into<String>) -> Self {
86        self.reject_target = Some(target.into());
87        self
88    }
89
90    pub fn apply_decision_to_ctx(&self, ctx: &mut NodeContext<'_, S>, decision: BarrierDecision) {
91        match decision {
92            BarrierDecision::Approve => {
93                tracing::info!(barrier = %self.name, "approved");
94                ctx.record(StateMutation::Put(
95                    self.approve_key.clone(),
96                    serde_json::json!(true),
97                ));
98                ctx.record(StateMutation::Delete(self.reject_key.clone()));
99            }
100            BarrierDecision::Reject { reason } => {
101                tracing::warn!(barrier = %self.name, reason = %reason, "rejected");
102                ctx.record(StateMutation::Put(
103                    self.reject_key.clone(),
104                    serde_json::json!(reason),
105                ));
106                ctx.record(StateMutation::Delete(self.approve_key.clone()));
107            }
108            BarrierDecision::Modify { key, value } => {
109                tracing::info!(barrier = %self.name, key = %key, "state modified");
110                ctx.record(StateMutation::Put(key, value));
111            }
112            BarrierDecision::Reroute { target } => {
113                tracing::info!(barrier = %self.name, target = %target, "rerouted");
114                ctx.goto(&target);
115            }
116        }
117    }
118}
119
120/// BarrierNode 实现 LeafNode(推荐路径 — 只读 state + pause)。
121#[async_trait]
122impl<S: WorkflowState> LeafNode<S> for BarrierNode<S> {
123    async fn execute(&self, ctx: &mut LeafContext<'_, S>) -> Result<(), GraphError> {
124        let occurrence = self
125            .occurrence_counter
126            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
127        let barrier_id = BarrierId::new(&self.name, occurrence);
128        ctx.pause(barrier_id, self.timeout);
129        ctx.set_has_side_effects();
130        Ok(())
131    }
132}
133
134#[allow(deprecated)]
135#[async_trait]
136impl<S: WorkflowState> FlowNode<S> for BarrierNode<S> {
137    async fn execute(&self, ctx: &mut NodeContext<'_, S>) -> Result<(), GraphError> {
138        let occurrence = self
139            .occurrence_counter
140            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
141        let barrier_id = BarrierId::new(&self.name, occurrence);
142        ctx.pause(barrier_id, self.timeout);
143        ctx.set_has_side_effects();
144        Ok(())
145    }
146}