Skip to main content

graphrt_llm/nodes/
agent.rs

1//! `agent` node: a tool-calling loop.
2//!
3//! Each iteration calls the model with the available tools, runs the tool
4//! calls it requests (concurrently when `parallel_tool_calls` is on) and feeds
5//! the results back, until the model answers without calling tools. On the
6//! last allowed iteration the tools stay declared (providers require that when
7//! the history contains tool calls) but the model may not call them
8//! (`tool_choice: none`), so the run always ends with an answer.
9//!
10//! Streaming: every turn streams its answer text on field `text` token by
11//! token (reasoning on `reasoning`), including turns that may still call
12//! tools, so the final answer reaches the client as it is generated.
13//! Tool-call fragments are never streamed as text. Once a turn produces its
14//! first tool-call fragment, the rest of that turn's text is no longer
15//! streamed. Text a turn streamed before its tool calls (a *preamble* such as
16//! "Let me look that up.") cannot be taken back, so it stays part of the
17//! answer: the `text` output is every streamed preamble followed by the final
18//! answer, separated by a blank line (streamed as its own `"\n\n"` chunk),
19//! and the streamed text always equals the `text` output. The full text of a
20//! turn that called tools is also reported as an `agent_thought` progress
21//! event (`streamed: true` when part of it was streamed).
22//!
23//! `stream_tool_turns: false` restores buffered tool turns: only the final
24//! answer is streamed (as one chunk when the turn could still have called
25//! tools) and preambles are reported only as `agent_thought`, never in `text`.
26//!
27//! Tool-call arguments that are not a JSON object are not executed; the model
28//! receives an error result explaining the problem so it can retry the call.
29//!
30//! Tools come from the [`ToolRegistry`] service and are referenced as
31//! `provider/name` (or `provider/*` for every tool of a provider). Tools listed
32//! in `require_approval` pause the run before they execute; other calls of the
33//! same turn run immediately. The host resumes with `{"approved": true|false}`
34//! for every pending call, or per call with `{"approvals": {"<call id>": true}}`,
35//! optionally with a `reason`. Calls without a decision (including when the
36//! resume input is missing or not understood) keep the run paused.
37//!
38//! Tool results may carry images (see `docs/tool-images.md`): they are checked
39//! against the limits of [`check_images`] (invalid ones are dropped with a
40//! note to the model) and follow the result text in the `tool` message.
41//! `keep_tool_images` (default 3, `null` for all) bounds how many image-bearing
42//! results keep their images.
43//!
44//! `tool_context` sends per-run values (e.g. the end user's JWT) to the tools of
45//! a provider beside their arguments, as a [`ToolCallContext`]. The model never
46//! sees them, they are never recorded, and they are only rendered (with secrets
47//! exposed) for providers that [accept secrets](ToolRuntime::accepts_secrets);
48//! any other provider fails the node. The values are registered as run secrets
49//! and scrubbed from tool results and logged arguments.
50//!
51//! Progress events: `agent_step`, `agent_thought`, `tool_call`, `tool_result`,
52//! `tool_denied`. Outputs: `text`, `tool_calls`
53//! (`[{name, provider, tool, arguments, result, is_error, images}]`), `iterations`,
54//! `stopped_reason` (`completed`, `max_iterations` or `length`), `usage`.
55
56use std::borrow::Cow;
57use std::collections::{HashMap, HashSet};
58use std::sync::Arc;
59
60use futures::future::BoxFuture;
61use graphrt_core::dsl::NodeDoc;
62use graphrt_core::event::Usage;
63use graphrt_core::node::{ConfigError, NodeOutcome, NodeResult, PauseRequest, parse_config};
64use graphrt_core::redact::redact_secrets;
65use graphrt_core::template::Template;
66use graphrt_core::tool::{ToolCallContext, ToolImage, ToolOutput, ToolRegistry, ToolRuntime, ToolSpec, check_images};
67use graphrt_core::value::Value;
68use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
69use serde::{Deserialize, Serialize};
70use serde_json::{Value as Json, json};
71
72use super::common::{
73    FinishCheck, MemoryConfig, ModelConfig, StreamField, StreamMode, VisionConfig, check_finish, invoke, model_for,
74    usage_value,
75};
76use crate::types::{
77    ChatDelta, ChatModel, ChatRequest, ChatResponse, ContentPart, FinishReason, Message, Role, ToolCall, ToolChoice,
78    collect,
79};
80
81/// Streamed between a preamble and the text that follows it in a later turn.
82const PREAMBLE_SEPARATOR: &str = "\n\n";
83
84/// Upper bound for `max_iterations`.
85pub const MAX_ITERATIONS_LIMIT: u32 = 100;
86
87/// Reference to a tool: `"provider/name"` or `{provider, name}`.
88#[derive(Clone, Debug, Deserialize)]
89#[serde(untagged)]
90pub enum ToolRef {
91    Path(String),
92    Pair { provider: String, name: String },
93}
94
95impl ToolRef {
96    fn split(&self) -> Option<(String, String)> {
97        match self {
98            ToolRef::Path(p) => {
99                let (provider, name) = p.split_once('/')?;
100                if provider.is_empty() || name.is_empty() {
101                    return None;
102                }
103                Some((provider.to_owned(), name.to_owned()))
104            }
105            ToolRef::Pair { provider, name } if !provider.is_empty() && !name.is_empty() => {
106                Some((provider.clone(), name.clone()))
107            }
108            ToolRef::Pair { .. } => None,
109        }
110    }
111}
112
113fn default_query() -> Template {
114    Template::parse("{{#sys.query#}}")
115}
116
117fn default_max_iterations() -> u32 {
118    10
119}
120
121fn default_true() -> bool {
122    true
123}
124
125fn default_max_tool_output() -> usize {
126    32_000
127}
128
129fn default_keep_tool_images() -> Option<usize> {
130    Some(3)
131}
132
133/// Configuration of the `agent` node.
134#[derive(Clone, Debug, Deserialize)]
135pub struct AgentConfig {
136    pub model: ModelConfig,
137    /// System prompt.
138    #[serde(default)]
139    pub instruction: Option<Template>,
140    /// User message (default `{{#sys.query#}}`).
141    #[serde(default = "default_query")]
142    pub query: Template,
143    #[serde(default)]
144    pub tools: Vec<ToolRef>,
145    /// Maximum model calls. Default 10.
146    #[serde(default = "default_max_iterations")]
147    pub max_iterations: u32,
148    /// Tool calls beyond this number in one turn are rejected with an error result.
149    #[serde(default)]
150    pub max_tool_calls_per_turn: Option<usize>,
151    #[serde(default = "default_true")]
152    pub parallel_tool_calls: bool,
153    #[serde(default)]
154    pub memory: Option<MemoryConfig>,
155    #[serde(default)]
156    pub vision: VisionConfig,
157    /// Tools that need host approval: `provider/name`, a tool name, or `*` for all.
158    #[serde(default)]
159    pub require_approval: Vec<String>,
160    /// Tool results longer than this (in characters) are truncated. Default 32 000.
161    #[serde(default = "default_max_tool_output")]
162    pub max_tool_output_chars: usize,
163    /// Keep the images of only the last N image-bearing tool results in the
164    /// conversation (older ones become a text placeholder). Default 3, since
165    /// images are resent on every turn; `null` keeps every image.
166    #[serde(default = "default_keep_tool_images")]
167    pub keep_tool_images: Option<usize>,
168    /// Stream the text of turns that may still call tools as it is generated
169    /// (see the module docs). Default `true`; `false` buffers those turns.
170    #[serde(default = "default_true")]
171    pub stream_tool_turns: bool,
172    /// Per provider, named values sent with every call to that provider's tools
173    /// (`{provider: {name: template}}`), outside the arguments. See the module docs.
174    /// Kept as raw JSON (parsed by [`AgentNode::from_doc`]) so no extra serde
175    /// code is generated for a rarely used field.
176    #[serde(default)]
177    pub tool_context: serde_json::Map<String, Json>,
178}
179
180/// A tool bound for one run.
181#[derive(Clone, Debug)]
182struct BoundTool {
183    /// Name exposed to the model (unique, provider-safe characters).
184    exposed: String,
185    provider: String,
186    name: String,
187    runtime: Arc<dyn ToolRuntime>,
188    spec: ToolSpec,
189    /// Rendered `tool_context` of the provider, shared by its tools.
190    context: Option<Arc<ToolCallContext>>,
191}
192
193impl BoundTool {
194    fn context(&self) -> &ToolCallContext {
195        self.context.as_deref().unwrap_or(ToolCallContext::empty())
196    }
197}
198
199/// One executed (or rejected) tool call.
200#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
201struct ToolLogEntry {
202    id: String,
203    name: String,
204    provider: String,
205    tool: String,
206    /// Parsed arguments, or the raw text when the model sent malformed JSON.
207    arguments: Json,
208    result: String,
209    is_error: bool,
210    /// Images sent to the model with the result.
211    #[serde(default)]
212    images: usize,
213}
214
215/// Persistable loop state, used to pause for tool approval.
216#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
217struct AgentState {
218    messages: Vec<Message>,
219    iteration: u32,
220    log: Vec<ToolLogEntry>,
221    usage: Usage,
222    /// Calls awaiting approval.
223    pending: Vec<ToolCall>,
224    /// Answer text streamed so far (preambles of tool-calling turns).
225    #[serde(default, skip_serializing_if = "String::is_empty")]
226    answer: String,
227}
228
229/// Why the loop ended.
230#[derive(Clone, Debug, PartialEq, Eq)]
231enum StopReason {
232    /// The model answered without calling tools.
233    Completed,
234    /// The iteration limit forced a final answer without tools.
235    MaxIterations,
236    /// The final answer was cut off by the output token limit.
237    Length,
238    /// The provider ended the turn with a reason graphrt does not recognize.
239    Unrecognized(String),
240}
241
242impl StopReason {
243    fn as_str(&self) -> String {
244        match self {
245            StopReason::Completed => "completed".into(),
246            StopReason::MaxIterations => "max_iterations".into(),
247            StopReason::Length => "length".into(),
248            StopReason::Unrecognized(reason) => format!("finish:{reason}"),
249        }
250    }
251}
252
253/// The `agent` node.
254#[derive(Debug)]
255pub struct AgentNode {
256    config: AgentConfig,
257    refs: Vec<(String, String)>,
258    /// Parsed `tool_context`.
259    tool_context: Vec<ProviderContext>,
260}
261
262/// One provider's `tool_context`: provider name and `(name, template)` pairs.
263type ProviderContext = (String, Vec<(String, Template)>);
264
265/// Parse `tool_context`: every provider must appear in `tools`, every value
266/// must be a non-empty name mapped to a template string.
267fn parse_tool_context(
268    doc: &NodeDoc,
269    raw: &serde_json::Map<String, Json>,
270    refs: &[(String, String)],
271) -> Result<Vec<ProviderContext>, ConfigError> {
272    let mut parsed = Vec::with_capacity(raw.len());
273    for (provider, values) in raw {
274        if !refs.iter().any(|(p, _)| p == provider) {
275            return Err(ConfigError::new(
276                doc,
277                format!("tool_context provider `{provider}` is not used by any entry of `tools`"),
278            ));
279        }
280        let Json::Object(values) = values else {
281            return Err(ConfigError::new(doc, format!("tool_context `{provider}` must map names to templates")));
282        };
283        let mut templates = Vec::with_capacity(values.len());
284        for (name, value) in values {
285            let (false, Json::String(text)) = (name.is_empty(), value) else {
286                return Err(ConfigError::new(
287                    doc,
288                    format!("tool_context `{provider}.{name}` must be a non-empty name with a template string"),
289                ));
290            };
291            templates.push((name.clone(), Template::parse(text)));
292        }
293        parsed.push((provider.clone(), templates));
294    }
295    Ok(parsed)
296}
297
298impl AgentNode {
299    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
300        let config: AgentConfig = parse_config(doc)?;
301        if config.max_iterations == 0 || config.max_iterations > MAX_ITERATIONS_LIMIT {
302            return Err(ConfigError::new(doc, format!("max_iterations must be between 1 and {MAX_ITERATIONS_LIMIT}")));
303        }
304        let refs = config
305            .tools
306            .iter()
307            .map(|r| {
308                r.split()
309                    .ok_or_else(|| ConfigError::new(doc, format!("invalid tool reference {r:?}; use `provider/name`")))
310            })
311            .collect::<Result<Vec<_>, _>>()?;
312        let tool_context = parse_tool_context(doc, &config.tool_context, &refs)?;
313        Ok(Self { config, refs, tool_context })
314    }
315
316    /// Resolve tool references against the registry, assigning unique exposed names.
317    async fn bind_tools(&self, ctx: &NodeContext) -> Result<Vec<BoundTool>, NodeError> {
318        if self.refs.is_empty() {
319            return Ok(Vec::new());
320        }
321        let registry = ctx.require_service::<ToolRegistry>("tool registry (graphrt_core::tool::ToolRegistry)")?;
322        let mut listings: HashMap<String, Vec<ToolSpec>> = HashMap::new();
323        let mut bound: Vec<BoundTool> = Vec::new();
324        let mut used: HashSet<String> = HashSet::new();
325        for (provider, name) in &self.refs {
326            let runtime = registry
327                .get(provider)
328                .cloned()
329                .ok_or_else(|| NodeError::fatal("tool_not_found", format!("unknown tool provider `{provider}`")))?;
330            if !listings.contains_key(provider) {
331                let specs = runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?;
332                listings.insert(provider.clone(), specs);
333            }
334            let specs = listings.get(provider).map(Vec::as_slice).unwrap_or_default();
335            for spec in select_specs(specs, provider, name)? {
336                if bound.iter().any(|b| &b.provider == provider && b.name == spec.name) {
337                    continue;
338                }
339                let exposed = unique_name(&spec.name, provider, &mut used);
340                bound.push(BoundTool {
341                    exposed: exposed.clone(),
342                    provider: provider.clone(),
343                    name: spec.name.clone(),
344                    runtime: Arc::clone(&runtime),
345                    spec: ToolSpec {
346                        name: exposed,
347                        description: spec.description.clone(),
348                        parameters: spec.parameters.clone(),
349                    },
350                    context: None,
351                });
352            }
353        }
354        self.attach_tool_context(ctx, &mut bound)?;
355        Ok(bound)
356    }
357
358    /// Render `tool_context` (secrets exposed) for each configured provider and
359    /// share it with that provider's bound tools. Fails when a provider does not
360    /// accept secrets: silently dropping the values would hide a misconfiguration.
361    fn attach_tool_context(&self, ctx: &NodeContext, bound: &mut [BoundTool]) -> Result<(), NodeError> {
362        for (provider, templates) in &self.tool_context {
363            let Some(first) = bound.iter().find(|b| &b.provider == provider) else { continue };
364            if !first.runtime.accepts_secrets() {
365                return Err(NodeError::fatal(
366                    "tool_context_denied",
367                    format!(
368                        "tool provider `{provider}` does not accept a tool context (a plugin needs \
369                         `permissions.secrets` and must be trusted, e.g. `--trust-plugin {provider}`)"
370                    ),
371                ));
372            }
373            let mut context = ToolCallContext::default();
374            for (name, template) in templates {
375                let value = template.render_exposed(&ctx.pool);
376                // A missing variable renders empty: leave the name out so the tool can refuse.
377                if value.is_empty() {
378                    continue;
379                }
380                ctx.observe_secret(&value);
381                context.secrets.insert(name.clone(), value);
382            }
383            let context = Arc::new(context);
384            for tool in bound.iter_mut().filter(|b| &b.provider == provider) {
385                tool.context = Some(Arc::clone(&context));
386            }
387        }
388        Ok(())
389    }
390
391    fn needs_approval(&self, tool: &BoundTool) -> bool {
392        self.config.require_approval.iter().any(|r| {
393            r == "*" || *r == tool.exposed || *r == tool.name || *r == format!("{}/{}", tool.provider, tool.name)
394        })
395    }
396
397    fn call_needs_approval(&self, tools: &[BoundTool], call: &ToolCall) -> bool {
398        bound_tool(tools, call).is_some_and(|t| self.needs_approval(t))
399    }
400
401    fn initial_state(&self, ctx: &NodeContext) -> Result<AgentState, NodeError> {
402        let cfg = &self.config;
403        let pool = &ctx.pool;
404        let mut messages = Vec::new();
405        if let Some(instruction) = &cfg.instruction {
406            let text = instruction.render(pool);
407            if !text.trim().is_empty() {
408                messages.push(Message::system(text));
409            }
410        }
411        if let Some(memory) = &cfg.memory {
412            messages.extend(memory.history(pool)?);
413        }
414        let query = cfg.query.render(pool);
415        let images = cfg.vision.image_parts(pool)?;
416        if query.trim().is_empty() && images.is_empty() {
417            if messages.iter().all(|m| m.role == Role::System) {
418                return Err(NodeError::invalid_input("agent query is empty"));
419            }
420        } else {
421            let mut user = Message::user(query);
422            user.content.extend(images);
423            messages.push(user);
424        }
425        Ok(AgentState { messages, ..AgentState::default() })
426    }
427
428    /// Apply the host's decisions to the pending calls. Returns the calls that
429    /// still have no decision.
430    async fn apply_decisions(
431        &self,
432        ctx: &NodeContext,
433        state: &mut AgentState,
434        tools: &[BoundTool],
435        input: Option<&Value>,
436    ) -> Vec<ToolCall> {
437        let decisions = Approvals::from_input(input);
438        let mut approved = Vec::new();
439        let mut undecided = Vec::new();
440        for call in std::mem::take(&mut state.pending) {
441            match decisions.decision(&call.id) {
442                Some(true) => approved.push(call),
443                Some(false) => self.deny(ctx, state, tools, &call, decisions.reason.as_deref()),
444                None => undecided.push(call),
445            }
446        }
447        self.run_calls(ctx, state, tools, approved).await;
448        undecided
449    }
450
451    async fn execute(&self, ctx: NodeContext) -> NodeResult {
452        let tools = self.bind_tools(&ctx).await?;
453        let model = model_for(&ctx, &self.config.model)?;
454        let mut state = match &ctx.resume {
455            Some(resume) => {
456                let mut state: AgentState = serde_json::from_value(resume.state.clone())
457                    .map_err(|e| NodeError::fatal("invalid_resume_state", e.to_string()))?;
458                let undecided = self.apply_decisions(&ctx, &mut state, &tools, resume.input.as_ref()).await;
459                if !undecided.is_empty() {
460                    state.pending = undecided;
461                    return self.pause(&state, &tools);
462                }
463                state
464            }
465            None => self.initial_state(&ctx)?,
466        };
467        let (final_text, stop) = loop {
468            state.iteration += 1;
469            let offer =
470                TurnTools { offered: !tools.is_empty(), final_turn: state.iteration >= self.config.max_iterations };
471            let turn = self.model_turn(&ctx, model.as_ref(), &mut state, &tools, offer).await?;
472            if !offer.callable() || turn.response.tool_calls.is_empty() {
473                break self.answer_turn(&ctx, &mut state, turn, offer);
474            }
475            self.tool_turn(&ctx, &mut state, &tools, turn).await;
476            if !state.pending.is_empty() {
477                return self.pause(&state, &tools);
478            }
479        };
480        Ok(agent_outputs(state, final_text, &stop))
481    }
482
483    /// Ask the model for the next turn (streaming per `stream_tool_turns`) and
484    /// add its usage to the state.
485    async fn model_turn(
486        &self,
487        ctx: &NodeContext,
488        model: &dyn ChatModel,
489        state: &mut AgentState,
490        tools: &[BoundTool],
491        offer: TurnTools,
492    ) -> Result<Turn, NodeError> {
493        let cfg = &self.config;
494        if let Some(keep) = cfg.keep_tool_images {
495            prune_tool_images(&mut state.messages, keep);
496        }
497        let mut request = cfg.model.request(state.messages.clone(), &ctx.pool)?;
498        if offer.offered {
499            // Tools stay declared on the final turn: the history may contain tool calls,
500            // which providers only accept alongside tool definitions.
501            request.tools = tools.iter().map(|t| t.spec.clone()).collect();
502            request.tool_choice = Some(if offer.callable() { ToolChoice::Auto } else { ToolChoice::None });
503        }
504        ctx.progress(
505            "agent_step",
506            Value::from_json(json!({"iteration": state.iteration, "tools_enabled": offer.callable()})),
507        );
508        let plan = TurnPlan {
509            live: cfg.stream_tool_turns || !offer.callable(),
510            stop_at_tool_call: offer.callable(),
511            separate: !state.answer.is_empty(),
512        };
513        let (response, streamed) = stream_turn(ctx, model, request, plan).await?;
514        state.usage.add(&response.usage);
515        // A content-filtered or malformed turn is an error, never an empty "completed" answer.
516        let finish = check_finish(&response)?;
517        Ok(Turn { response, streamed, finish, live: plan.live })
518    }
519
520    /// A turn without tool calls ends the loop: its text completes the answer.
521    fn answer_turn(
522        &self,
523        ctx: &NodeContext,
524        state: &mut AgentState,
525        mut turn: Turn,
526        offer: TurnTools,
527    ) -> (String, StopReason) {
528        let response = turn.response;
529        if !turn.live && !response.text.is_empty() {
530            ctx.chunk_shared(StreamField::Text.shared(), response.text.clone());
531            turn.streamed = response.text.len();
532        }
533        let stop = if response.finish_reason == Some(FinishReason::Length) {
534            StopReason::Length
535        } else if let FinishCheck::Unknown(reason) = turn.finish {
536            StopReason::Unrecognized(reason)
537        } else if offer.offered && offer.final_turn {
538            StopReason::MaxIterations
539        } else {
540            StopReason::Completed
541        };
542        state.messages.push(Message::assistant(response.text.clone()));
543        (final_answer(std::mem::take(&mut state.answer), response.text, turn.streamed), stop)
544    }
545
546    /// A turn with tool calls: keep its preamble, then reject, run or hold
547    /// (in `state.pending`, for approval) each call.
548    async fn tool_turn(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], turn: Turn) {
549        let response = turn.response;
550        if !response.text.trim().is_empty() {
551            ctx.progress(
552                "agent_thought",
553                Value::from_json(
554                    json!({"iteration": state.iteration, "text": response.text, "streamed": turn.streamed > 0}),
555                ),
556            );
557        }
558        commit_preamble(&mut state.answer, &response.text, turn.streamed);
559        state.messages.push(replayable_message(&response));
560        let runnable = self.runnable_calls(state, tools, response.tool_calls);
561        let (gated, free): (Vec<ToolCall>, Vec<ToolCall>) =
562            runnable.into_iter().partition(|c| self.call_needs_approval(tools, c));
563        self.run_calls(ctx, state, tools, free).await;
564        state.pending = gated;
565    }
566
567    /// The calls that can run. Calls past `max_tool_calls_per_turn` and calls
568    /// with malformed arguments get an error result for the model instead.
569    fn runnable_calls(&self, state: &mut AgentState, tools: &[BoundTool], mut calls: Vec<ToolCall>) -> Vec<ToolCall> {
570        if let Some(limit) = self.config.max_tool_calls_per_turn
571            && calls.len() > limit
572        {
573            for call in calls.split_off(limit) {
574                self.record(state, tools, &call, ToolOutput::error("rejected: too many tool calls in one turn"));
575            }
576        }
577        let mut runnable = Vec::with_capacity(calls.len());
578        for call in calls {
579            match call.arguments_json() {
580                Ok(_) => runnable.push(call),
581                Err(e) => {
582                    let message = format!("error: {e}. Call the tool again with a valid JSON object.");
583                    self.record(state, tools, &call, ToolOutput::error(message));
584                }
585            }
586        }
587        runnable
588    }
589
590    fn pause(&self, state: &AgentState, tools: &[BoundTool]) -> NodeResult {
591        let calls: Vec<Json> = state
592            .pending
593            .iter()
594            .map(|c| json!({"id": c.id, "name": c.name, "arguments": log_arguments(c, tools)}))
595            .collect();
596        let saved = serde_json::to_value(state)
597            .map_err(|e| NodeError::fatal("agent_state", format!("cannot save agent state: {e}")))?;
598        Ok(NodeOutcome::Paused(PauseRequest {
599            kind: "tool_approval".to_owned(),
600            data: Value::from_json(json!({"calls": calls})),
601            state: saved,
602        }))
603    }
604
605    fn deny(
606        &self,
607        ctx: &NodeContext,
608        state: &mut AgentState,
609        tools: &[BoundTool],
610        call: &ToolCall,
611        reason: Option<&str>,
612    ) {
613        let text = match reason {
614            Some(r) if !r.is_empty() => format!("The user did not approve this tool call: {r}"),
615            _ => "The user did not approve this tool call.".to_owned(),
616        };
617        ctx.progress("tool_denied", Value::from_json(json!({"id": call.id, "name": call.name})));
618        self.record(state, tools, call, ToolOutput::error(text));
619    }
620
621    /// A tool result as the model, the `tool_calls` output and the captured
622    /// `tool_result` progress all see it: the tool's context masked, cut to
623    /// `max_tool_output_chars`, and a note in place of images that fail
624    /// [`check_images`].
625    ///
626    /// A tool may echo its context (e.g. an upstream error repeating the JWT):
627    /// the model, the outputs and the progress events must never see it. Masking
628    /// comes first so a cut through the secret cannot leave its prefix behind.
629    /// Every consumer takes the text from here, so none can skip the masking.
630    fn visible_result(&self, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) -> VisibleResult {
631        let bound = bound_tool(tools, call);
632        let scrubbed = bound.map_or(Cow::Borrowed(output.text.as_str()), |b| scrub_context(&output.text, b.context()));
633        let mut text = truncate(&scrubbed, self.config.max_tool_output_chars);
634        let images = match check_images(&output.images) {
635            Ok(()) => output.images,
636            Err(e) => {
637                let note = format!("[images dropped: {e}]");
638                text = if text.is_empty() { note } else { format!("{text}\n{note}") };
639                Vec::new()
640            }
641        };
642        VisibleResult { text, images, is_error: output.is_error }
643    }
644
645    /// Append a tool result to the conversation and the log.
646    fn record(&self, state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) {
647        let result = self.visible_result(tools, call, output);
648        push_result(state, tools, call, result);
649    }
650
651    async fn run_calls(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], calls: Vec<ToolCall>) {
652        if calls.is_empty() {
653            return;
654        }
655        for call in &calls {
656            ctx.progress(
657                "tool_call",
658                Value::from_json(json!({"id": call.id, "name": call.name, "arguments": log_arguments(call, tools)})),
659            );
660        }
661        let outputs = self.call_tools(tools, &calls).await;
662        let capture = ctx.captures_content();
663        for (call, output) in calls.iter().zip(outputs) {
664            // The tool's own image count, including images the result drops.
665            let offered_images = output.images.len();
666            let result = self.visible_result(tools, call, output);
667            let mut data =
668                json!({"id": call.id, "name": call.name, "is_error": result.is_error, "images": offered_images});
669            if capture && let Some(fields) = data.as_object_mut() {
670                fields.insert("result".to_owned(), Json::String(result.text.clone()));
671            }
672            ctx.progress("tool_result", Value::from_json(data));
673            push_result(state, tools, call, result);
674        }
675    }
676
677    /// Run `calls` concurrently or one after another, per `parallel_tool_calls`.
678    async fn call_tools(&self, tools: &[BoundTool], calls: &[ToolCall]) -> Vec<ToolOutput> {
679        if self.config.parallel_tool_calls {
680            return futures::future::join_all(calls.iter().map(|c| call_tool(tools, c))).await;
681        }
682        let mut outputs = Vec::with_capacity(calls.len());
683        for call in calls {
684            outputs.push(call_tool(tools, call).await);
685        }
686        outputs
687    }
688}
689
690/// A tool result after [`AgentNode::visible_result`]: safe to show to the model and the host.
691struct VisibleResult {
692    text: String,
693    images: Vec<ToolImage>,
694    is_error: bool,
695}
696
697/// Append a visible tool result to the conversation and the log.
698fn push_result(state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, result: VisibleResult) {
699    let bound = bound_tool(tools, call);
700    state.messages.push(Message::tool_with_images(
701        call.id.clone(),
702        result.text.clone(),
703        result.images.iter().map(ToolImage::to_url),
704    ));
705    state.log.push(ToolLogEntry {
706        id: call.id.clone(),
707        name: call.name.clone(),
708        provider: bound.map(|b| b.provider.clone()).unwrap_or_default(),
709        tool: bound.map(|b| b.name.clone()).unwrap_or_default(),
710        arguments: log_arguments(call, tools),
711        result: result.text,
712        is_error: result.is_error,
713        images: result.images.len(),
714    });
715}
716
717/// Whether a turn offers tools, and whether it is the last one the iteration limit allows.
718#[derive(Clone, Copy, Debug)]
719struct TurnTools {
720    offered: bool,
721    final_turn: bool,
722}
723
724impl TurnTools {
725    /// The model may call tools: they are offered and this is not the forced final turn.
726    fn callable(self) -> bool {
727        self.offered && !self.final_turn
728    }
729}
730
731/// One model turn: the response, how many leading bytes of its text were
732/// already streamed, its finish check, and whether it streamed live.
733struct Turn {
734    response: ChatResponse,
735    streamed: usize,
736    finish: FinishCheck,
737    live: bool,
738}
739
740/// The assistant message of a tool turn as it is kept in the history. Malformed
741/// arguments are never replayed to the provider: the history keeps `{}` and
742/// the tool result explains the problem to the model.
743fn replayable_message(response: &ChatResponse) -> Message {
744    let mut assistant = response.to_message();
745    for call in &mut assistant.tool_calls {
746        if call.arguments_json().is_err() {
747            call.arguments = "{}".to_owned();
748        }
749    }
750    assistant
751}
752
753/// The node outputs of a finished loop.
754fn agent_outputs(state: AgentState, final_text: String, stop: &StopReason) -> NodeOutcome {
755    let log: Vec<Value> = state
756        .log
757        .iter()
758        .map(|e| {
759            Value::from_json(json!({
760                "name": e.name, "provider": e.provider, "tool": e.tool,
761                "arguments": e.arguments, "result": e.result, "is_error": e.is_error, "images": e.images,
762            }))
763        })
764        .collect();
765    NodeOutput::new()
766        .with("text", final_text)
767        .with("tool_calls", Value::from(log))
768        .with("iterations", i64::from(state.iteration))
769        .with("stopped_reason", stop.as_str())
770        .with("usage", usage_value(&state.usage))
771        .usage(state.usage)
772        .into()
773}
774
775/// The tools a `provider/name` reference selects from the provider's listing:
776/// all of them for `*`, else the one named (an error when it is missing).
777fn select_specs<'a>(specs: &'a [ToolSpec], provider: &str, name: &str) -> Result<Vec<&'a ToolSpec>, NodeError> {
778    if name == "*" {
779        return Ok(specs.iter().collect());
780    }
781    let spec = specs
782        .iter()
783        .find(|s| s.name == name)
784        .ok_or_else(|| NodeError::fatal("tool_not_found", format!("provider `{provider}` has no tool `{name}`")))?;
785    Ok(vec![spec])
786}
787
788/// The bound tool a call names (by its exposed, possibly de-duplicated name).
789fn bound_tool<'a>(tools: &'a [BoundTool], call: &ToolCall) -> Option<&'a BoundTool> {
790    tools.iter().find(|t| t.exposed == call.name)
791}
792
793/// How one model turn streams.
794#[derive(Clone, Copy, Debug)]
795struct TurnPlan {
796    /// Stream text and reasoning as they arrive (otherwise nothing is streamed).
797    live: bool,
798    /// Stop streaming text at the turn's first tool-call fragment.
799    stop_at_tool_call: bool,
800    /// Earlier turns streamed text: send [`PREAMBLE_SEPARATOR`] before this turn's first text.
801    separate: bool,
802}
803
804/// Run one turn. Returns the response and how many leading bytes of its text
805/// were streamed on field `text` (always whole deltas, so a char boundary).
806/// Deltas are moved into chunks, never copied.
807async fn stream_turn(
808    ctx: &NodeContext,
809    model: &dyn ChatModel,
810    request: ChatRequest,
811    plan: TurnPlan,
812) -> Result<(ChatResponse, usize), NodeError> {
813    if !plan.live {
814        return Ok((invoke(ctx, model, request, StreamMode::Off).await?, 0));
815    }
816    let stream = model.chat(request).await?;
817    let mut streamed = 0;
818    let mut text_closed = false;
819    let mut separator_pending = plan.separate;
820    let response = collect(stream, |delta| match delta {
821        ChatDelta::ToolCall { .. } => text_closed |= plan.stop_at_tool_call,
822        ChatDelta::Text(text) if !text.is_empty() && !text_closed => {
823            if std::mem::take(&mut separator_pending) {
824                ctx.chunk_shared(StreamField::Text.shared(), PREAMBLE_SEPARATOR);
825            }
826            streamed += text.len();
827            ctx.chunk_shared(StreamField::Text.shared(), text);
828        }
829        ChatDelta::Reasoning(text) if !text.is_empty() => ctx.chunk_shared(StreamField::Reasoning.shared(), text),
830        _ => {}
831    })
832    .await?;
833    Ok((response, streamed))
834}
835
836/// Append the streamed part of a tool-calling turn's text to the answer,
837/// mirroring what [`stream_turn`] sent (separator included).
838fn commit_preamble(answer: &mut String, text: &str, streamed: usize) {
839    let Some(preamble) = text.get(..streamed).filter(|p| !p.is_empty()) else { return };
840    if !answer.is_empty() {
841        answer.push_str(PREAMBLE_SEPARATOR);
842    }
843    answer.push_str(preamble);
844}
845
846/// The `text` output: streamed preambles, then the final turn's text (which
847/// is always streamed whole). Without preambles the final text is moved as is.
848fn final_answer(mut answer: String, text: String, streamed: usize) -> String {
849    if answer.is_empty() {
850        return text;
851    }
852    commit_preamble(&mut answer, &text, streamed);
853    answer
854}
855
856/// Replace the images of all but the last `keep` image-bearing tool results
857/// with a text placeholder, so a screenshot loop does not resend every
858/// screenshot on every turn.
859fn prune_tool_images(messages: &mut [Message], keep: usize) {
860    let mut seen = 0;
861    for message in messages.iter_mut().rev().filter(|m| m.role == Role::Tool) {
862        let count = message.images().count();
863        if count == 0 {
864            continue;
865        }
866        seen += 1;
867        if seen <= keep {
868            continue;
869        }
870        let note = if count == 1 {
871            "[1 image removed from history]".to_owned()
872        } else {
873            format!("[{count} images removed from history]")
874        };
875        let text = message.text();
876        let text = if text.is_empty() { note } else { format!("{text}\n{note}") };
877        message.content = vec![ContentPart::Text { text }];
878    }
879}
880
881/// Arguments as shown in logs and approval requests: the parsed object, or the
882/// raw text when it is not valid JSON (so nothing is hidden from the reader),
883/// with the tool's context values masked.
884fn log_arguments(call: &ToolCall, tools: &[BoundTool]) -> Json {
885    let mut arguments = match call.arguments_json() {
886        Ok(map) => Json::Object(map),
887        Err(_) => Json::String(call.arguments.clone()),
888    };
889    if let Some(tool) = bound_tool(tools, call)
890        && !tool.context().is_empty()
891    {
892        scrub_json(&mut arguments, tool.context());
893    }
894    arguments
895}
896
897/// `text` with every value of `context` masked. Borrows when there is nothing to mask.
898fn scrub_context<'a>(text: &'a str, context: &ToolCallContext) -> Cow<'a, str> {
899    if context.is_empty() {
900        return Cow::Borrowed(text);
901    }
902    let values: Vec<&str> = context.secrets.values().map(String::as_str).collect();
903    redact_secrets(text, &values)
904}
905
906/// Mask the values of `context` in every string of `value`.
907fn scrub_json(value: &mut Json, context: &ToolCallContext) {
908    match value {
909        Json::String(text) => {
910            if let Cow::Owned(scrubbed) = scrub_context(text, context) {
911                *text = scrubbed;
912            }
913        }
914        Json::Array(items) => items.iter_mut().for_each(|item| scrub_json(item, context)),
915        Json::Object(map) => map.values_mut().for_each(|item| scrub_json(item, context)),
916        _ => {}
917    }
918}
919
920async fn call_tool(tools: &[BoundTool], call: &ToolCall) -> ToolOutput {
921    let Some(tool) = bound_tool(tools, call) else {
922        return ToolOutput::error(format!("error: unknown tool `{}`", call.name));
923    };
924    let arguments = match call.arguments_json() {
925        Ok(map) => Json::Object(map),
926        Err(e) => return ToolOutput::error(format!("error: {e}")),
927    };
928    match tool.runtime.call(&tool.name, arguments, tool.context()).await {
929        Ok(output) => output,
930        Err(e) => ToolOutput::error(format!("error: {e}")),
931    }
932}
933
934/// Host decision for paused tool calls.
935#[derive(Debug, Default)]
936struct Approvals {
937    all: Option<bool>,
938    per_call: HashMap<String, bool>,
939    reason: Option<String>,
940}
941
942impl Approvals {
943    /// Recognized forms: `true`/`false`, `{"approved": bool}`,
944    /// `{"approvals": {"<call id>": bool}}` (both may be combined, per-call wins),
945    /// plus an optional `reason`. Anything else decides nothing.
946    fn from_input(input: Option<&Value>) -> Self {
947        let mut out = Self::default();
948        match input {
949            Some(Value::Bool(b)) => out.all = Some(*b),
950            Some(Value::Object(map)) => {
951                out.all = map.get("approved").and_then(Value::as_bool);
952                if let Some(Value::Object(per)) = map.get("approvals") {
953                    for (id, v) in per.iter() {
954                        if let Some(b) = v.as_bool() {
955                            out.per_call.insert(id.clone(), b);
956                        }
957                    }
958                }
959                out.reason = map.get("reason").and_then(Value::as_str).map(str::to_owned);
960            }
961            _ => {}
962        }
963        out
964    }
965
966    /// `Some(true)` approved, `Some(false)` denied, `None` no decision yet.
967    fn decision(&self, id: &str) -> Option<bool> {
968        self.per_call.get(id).copied().or(self.all)
969    }
970}
971
972/// Model-safe tool name: `[A-Za-z0-9_-]{1,64}`, unique within the run.
973fn unique_name(name: &str, provider: &str, used: &mut HashSet<String>) -> String {
974    let clean = |s: &str| -> String {
975        let mut out: String = s
976            .chars()
977            .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
978            .take(64)
979            .collect();
980        if out.is_empty() {
981            out.push_str("tool");
982        }
983        out
984    };
985    let mut candidate = clean(name);
986    if used.contains(&candidate) {
987        candidate = clean(&format!("{provider}_{name}"));
988    }
989    let base = candidate.clone();
990    let mut n = 2;
991    while used.contains(&candidate) {
992        let suffix = format!("_{n}");
993        let keep = 64usize.saturating_sub(suffix.len());
994        candidate = format!("{}{suffix}", base.chars().take(keep).collect::<String>());
995        n += 1;
996    }
997    used.insert(candidate.clone());
998    candidate
999}
1000
1001fn truncate(text: &str, max_chars: usize) -> String {
1002    if max_chars == 0 || text.chars().count() <= max_chars {
1003        return text.to_owned();
1004    }
1005    let mut out: String = text.chars().take(max_chars).collect();
1006    out.push_str("\n[truncated]");
1007    out
1008}
1009
1010impl Node for AgentNode {
1011    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
1012        Box::pin(self.execute(ctx))
1013    }
1014
1015    fn inputs(&self) -> Vec<Selector> {
1016        let cfg = &self.config;
1017        let mut out: Vec<Selector> = cfg.query.selectors().cloned().collect();
1018        if let Some(i) = &cfg.instruction {
1019            out.extend(i.selectors().cloned());
1020        }
1021        if let Some(memory) = &cfg.memory {
1022            out.extend(memory.selectors());
1023        }
1024        out.extend(cfg.vision.selectors());
1025        out.extend(cfg.model.selectors());
1026        out.extend(self.tool_context.iter().flat_map(|(_, t)| t).flat_map(|(_, t)| t.selectors().cloned()));
1027        out
1028    }
1029}
1030
1031/// Factory for the node registry.
1032pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
1033    Ok(Arc::new(AgentNode::from_doc(doc)?))
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039    use crate::mock::MockModel;
1040    use crate::registry::ModelRegistry;
1041    use crate::types::Role;
1042    use graphrt_core::event::Event;
1043    use graphrt_core::node::Resume;
1044    use graphrt_core::tool::ToolError;
1045    use graphrt_core::{Services, VariablePool};
1046    use std::sync::Mutex;
1047
1048    /// Tools: `add {a, b}` and `fail {}`.
1049    #[derive(Debug, Default)]
1050    struct MathTools {
1051        calls: Mutex<Vec<String>>,
1052    }
1053
1054    impl ToolRuntime for MathTools {
1055        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1056            Box::pin(async {
1057                Ok(vec![
1058                    ToolSpec {
1059                        name: "add".into(),
1060                        description: "add numbers".into(),
1061                        parameters: json!({"type": "object"}),
1062                    },
1063                    ToolSpec {
1064                        name: "fail".into(),
1065                        description: "always fails".into(),
1066                        parameters: json!({"type": "object"}),
1067                    },
1068                ])
1069            })
1070        }
1071
1072        fn call<'a>(
1073            &'a self,
1074            name: &'a str,
1075            arguments: Json,
1076            _context: &'a ToolCallContext,
1077        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1078            self.calls.lock().unwrap().push(name.to_owned());
1079            Box::pin(async move {
1080                match name {
1081                    "add" => {
1082                        let a = arguments["a"].as_i64().unwrap_or(0);
1083                        let b = arguments["b"].as_i64().unwrap_or(0);
1084                        Ok(ToolOutput::text((a + b).to_string()))
1085                    }
1086                    _ => Err(ToolError { tool: name.to_owned(), message: "broken".into() }),
1087                }
1088            })
1089        }
1090    }
1091
1092    /// Tools: `screenshot {}` (one PNG), `bad_image {}` (an unsupported type).
1093    #[derive(Debug, Default)]
1094    struct ScreenTools;
1095
1096    impl ToolRuntime for ScreenTools {
1097        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1098            let spec = |name: &str| ToolSpec { name: name.into(), description: "d".into(), parameters: json!({}) };
1099            Box::pin(async move { Ok(vec![spec("screenshot"), spec("bad_image")]) })
1100        }
1101
1102        fn call<'a>(
1103            &'a self,
1104            name: &'a str,
1105            _arguments: Json,
1106            _context: &'a ToolCallContext,
1107        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1108            Box::pin(async move {
1109                Ok(match name {
1110                    "screenshot" => ToolOutput::text("800x600").with_image(ToolImage::png("aGVsbG8=")),
1111                    _ => ToolOutput::text("odd")
1112                        .with_image(ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() }),
1113                })
1114            })
1115        }
1116    }
1117
1118    struct Setup {
1119        model: Arc<MockModel>,
1120        tools: Arc<MathTools>,
1121        events: Arc<Mutex<Vec<Event>>>,
1122    }
1123
1124    fn setup(responses: Vec<Vec<crate::ChatDelta>>) -> Setup {
1125        Setup {
1126            model: Arc::new(MockModel::new(responses)),
1127            tools: Arc::new(MathTools::default()),
1128            events: Arc::default(),
1129        }
1130    }
1131
1132    fn ctx(s: &Setup) -> NodeContext {
1133        let mut tool_registry = ToolRegistry::new();
1134        tool_registry.add("math", Arc::clone(&s.tools) as Arc<dyn ToolRuntime>);
1135        tool_registry.add("screen", Arc::new(ScreenTools) as Arc<dyn ToolRuntime>);
1136        let services = Services::new()
1137            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
1138            .with(tool_registry);
1139        let mut pool = VariablePool::new();
1140        pool.insert("sys", "query", Value::from("what is 2+3?"));
1141        let events = Arc::clone(&s.events);
1142        NodeContext::for_test("agent", pool)
1143            .with_services(Arc::new(services))
1144            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
1145    }
1146
1147    fn agent(extra: Json) -> AgentNode {
1148        let mut config = json!({
1149            "model": {"provider": "openai", "name": "gpt"},
1150            "instruction": "You are a calculator.",
1151            "tools": ["math/*"],
1152        });
1153        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
1154            c.extend(e);
1155        }
1156        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1157    }
1158
1159    fn completed(r: NodeResult) -> NodeOutput {
1160        match r.unwrap() {
1161            NodeOutcome::Completed(o) => o,
1162            NodeOutcome::Paused(p) => panic!("unexpected pause: {p:?}"),
1163        }
1164    }
1165
1166    #[tokio::test]
1167    async fn loops_until_answer() {
1168        let s = setup(vec![
1169            MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#), ("c2", "fail", "{}")]),
1170            MockModel::text("The answer is 5."),
1171        ]);
1172        let out = completed(agent(json!({})).run(ctx(&s)).await);
1173        assert_eq!(out.outputs["text"], Value::from("The answer is 5."));
1174        assert_eq!(out.outputs["iterations"], Value::Int(2));
1175        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1176        assert_eq!(log.len(), 2);
1177        assert_eq!(log[0].get_path(&["result"]), Some(Value::from("5")));
1178        assert_eq!(log[1].get_path(&["is_error"]), Some(Value::Bool(true)));
1179        assert_eq!(out.usage.unwrap().total_tokens, 4);
1180
1181        let requests = s.model.requests();
1182        assert_eq!(requests[0].tools.len(), 2);
1183        let second = &requests[1].messages;
1184        assert_eq!(second[0].role, Role::System);
1185        assert_eq!(second[2].tool_calls.len(), 2);
1186        assert_eq!(second[3].tool_call_id.as_deref(), Some("c1"));
1187        assert_eq!(second[3].text(), "5");
1188        assert!(second[4].text().contains("broken"));
1189
1190        let progress: Vec<String> = s
1191            .events
1192            .lock()
1193            .unwrap()
1194            .iter()
1195            .filter_map(|e| match e {
1196                Event::NodeProgress { name, .. } => Some(name.clone()),
1197                _ => None,
1198            })
1199            .collect();
1200        assert_eq!(progress, ["agent_step", "tool_call", "tool_call", "tool_result", "tool_result", "agent_step"]);
1201    }
1202
1203    const JWT: &str = "eyJhbGciOiJIUzI1NiJ9.user-token";
1204
1205    /// Tool `whoami {}` that echoes its context (as a careless upstream error would).
1206    #[derive(Debug)]
1207    struct VaultTools {
1208        accepts: bool,
1209        contexts: Mutex<Vec<ToolCallContext>>,
1210    }
1211
1212    impl VaultTools {
1213        fn new(accepts: bool) -> Arc<Self> {
1214            Arc::new(Self { accepts, contexts: Mutex::default() })
1215        }
1216    }
1217
1218    impl ToolRuntime for VaultTools {
1219        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1220            let spec = ToolSpec { name: "whoami".into(), description: "d".into(), parameters: json!({}) };
1221            Box::pin(async move { Ok(vec![spec]) })
1222        }
1223
1224        fn call<'a>(
1225            &'a self,
1226            _name: &'a str,
1227            _arguments: Json,
1228            context: &'a ToolCallContext,
1229        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1230            self.contexts.lock().unwrap().push(context.clone());
1231            let token = context.secret("user_jwt").unwrap_or("none").to_owned();
1232            Box::pin(async move { Ok(ToolOutput::text(format!("rejected token {token}"))) })
1233        }
1234
1235        fn accepts_secrets(&self) -> bool {
1236            self.accepts
1237        }
1238    }
1239
1240    fn vault_ctx(s: &Setup, vault: &Arc<VaultTools>) -> NodeContext {
1241        let mut registry = ToolRegistry::new();
1242        registry.add("vault", Arc::clone(vault) as Arc<dyn ToolRuntime>);
1243        let services = Services::new()
1244            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
1245            .with(registry);
1246        let mut pool = VariablePool::new();
1247        pool.insert("sys", "query", Value::from("who am I?"));
1248        pool.insert("start", "user_jwt", Value::Secret(Arc::from(JWT)));
1249        let events = Arc::clone(&s.events);
1250        NodeContext::for_test("agent", pool)
1251            .with_services(Arc::new(services))
1252            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
1253    }
1254
1255    fn vault_agent(extra: Json) -> AgentNode {
1256        let mut config = json!({
1257            "model": {"provider": "openai", "name": "gpt"},
1258            "tools": ["vault/whoami"],
1259            "tool_context": {"vault": {"user_jwt": "{{#start.user_jwt#}}", "missing": "{{#start.nope#}}"}},
1260        });
1261        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
1262            c.extend(e);
1263        }
1264        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1265    }
1266
1267    #[tokio::test]
1268    async fn tool_context_reaches_the_tool_but_nothing_else() {
1269        let s = setup(vec![
1270            MockModel::tool_calls(&[("c1", "whoami", &format!(r#"{{"echo":"{JWT}"}}"#))]),
1271            MockModel::text("done"),
1272        ]);
1273        let vault = VaultTools::new(true);
1274        let secrets = Arc::new(graphrt_core::redact::SecretSet::new());
1275        let ctx = vault_ctx(&s, &vault).with_secret_values(Arc::clone(&secrets));
1276        let node = vault_agent(json!({}));
1277        let out = completed(node.run(ctx).await);
1278
1279        let contexts = vault.contexts.lock().unwrap().clone();
1280        assert_eq!(contexts.len(), 1);
1281        assert_eq!(contexts[0].secret("user_jwt"), Some(JWT));
1282        assert_eq!(contexts[0].secret("missing"), None, "empty renders are left out");
1283
1284        // Not in the model's history, the outputs or any event.
1285        let requests = s.model.requests();
1286        assert_eq!(requests[1].messages.last().unwrap().text(), "rejected token ******");
1287        // (The model's own arguments stay in its history as it wrote them.)
1288        let tool_messages: Vec<_> = requests[1].messages.iter().filter(|m| m.role == Role::Tool).collect();
1289        assert!(!format!("{tool_messages:?}").contains(JWT));
1290        assert!(!serde_json::to_string(&out.outputs).unwrap().contains(JWT));
1291        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
1292        assert!(!events.contains(JWT), "{events}");
1293        // Registered with the run so later node errors are scrubbed too.
1294        assert_eq!(secrets.scrub(&format!("bad {JWT}")), "bad ******");
1295        assert!(node.inputs().iter().any(|sel| sel.to_string() == "start.user_jwt"));
1296    }
1297
1298    #[tokio::test]
1299    async fn captured_tool_results_never_carry_the_tool_context() {
1300        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
1301        let vault = VaultTools::new(true);
1302        let base = vault_ctx(&s, &vault);
1303        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
1304        completed(vault_agent(json!({})).run(base.with_services(Arc::new(services))).await);
1305        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("rejected token ******")));
1306        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
1307        assert!(!events.contains(JWT), "{events}");
1308    }
1309
1310    #[tokio::test]
1311    async fn tool_results_are_masked_before_they_are_cut() {
1312        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
1313        let vault = VaultTools::new(true);
1314        let base = vault_ctx(&s, &vault);
1315        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
1316        // The cut falls inside the echoed token: masking afterwards would miss its prefix.
1317        let limit = "rejected token ".len() + 12;
1318        let node = vault_agent(json!({"max_tool_output_chars": limit}));
1319        completed(node.run(base.with_services(Arc::new(services))).await);
1320        let token_prefix = &JWT[..12];
1321        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
1322        assert!(!events.contains(token_prefix), "{events}");
1323        let requests = s.model.requests();
1324        assert!(!format!("{:?}", requests[1].messages).contains(token_prefix));
1325    }
1326
1327    #[tokio::test]
1328    async fn tool_context_is_sent_again_after_approval() {
1329        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
1330        let vault = VaultTools::new(true);
1331        let node = vault_agent(json!({"require_approval": ["*"]}));
1332        let paused = match node.run(vault_ctx(&s, &vault)).await.unwrap() {
1333            NodeOutcome::Paused(p) => p,
1334            NodeOutcome::Completed(_) => panic!("expected a pause"),
1335        };
1336        assert!(!paused.state.to_string().contains(JWT), "the snapshot state never holds the context");
1337        let resume = Resume { state: paused.state, input: Some(Value::Bool(true)) };
1338        completed(node.run(vault_ctx(&s, &vault).with_resume(Some(resume))).await);
1339        assert_eq!(vault.contexts.lock().unwrap()[0].secret("user_jwt"), Some(JWT));
1340    }
1341
1342    #[tokio::test]
1343    async fn tool_context_needs_a_provider_that_accepts_secrets() {
1344        let s = setup(vec![MockModel::text("unused")]);
1345        let vault = VaultTools::new(false);
1346        let error = vault_agent(json!({})).run(vault_ctx(&s, &vault)).await.unwrap_err();
1347        assert_eq!(error.kind, "tool_context_denied");
1348        assert!(vault.contexts.lock().unwrap().is_empty());
1349    }
1350
1351    #[test]
1352    fn tool_context_providers_must_be_used() {
1353        let config = json!({
1354            "model": {"provider": "openai", "name": "gpt"},
1355            "tools": ["math/add"],
1356            "tool_context": {"vault": {"user_jwt": "x"}},
1357        });
1358        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
1359        assert!(error.to_string().contains("`vault` is not used"), "{error}");
1360        for bad in [json!({"math": {"jwt": 1}}), json!({"math": {"": "x"}}), json!({"math": "x"})] {
1361            let config =
1362                json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["math/add"], "tool_context": bad});
1363            assert!(AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).is_err());
1364        }
1365    }
1366
1367    fn tool_results(s: &Setup) -> Vec<Value> {
1368        let events = s.events.lock().unwrap();
1369        let results = events.iter().filter_map(|e| match e {
1370            Event::NodeProgress { name, data, .. } if name == "tool_result" => Some(data.clone()),
1371            _ => None,
1372        });
1373        results.collect()
1374    }
1375
1376    #[tokio::test]
1377    async fn tool_results_carry_text_only_when_the_host_captures_content() {
1378        let responses = || vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")];
1379        let s = setup(responses());
1380        completed(agent(json!({})).run(ctx(&s)).await);
1381        assert_eq!(tool_results(&s)[0].get_path(&["result"]), None);
1382
1383        let s = setup(responses());
1384        let base = ctx(&s);
1385        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
1386        completed(agent(json!({})).run(base.with_services(Arc::new(services))).await);
1387        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("5")));
1388    }
1389
1390    #[tokio::test]
1391    async fn tool_images_reach_the_model() {
1392        let s = setup(vec![MockModel::tool_calls(&[("c1", "screenshot", "{}")]), MockModel::text("a login form")]);
1393        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1394        let requests = s.model.requests();
1395        let result = &requests[1].messages[3];
1396        assert_eq!(result.role, Role::Tool);
1397        assert_eq!(result.text(), "800x600");
1398        assert_eq!(
1399            result.images().cloned().collect::<Vec<_>>(),
1400            vec![ContentPart::Image { url: "data:image/png;base64,aGVsbG8=".into(), detail: None }]
1401        );
1402        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1403        assert_eq!(log[0].get_path(&["images"]), Some(Value::Int(1)));
1404        let reported = s.events.lock().unwrap().iter().find_map(|e| match e {
1405            Event::NodeProgress { name, data, .. } if name == "tool_result" => data.get_path(&["images"]),
1406            _ => None,
1407        });
1408        assert_eq!(reported, Some(Value::Int(1)));
1409    }
1410
1411    #[tokio::test]
1412    async fn invalid_tool_images_are_dropped_with_a_note() {
1413        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
1414        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1415        let result = &s.model.requests()[1].messages[3];
1416        assert_eq!(result.images().count(), 0);
1417        assert!(
1418            result.text().starts_with("odd\n[images dropped: image #0: image media type `image/bmp`"),
1419            "{}",
1420            result.text()
1421        );
1422    }
1423
1424    #[tokio::test]
1425    async fn captured_tool_result_text_matches_what_the_model_sees() {
1426        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
1427        let base = ctx(&s);
1428        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
1429        let out = completed(agent(json!({"tools": ["screen/*"]})).run(base.with_services(Arc::new(services))).await);
1430        let seen_by_model = s.model.requests()[1].messages[3].text();
1431        assert!(seen_by_model.contains("[images dropped:"), "{seen_by_model}");
1432        let reported = tool_results(&s)[0].get_path(&["result"]);
1433        assert_eq!(reported, Some(Value::from(seen_by_model.clone())), "progress event");
1434        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1435        assert_eq!(log[0].get_path(&["result"]), Some(Value::from(seen_by_model)), "tool_calls output");
1436    }
1437
1438    #[tokio::test]
1439    async fn keep_tool_images_prunes_older_screenshots() {
1440        let s = setup(vec![
1441            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
1442            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
1443            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
1444            MockModel::text("done"),
1445        ]);
1446        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": 2})).run(ctx(&s)).await);
1447        let last = s.model.requests().last().cloned().unwrap();
1448        let results: Vec<&Message> = last.messages.iter().filter(|m| m.role == Role::Tool).collect();
1449        assert_eq!(results.iter().map(|m| m.images().count()).collect::<Vec<_>>(), [0, 1, 1]);
1450        assert_eq!(results[0].text(), "800x600\n[1 image removed from history]");
1451        // The second request still had every image (only two existed).
1452        let second = &s.model.requests()[2];
1453        assert_eq!(second.messages.iter().map(|m| m.images().count()).sum::<usize>(), 2);
1454    }
1455
1456    fn four_screenshots() -> Vec<Vec<crate::ChatDelta>> {
1457        vec![
1458            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
1459            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
1460            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
1461            MockModel::tool_calls(&[("c4", "screenshot", "{}")]),
1462            MockModel::text("done"),
1463        ]
1464    }
1465
1466    fn images_per_tool_result(s: &Setup) -> Vec<usize> {
1467        let last = s.model.requests().last().cloned().unwrap();
1468        last.messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.images().count()).collect()
1469    }
1470
1471    #[tokio::test]
1472    async fn keep_tool_images_defaults_to_the_last_three() {
1473        let s = setup(four_screenshots());
1474        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1475        assert_eq!(images_per_tool_result(&s), [0, 1, 1, 1]);
1476    }
1477
1478    #[tokio::test]
1479    async fn keep_tool_images_null_keeps_every_image() {
1480        let s = setup(four_screenshots());
1481        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": null})).run(ctx(&s)).await);
1482        assert_eq!(images_per_tool_result(&s), [1, 1, 1, 1]);
1483    }
1484
1485    #[tokio::test]
1486    async fn last_iteration_keeps_tools_but_forbids_calls() {
1487        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), MockModel::text("2")]);
1488        let out = completed(agent(json!({"max_iterations": 2})).run(ctx(&s)).await);
1489        assert_eq!(out.outputs["text"], Value::from("2"));
1490        assert_eq!(out.outputs["stopped_reason"], Value::from("max_iterations"));
1491        let requests = s.model.requests();
1492        assert_eq!(requests[0].tool_choice, Some(ToolChoice::Auto));
1493        assert!(!requests[1].tools.is_empty(), "tool definitions stay for the history's tool calls");
1494        assert_eq!(requests[1].tool_choice, Some(ToolChoice::None));
1495    }
1496
1497    fn text_chunks(s: &Setup) -> Vec<String> {
1498        s.events
1499            .lock()
1500            .unwrap()
1501            .iter()
1502            .filter_map(|e| match e {
1503                Event::NodeChunk { field, chunk, .. } if field.as_ref() == "text" => Some(chunk.clone()),
1504                _ => None,
1505            })
1506            .collect()
1507    }
1508
1509    fn thought(s: &Setup) -> Option<Value> {
1510        s.events.lock().unwrap().iter().find_map(|e| match e {
1511            Event::NodeProgress { name, data, .. } if name == "agent_thought" => Some(data.clone()),
1512            _ => None,
1513        })
1514    }
1515
1516    fn tokens(pieces: &[&str]) -> Vec<crate::ChatDelta> {
1517        let mut out: Vec<crate::ChatDelta> = pieces.iter().map(|p| crate::ChatDelta::Text((*p).into())).collect();
1518        out.push(crate::ChatDelta::Finish(FinishReason::Stop));
1519        out
1520    }
1521
1522    #[tokio::test]
1523    async fn final_answer_streams_token_by_token() {
1524        let s =
1525            setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), tokens(&["It", " is", " 5", "."])]);
1526        let out = completed(agent(json!({})).run(ctx(&s)).await);
1527        // One chunk per provider delta, on a turn that was still allowed to call tools.
1528        assert_eq!(text_chunks(&s), ["It", " is", " 5", "."]);
1529        assert_eq!(out.outputs["text"], Value::from("It is 5."));
1530        assert_eq!(s.model.requests()[1].tool_choice, Some(ToolChoice::Auto));
1531    }
1532
1533    #[tokio::test]
1534    async fn preamble_before_a_tool_call_is_streamed_and_kept_in_the_answer() {
1535        let mut first = tokens(&["Let me", " check."]);
1536        first.pop();
1537        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
1538        let s = setup(vec![first, tokens(&["It is", " 5."])]);
1539        let out = completed(agent(json!({})).run(ctx(&s)).await);
1540        let chunks = text_chunks(&s);
1541        assert_eq!(chunks, ["Let me", " check.", "\n\n", "It is", " 5."]);
1542        assert_eq!(out.outputs["text"], Value::from(chunks.concat().as_str()));
1543        let thought = thought(&s).unwrap();
1544        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
1545        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(true)));
1546        // The history keeps each turn separate: the preamble belongs to the tool-call turn.
1547        let second = &s.model.requests()[1].messages;
1548        assert_eq!(second[2].text(), "Let me check.");
1549        assert_eq!(second[2].tool_calls.len(), 1);
1550    }
1551
1552    #[tokio::test]
1553    async fn tool_call_fragments_and_later_text_are_never_streamed() {
1554        use crate::ChatDelta::{Finish, Text, ToolCall};
1555        let first = vec![
1556            Text("A".into()),
1557            ToolCall { index: 0, id: Some("c1".into()), name: Some("add".into()), arguments: r#"{"a":"#.into() },
1558            Text("B".into()),
1559            ToolCall { index: 0, id: None, name: None, arguments: "1}".into() },
1560            Finish(FinishReason::ToolCalls),
1561        ];
1562        let s = setup(vec![first, MockModel::text("done")]);
1563        let out = completed(agent(json!({})).run(ctx(&s)).await);
1564        assert_eq!(text_chunks(&s), ["A", "\n\n", "done"]);
1565        assert_eq!(out.outputs["text"], Value::from("A\n\ndone"));
1566        assert_eq!(thought(&s).unwrap().get_path(&["text"]), Some(Value::from("AB")));
1567        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
1568    }
1569
1570    #[tokio::test]
1571    async fn stream_tool_turns_false_buffers_tool_turns() {
1572        let mut first = vec![crate::ChatDelta::Text("Let me check.".into())];
1573        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
1574        let s = setup(vec![first, tokens(&["It is", " 5."])]);
1575        let out = completed(agent(json!({"stream_tool_turns": false})).run(ctx(&s)).await);
1576        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
1577        assert_eq!(text_chunks(&s), ["It is 5."]);
1578        assert_eq!(out.outputs["text"], Value::from("It is 5."));
1579        let thought = thought(&s).unwrap();
1580        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
1581        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(false)));
1582    }
1583
1584    #[tokio::test]
1585    async fn forced_final_turn_streams_token_by_token() {
1586        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), tokens(&["=", "2"])]);
1587        let out = completed(agent(json!({"max_iterations": 2, "stream_tool_turns": false})).run(ctx(&s)).await);
1588        assert_eq!(text_chunks(&s), ["=", "2"]);
1589        assert_eq!(out.outputs["text"], Value::from("=2"));
1590    }
1591
1592    #[tokio::test]
1593    async fn preamble_survives_a_tool_approval_pause() {
1594        let mut first = vec![crate::ChatDelta::Text("Checking.".into())];
1595        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
1596        let s = setup(vec![first, MockModel::text("4")]);
1597        let node = agent(json!({"require_approval": ["add"]}));
1598        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1599        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
1600        let resumed =
1601            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
1602        let out = completed(node.run(resumed).await);
1603        assert_eq!(out.outputs["text"], Value::from("Checking.\n\n4"));
1604        assert_eq!(text_chunks(&s), ["Checking.", "\n\n", "4"]);
1605    }
1606
1607    #[tokio::test]
1608    async fn malformed_arguments_are_reported_back_to_the_model() {
1609        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"#)]), MockModel::text("sorry")]);
1610        let out = completed(agent(json!({})).run(ctx(&s)).await);
1611        assert!(s.tools.calls.lock().unwrap().is_empty(), "malformed calls never run");
1612        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1613        assert_eq!(log[0].get_path(&["arguments"]), Some(Value::from(r#"{"a":2,"#)));
1614        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
1615        let second = &s.model.requests()[1];
1616        assert_eq!(second.messages[2].tool_calls[0].arguments, "{}", "history never replays malformed JSON");
1617        assert!(second.messages[3].text().contains("invalid JSON arguments"));
1618    }
1619
1620    #[tokio::test]
1621    async fn per_turn_limit_rejects_extra_calls() {
1622        let s = setup(vec![
1623            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
1624            MockModel::text("ok"),
1625        ]);
1626        let out =
1627            completed(agent(json!({"max_tool_calls_per_turn": 1, "parallel_tool_calls": false})).run(ctx(&s)).await);
1628        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
1629        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1630        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
1631    }
1632
1633    #[tokio::test]
1634    async fn approval_pauses_and_resumes() {
1635        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]), MockModel::text("4")]);
1636        let node = agent(json!({"tools": [{"provider": "math", "name": "add"}], "require_approval": ["math/add"]}));
1637        let paused = match node.run(ctx(&s)).await.unwrap() {
1638            NodeOutcome::Paused(p) => p,
1639            NodeOutcome::Completed(_) => panic!("expected pause"),
1640        };
1641        assert_eq!(paused.kind, "tool_approval");
1642        assert_eq!(paused.data.get_path(&["calls", "0", "name"]), Some(Value::from("add")));
1643        assert!(s.tools.calls.lock().unwrap().is_empty(), "nothing runs before approval");
1644
1645        // The saved state survives serialization (snapshots store it as JSON).
1646        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
1647        let resumed =
1648            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
1649        let out = completed(node.run(resumed).await);
1650        assert_eq!(out.outputs["text"], Value::from("4"));
1651        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
1652    }
1653
1654    #[tokio::test]
1655    async fn denied_calls_are_reported_to_the_model() {
1656        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", "{}")]), MockModel::text("fine")]);
1657        let node = agent(json!({"require_approval": ["*"]}));
1658        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1659        let input = Value::from_json(json!({"approvals": {"c1": false}, "reason": "not now"}));
1660        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
1661        assert_eq!(out.outputs["text"], Value::from("fine"));
1662        assert!(s.tools.calls.lock().unwrap().is_empty());
1663        let last_request = s.model.requests().pop().unwrap();
1664        assert!(last_request.messages.iter().any(|m| m.text().contains("not now")));
1665    }
1666
1667    #[tokio::test]
1668    async fn only_gated_calls_wait_for_approval() {
1669        let s = setup(vec![
1670            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "fail", "{}")]),
1671            MockModel::text("done"),
1672        ]);
1673        let node = agent(json!({"require_approval": ["math/fail"]}));
1674        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1675        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"], "ungated calls run immediately");
1676        assert_eq!(p.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
1677        assert!(p.data.get_path(&["calls", "1"]).is_none());
1678
1679        // No decision (or one that is not understood) keeps the run paused.
1680        for input in [None, Some(Value::from("yes")), Some(Value::from_json(json!({"approved": "true"})))] {
1681            let resumed = ctx(&s).with_resume(Some(Resume { state: p.state.clone(), input }));
1682            assert!(matches!(node.run(resumed).await.unwrap(), NodeOutcome::Paused(_)));
1683        }
1684        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
1685
1686        let input = Value::from_json(json!({"approvals": {"c2": true}}));
1687        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
1688        assert_eq!(out.outputs["text"], Value::from("done"));
1689        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add", "fail"]);
1690    }
1691
1692    #[tokio::test]
1693    async fn per_call_decisions_can_arrive_in_steps() {
1694        let s = setup(vec![
1695            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
1696            MockModel::text("ok"),
1697        ]);
1698        let node = agent(json!({"require_approval": ["*"], "parallel_tool_calls": false}));
1699        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1700        let input = Value::from_json(json!({"approvals": {"c1": true}}));
1701        let NodeOutcome::Paused(p2) =
1702            node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await.unwrap()
1703        else {
1704            panic!("c2 is still undecided")
1705        };
1706        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
1707        assert_eq!(p2.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
1708        let input = Value::from_json(json!({"approved": false}));
1709        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p2.state, input: Some(input) }))).await);
1710        assert_eq!(out.outputs["text"], Value::from("ok"));
1711        assert_eq!(s.tools.calls.lock().unwrap().len(), 1, "c2 was denied");
1712    }
1713
1714    #[test]
1715    fn inputs_cover_templates_and_memory() {
1716        let node = agent(json!({"query": "{{#start.q#}}", "instruction": "{{#env.persona#}}", "memory": {}}));
1717        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
1718        for expected in ["start.q", "env.persona", "sys.history", "sys.query"] {
1719            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
1720        }
1721    }
1722
1723    #[tokio::test]
1724    async fn unknown_provider_is_fatal() {
1725        let s = setup(vec![]);
1726        let err = agent(json!({"tools": ["nope/x"]})).run(ctx(&s)).await.unwrap_err();
1727        assert!(!err.retryable);
1728        assert_eq!(err.kind, "tool_not_found");
1729    }
1730
1731    #[test]
1732    fn config_validation_and_names() {
1733        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "tools": ["no-slash"]}));
1734        assert!(AgentNode::from_doc(&bad).is_err());
1735        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "max_iterations": 0}));
1736        assert!(AgentNode::from_doc(&bad).is_err());
1737        let mut used = HashSet::new();
1738        assert_eq!(unique_name("search", "web", &mut used), "search");
1739        assert_eq!(unique_name("search", "docs", &mut used), "docs_search");
1740        assert_eq!(unique_name("search", "docs", &mut used), "docs_search_2");
1741        assert_eq!(unique_name("a.b/c", "p", &mut used), "a_b_c");
1742    }
1743}