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            let selected: Vec<&ToolSpec> = if name == "*" {
336                specs.iter().collect()
337            } else {
338                let spec = specs.iter().find(|s| &s.name == name).ok_or_else(|| {
339                    NodeError::fatal("tool_not_found", format!("provider `{provider}` has no tool `{name}`"))
340                })?;
341                vec![spec]
342            };
343            for spec in selected {
344                if bound.iter().any(|b| &b.provider == provider && b.name == spec.name) {
345                    continue;
346                }
347                let exposed = unique_name(&spec.name, provider, &mut used);
348                bound.push(BoundTool {
349                    exposed: exposed.clone(),
350                    provider: provider.clone(),
351                    name: spec.name.clone(),
352                    runtime: Arc::clone(&runtime),
353                    spec: ToolSpec {
354                        name: exposed,
355                        description: spec.description.clone(),
356                        parameters: spec.parameters.clone(),
357                    },
358                    context: None,
359                });
360            }
361        }
362        self.attach_tool_context(ctx, &mut bound)?;
363        Ok(bound)
364    }
365
366    /// Render `tool_context` (secrets exposed) for each configured provider and
367    /// share it with that provider's bound tools. Fails when a provider does not
368    /// accept secrets: silently dropping the values would hide a misconfiguration.
369    fn attach_tool_context(&self, ctx: &NodeContext, bound: &mut [BoundTool]) -> Result<(), NodeError> {
370        for (provider, templates) in &self.tool_context {
371            let Some(first) = bound.iter().find(|b| &b.provider == provider) else { continue };
372            if !first.runtime.accepts_secrets() {
373                return Err(NodeError::fatal(
374                    "tool_context_denied",
375                    format!(
376                        "tool provider `{provider}` does not accept a tool context (a plugin needs \
377                         `permissions.secrets` and must be trusted, e.g. `--trust-plugin {provider}`)"
378                    ),
379                ));
380            }
381            let mut context = ToolCallContext::default();
382            for (name, template) in templates {
383                let value = template.render_exposed(&ctx.pool);
384                // A missing variable renders empty: leave the name out so the tool can refuse.
385                if value.is_empty() {
386                    continue;
387                }
388                ctx.observe_secret(&value);
389                context.secrets.insert(name.clone(), value);
390            }
391            let context = Arc::new(context);
392            for tool in bound.iter_mut().filter(|b| &b.provider == provider) {
393                tool.context = Some(Arc::clone(&context));
394            }
395        }
396        Ok(())
397    }
398
399    fn needs_approval(&self, tool: &BoundTool) -> bool {
400        self.config.require_approval.iter().any(|r| {
401            r == "*" || *r == tool.exposed || *r == tool.name || *r == format!("{}/{}", tool.provider, tool.name)
402        })
403    }
404
405    fn call_needs_approval(&self, tools: &[BoundTool], call: &ToolCall) -> bool {
406        tools.iter().any(|t| t.exposed == call.name && self.needs_approval(t))
407    }
408
409    fn initial_state(&self, ctx: &NodeContext) -> Result<AgentState, NodeError> {
410        let cfg = &self.config;
411        let pool = &ctx.pool;
412        let mut messages = Vec::new();
413        if let Some(instruction) = &cfg.instruction {
414            let text = instruction.render(pool);
415            if !text.trim().is_empty() {
416                messages.push(Message::system(text));
417            }
418        }
419        if let Some(memory) = &cfg.memory {
420            messages.extend(memory.history(pool)?);
421        }
422        let query = cfg.query.render(pool);
423        let images = cfg.vision.image_parts(pool)?;
424        if query.trim().is_empty() && images.is_empty() {
425            if messages.iter().all(|m| m.role == Role::System) {
426                return Err(NodeError::invalid_input("agent query is empty"));
427            }
428        } else {
429            let mut user = Message::user(query);
430            user.content.extend(images);
431            messages.push(user);
432        }
433        Ok(AgentState { messages, ..AgentState::default() })
434    }
435
436    /// Apply the host's decisions to the pending calls. Returns the calls that
437    /// still have no decision.
438    async fn apply_decisions(
439        &self,
440        ctx: &NodeContext,
441        state: &mut AgentState,
442        tools: &[BoundTool],
443        input: Option<&Value>,
444    ) -> Vec<ToolCall> {
445        let decisions = Approvals::from_input(input);
446        let mut approved = Vec::new();
447        let mut undecided = Vec::new();
448        for call in std::mem::take(&mut state.pending) {
449            match decisions.decision(&call.id) {
450                Some(true) => approved.push(call),
451                Some(false) => self.deny(ctx, state, tools, &call, decisions.reason.as_deref()),
452                None => undecided.push(call),
453            }
454        }
455        self.run_calls(ctx, state, tools, approved).await;
456        undecided
457    }
458
459    async fn execute(&self, ctx: NodeContext) -> NodeResult {
460        let cfg = &self.config;
461        let tools = self.bind_tools(&ctx).await?;
462        let model = model_for(&ctx, &cfg.model)?;
463
464        let mut state = match &ctx.resume {
465            Some(resume) => {
466                let mut state: AgentState = serde_json::from_value(resume.state.clone())
467                    .map_err(|e| NodeError::fatal("invalid_resume_state", e.to_string()))?;
468                let undecided = self.apply_decisions(&ctx, &mut state, &tools, resume.input.as_ref()).await;
469                if !undecided.is_empty() {
470                    state.pending = undecided;
471                    return self.pause(&state, &tools);
472                }
473                state
474            }
475            None => self.initial_state(&ctx)?,
476        };
477
478        let (final_text, stop) = loop {
479            state.iteration += 1;
480            let final_turn = state.iteration >= cfg.max_iterations;
481            let offer_tools = !tools.is_empty();
482            let can_call_tools = offer_tools && !final_turn;
483            if let Some(keep) = cfg.keep_tool_images {
484                prune_tool_images(&mut state.messages, keep);
485            }
486            let mut request = cfg.model.request(state.messages.clone(), &ctx.pool)?;
487            if offer_tools {
488                // Tools stay declared on the final turn: the history may contain tool calls,
489                // which providers only accept alongside tool definitions.
490                request.tools = tools.iter().map(|t| t.spec.clone()).collect();
491                request.tool_choice = Some(if can_call_tools { ToolChoice::Auto } else { ToolChoice::None });
492            }
493            ctx.progress(
494                "agent_step",
495                Value::from_json(json!({"iteration": state.iteration, "tools_enabled": can_call_tools})),
496            );
497
498            let plan = TurnPlan {
499                live: cfg.stream_tool_turns || !can_call_tools,
500                stop_at_tool_call: can_call_tools,
501                separate: !state.answer.is_empty(),
502            };
503            let (response, mut streamed) = stream_turn(&ctx, model.as_ref(), request, plan).await?;
504            state.usage.add(&response.usage);
505            // A content-filtered or malformed turn is an error, never an empty "completed" answer.
506            let finish = check_finish(&response)?;
507
508            if !can_call_tools || response.tool_calls.is_empty() {
509                if !plan.live && !response.text.is_empty() {
510                    ctx.chunk_shared(StreamField::Text.shared(), response.text.clone());
511                    streamed = response.text.len();
512                }
513                let stop = if response.finish_reason == Some(FinishReason::Length) {
514                    StopReason::Length
515                } else if let FinishCheck::Unknown(reason) = finish {
516                    StopReason::Unrecognized(reason)
517                } else if offer_tools && final_turn {
518                    StopReason::MaxIterations
519                } else {
520                    StopReason::Completed
521                };
522                state.messages.push(Message::assistant(response.text.clone()));
523                break (final_answer(std::mem::take(&mut state.answer), response.text, streamed), stop);
524            }
525
526            if !response.text.trim().is_empty() {
527                ctx.progress(
528                    "agent_thought",
529                    Value::from_json(
530                        json!({"iteration": state.iteration, "text": response.text, "streamed": streamed > 0}),
531                    ),
532                );
533            }
534            commit_preamble(&mut state.answer, &response.text, streamed);
535            // Malformed arguments are never replayed to the provider: the history keeps `{}`
536            // and the tool result explains the problem to the model.
537            let mut assistant = response.to_message();
538            for call in &mut assistant.tool_calls {
539                if call.arguments_json().is_err() {
540                    call.arguments = "{}".to_owned();
541                }
542            }
543            state.messages.push(assistant);
544
545            let mut calls = response.tool_calls;
546            if let Some(limit) = cfg.max_tool_calls_per_turn
547                && calls.len() > limit
548            {
549                for call in calls.split_off(limit) {
550                    self.record(
551                        &mut state,
552                        &tools,
553                        &call,
554                        ToolOutput::error("rejected: too many tool calls in one turn"),
555                    );
556                }
557            }
558            let mut runnable = Vec::with_capacity(calls.len());
559            for call in calls {
560                match call.arguments_json() {
561                    Ok(_) => runnable.push(call),
562                    Err(e) => {
563                        let message = format!("error: {e}. Call the tool again with a valid JSON object.");
564                        self.record(&mut state, &tools, &call, ToolOutput::error(message));
565                    }
566                }
567            }
568            let (gated, free): (Vec<ToolCall>, Vec<ToolCall>) =
569                runnable.into_iter().partition(|c| self.call_needs_approval(&tools, c));
570            self.run_calls(&ctx, &mut state, &tools, free).await;
571            if !gated.is_empty() {
572                state.pending = gated;
573                return self.pause(&state, &tools);
574            }
575        };
576
577        let log: Vec<Value> = state
578            .log
579            .iter()
580            .map(|e| {
581                Value::from_json(json!({
582                    "name": e.name, "provider": e.provider, "tool": e.tool,
583                    "arguments": e.arguments, "result": e.result, "is_error": e.is_error, "images": e.images,
584                }))
585            })
586            .collect();
587        Ok(NodeOutput::new()
588            .with("text", final_text)
589            .with("tool_calls", Value::from(log))
590            .with("iterations", i64::from(state.iteration))
591            .with("stopped_reason", stop.as_str())
592            .with("usage", usage_value(&state.usage))
593            .usage(state.usage)
594            .into())
595    }
596
597    fn pause(&self, state: &AgentState, tools: &[BoundTool]) -> NodeResult {
598        let calls: Vec<Json> = state
599            .pending
600            .iter()
601            .map(|c| json!({"id": c.id, "name": c.name, "arguments": log_arguments(c, tools)}))
602            .collect();
603        let saved = serde_json::to_value(state)
604            .map_err(|e| NodeError::fatal("agent_state", format!("cannot save agent state: {e}")))?;
605        Ok(NodeOutcome::Paused(PauseRequest {
606            kind: "tool_approval".to_owned(),
607            data: Value::from_json(json!({"calls": calls})),
608            state: saved,
609        }))
610    }
611
612    fn deny(
613        &self,
614        ctx: &NodeContext,
615        state: &mut AgentState,
616        tools: &[BoundTool],
617        call: &ToolCall,
618        reason: Option<&str>,
619    ) {
620        let text = match reason {
621            Some(r) if !r.is_empty() => format!("The user did not approve this tool call: {r}"),
622            _ => "The user did not approve this tool call.".to_owned(),
623        };
624        ctx.progress("tool_denied", Value::from_json(json!({"id": call.id, "name": call.name})));
625        self.record(state, tools, call, ToolOutput::error(text));
626    }
627
628    /// Append a tool result to the conversation and the log.
629    fn record(&self, state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) {
630        let bound = tools.iter().find(|t| t.exposed == call.name);
631        // A tool may echo its context (e.g. an upstream error repeating the JWT): the
632        // model, the outputs and the progress events must never see it.
633        let scrubbed = bound.map_or(Cow::Borrowed(output.text.as_str()), |b| scrub_context(&output.text, b.context()));
634        let mut text = truncate(&scrubbed, self.config.max_tool_output_chars);
635        let images = match check_images(&output.images) {
636            Ok(()) => output.images,
637            Err(e) => {
638                let note = format!("[images dropped: {e}]");
639                text = if text.is_empty() { note } else { format!("{text}\n{note}") };
640                Vec::new()
641            }
642        };
643        let image_count = images.len();
644        state.messages.push(Message::tool_with_images(
645            call.id.clone(),
646            text.clone(),
647            images.iter().map(ToolImage::to_url),
648        ));
649        state.log.push(ToolLogEntry {
650            id: call.id.clone(),
651            name: call.name.clone(),
652            provider: bound.map(|b| b.provider.clone()).unwrap_or_default(),
653            tool: bound.map(|b| b.name.clone()).unwrap_or_default(),
654            arguments: log_arguments(call, tools),
655            result: text,
656            is_error: output.is_error,
657            images: image_count,
658        });
659    }
660
661    async fn run_calls(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], calls: Vec<ToolCall>) {
662        if calls.is_empty() {
663            return;
664        }
665        for call in &calls {
666            ctx.progress(
667                "tool_call",
668                Value::from_json(json!({"id": call.id, "name": call.name, "arguments": log_arguments(call, tools)})),
669            );
670        }
671        let outputs: Vec<ToolOutput> = if self.config.parallel_tool_calls {
672            futures::future::join_all(calls.iter().map(|c| call_tool(tools, c))).await
673        } else {
674            let mut out = Vec::with_capacity(calls.len());
675            for c in &calls {
676                out.push(call_tool(tools, c).await);
677            }
678            out
679        };
680        let capture = ctx.captures_content();
681        for (call, output) in calls.iter().zip(outputs) {
682            let mut data =
683                json!({"id": call.id, "name": call.name, "is_error": output.is_error, "images": output.images.len()});
684            if capture && let Some(fields) = data.as_object_mut() {
685                // Same text the model and the `tool_calls` output see.
686                let result = truncate(&output.text, self.config.max_tool_output_chars);
687                fields.insert("result".to_owned(), Json::String(result));
688            }
689            ctx.progress("tool_result", Value::from_json(data));
690            self.record(state, tools, call, output);
691        }
692    }
693}
694
695/// How one model turn streams.
696#[derive(Clone, Copy, Debug)]
697struct TurnPlan {
698    /// Stream text and reasoning as they arrive (otherwise nothing is streamed).
699    live: bool,
700    /// Stop streaming text at the turn's first tool-call fragment.
701    stop_at_tool_call: bool,
702    /// Earlier turns streamed text: send [`PREAMBLE_SEPARATOR`] before this turn's first text.
703    separate: bool,
704}
705
706/// Run one turn. Returns the response and how many leading bytes of its text
707/// were streamed on field `text` (always whole deltas, so a char boundary).
708/// Deltas are moved into chunks, never copied.
709async fn stream_turn(
710    ctx: &NodeContext,
711    model: &dyn ChatModel,
712    request: ChatRequest,
713    plan: TurnPlan,
714) -> Result<(ChatResponse, usize), NodeError> {
715    if !plan.live {
716        return Ok((invoke(ctx, model, request, StreamMode::Off).await?, 0));
717    }
718    let stream = model.chat(request).await?;
719    let mut streamed = 0;
720    let mut text_closed = false;
721    let mut separator_pending = plan.separate;
722    let response = collect(stream, |delta| match delta {
723        ChatDelta::ToolCall { .. } => text_closed |= plan.stop_at_tool_call,
724        ChatDelta::Text(text) if !text.is_empty() && !text_closed => {
725            if std::mem::take(&mut separator_pending) {
726                ctx.chunk_shared(StreamField::Text.shared(), PREAMBLE_SEPARATOR);
727            }
728            streamed += text.len();
729            ctx.chunk_shared(StreamField::Text.shared(), text);
730        }
731        ChatDelta::Reasoning(text) if !text.is_empty() => ctx.chunk_shared(StreamField::Reasoning.shared(), text),
732        _ => {}
733    })
734    .await?;
735    Ok((response, streamed))
736}
737
738/// Append the streamed part of a tool-calling turn's text to the answer,
739/// mirroring what [`stream_turn`] sent (separator included).
740fn commit_preamble(answer: &mut String, text: &str, streamed: usize) {
741    let Some(preamble) = text.get(..streamed).filter(|p| !p.is_empty()) else { return };
742    if !answer.is_empty() {
743        answer.push_str(PREAMBLE_SEPARATOR);
744    }
745    answer.push_str(preamble);
746}
747
748/// The `text` output: streamed preambles, then the final turn's text (which
749/// is always streamed whole). Without preambles the final text is moved as is.
750fn final_answer(mut answer: String, text: String, streamed: usize) -> String {
751    if answer.is_empty() {
752        return text;
753    }
754    commit_preamble(&mut answer, &text, streamed);
755    answer
756}
757
758/// Replace the images of all but the last `keep` image-bearing tool results
759/// with a text placeholder, so a screenshot loop does not resend every
760/// screenshot on every turn.
761fn prune_tool_images(messages: &mut [Message], keep: usize) {
762    let mut seen = 0;
763    for message in messages.iter_mut().rev().filter(|m| m.role == Role::Tool) {
764        let count = message.images().count();
765        if count == 0 {
766            continue;
767        }
768        seen += 1;
769        if seen <= keep {
770            continue;
771        }
772        let note = if count == 1 {
773            "[1 image removed from history]".to_owned()
774        } else {
775            format!("[{count} images removed from history]")
776        };
777        let text = message.text();
778        let text = if text.is_empty() { note } else { format!("{text}\n{note}") };
779        message.content = vec![ContentPart::Text { text }];
780    }
781}
782
783/// Arguments as shown in logs and approval requests: the parsed object, or the
784/// raw text when it is not valid JSON (so nothing is hidden from the reader),
785/// with the tool's context values masked.
786fn log_arguments(call: &ToolCall, tools: &[BoundTool]) -> Json {
787    let mut arguments = match call.arguments_json() {
788        Ok(map) => Json::Object(map),
789        Err(_) => Json::String(call.arguments.clone()),
790    };
791    if let Some(tool) = tools.iter().find(|t| t.exposed == call.name)
792        && !tool.context().is_empty()
793    {
794        scrub_json(&mut arguments, tool.context());
795    }
796    arguments
797}
798
799/// `text` with every value of `context` masked. Borrows when there is nothing to mask.
800fn scrub_context<'a>(text: &'a str, context: &ToolCallContext) -> Cow<'a, str> {
801    if context.is_empty() {
802        return Cow::Borrowed(text);
803    }
804    let values: Vec<&str> = context.secrets.values().map(String::as_str).collect();
805    redact_secrets(text, &values)
806}
807
808/// Mask the values of `context` in every string of `value`.
809fn scrub_json(value: &mut Json, context: &ToolCallContext) {
810    match value {
811        Json::String(text) => {
812            if let Cow::Owned(scrubbed) = scrub_context(text, context) {
813                *text = scrubbed;
814            }
815        }
816        Json::Array(items) => items.iter_mut().for_each(|item| scrub_json(item, context)),
817        Json::Object(map) => map.values_mut().for_each(|item| scrub_json(item, context)),
818        _ => {}
819    }
820}
821
822async fn call_tool(tools: &[BoundTool], call: &ToolCall) -> ToolOutput {
823    let Some(tool) = tools.iter().find(|t| t.exposed == call.name) else {
824        return ToolOutput::error(format!("error: unknown tool `{}`", call.name));
825    };
826    let arguments = match call.arguments_json() {
827        Ok(map) => Json::Object(map),
828        Err(e) => return ToolOutput::error(format!("error: {e}")),
829    };
830    match tool.runtime.call(&tool.name, arguments, tool.context()).await {
831        Ok(output) => output,
832        Err(e) => ToolOutput::error(format!("error: {e}")),
833    }
834}
835
836/// Host decision for paused tool calls.
837#[derive(Debug, Default)]
838struct Approvals {
839    all: Option<bool>,
840    per_call: HashMap<String, bool>,
841    reason: Option<String>,
842}
843
844impl Approvals {
845    /// Recognized forms: `true`/`false`, `{"approved": bool}`,
846    /// `{"approvals": {"<call id>": bool}}` (both may be combined, per-call wins),
847    /// plus an optional `reason`. Anything else decides nothing.
848    fn from_input(input: Option<&Value>) -> Self {
849        let mut out = Self::default();
850        match input {
851            Some(Value::Bool(b)) => out.all = Some(*b),
852            Some(Value::Object(map)) => {
853                out.all = map.get("approved").and_then(Value::as_bool);
854                if let Some(Value::Object(per)) = map.get("approvals") {
855                    for (id, v) in per.iter() {
856                        if let Some(b) = v.as_bool() {
857                            out.per_call.insert(id.clone(), b);
858                        }
859                    }
860                }
861                out.reason = map.get("reason").and_then(Value::as_str).map(str::to_owned);
862            }
863            _ => {}
864        }
865        out
866    }
867
868    /// `Some(true)` approved, `Some(false)` denied, `None` no decision yet.
869    fn decision(&self, id: &str) -> Option<bool> {
870        self.per_call.get(id).copied().or(self.all)
871    }
872}
873
874/// Model-safe tool name: `[A-Za-z0-9_-]{1,64}`, unique within the run.
875fn unique_name(name: &str, provider: &str, used: &mut HashSet<String>) -> String {
876    let clean = |s: &str| -> String {
877        let mut out: String = s
878            .chars()
879            .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
880            .take(64)
881            .collect();
882        if out.is_empty() {
883            out.push_str("tool");
884        }
885        out
886    };
887    let mut candidate = clean(name);
888    if used.contains(&candidate) {
889        candidate = clean(&format!("{provider}_{name}"));
890    }
891    let base = candidate.clone();
892    let mut n = 2;
893    while used.contains(&candidate) {
894        let suffix = format!("_{n}");
895        let keep = 64usize.saturating_sub(suffix.len());
896        candidate = format!("{}{suffix}", base.chars().take(keep).collect::<String>());
897        n += 1;
898    }
899    used.insert(candidate.clone());
900    candidate
901}
902
903fn truncate(text: &str, max_chars: usize) -> String {
904    if max_chars == 0 || text.chars().count() <= max_chars {
905        return text.to_owned();
906    }
907    let mut out: String = text.chars().take(max_chars).collect();
908    out.push_str("\n[truncated]");
909    out
910}
911
912impl Node for AgentNode {
913    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
914        Box::pin(self.execute(ctx))
915    }
916
917    fn inputs(&self) -> Vec<Selector> {
918        let cfg = &self.config;
919        let mut out: Vec<Selector> = cfg.query.selectors().cloned().collect();
920        if let Some(i) = &cfg.instruction {
921            out.extend(i.selectors().cloned());
922        }
923        if let Some(memory) = &cfg.memory {
924            out.extend(memory.selectors());
925        }
926        out.extend(cfg.vision.selectors());
927        out.extend(cfg.model.selectors());
928        out.extend(self.tool_context.iter().flat_map(|(_, t)| t).flat_map(|(_, t)| t.selectors().cloned()));
929        out
930    }
931}
932
933/// Factory for the node registry.
934pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
935    Ok(Arc::new(AgentNode::from_doc(doc)?))
936}
937
938#[cfg(test)]
939mod tests {
940    use super::*;
941    use crate::mock::MockModel;
942    use crate::registry::ModelRegistry;
943    use crate::types::Role;
944    use graphrt_core::event::Event;
945    use graphrt_core::node::Resume;
946    use graphrt_core::tool::ToolError;
947    use graphrt_core::{Services, VariablePool};
948    use std::sync::Mutex;
949
950    /// Tools: `add {a, b}` and `fail {}`.
951    #[derive(Debug, Default)]
952    struct MathTools {
953        calls: Mutex<Vec<String>>,
954    }
955
956    impl ToolRuntime for MathTools {
957        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
958            Box::pin(async {
959                Ok(vec![
960                    ToolSpec {
961                        name: "add".into(),
962                        description: "add numbers".into(),
963                        parameters: json!({"type": "object"}),
964                    },
965                    ToolSpec {
966                        name: "fail".into(),
967                        description: "always fails".into(),
968                        parameters: json!({"type": "object"}),
969                    },
970                ])
971            })
972        }
973
974        fn call<'a>(
975            &'a self,
976            name: &'a str,
977            arguments: Json,
978            _context: &'a ToolCallContext,
979        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
980            self.calls.lock().unwrap().push(name.to_owned());
981            Box::pin(async move {
982                match name {
983                    "add" => {
984                        let a = arguments["a"].as_i64().unwrap_or(0);
985                        let b = arguments["b"].as_i64().unwrap_or(0);
986                        Ok(ToolOutput::text((a + b).to_string()))
987                    }
988                    _ => Err(ToolError { tool: name.to_owned(), message: "broken".into() }),
989                }
990            })
991        }
992    }
993
994    /// Tools: `screenshot {}` (one PNG), `bad_image {}` (an unsupported type).
995    #[derive(Debug, Default)]
996    struct ScreenTools;
997
998    impl ToolRuntime for ScreenTools {
999        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1000            let spec = |name: &str| ToolSpec { name: name.into(), description: "d".into(), parameters: json!({}) };
1001            Box::pin(async move { Ok(vec![spec("screenshot"), spec("bad_image")]) })
1002        }
1003
1004        fn call<'a>(
1005            &'a self,
1006            name: &'a str,
1007            _arguments: Json,
1008            _context: &'a ToolCallContext,
1009        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1010            Box::pin(async move {
1011                Ok(match name {
1012                    "screenshot" => ToolOutput::text("800x600").with_image(ToolImage::png("aGVsbG8=")),
1013                    _ => ToolOutput::text("odd")
1014                        .with_image(ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() }),
1015                })
1016            })
1017        }
1018    }
1019
1020    struct Setup {
1021        model: Arc<MockModel>,
1022        tools: Arc<MathTools>,
1023        events: Arc<Mutex<Vec<Event>>>,
1024    }
1025
1026    fn setup(responses: Vec<Vec<crate::ChatDelta>>) -> Setup {
1027        Setup {
1028            model: Arc::new(MockModel::new(responses)),
1029            tools: Arc::new(MathTools::default()),
1030            events: Arc::default(),
1031        }
1032    }
1033
1034    fn ctx(s: &Setup) -> NodeContext {
1035        let mut tool_registry = ToolRegistry::new();
1036        tool_registry.add("math", Arc::clone(&s.tools) as Arc<dyn ToolRuntime>);
1037        tool_registry.add("screen", Arc::new(ScreenTools) as Arc<dyn ToolRuntime>);
1038        let services = Services::new()
1039            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
1040            .with(tool_registry);
1041        let mut pool = VariablePool::new();
1042        pool.insert("sys", "query", Value::from("what is 2+3?"));
1043        let events = Arc::clone(&s.events);
1044        NodeContext::for_test("agent", pool)
1045            .with_services(Arc::new(services))
1046            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
1047    }
1048
1049    fn agent(extra: Json) -> AgentNode {
1050        let mut config = json!({
1051            "model": {"provider": "openai", "name": "gpt"},
1052            "instruction": "You are a calculator.",
1053            "tools": ["math/*"],
1054        });
1055        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
1056            c.extend(e);
1057        }
1058        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1059    }
1060
1061    fn completed(r: NodeResult) -> NodeOutput {
1062        match r.unwrap() {
1063            NodeOutcome::Completed(o) => o,
1064            NodeOutcome::Paused(p) => panic!("unexpected pause: {p:?}"),
1065        }
1066    }
1067
1068    #[tokio::test]
1069    async fn loops_until_answer() {
1070        let s = setup(vec![
1071            MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#), ("c2", "fail", "{}")]),
1072            MockModel::text("The answer is 5."),
1073        ]);
1074        let out = completed(agent(json!({})).run(ctx(&s)).await);
1075        assert_eq!(out.outputs["text"], Value::from("The answer is 5."));
1076        assert_eq!(out.outputs["iterations"], Value::Int(2));
1077        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1078        assert_eq!(log.len(), 2);
1079        assert_eq!(log[0].get_path(&["result"]), Some(Value::from("5")));
1080        assert_eq!(log[1].get_path(&["is_error"]), Some(Value::Bool(true)));
1081        assert_eq!(out.usage.unwrap().total_tokens, 4);
1082
1083        let requests = s.model.requests();
1084        assert_eq!(requests[0].tools.len(), 2);
1085        let second = &requests[1].messages;
1086        assert_eq!(second[0].role, Role::System);
1087        assert_eq!(second[2].tool_calls.len(), 2);
1088        assert_eq!(second[3].tool_call_id.as_deref(), Some("c1"));
1089        assert_eq!(second[3].text(), "5");
1090        assert!(second[4].text().contains("broken"));
1091
1092        let progress: Vec<String> = s
1093            .events
1094            .lock()
1095            .unwrap()
1096            .iter()
1097            .filter_map(|e| match e {
1098                Event::NodeProgress { name, .. } => Some(name.clone()),
1099                _ => None,
1100            })
1101            .collect();
1102        assert_eq!(progress, ["agent_step", "tool_call", "tool_call", "tool_result", "tool_result", "agent_step"]);
1103    }
1104
1105    const JWT: &str = "eyJhbGciOiJIUzI1NiJ9.user-token";
1106
1107    /// Tool `whoami {}` that echoes its context (as a careless upstream error would).
1108    #[derive(Debug)]
1109    struct VaultTools {
1110        accepts: bool,
1111        contexts: Mutex<Vec<ToolCallContext>>,
1112    }
1113
1114    impl VaultTools {
1115        fn new(accepts: bool) -> Arc<Self> {
1116            Arc::new(Self { accepts, contexts: Mutex::default() })
1117        }
1118    }
1119
1120    impl ToolRuntime for VaultTools {
1121        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1122            let spec = ToolSpec { name: "whoami".into(), description: "d".into(), parameters: json!({}) };
1123            Box::pin(async move { Ok(vec![spec]) })
1124        }
1125
1126        fn call<'a>(
1127            &'a self,
1128            _name: &'a str,
1129            _arguments: Json,
1130            context: &'a ToolCallContext,
1131        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1132            self.contexts.lock().unwrap().push(context.clone());
1133            let token = context.secret("user_jwt").unwrap_or("none").to_owned();
1134            Box::pin(async move { Ok(ToolOutput::text(format!("rejected token {token}"))) })
1135        }
1136
1137        fn accepts_secrets(&self) -> bool {
1138            self.accepts
1139        }
1140    }
1141
1142    fn vault_ctx(s: &Setup, vault: &Arc<VaultTools>) -> NodeContext {
1143        let mut registry = ToolRegistry::new();
1144        registry.add("vault", Arc::clone(vault) as Arc<dyn ToolRuntime>);
1145        let services = Services::new()
1146            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
1147            .with(registry);
1148        let mut pool = VariablePool::new();
1149        pool.insert("sys", "query", Value::from("who am I?"));
1150        pool.insert("start", "user_jwt", Value::Secret(Arc::from(JWT)));
1151        let events = Arc::clone(&s.events);
1152        NodeContext::for_test("agent", pool)
1153            .with_services(Arc::new(services))
1154            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
1155    }
1156
1157    fn vault_agent(extra: Json) -> AgentNode {
1158        let mut config = json!({
1159            "model": {"provider": "openai", "name": "gpt"},
1160            "tools": ["vault/whoami"],
1161            "tool_context": {"vault": {"user_jwt": "{{#start.user_jwt#}}", "missing": "{{#start.nope#}}"}},
1162        });
1163        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
1164            c.extend(e);
1165        }
1166        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1167    }
1168
1169    #[tokio::test]
1170    async fn tool_context_reaches_the_tool_but_nothing_else() {
1171        let s = setup(vec![
1172            MockModel::tool_calls(&[("c1", "whoami", &format!(r#"{{"echo":"{JWT}"}}"#))]),
1173            MockModel::text("done"),
1174        ]);
1175        let vault = VaultTools::new(true);
1176        let secrets = Arc::new(graphrt_core::redact::SecretSet::new());
1177        let ctx = vault_ctx(&s, &vault).with_secret_values(Arc::clone(&secrets));
1178        let node = vault_agent(json!({}));
1179        let out = completed(node.run(ctx).await);
1180
1181        let contexts = vault.contexts.lock().unwrap().clone();
1182        assert_eq!(contexts.len(), 1);
1183        assert_eq!(contexts[0].secret("user_jwt"), Some(JWT));
1184        assert_eq!(contexts[0].secret("missing"), None, "empty renders are left out");
1185
1186        // Not in the model's history, the outputs or any event.
1187        let requests = s.model.requests();
1188        assert_eq!(requests[1].messages.last().unwrap().text(), "rejected token ******");
1189        // (The model's own arguments stay in its history as it wrote them.)
1190        let tool_messages: Vec<_> = requests[1].messages.iter().filter(|m| m.role == Role::Tool).collect();
1191        assert!(!format!("{tool_messages:?}").contains(JWT));
1192        assert!(!serde_json::to_string(&out.outputs).unwrap().contains(JWT));
1193        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
1194        assert!(!events.contains(JWT), "{events}");
1195        // Registered with the run so later node errors are scrubbed too.
1196        assert_eq!(secrets.scrub(&format!("bad {JWT}")), "bad ******");
1197        assert!(node.inputs().iter().any(|sel| sel.to_string() == "start.user_jwt"));
1198    }
1199
1200    #[tokio::test]
1201    async fn tool_context_is_sent_again_after_approval() {
1202        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
1203        let vault = VaultTools::new(true);
1204        let node = vault_agent(json!({"require_approval": ["*"]}));
1205        let paused = match node.run(vault_ctx(&s, &vault)).await.unwrap() {
1206            NodeOutcome::Paused(p) => p,
1207            NodeOutcome::Completed(_) => panic!("expected a pause"),
1208        };
1209        assert!(!paused.state.to_string().contains(JWT), "the snapshot state never holds the context");
1210        let resume = Resume { state: paused.state, input: Some(Value::Bool(true)) };
1211        completed(node.run(vault_ctx(&s, &vault).with_resume(Some(resume))).await);
1212        assert_eq!(vault.contexts.lock().unwrap()[0].secret("user_jwt"), Some(JWT));
1213    }
1214
1215    #[tokio::test]
1216    async fn tool_context_needs_a_provider_that_accepts_secrets() {
1217        let s = setup(vec![MockModel::text("unused")]);
1218        let vault = VaultTools::new(false);
1219        let error = vault_agent(json!({})).run(vault_ctx(&s, &vault)).await.unwrap_err();
1220        assert_eq!(error.kind, "tool_context_denied");
1221        assert!(vault.contexts.lock().unwrap().is_empty());
1222    }
1223
1224    #[test]
1225    fn tool_context_providers_must_be_used() {
1226        let config = json!({
1227            "model": {"provider": "openai", "name": "gpt"},
1228            "tools": ["math/add"],
1229            "tool_context": {"vault": {"user_jwt": "x"}},
1230        });
1231        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
1232        assert!(error.to_string().contains("`vault` is not used"), "{error}");
1233        for bad in [json!({"math": {"jwt": 1}}), json!({"math": {"": "x"}}), json!({"math": "x"})] {
1234            let config =
1235                json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["math/add"], "tool_context": bad});
1236            assert!(AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).is_err());
1237        }
1238    }
1239
1240    fn tool_results(s: &Setup) -> Vec<Value> {
1241        let events = s.events.lock().unwrap();
1242        let results = events.iter().filter_map(|e| match e {
1243            Event::NodeProgress { name, data, .. } if name == "tool_result" => Some(data.clone()),
1244            _ => None,
1245        });
1246        results.collect()
1247    }
1248
1249    #[tokio::test]
1250    async fn tool_results_carry_text_only_when_the_host_captures_content() {
1251        let responses = || vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")];
1252        let s = setup(responses());
1253        completed(agent(json!({})).run(ctx(&s)).await);
1254        assert_eq!(tool_results(&s)[0].get_path(&["result"]), None);
1255
1256        let s = setup(responses());
1257        let base = ctx(&s);
1258        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
1259        completed(agent(json!({})).run(base.with_services(Arc::new(services))).await);
1260        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("5")));
1261    }
1262
1263    #[tokio::test]
1264    async fn tool_images_reach_the_model() {
1265        let s = setup(vec![MockModel::tool_calls(&[("c1", "screenshot", "{}")]), MockModel::text("a login form")]);
1266        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1267        let requests = s.model.requests();
1268        let result = &requests[1].messages[3];
1269        assert_eq!(result.role, Role::Tool);
1270        assert_eq!(result.text(), "800x600");
1271        assert_eq!(
1272            result.images().cloned().collect::<Vec<_>>(),
1273            vec![ContentPart::Image { url: "data:image/png;base64,aGVsbG8=".into(), detail: None }]
1274        );
1275        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1276        assert_eq!(log[0].get_path(&["images"]), Some(Value::Int(1)));
1277        let reported = s.events.lock().unwrap().iter().find_map(|e| match e {
1278            Event::NodeProgress { name, data, .. } if name == "tool_result" => data.get_path(&["images"]),
1279            _ => None,
1280        });
1281        assert_eq!(reported, Some(Value::Int(1)));
1282    }
1283
1284    #[tokio::test]
1285    async fn invalid_tool_images_are_dropped_with_a_note() {
1286        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
1287        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1288        let result = &s.model.requests()[1].messages[3];
1289        assert_eq!(result.images().count(), 0);
1290        assert!(
1291            result.text().starts_with("odd\n[images dropped: image #0: image media type `image/bmp`"),
1292            "{}",
1293            result.text()
1294        );
1295    }
1296
1297    #[tokio::test]
1298    async fn keep_tool_images_prunes_older_screenshots() {
1299        let s = setup(vec![
1300            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
1301            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
1302            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
1303            MockModel::text("done"),
1304        ]);
1305        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": 2})).run(ctx(&s)).await);
1306        let last = s.model.requests().last().cloned().unwrap();
1307        let results: Vec<&Message> = last.messages.iter().filter(|m| m.role == Role::Tool).collect();
1308        assert_eq!(results.iter().map(|m| m.images().count()).collect::<Vec<_>>(), [0, 1, 1]);
1309        assert_eq!(results[0].text(), "800x600\n[1 image removed from history]");
1310        // The second request still had every image (only two existed).
1311        let second = &s.model.requests()[2];
1312        assert_eq!(second.messages.iter().map(|m| m.images().count()).sum::<usize>(), 2);
1313    }
1314
1315    fn four_screenshots() -> Vec<Vec<crate::ChatDelta>> {
1316        vec![
1317            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
1318            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
1319            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
1320            MockModel::tool_calls(&[("c4", "screenshot", "{}")]),
1321            MockModel::text("done"),
1322        ]
1323    }
1324
1325    fn images_per_tool_result(s: &Setup) -> Vec<usize> {
1326        let last = s.model.requests().last().cloned().unwrap();
1327        last.messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.images().count()).collect()
1328    }
1329
1330    #[tokio::test]
1331    async fn keep_tool_images_defaults_to_the_last_three() {
1332        let s = setup(four_screenshots());
1333        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1334        assert_eq!(images_per_tool_result(&s), [0, 1, 1, 1]);
1335    }
1336
1337    #[tokio::test]
1338    async fn keep_tool_images_null_keeps_every_image() {
1339        let s = setup(four_screenshots());
1340        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": null})).run(ctx(&s)).await);
1341        assert_eq!(images_per_tool_result(&s), [1, 1, 1, 1]);
1342    }
1343
1344    #[tokio::test]
1345    async fn last_iteration_keeps_tools_but_forbids_calls() {
1346        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), MockModel::text("2")]);
1347        let out = completed(agent(json!({"max_iterations": 2})).run(ctx(&s)).await);
1348        assert_eq!(out.outputs["text"], Value::from("2"));
1349        assert_eq!(out.outputs["stopped_reason"], Value::from("max_iterations"));
1350        let requests = s.model.requests();
1351        assert_eq!(requests[0].tool_choice, Some(ToolChoice::Auto));
1352        assert!(!requests[1].tools.is_empty(), "tool definitions stay for the history's tool calls");
1353        assert_eq!(requests[1].tool_choice, Some(ToolChoice::None));
1354    }
1355
1356    fn text_chunks(s: &Setup) -> Vec<String> {
1357        s.events
1358            .lock()
1359            .unwrap()
1360            .iter()
1361            .filter_map(|e| match e {
1362                Event::NodeChunk { field, chunk, .. } if field.as_ref() == "text" => Some(chunk.clone()),
1363                _ => None,
1364            })
1365            .collect()
1366    }
1367
1368    fn thought(s: &Setup) -> Option<Value> {
1369        s.events.lock().unwrap().iter().find_map(|e| match e {
1370            Event::NodeProgress { name, data, .. } if name == "agent_thought" => Some(data.clone()),
1371            _ => None,
1372        })
1373    }
1374
1375    fn tokens(pieces: &[&str]) -> Vec<crate::ChatDelta> {
1376        let mut out: Vec<crate::ChatDelta> = pieces.iter().map(|p| crate::ChatDelta::Text((*p).into())).collect();
1377        out.push(crate::ChatDelta::Finish(FinishReason::Stop));
1378        out
1379    }
1380
1381    #[tokio::test]
1382    async fn final_answer_streams_token_by_token() {
1383        let s =
1384            setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), tokens(&["It", " is", " 5", "."])]);
1385        let out = completed(agent(json!({})).run(ctx(&s)).await);
1386        // One chunk per provider delta, on a turn that was still allowed to call tools.
1387        assert_eq!(text_chunks(&s), ["It", " is", " 5", "."]);
1388        assert_eq!(out.outputs["text"], Value::from("It is 5."));
1389        assert_eq!(s.model.requests()[1].tool_choice, Some(ToolChoice::Auto));
1390    }
1391
1392    #[tokio::test]
1393    async fn preamble_before_a_tool_call_is_streamed_and_kept_in_the_answer() {
1394        let mut first = tokens(&["Let me", " check."]);
1395        first.pop();
1396        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
1397        let s = setup(vec![first, tokens(&["It is", " 5."])]);
1398        let out = completed(agent(json!({})).run(ctx(&s)).await);
1399        let chunks = text_chunks(&s);
1400        assert_eq!(chunks, ["Let me", " check.", "\n\n", "It is", " 5."]);
1401        assert_eq!(out.outputs["text"], Value::from(chunks.concat().as_str()));
1402        let thought = thought(&s).unwrap();
1403        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
1404        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(true)));
1405        // The history keeps each turn separate: the preamble belongs to the tool-call turn.
1406        let second = &s.model.requests()[1].messages;
1407        assert_eq!(second[2].text(), "Let me check.");
1408        assert_eq!(second[2].tool_calls.len(), 1);
1409    }
1410
1411    #[tokio::test]
1412    async fn tool_call_fragments_and_later_text_are_never_streamed() {
1413        use crate::ChatDelta::{Finish, Text, ToolCall};
1414        let first = vec![
1415            Text("A".into()),
1416            ToolCall { index: 0, id: Some("c1".into()), name: Some("add".into()), arguments: r#"{"a":"#.into() },
1417            Text("B".into()),
1418            ToolCall { index: 0, id: None, name: None, arguments: "1}".into() },
1419            Finish(FinishReason::ToolCalls),
1420        ];
1421        let s = setup(vec![first, MockModel::text("done")]);
1422        let out = completed(agent(json!({})).run(ctx(&s)).await);
1423        assert_eq!(text_chunks(&s), ["A", "\n\n", "done"]);
1424        assert_eq!(out.outputs["text"], Value::from("A\n\ndone"));
1425        assert_eq!(thought(&s).unwrap().get_path(&["text"]), Some(Value::from("AB")));
1426        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
1427    }
1428
1429    #[tokio::test]
1430    async fn stream_tool_turns_false_buffers_tool_turns() {
1431        let mut first = vec![crate::ChatDelta::Text("Let me check.".into())];
1432        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
1433        let s = setup(vec![first, tokens(&["It is", " 5."])]);
1434        let out = completed(agent(json!({"stream_tool_turns": false})).run(ctx(&s)).await);
1435        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
1436        assert_eq!(text_chunks(&s), ["It is 5."]);
1437        assert_eq!(out.outputs["text"], Value::from("It is 5."));
1438        let thought = thought(&s).unwrap();
1439        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
1440        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(false)));
1441    }
1442
1443    #[tokio::test]
1444    async fn forced_final_turn_streams_token_by_token() {
1445        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), tokens(&["=", "2"])]);
1446        let out = completed(agent(json!({"max_iterations": 2, "stream_tool_turns": false})).run(ctx(&s)).await);
1447        assert_eq!(text_chunks(&s), ["=", "2"]);
1448        assert_eq!(out.outputs["text"], Value::from("=2"));
1449    }
1450
1451    #[tokio::test]
1452    async fn preamble_survives_a_tool_approval_pause() {
1453        let mut first = vec![crate::ChatDelta::Text("Checking.".into())];
1454        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
1455        let s = setup(vec![first, MockModel::text("4")]);
1456        let node = agent(json!({"require_approval": ["add"]}));
1457        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1458        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
1459        let resumed =
1460            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
1461        let out = completed(node.run(resumed).await);
1462        assert_eq!(out.outputs["text"], Value::from("Checking.\n\n4"));
1463        assert_eq!(text_chunks(&s), ["Checking.", "\n\n", "4"]);
1464    }
1465
1466    #[tokio::test]
1467    async fn malformed_arguments_are_reported_back_to_the_model() {
1468        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"#)]), MockModel::text("sorry")]);
1469        let out = completed(agent(json!({})).run(ctx(&s)).await);
1470        assert!(s.tools.calls.lock().unwrap().is_empty(), "malformed calls never run");
1471        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1472        assert_eq!(log[0].get_path(&["arguments"]), Some(Value::from(r#"{"a":2,"#)));
1473        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
1474        let second = &s.model.requests()[1];
1475        assert_eq!(second.messages[2].tool_calls[0].arguments, "{}", "history never replays malformed JSON");
1476        assert!(second.messages[3].text().contains("invalid JSON arguments"));
1477    }
1478
1479    #[tokio::test]
1480    async fn per_turn_limit_rejects_extra_calls() {
1481        let s = setup(vec![
1482            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
1483            MockModel::text("ok"),
1484        ]);
1485        let out =
1486            completed(agent(json!({"max_tool_calls_per_turn": 1, "parallel_tool_calls": false})).run(ctx(&s)).await);
1487        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
1488        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1489        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
1490    }
1491
1492    #[tokio::test]
1493    async fn approval_pauses_and_resumes() {
1494        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]), MockModel::text("4")]);
1495        let node = agent(json!({"tools": [{"provider": "math", "name": "add"}], "require_approval": ["math/add"]}));
1496        let paused = match node.run(ctx(&s)).await.unwrap() {
1497            NodeOutcome::Paused(p) => p,
1498            NodeOutcome::Completed(_) => panic!("expected pause"),
1499        };
1500        assert_eq!(paused.kind, "tool_approval");
1501        assert_eq!(paused.data.get_path(&["calls", "0", "name"]), Some(Value::from("add")));
1502        assert!(s.tools.calls.lock().unwrap().is_empty(), "nothing runs before approval");
1503
1504        // The saved state survives serialization (snapshots store it as JSON).
1505        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
1506        let resumed =
1507            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
1508        let out = completed(node.run(resumed).await);
1509        assert_eq!(out.outputs["text"], Value::from("4"));
1510        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
1511    }
1512
1513    #[tokio::test]
1514    async fn denied_calls_are_reported_to_the_model() {
1515        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", "{}")]), MockModel::text("fine")]);
1516        let node = agent(json!({"require_approval": ["*"]}));
1517        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1518        let input = Value::from_json(json!({"approvals": {"c1": false}, "reason": "not now"}));
1519        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
1520        assert_eq!(out.outputs["text"], Value::from("fine"));
1521        assert!(s.tools.calls.lock().unwrap().is_empty());
1522        let last_request = s.model.requests().pop().unwrap();
1523        assert!(last_request.messages.iter().any(|m| m.text().contains("not now")));
1524    }
1525
1526    #[tokio::test]
1527    async fn only_gated_calls_wait_for_approval() {
1528        let s = setup(vec![
1529            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "fail", "{}")]),
1530            MockModel::text("done"),
1531        ]);
1532        let node = agent(json!({"require_approval": ["math/fail"]}));
1533        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1534        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"], "ungated calls run immediately");
1535        assert_eq!(p.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
1536        assert!(p.data.get_path(&["calls", "1"]).is_none());
1537
1538        // No decision (or one that is not understood) keeps the run paused.
1539        for input in [None, Some(Value::from("yes")), Some(Value::from_json(json!({"approved": "true"})))] {
1540            let resumed = ctx(&s).with_resume(Some(Resume { state: p.state.clone(), input }));
1541            assert!(matches!(node.run(resumed).await.unwrap(), NodeOutcome::Paused(_)));
1542        }
1543        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
1544
1545        let input = Value::from_json(json!({"approvals": {"c2": true}}));
1546        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
1547        assert_eq!(out.outputs["text"], Value::from("done"));
1548        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add", "fail"]);
1549    }
1550
1551    #[tokio::test]
1552    async fn per_call_decisions_can_arrive_in_steps() {
1553        let s = setup(vec![
1554            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
1555            MockModel::text("ok"),
1556        ]);
1557        let node = agent(json!({"require_approval": ["*"], "parallel_tool_calls": false}));
1558        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
1559        let input = Value::from_json(json!({"approvals": {"c1": true}}));
1560        let NodeOutcome::Paused(p2) =
1561            node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await.unwrap()
1562        else {
1563            panic!("c2 is still undecided")
1564        };
1565        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
1566        assert_eq!(p2.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
1567        let input = Value::from_json(json!({"approved": false}));
1568        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p2.state, input: Some(input) }))).await);
1569        assert_eq!(out.outputs["text"], Value::from("ok"));
1570        assert_eq!(s.tools.calls.lock().unwrap().len(), 1, "c2 was denied");
1571    }
1572
1573    #[test]
1574    fn inputs_cover_templates_and_memory() {
1575        let node = agent(json!({"query": "{{#start.q#}}", "instruction": "{{#env.persona#}}", "memory": {}}));
1576        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
1577        for expected in ["start.q", "env.persona", "sys.history", "sys.query"] {
1578            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
1579        }
1580    }
1581
1582    #[tokio::test]
1583    async fn unknown_provider_is_fatal() {
1584        let s = setup(vec![]);
1585        let err = agent(json!({"tools": ["nope/x"]})).run(ctx(&s)).await.unwrap_err();
1586        assert!(!err.retryable);
1587        assert_eq!(err.kind, "tool_not_found");
1588    }
1589
1590    #[test]
1591    fn config_validation_and_names() {
1592        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "tools": ["no-slash"]}));
1593        assert!(AgentNode::from_doc(&bad).is_err());
1594        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "max_iterations": 0}));
1595        assert!(AgentNode::from_doc(&bad).is_err());
1596        let mut used = HashSet::new();
1597        assert_eq!(unique_name("search", "web", &mut used), "search");
1598        assert_eq!(unique_name("search", "docs", &mut used), "docs_search");
1599        assert_eq!(unique_name("search", "docs", &mut used), "docs_search_2");
1600        assert_eq!(unique_name("a.b/c", "p", &mut used), "a_b_c");
1601    }
1602}