Skip to main content

rusty_agent_runtime/
react.rs

1//! The prebuilt ReAct agent (LangGraph `create_react_agent` parity).
2//!
3//! [`create_react_agent`] assembles the classic reasoning-acting loop as a
4//! two-node cyclic graph over a single `messages` channel
5//! ([`Reducer::AddMessages`](crate::state::Reducer::AddMessages)):
6//!
7//! ```text
8//!         ┌──────────────────────────────────────────┐
9//!         │                                          │
10//!         ▼                                          │
11//!      [agent] ── last message has tool_calls? ──► [tools]
12//!         │                                          │
13//!         └─ no tool_calls ──► End ◄── static edge ──┘
14//! ```
15//!
16//! - **`agent`** — serializes the `messages` channel into
17//!   [`ChatMessage`]s, calls [`ChatModel::chat`] with the registry's
18//!   OpenAI-format tool schemas, and appends the assistant message (final
19//!   answer *or* tool-call request) back onto `messages`.
20//! - **`tools`** — takes the `tool_calls` of the last assistant message,
21//!   dispatches them in parallel through [`ToolExecutor::execute_batch`],
22//!   and appends one `role: "tool"` message per call.
23//! - **Routing** — a conditional edge on `agent` routes to `tools` when the
24//!   last message carries tool calls, otherwise to [`Route::End`]; a static
25//!   edge loops `tools → agent` so the model observes the tool results.
26//!
27//! The caller drives the returned [`Graph`] with a [`crate::state::StateSpec`]
28//! declaring `messages` with `Reducer::AddMessages` and an initial state
29//! seeding the conversation (see `examples/react_agent.rs`).
30//!
31//! Four flavors exist: [`create_react_agent`] (the agent node calls
32//! [`ChatModel::chat`]; no [`crate::executor::GraphEvent::Token`] events),
33//! [`create_react_agent_streaming`] (the agent node calls
34//! [`ChatModel::chat_stream`] and forwards deltas as
35//! [`crate::executor::GraphEvent::Token`]s into the run's event channel),
36//! and the Flight Recorder pair [`create_react_agent_with_recording`] /
37//! [`create_react_agent_replaying`].
38//!
39//! # Flight Recorder
40//!
41//! [`create_react_agent_with_recording`] wires the run's [`Journal`] into
42//! both nodes: every model call is journaled through
43//! [`crate::replay::RecordingChatModel`] and every tool call through
44//! [`crate::replay::RecordingTool`], in the canonical
45//! [`crate::replay::model_call_request`] / [`crate::replay::tool_call_request`]
46//! payload shapes, parented per iteration to the invocation's node-input
47//! event (the executor hands its id over via
48//! [`crate::journal::PARENT_EVENT_KEY`]). Attach the same journal to the run
49//! with [`crate::executor::RunConfig::with_journal`].
50//! [`create_react_agent_replaying`] is the mirror image for exact replay:
51//! the same topology with [`crate::replay::ReplayingChatModel`] /
52//! [`crate::replay::ReplayingTool`] answering from the recorded journal —
53//! zero outbound calls, so the wrapped model and tools may be
54//! panic-on-call sentinels. See `examples/react_record_replay.rs` for the
55//! full record → replay loop.
56
57use std::sync::Arc;
58
59use serde_json::Value;
60use tokio::sync::mpsc;
61
62use crate::error::{Result, RustyError};
63use crate::executor::GraphEvent;
64use crate::graph::{Graph, GraphBuilder, Route};
65use crate::journal::{Journal, PARENT_EVENT_KEY};
66use crate::llm::{ChatMessage, ChatModel};
67use crate::node::NodeOutput;
68use crate::replay::{
69    RecordingChatModel, RecordingTool, ReplaySource, ReplayingChatModel, ReplayingTool,
70};
71use crate::tool::{ToolExecutor, ToolRegistry};
72
73/// The state channel the ReAct loop reads from and appends to. Declare it
74/// with `Reducer::AddMessages` in the run's [`crate::state::StateSpec`].
75pub const MESSAGES_CHANNEL: &str = "messages";
76
77/// The name of the model-calling node in the compiled graph.
78pub const AGENT_NODE: &str = "agent";
79
80/// The name of the tool-dispatch node in the compiled graph.
81pub const TOOLS_NODE: &str = "tools";
82
83/// Read and deserialize the `messages` channel from a state snapshot.
84///
85/// A missing channel yields an empty conversation (the run may legitimately
86/// start before any message is seeded); a malformed channel is a hard error.
87fn read_messages(state: &crate::state::State) -> Result<Vec<ChatMessage>> {
88    Ok(state
89        .get_as::<Vec<ChatMessage>>(MESSAGES_CHANNEL)?
90        .unwrap_or_default())
91}
92
93/// How the prebuilt agent's model and tool calls relate to the Flight
94/// Recorder: not at all (the default), journaled live (record mode), or
95/// served from a recorded journal (exact-replay mode).
96#[derive(Debug, Clone)]
97enum EvidenceMode {
98    /// No recording — the pre-R0.5 behavior, byte-identical by construction
99    /// (the wrappers are never built and no parent key is read).
100    None,
101
102    /// Journal every model/tool call through the recording wrappers.
103    Record(Journal),
104
105    /// Answer every model/tool call from the recorded journal; the wrapped
106    /// implementations are carried for identity and never invoked.
107    Replay {
108        /// The serving cursor over the recorded run's effects.
109        source: ReplaySource,
110        /// The replay run's own journal (the recorded run's identity).
111        journal: Journal,
112    },
113}
114
115/// The causal parent for effects a node invocation records: the id of the
116/// invocation's node-input journal event, delivered by the executor under
117/// [`PARENT_EVENT_KEY`]. A missing key means the graph is being driven by
118/// something other than [`crate::executor::Executor::run`] (a hand-rolled
119/// harness, a unit test) — evidence recorded without its causal anchor
120/// would misrepresent the run, so this is a hard error rather than a
121/// silently unparented event.
122fn invocation_parent(ctx: &crate::node::NodeContext, node: &str) -> Result<String> {
123    ctx.config()
124        .extra
125        .get(PARENT_EVENT_KEY)
126        .and_then(Value::as_str)
127        .map(str::to_owned)
128        .ok_or_else(|| {
129            RustyError::Node(format!(
130                "node `{node}` is wired for Flight Recorder evidence but the run supplied no \
131                 `{PARENT_EVENT_KEY}` — drive the graph through `Executor::run`, which hands each \
132                 invocation its node-input event id as the causal parent"
133            ))
134        })
135}
136
137/// The registry's OpenAI-format tool schemas in a canonical order.
138///
139/// [`ToolRegistry`] is `HashMap`-backed, so [`ToolRegistry::schemas`] order
140/// is process-random — harmless for a live call, but the Flight Recorder
141/// hashes the model-call request payload and exact replay matches on that
142/// hash, so the schema list must serialize identically in the recording and
143/// replaying graphs (two distinct registry instances). Sorting by tool name
144/// makes the request canonical across processes. Applied to every flavor so
145/// all variants of the prebuilt agent put identical content on the wire.
146fn sorted_tool_schemas(tools: &ToolRegistry) -> Vec<Value> {
147    fn tool_name(schema: &Value) -> &str {
148        schema
149            .pointer("/function/name")
150            .and_then(Value::as_str)
151            .unwrap_or("")
152    }
153    let mut schemas = tools.schemas();
154    schemas.sort_by(|a, b| tool_name(a).cmp(tool_name(b)));
155    schemas
156}
157
158/// Build a prebuilt ReAct agent graph over `model` and `tools`.
159///
160/// The returned graph has exactly two nodes ([`AGENT_NODE`], [`TOOLS_NODE`]),
161/// a conditional edge `agent → tools | End`, and a static edge
162/// `tools → agent`. It is stateless with respect to any single run: clone it
163/// freely and drive it with the [`crate::executor::Executor`].
164///
165/// The graph never errors at build time for an empty registry — a tool-less
166/// agent simply answers directly on the first `agent` pass.
167///
168/// **This variant never emits [`GraphEvent::Token`]:** the agent node calls
169/// [`ChatModel::chat`]. Use [`create_react_agent_streaming`] to stream token
170/// deltas into the run's event channel.
171pub fn create_react_agent(model: Arc<dyn ChatModel>, tools: ToolRegistry) -> Result<Graph> {
172    build_react_agent(model, tools, None, EvidenceMode::None)
173}
174
175/// Build a prebuilt ReAct agent graph whose `agent` node streams token
176/// deltas as [`GraphEvent::Token`]s through `token_tx`
177/// ([`ChatModel::chat_stream`] under the hood; LangGraph's `messages`
178/// stream mode).
179///
180/// Typically `token_tx` is a clone of the run's event sender
181/// ([`crate::executor::RunConfig::token_tx`]) so token deltas interleave with
182/// the executor's own events on one channel. Forwarding is best-effort
183/// (`try_send`): a full or closed channel drops tokens but never aborts the
184/// run.
185///
186/// Identical to [`create_react_agent`] in topology and behavior otherwise;
187/// models that only implement [`ChatModel::chat`] work unchanged (the
188/// trait's default `chat_stream` delivers the whole answer as one token).
189pub fn create_react_agent_streaming(
190    model: Arc<dyn ChatModel>,
191    tools: ToolRegistry,
192    token_tx: mpsc::Sender<GraphEvent>,
193) -> Result<Graph> {
194    build_react_agent(model, tools, Some(token_tx), EvidenceMode::None)
195}
196
197/// Build a prebuilt ReAct agent graph that journals every model and tool
198/// call into `journal` (Flight Recorder, R0.5).
199///
200/// Identical to [`create_react_agent`] in topology and behavior; the only
201/// delta is evidence: the `agent` node wraps the model in
202/// [`crate::replay::RecordingChatModel`] and the `tools` node wraps each
203/// dispatched tool in [`crate::replay::RecordingTool`], so the journal
204/// gains `model_call` / `tool_call` events in the canonical
205/// [`crate::replay::model_call_request`] / [`crate::replay::tool_call_request`]
206/// shapes. Each event's causal parent is the invocation's node-input event
207/// ([`PARENT_EVENT_KEY`]), so iteration *N*'s model call hangs off iteration
208/// *N*'s `agent` input, and each tool call off its `tools` input.
209///
210/// Attach the same journal to the run ([`crate::executor::RunConfig::with_journal`])
211/// so node and executor evidence share one journal; for a byte-identical
212/// replay later, record under the determinism seams
213/// ([`crate::journal::Clock::logical`] + [`crate::journal::RngSource::seeded`]).
214/// Replay the recorded run with [`create_react_agent_replaying`] under
215/// [`crate::replay::ExactReplay`].
216///
217/// There is deliberately no streaming recording flavor: the streaming
218/// variant's token forwarding is a live-observability concern, and the
219/// recording wrappers record through [`ChatModel::chat`].
220pub fn create_react_agent_with_recording(
221    model: Arc<dyn ChatModel>,
222    tools: ToolRegistry,
223    journal: Journal,
224) -> Result<Graph> {
225    build_react_agent(model, tools, None, EvidenceMode::Record(journal))
226}
227
228/// Build a prebuilt ReAct agent graph that answers every model and tool
229/// call from a recorded journal instead of executing it (exact replay).
230///
231/// The replaying analogue of [`create_react_agent_with_recording`]: same
232/// topology, but the nodes wrap `model` and `tools` in
233/// [`crate::replay::ReplayingChatModel`] / [`crate::replay::ReplayingTool`],
234/// which serve each call from `source` (matched by sequence + canonical
235/// request hash) and re-journal it into `journal`. **The wrapped model and
236/// tools are never invoked** — carry them for their identity (effect class,
237/// tool schemas) and pass panic-on-call sentinels to prove the
238/// zero-outbound guarantee. The registry must offer the same tool
239/// identities (name, description, parameter schema) as the recorded run's:
240/// schema content feeds the model-call request hash.
241///
242/// Build `source` and `journal` from an [`crate::replay::ExactReplay`]
243/// session (`source()` / `fresh_journal()`) and drive the graph via
244/// [`crate::replay::ExactReplay::run_and_verify`]; see
245/// `examples/react_record_replay.rs`.
246pub fn create_react_agent_replaying(
247    model: Arc<dyn ChatModel>,
248    tools: ToolRegistry,
249    source: ReplaySource,
250    journal: Journal,
251) -> Result<Graph> {
252    build_react_agent(model, tools, None, EvidenceMode::Replay { source, journal })
253}
254
255fn build_react_agent(
256    model: Arc<dyn ChatModel>,
257    tools: ToolRegistry,
258    token_tx: Option<mpsc::Sender<GraphEvent>>,
259    evidence: EvidenceMode,
260) -> Result<Graph> {
261    let tool_schemas = sorted_tool_schemas(&tools);
262    let tool_executor = ToolExecutor::new(tools);
263
264    let agent_node = {
265        let model = Arc::clone(&model);
266        let evidence = evidence.clone();
267        move |ctx: crate::node::NodeContext| {
268            let model = Arc::clone(&model);
269            let evidence = evidence.clone();
270            let tool_schemas = tool_schemas.clone();
271            let token_tx = token_tx.clone();
272            async move {
273                let messages = read_messages(ctx.state())?;
274                // Evidence wiring is per invocation: the recording/replaying
275                // wrappers carry the invocation's causal parent, which only
276                // exists once the executor has journaled the node input.
277                let model: Arc<dyn ChatModel> = match &evidence {
278                    EvidenceMode::None => model,
279                    EvidenceMode::Record(journal) => Arc::new(
280                        RecordingChatModel::new(
281                            model,
282                            journal.clone(),
283                            invocation_parent(&ctx, AGENT_NODE)?,
284                        )
285                        .node(AGENT_NODE),
286                    ),
287                    EvidenceMode::Replay { source, journal } => Arc::new(ReplayingChatModel::new(
288                        model,
289                        source.clone(),
290                        journal.clone(),
291                        invocation_parent(&ctx, AGENT_NODE)?,
292                    )),
293                };
294                tracing::debug!(
295                    node = AGENT_NODE,
296                    messages = messages.len(),
297                    tools = tool_schemas.len(),
298                    "calling chat model"
299                );
300                let response = match token_tx {
301                    Some(tx) => {
302                        model
303                            .chat_stream(&messages, &tool_schemas, &mut |chunk| {
304                                if !chunk.delta.is_empty() {
305                                    let _ = tx.try_send(GraphEvent::Token {
306                                        node: AGENT_NODE.to_owned(),
307                                        delta: chunk.delta,
308                                    });
309                                }
310                            })
311                            .await?
312                    }
313                    None => model.chat(&messages, &tool_schemas).await?,
314                };
315                let appended = serde_json::to_value(&response.message)?;
316                // A single message object is fine: AddMessages accepts one
317                // message or an array and upserts/appends accordingly.
318                Ok(NodeOutput::update(MESSAGES_CHANNEL, appended))
319            }
320        }
321    };
322
323    let tools_node = move |ctx: crate::node::NodeContext| {
324        let tool_executor = tool_executor.clone();
325        let evidence = evidence.clone();
326        async move {
327            let messages = read_messages(ctx.state())?;
328            let last = messages.last().ok_or_else(|| {
329                RustyError::Node(format!(
330                    "node `{TOOLS_NODE}` ran with an empty `{MESSAGES_CHANNEL}` channel"
331                ))
332            })?;
333            if !last.has_tool_calls() {
334                return Err(RustyError::Node(format!(
335                    "node `{TOOLS_NODE}` expected the last message to carry tool calls"
336                )));
337            }
338            let tool_names: Vec<&str> = last
339                .tool_calls
340                .iter()
341                .map(|call| call.name.as_str())
342                .collect();
343            tracing::debug!(
344                node = TOOLS_NODE,
345                calls = last.tool_calls.len(),
346                tools = ?tool_names,
347                "dispatching tool calls"
348            );
349            // Evidence wiring is per invocation, like the agent node's: in
350            // record/replay mode each tool is wrapped with the invocation's
351            // causal parent, then dispatched through the same batch executor
352            // (parallel, order-preserving, panic-containing).
353            let mut tool_executor =
354                match &evidence {
355                    EvidenceMode::None => tool_executor,
356                    EvidenceMode::Record(journal) => {
357                        let parent = invocation_parent(&ctx, TOOLS_NODE)?;
358                        let mut wrapped = ToolRegistry::new();
359                        for name in tool_executor.registry().names() {
360                            let tool = tool_executor.registry().get(name).expect(
361                                "tool names iterated from a registry resolve in that registry",
362                            );
363                            wrapped.register_shared(Arc::new(
364                                RecordingTool::new(tool, journal.clone(), parent.clone())
365                                    .node(TOOLS_NODE),
366                            ));
367                        }
368                        ToolExecutor::new(wrapped)
369                    }
370                    EvidenceMode::Replay { source, journal } => {
371                        let parent = invocation_parent(&ctx, TOOLS_NODE)?;
372                        let mut wrapped = ToolRegistry::new();
373                        for name in tool_executor.registry().names() {
374                            let tool = tool_executor.registry().get(name).expect(
375                                "tool names iterated from a registry resolve in that registry",
376                            );
377                            wrapped.register_shared(Arc::new(ReplayingTool::new(
378                                tool,
379                                source.clone(),
380                                journal.clone(),
381                                parent.clone(),
382                            )));
383                        }
384                        ToolExecutor::new(wrapped)
385                    }
386                };
387            // The executor attaches both cross-cutting boundaries to the
388            // node context. Re-attach them after evidence wrapping so the
389            // finalized, post-middleware call is admitted immediately before
390            // the recording/replay wrapper (and ultimately the tool) runs.
391            tool_executor = tool_executor
392                .with_middleware(ctx.middleware().clone())
393                .with_call_context(ctx.thread_id(), TOOLS_NODE);
394            if let Some(admission) = ctx.effect_admission() {
395                tool_executor = tool_executor.with_effect_admission(admission.clone());
396            }
397            // Per-call error policy: see ToolExecutor::execute_batch docs.
398            let results = tool_executor.execute_batch(&last.tool_calls).await;
399            let appended = serde_json::to_value(&results)?;
400            Ok(NodeOutput::update(MESSAGES_CHANNEL, appended))
401        }
402    };
403
404    let mut builder = GraphBuilder::new();
405    builder.add_node(AGENT_NODE, agent_node);
406    builder.add_node(TOOLS_NODE, tools_node);
407    builder.set_entry_point(AGENT_NODE);
408
409    // Route on the post-barrier state: the appended assistant message decides.
410    builder.add_conditional_edges(AGENT_NODE, |state| async move {
411        let needs_tools = read_messages(&state)?
412            .last()
413            .map(ChatMessage::has_tool_calls)
414            .unwrap_or(false);
415        Ok(if needs_tools {
416            Route::Node(TOOLS_NODE.to_owned())
417        } else {
418            Route::End
419        })
420    });
421    builder.add_edge(TOOLS_NODE, AGENT_NODE);
422
423    builder.compile()
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429    use crate::graph::Edge;
430    use crate::llm::{ChatResponse, TokenChunk, ToolCall};
431    use crate::node::{Node, NodeConfig, NodeContext};
432    use crate::state::{Reducer, State, StateSpec};
433    use crate::tool::Tool;
434    use async_trait::async_trait;
435    use serde_json::{json, Value};
436    use std::collections::VecDeque;
437    use std::sync::Mutex;
438
439    /// A scripted model: pops one canned response per `chat` call.
440    struct ScriptedModel {
441        script: Mutex<VecDeque<ChatMessage>>,
442        seen_tool_schemas: Mutex<Vec<usize>>,
443    }
444
445    impl ScriptedModel {
446        fn new(script: Vec<ChatMessage>) -> Self {
447            Self {
448                script: Mutex::new(script.into()),
449                seen_tool_schemas: Mutex::new(Vec::new()),
450            }
451        }
452    }
453
454    #[async_trait]
455    impl ChatModel for ScriptedModel {
456        async fn chat(&self, _messages: &[ChatMessage], tools: &[Value]) -> Result<ChatResponse> {
457            self.seen_tool_schemas.lock().unwrap().push(tools.len());
458            let message = self
459                .script
460                .lock()
461                .unwrap()
462                .pop_front()
463                .ok_or_else(|| RustyError::Llm("script exhausted".into()))?;
464            Ok(ChatResponse {
465                message,
466                model: None,
467                usage: None,
468            })
469        }
470    }
471
472    /// A model whose `chat_stream` emits real deltas (accumulating the full
473    /// answer, as wire-backed implementations do).
474    struct StreamingModel;
475
476    #[async_trait]
477    impl ChatModel for StreamingModel {
478        async fn chat(&self, _messages: &[ChatMessage], _tools: &[Value]) -> Result<ChatResponse> {
479            Ok(ChatResponse {
480                message: ChatMessage::assistant("streamed"),
481                model: None,
482                usage: None,
483            })
484        }
485        async fn chat_stream(
486            &self,
487            messages: &[ChatMessage],
488            tools: &[Value],
489            on_token: &mut (dyn FnMut(TokenChunk) + Send),
490        ) -> Result<ChatResponse> {
491            for delta in ["str", "eamed"] {
492                on_token(TokenChunk {
493                    delta: delta.to_owned(),
494                    finish: false,
495                    raw: None,
496                });
497            }
498            self.chat(messages, tools).await
499        }
500    }
501
502    #[tokio::test]
503    async fn streaming_variant_forwards_token_events() {
504        let (tx, mut rx) = mpsc::channel::<GraphEvent>(8);
505        let model: Arc<dyn ChatModel> = Arc::new(StreamingModel);
506        let graph = create_react_agent_streaming(model, registry(), tx).unwrap();
507
508        let state = State::from_value(json!({
509            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::user("hi")).unwrap()]
510        }))
511        .unwrap();
512        let ctx = NodeContext::new(state, NodeConfig::default());
513        let out = graph.node(AGENT_NODE).unwrap().run(ctx).await.unwrap();
514
515        // The accumulated response is appended exactly as in chat().
516        let appended = out.updates.get(MESSAGES_CHANNEL).unwrap();
517        let msg: ChatMessage = serde_json::from_value(appended.clone()).unwrap();
518        assert_eq!(msg.content.as_deref(), Some("streamed"));
519
520        // Both deltas arrived as Token events on the forwarded channel.
521        let mut deltas = String::new();
522        for _ in 0..2 {
523            match rx.try_recv().expect("two token events") {
524                GraphEvent::Token { node, delta } => {
525                    assert_eq!(node, AGENT_NODE);
526                    deltas.push_str(&delta);
527                }
528                other => panic!("expected Token event, got {other:?}"),
529            }
530        }
531        assert_eq!(deltas, "streamed");
532    }
533
534    /// The non-streaming variant must emit no Token events (it calls chat()).
535    #[tokio::test]
536    async fn non_streaming_variant_emits_no_token_events() {
537        let model: Arc<dyn ChatModel> =
538            Arc::new(ScriptedModel::new(vec![ChatMessage::assistant("done")]));
539        let graph = create_react_agent(model, registry()).unwrap();
540        // No token sender is even available to this graph: the assertion is
541        // structural (create_react_agent takes no channel), documented here
542        // so the two variants do not drift.
543        assert!(graph.has_node(AGENT_NODE));
544    }
545
546    struct Echo;
547
548    #[async_trait]
549    impl Tool for Echo {
550        fn name(&self) -> &str {
551            "echo"
552        }
553        fn description(&self) -> &str {
554            "Echoes its input."
555        }
556        fn parameters_schema(&self) -> Value {
557            json!({"type": "object", "properties": {"text": {"type": "string"}}})
558        }
559        async fn call(&self, args: Value) -> Result<Value> {
560            Ok(json!(args.get("text").cloned().unwrap_or(Value::Null)))
561        }
562    }
563
564    fn registry() -> ToolRegistry {
565        let mut r = ToolRegistry::new();
566        r.register(Echo);
567        r
568    }
569
570    #[test]
571    fn graph_topology_is_the_react_loop() {
572        let model: Arc<dyn ChatModel> = Arc::new(ScriptedModel::new(vec![]));
573        let graph = create_react_agent(model, registry()).unwrap();
574
575        assert_eq!(graph.node_count(), 2);
576        assert_eq!(graph.entry_point(), AGENT_NODE);
577        assert!(graph.has_node(AGENT_NODE));
578        assert!(graph.has_node(TOOLS_NODE));
579
580        // agent: one conditional edge; tools: one static edge back to agent.
581        let agent_edges = graph.outgoing_edges(AGENT_NODE);
582        assert_eq!(agent_edges.len(), 1);
583        assert!(matches!(agent_edges[0], Edge::Conditional { .. }));
584        let tools_edges = graph.outgoing_edges(TOOLS_NODE);
585        assert_eq!(tools_edges.len(), 1);
586        assert!(matches!(
587            tools_edges[0],
588            Edge::Direct { from, to } if from == TOOLS_NODE && to == AGENT_NODE
589        ));
590    }
591
592    #[tokio::test]
593    async fn agent_node_appends_assistant_message_and_sees_schemas() {
594        let model = Arc::new(ScriptedModel::new(vec![ChatMessage::assistant("done")]));
595        let graph = create_react_agent(model.clone(), registry()).unwrap();
596
597        let state = State::from_value(json!({
598            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::user("hi")).unwrap()]
599        }))
600        .unwrap();
601        let ctx = NodeContext::new(state, NodeConfig::default());
602        let out = graph.node(AGENT_NODE).unwrap().run(ctx).await.unwrap();
603
604        let appended = out.updates.get(MESSAGES_CHANNEL).unwrap();
605        let msg: ChatMessage = serde_json::from_value(appended.clone()).unwrap();
606        assert_eq!(msg.content.as_deref(), Some("done"));
607
608        // The registry's schemas were passed to the model.
609        assert_eq!(model.seen_tool_schemas.lock().unwrap().as_slice(), &[1]);
610    }
611
612    #[tokio::test]
613    async fn tools_node_executes_pending_calls_in_order() {
614        let model: Arc<dyn ChatModel> = Arc::new(ScriptedModel::new(vec![]));
615        let graph = create_react_agent(model, registry()).unwrap();
616
617        let calls = vec![
618            ToolCall::new("c1", "echo", json!({"text": "a"})),
619            ToolCall::new("c2", "echo", json!({"text": "b"})),
620        ];
621        let state = State::from_value(json!({
622            MESSAGES_CHANNEL: [
623                serde_json::to_value(ChatMessage::assistant_tool_calls(calls)).unwrap()
624            ]
625        }))
626        .unwrap();
627        let ctx = NodeContext::new(state, NodeConfig::default());
628        let out = graph.node(TOOLS_NODE).unwrap().run(ctx).await.unwrap();
629
630        let appended = out.updates.get(MESSAGES_CHANNEL).unwrap();
631        let msgs: Vec<ChatMessage> = serde_json::from_value(appended.clone()).unwrap();
632        assert_eq!(msgs.len(), 2);
633        assert_eq!(msgs[0].tool_call_id.as_deref(), Some("c1"));
634        assert_eq!(msgs[0].content.as_deref(), Some("a"));
635        assert_eq!(msgs[1].tool_call_id.as_deref(), Some("c2"));
636        assert_eq!(msgs[1].content.as_deref(), Some("b"));
637    }
638
639    #[tokio::test]
640    async fn router_follows_tool_calls_else_ends() {
641        let model: Arc<dyn ChatModel> = Arc::new(ScriptedModel::new(vec![]));
642        let graph = create_react_agent(model, registry()).unwrap();
643        let edges = graph.outgoing_edges(AGENT_NODE);
644        let router = match edges[0] {
645            Edge::Conditional { router, .. } => router,
646            _ => panic!("expected conditional edge"),
647        };
648
649        let with_calls = State::from_value(json!({
650            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::assistant_tool_calls(vec![
651                ToolCall::new("c1", "echo", json!({"text": "x"})),
652            ]))
653            .unwrap()]
654        }))
655        .unwrap();
656        assert_eq!(
657            router(with_calls).await.unwrap(),
658            Route::Node(TOOLS_NODE.to_owned())
659        );
660
661        let final_answer = State::from_value(json!({
662            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::assistant("42")).unwrap()]
663        }))
664        .unwrap();
665        assert_eq!(router(final_answer).await.unwrap(), Route::End);
666    }
667
668    /// Drive the loop by hand (one super-step at a time, through the public
669    /// `StateSpec` merge) to prove the wiring end-to-end without depending on
670    /// the concurrently-implemented `Executor::run`.
671    #[tokio::test]
672    async fn manual_super_steps_reproduce_the_react_loop() {
673        let model: Arc<dyn ChatModel> = Arc::new(ScriptedModel::new(vec![
674            ChatMessage::assistant_tool_calls(vec![ToolCall::new(
675                "c1",
676                "echo",
677                json!({"text": "hello"}),
678            )]),
679            ChatMessage::assistant("echoed: hello"),
680        ]));
681        let graph = create_react_agent(model, registry()).unwrap();
682        let spec = StateSpec::new().channel(MESSAGES_CHANNEL, Reducer::AddMessages);
683        let mut state = State::from_value(json!({
684            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::user("say hello")).unwrap()]
685        }))
686        .unwrap();
687
688        // Step 0: agent -> assistant tool-call request.
689        let out = graph
690            .node(AGENT_NODE)
691            .unwrap()
692            .run(NodeContext::new(state.clone(), NodeConfig::default()))
693            .await
694            .unwrap();
695        spec.apply_single(&mut state, AGENT_NODE, out.updates)
696            .unwrap();
697
698        // Route: tool calls present -> tools.
699        let edges = graph.outgoing_edges(AGENT_NODE);
700        let route = match edges[0] {
701            Edge::Conditional { router, .. } => router(state.clone()).await.unwrap(),
702            _ => unreachable!(),
703        };
704        assert_eq!(route, Route::Node(TOOLS_NODE.to_owned()));
705
706        // Step 1: tools -> tool result message.
707        let out = graph
708            .node(TOOLS_NODE)
709            .unwrap()
710            .run(NodeContext::new(state.clone(), NodeConfig::default()))
711            .await
712            .unwrap();
713        spec.apply_single(&mut state, TOOLS_NODE, out.updates)
714            .unwrap();
715
716        // Step 2: agent -> final answer; route -> End.
717        let out = graph
718            .node(AGENT_NODE)
719            .unwrap()
720            .run(NodeContext::new(state.clone(), NodeConfig::default()))
721            .await
722            .unwrap();
723        spec.apply_single(&mut state, AGENT_NODE, out.updates)
724            .unwrap();
725        let route = match edges[0] {
726            Edge::Conditional { router, .. } => router(state.clone()).await.unwrap(),
727            _ => unreachable!(),
728        };
729        assert_eq!(route, Route::End);
730
731        // Full transcript: user, assistant(tool_calls), tool, assistant(final).
732        let msgs: Vec<ChatMessage> = state.get_as(MESSAGES_CHANNEL).unwrap().unwrap();
733        assert_eq!(msgs.len(), 4);
734        assert_eq!(msgs[3].content.as_deref(), Some("echoed: hello"));
735    }
736
737    // ---- Flight Recorder wiring (record / replay flavors) ----
738
739    use crate::journal::{Clock, Journal};
740    use crate::replay::ReplaySource;
741
742    fn recording_journal() -> Journal {
743        Journal::new("run-react-test", "thread-react-test", Clock::System)
744    }
745
746    #[test]
747    fn recording_and_replaying_variants_share_the_react_topology() {
748        let model: Arc<dyn ChatModel> = Arc::new(ScriptedModel::new(vec![]));
749        let journal = recording_journal();
750        let source = ReplaySource::new(&journal.snapshot());
751        let recording =
752            create_react_agent_with_recording(model.clone(), registry(), journal.clone()).unwrap();
753        let replaying =
754            create_react_agent_replaying(model.clone(), registry(), source, journal).unwrap();
755
756        for graph in [recording, replaying] {
757            assert_eq!(graph.node_count(), 2);
758            assert_eq!(graph.entry_point(), AGENT_NODE);
759            let agent_edges = graph.outgoing_edges(AGENT_NODE);
760            assert_eq!(agent_edges.len(), 1);
761            assert!(matches!(agent_edges[0], Edge::Conditional { .. }));
762            let tools_edges = graph.outgoing_edges(TOOLS_NODE);
763            assert_eq!(tools_edges.len(), 1);
764            assert!(matches!(
765                tools_edges[0],
766                Edge::Direct { from, to } if from == TOOLS_NODE && to == AGENT_NODE
767            ));
768        }
769    }
770
771    /// Node closures driven outside `Executor::run` have no
772    /// `PARENT_EVENT_KEY`; recording without a causal anchor must fail
773    /// loudly, not journal an unparented event.
774    #[tokio::test]
775    async fn recording_nodes_error_without_the_executor_parent_event() {
776        let model: Arc<dyn ChatModel> =
777            Arc::new(ScriptedModel::new(vec![ChatMessage::assistant("done")]));
778        let graph =
779            create_react_agent_with_recording(model, registry(), recording_journal()).unwrap();
780
781        let state = State::from_value(json!({
782            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::user("hi")).unwrap()]
783        }))
784        .unwrap();
785        let err = graph
786            .node(AGENT_NODE)
787            .unwrap()
788            .run(NodeContext::new(state, NodeConfig::default()))
789            .await
790            .unwrap_err();
791        let message = err.to_string();
792        assert!(matches!(err, RustyError::Node(_)), "got: {message}");
793        assert!(message.contains(PARENT_EVENT_KEY), "got: {message}");
794
795        // The tools node fails the same way, after its input validation.
796        let state = State::from_value(json!({
797            MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::assistant_tool_calls(vec![
798                ToolCall::new("c1", "echo", json!({"text": "x"})),
799            ]))
800            .unwrap()]
801        }))
802        .unwrap();
803        let err = graph
804            .node(TOOLS_NODE)
805            .unwrap()
806            .run(NodeContext::new(state, NodeConfig::default()))
807            .await
808            .unwrap_err();
809        assert!(err.to_string().contains(PARENT_EVENT_KEY), "got: {err}");
810    }
811
812    /// A model that captures the tool names it was offered, in order.
813    struct SchemaRecorder {
814        seen: Mutex<Vec<String>>,
815    }
816
817    #[async_trait]
818    impl ChatModel for SchemaRecorder {
819        async fn chat(&self, _messages: &[ChatMessage], tools: &[Value]) -> Result<ChatResponse> {
820            *self.seen.lock().unwrap() = tools
821                .iter()
822                .map(|schema| {
823                    schema
824                        .pointer("/function/name")
825                        .and_then(Value::as_str)
826                        .unwrap_or("")
827                        .to_owned()
828                })
829                .collect();
830            Ok(ChatResponse {
831                message: ChatMessage::assistant("done"),
832                model: None,
833                usage: None,
834            })
835        }
836    }
837
838    struct Zeta;
839
840    #[async_trait]
841    impl Tool for Zeta {
842        fn name(&self) -> &str {
843            "zeta"
844        }
845        fn description(&self) -> &str {
846            "Alphabetically after echo."
847        }
848        fn parameters_schema(&self) -> Value {
849            json!({"type": "object"})
850        }
851        async fn call(&self, _args: Value) -> Result<Value> {
852            Ok(Value::Null)
853        }
854    }
855
856    /// Registries are HashMap-backed (random iteration order); the prebuilt
857    /// agent sorts schemas by tool name so the model request — which exact
858    /// replay hashes — is canonical across registry instances and processes.
859    /// All flavors share this via `build_react_agent`.
860    #[tokio::test]
861    async fn tool_schemas_reach_the_model_in_canonical_name_order() {
862        let model = Arc::new(SchemaRecorder {
863            seen: Mutex::new(Vec::new()),
864        });
865
866        // Two registries, same tools, opposite insertion orders.
867        let mut forward = ToolRegistry::new();
868        forward.register(Echo);
869        forward.register(Zeta);
870        let mut reverse = ToolRegistry::new();
871        reverse.register(Zeta);
872        reverse.register(Echo);
873
874        for registry in [forward, reverse] {
875            let graph = create_react_agent(model.clone(), registry).unwrap();
876            let state = State::from_value(json!({
877                MESSAGES_CHANNEL: [serde_json::to_value(ChatMessage::user("hi")).unwrap()]
878            }))
879            .unwrap();
880            graph
881                .node(AGENT_NODE)
882                .unwrap()
883                .run(NodeContext::new(state, NodeConfig::default()))
884                .await
885                .unwrap();
886            assert_eq!(model.seen.lock().unwrap().as_slice(), ["echo", "zeta"]);
887        }
888    }
889}