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//! `skills` attaches installed skills (see [`graphrt_core::skill`]): the system
52//! prompt gets one line per skill, and the model loads a skill's instructions
53//! with the `load_skill` tool when a task needs them. Tools the owner granted
54//! to a skill are offered to the model only after that skill was loaded in the
55//! run, and wait for approval unless the grant says otherwise. An agent
56//! without `skills` does none of this. The code is behind the cargo feature
57//! `skills`: without it, a node that lists skills is a configuration error.
58//!
59//! `learning` adds the approved lessons of one agent, and of the run's user,
60//! to the system prompt (see [`graphrt_core::learning`]). The node only reads
61//! lessons. Nothing is learned during a run. The code is behind the cargo
62//! feature `learning`: without it, a node with `learning` is a configuration
63//! error.
64//!
65//! `context_window` keeps the conversation of a long loop inside the model's
66//! context window (see [`crate::context`]): by default it acts when the
67//! provider refuses a turn for its size, trims the conversation and sends the
68//! turn once more. A tool call is never parted from its result. The code is
69//! behind the cargo feature `context`: without it nothing is trimmed, and a
70//! node that sets `context_window` to anything but `off` is a configuration
71//! error.
72//!
73//! Progress events: `agent_step`, `agent_thought`, `tool_call`, `tool_result`,
74//! `tool_denied`, `skill_tool_unavailable`, `lessons_applied`, `context_trimmed`. Outputs: `text`, `tool_calls`
75//! (`[{name, provider, tool, arguments, result, is_error, images}]`), `ui` (the UI blocks of
76//! successful tool results, see [`graphrt_core::ui`]; never sent to the model), `files` (feature
77//! `tool-files`: the files successful tool results returned, see
78//! `graphrt_core::tool::collect_files`; never sent to the model), `context`
79//! (feature `context`, only when the guard removed something:
80//! `{removed_messages, summarized}`), `iterations`,
81//! `stopped_reason` (`completed`, `max_iterations` or `length`), `usage`.
82
83use std::borrow::Cow;
84use std::collections::{HashMap, HashSet};
85use std::sync::Arc;
86
87use futures::future::BoxFuture;
88use graphrt_core::dsl::NodeDoc;
89use graphrt_core::event::Usage;
90#[cfg(feature = "learning")]
91use graphrt_core::learning::{LessonScope, Lessons};
92use graphrt_core::node::{ConfigError, NodeOutcome, NodeResult, PauseRequest, parse_config};
93use graphrt_core::redact::redact_secrets;
94#[cfg(feature = "skills")]
95use graphrt_core::skill::{LOAD_SKILL_TOOL, SKILL_PROVIDER, SkillToolGrant, Skills};
96use graphrt_core::template::Template;
97#[cfg(feature = "tool-files")]
98use graphrt_core::tool::collect_files;
99use graphrt_core::tool::{ToolCallContext, ToolImage, ToolOutput, ToolRegistry, ToolRuntime, ToolSpec, check_images};
100use graphrt_core::value::Value;
101use graphrt_core::{Node, NodeContext, NodeError, NodeOutput, Selector};
102use serde::{Deserialize, Serialize};
103use serde_json::{Value as Json, json};
104
105#[cfg(feature = "context")]
106use crate::context::{ContextState, ContextWindow};
107
108use super::common::{
109    FinishCheck, MemoryConfig, ModelConfig, StreamField, StreamMode, VisionConfig, check_finish, invoke, model_for,
110    usage_value,
111};
112use super::tool_call_repair;
113use crate::types::{
114    ChatDelta, ChatModel, ChatRequest, ChatResponse, ContentPart, FinishReason, Message, Role, ToolCall, ToolChoice,
115    collect,
116};
117
118/// Streamed between a preamble and the text that follows it in a later turn.
119const PREAMBLE_SEPARATOR: &str = "\n\n";
120
121/// Upper bound for `max_iterations`.
122pub const MAX_ITERATIONS_LIMIT: u32 = 100;
123
124/// Reference to a tool: `"provider/name"` or `{provider, name}`.
125#[derive(Clone, Debug, Deserialize)]
126#[serde(untagged)]
127pub enum ToolRef {
128    Path(String),
129    Pair { provider: String, name: String },
130}
131
132impl ToolRef {
133    fn split(&self) -> Option<(String, String)> {
134        match self {
135            ToolRef::Path(p) => {
136                let (provider, name) = p.split_once('/')?;
137                if provider.is_empty() || name.is_empty() {
138                    return None;
139                }
140                Some((provider.to_owned(), name.to_owned()))
141            }
142            ToolRef::Pair { provider, name } if !provider.is_empty() && !name.is_empty() => {
143                Some((provider.clone(), name.clone()))
144            }
145            ToolRef::Pair { .. } => None,
146        }
147    }
148}
149
150fn default_query() -> Template {
151    Template::parse("{{#sys.query#}}")
152}
153
154fn default_max_iterations() -> u32 {
155    10
156}
157
158fn default_true() -> bool {
159    true
160}
161
162fn default_max_tool_output() -> usize {
163    32_000
164}
165
166fn default_keep_tool_images() -> Option<usize> {
167    Some(3)
168}
169
170/// Configuration of the `agent` node.
171#[derive(Clone, Debug, Deserialize)]
172pub struct AgentConfig {
173    pub model: ModelConfig,
174    /// System prompt.
175    #[serde(default)]
176    pub instruction: Option<Template>,
177    /// User message (default `{{#sys.query#}}`).
178    #[serde(default = "default_query")]
179    pub query: Template,
180    #[serde(default)]
181    pub tools: Vec<ToolRef>,
182    /// Maximum model calls. Default 10.
183    #[serde(default = "default_max_iterations")]
184    pub max_iterations: u32,
185    /// Tool calls beyond this number in one turn are rejected with an error result.
186    #[serde(default)]
187    pub max_tool_calls_per_turn: Option<usize>,
188    #[serde(default = "default_true")]
189    pub parallel_tool_calls: bool,
190    #[serde(default)]
191    pub memory: Option<MemoryConfig>,
192    #[serde(default)]
193    pub vision: VisionConfig,
194    /// Tools that need host approval: `provider/name`, a tool name, or `*` for all.
195    #[serde(default)]
196    pub require_approval: Vec<String>,
197    /// Tool results longer than this (in characters) are truncated. Default 32 000.
198    #[serde(default = "default_max_tool_output")]
199    pub max_tool_output_chars: usize,
200    /// Keep the images of only the last N image-bearing tool results in the
201    /// conversation (older ones become a text placeholder). Default 3, since
202    /// images are resent on every turn; `null` keeps every image.
203    #[serde(default = "default_keep_tool_images")]
204    pub keep_tool_images: Option<usize>,
205    /// Stream the text of turns that may still call tools as it is generated
206    /// (see the module docs). Default `true`; `false` buffers those turns.
207    #[serde(default = "default_true")]
208    pub stream_tool_turns: bool,
209    /// Per provider, named values sent with every call to that provider's tools
210    /// (`{provider: {name: template}}`), outside the arguments. See the module docs.
211    /// Kept as raw JSON (parsed by [`AgentNode::from_doc`]) so no extra serde
212    /// code is generated for a rarely used field.
213    #[serde(default)]
214    pub tool_context: serde_json::Map<String, Json>,
215    /// Installed skills this agent may load (see the module docs). Needs the
216    /// cargo feature `skills` and a `graphrt_core::skill::Skills` service.
217    #[serde(default)]
218    pub skills: Vec<String>,
219    /// Read approved lessons into the system prompt: `{agent, user}` (see the
220    /// module docs). Needs the cargo feature `learning` and a
221    /// `graphrt_core::learning::Lessons` service. Kept as raw JSON, like
222    /// `tool_context`, so builds without the feature carry no code for it.
223    #[serde(default)]
224    pub learning: Option<Json>,
225    /// What happens when the conversation outgrows the model's context
226    /// window: `auto` (the default), `summarize`, `off` or a mapping (see
227    /// [`crate::context`]). Needs the cargo feature `context`. Kept as raw
228    /// JSON, like `learning`.
229    #[serde(default)]
230    pub context_window: Option<Json>,
231}
232
233/// `learning` of the `agent` node: whose lessons a run reads.
234#[cfg(feature = "learning")]
235#[derive(Clone, Debug)]
236struct Learning {
237    /// The agent the lessons belong to.
238    agent: String,
239    /// The user the run is for (a template, for example `{{#sys.user_id#}}`).
240    /// Lessons of that user are added to the lessons of the agent as a whole.
241    /// Without it, or when it renders empty, only the agent's lessons are read.
242    user: Option<Template>,
243}
244
245/// Parse `learning`: `{agent: <name>, user?: <template>}`. Any other key is an
246/// error, so a misspelled `user` cannot silently widen what a run reads.
247#[cfg(feature = "learning")]
248fn parse_learning(doc: &NodeDoc, raw: Option<&Json>) -> Result<Option<Learning>, ConfigError> {
249    let Some(raw) = raw.filter(|raw| !raw.is_null()) else { return Ok(None) };
250    let invalid = |why: &str| ConfigError::new(doc, format!("learning: {why}"));
251    let fields = raw.as_object().ok_or_else(|| invalid("expected `{agent, user}`"))?;
252    if let Some(unknown) = fields.keys().find(|key| !matches!(key.as_str(), "agent" | "user")) {
253        return Err(invalid(&format!("unknown field `{unknown}`")));
254    }
255    let agent = fields.get("agent").and_then(Json::as_str).filter(|agent| !agent.is_empty());
256    let agent = agent.ok_or_else(|| invalid("`agent` must be the name of the agent the lessons belong to"))?;
257    let user = match fields.get("user") {
258        None | Some(Json::Null) => None,
259        Some(Json::String(template)) => Some(Template::parse(template)),
260        Some(_) => return Err(invalid("`user` must be a template string")),
261    };
262    Ok(Some(Learning { agent: agent.to_owned(), user }))
263}
264
265/// A tool bound for one run.
266#[derive(Clone, Debug)]
267struct BoundTool {
268    /// Name exposed to the model (unique, provider-safe characters).
269    exposed: String,
270    provider: String,
271    name: String,
272    runtime: Arc<dyn ToolRuntime>,
273    spec: ToolSpec,
274    /// Rendered `tool_context` of the provider, shared by its tools.
275    context: Option<Arc<ToolCallContext>>,
276    /// Skills that grant this tool. Empty for the agent's own tools. Otherwise
277    /// the tool is offered only once one of these skills was loaded in the run.
278    #[cfg(feature = "skills")]
279    gates: Vec<String>,
280    /// A skill grant that asks first: every call waits for approval.
281    #[cfg(feature = "skills")]
282    ask: bool,
283    /// One of the skill tools themselves (never set for a registry provider,
284    /// whatever its name), so only they can mark a skill as loaded.
285    #[cfg(feature = "skills")]
286    skill_tool: bool,
287}
288
289impl BoundTool {
290    fn context(&self) -> &ToolCallContext {
291        self.context.as_deref().unwrap_or(ToolCallContext::empty())
292    }
293
294    /// The same tool was selected a second time.
295    ///
296    /// A tool the agent lists itself stays as the agent configured it. A tool
297    /// granted by several skills opens with any of them and asks first if any
298    /// of the grants does.
299    #[cfg_attr(not(feature = "skills"), allow(clippy::unused_self, clippy::needless_pass_by_ref_mut))]
300    fn bound_again(&mut self, origin: Origin<'_>) {
301        #[cfg(feature = "skills")]
302        if let (false, Origin::Grant(grant)) = (self.gates.is_empty(), origin) {
303            self.gates.push(grant.skill.clone());
304            self.ask |= grant.ask;
305        }
306        #[cfg(not(feature = "skills"))]
307        let _ = origin;
308    }
309
310    /// Whether the model may see and call this tool given the skills loaded so far.
311    #[cfg(feature = "skills")]
312    fn offered(&self, state: &AgentState) -> bool {
313        self.gates.is_empty() || self.gates.iter().any(|gate| state.loaded_skills.contains(gate))
314    }
315
316    /// Without skill support every bound tool is one of the agent's own.
317    #[cfg(not(feature = "skills"))]
318    #[allow(clippy::unused_self)]
319    fn offered(&self, _state: &AgentState) -> bool {
320        true
321    }
322
323    /// Whether a skill grant makes every call of this tool wait for approval.
324    #[cfg(feature = "skills")]
325    fn asks_first(&self) -> bool {
326        self.ask
327    }
328
329    #[cfg(not(feature = "skills"))]
330    #[allow(clippy::unused_self)]
331    fn asks_first(&self) -> bool {
332        false
333    }
334}
335
336/// Where a tool being bound comes from.
337#[derive(Clone, Copy)]
338enum Origin<'a> {
339    /// Listed in the agent's own `tools`.
340    Agent,
341    /// One of the skill tools (`load_skill`, `read_skill_file`).
342    #[cfg(feature = "skills")]
343    SkillTool,
344    /// Granted to a skill by the owner.
345    #[cfg(feature = "skills")]
346    Grant(&'a SkillToolGrant),
347    /// Keeps the lifetime in use in builds without skills.
348    #[cfg(not(feature = "skills"))]
349    #[allow(dead_code)]
350    Unused(std::marker::PhantomData<&'a ()>),
351}
352
353/// Collects the tools of one run, giving each a unique exposed name.
354#[derive(Default)]
355struct Binder {
356    listings: HashMap<String, Vec<ToolSpec>>,
357    bound: Vec<BoundTool>,
358    used: HashSet<String>,
359}
360
361impl Binder {
362    /// Bind `name` (or `*`) of a registry provider, listing the provider once.
363    async fn bind_registered(
364        &mut self,
365        provider: &str,
366        name: &str,
367        runtime: &Arc<dyn ToolRuntime>,
368        origin: Origin<'_>,
369    ) -> Result<(), NodeError> {
370        // The listing is taken out while it is read, so binding can borrow `self`.
371        let specs = match self.listings.remove(provider) {
372            Some(specs) => specs,
373            None => runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?,
374        };
375        let result = self.bind_specs(provider, name, &specs, runtime, origin);
376        self.listings.insert(provider.to_owned(), specs);
377        result
378    }
379
380    fn bind_specs(
381        &mut self,
382        provider: &str,
383        name: &str,
384        specs: &[ToolSpec],
385        runtime: &Arc<dyn ToolRuntime>,
386        origin: Origin<'_>,
387    ) -> Result<(), NodeError> {
388        for spec in select_specs(specs, provider, name)? {
389            if let Some(existing) = self.bound.iter_mut().find(|b| b.provider == provider && b.name == spec.name) {
390                existing.bound_again(origin);
391                continue;
392            }
393            let exposed = unique_name(&spec.name, provider, &mut self.used);
394            #[cfg(feature = "skills")]
395            let (gates, ask) = match origin {
396                Origin::Grant(grant) => (vec![grant.skill.clone()], grant.ask),
397                Origin::Agent | Origin::SkillTool => (Vec::new(), false),
398            };
399            self.bound.push(BoundTool {
400                exposed: exposed.clone(),
401                provider: provider.to_owned(),
402                name: spec.name.clone(),
403                runtime: Arc::clone(runtime),
404                spec: ToolSpec {
405                    name: exposed,
406                    description: spec.description.clone(),
407                    parameters: spec.parameters.clone(),
408                },
409                context: None,
410                #[cfg(feature = "skills")]
411                gates,
412                #[cfg(feature = "skills")]
413                ask,
414                #[cfg(feature = "skills")]
415                skill_tool: matches!(origin, Origin::SkillTool),
416            });
417        }
418        Ok(())
419    }
420}
421
422/// One executed (or rejected) tool call.
423#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
424struct ToolLogEntry {
425    id: String,
426    name: String,
427    provider: String,
428    tool: String,
429    /// Parsed arguments, or the raw text when the model sent malformed JSON.
430    arguments: Json,
431    result: String,
432    is_error: bool,
433    /// Images sent to the model with the result.
434    #[serde(default)]
435    images: usize,
436    /// UI blocks in the tool's structured result (see [`graphrt_core::ui`]), for the host.
437    #[serde(default, skip_serializing_if = "Vec::is_empty")]
438    ui: Vec<Json>,
439    /// Files in the tool's structured result (see [`collect_files`]), for the host.
440    #[cfg(feature = "tool-files")]
441    #[serde(default, skip_serializing_if = "Vec::is_empty")]
442    files: Vec<Json>,
443}
444
445/// Persistable loop state, used to pause for tool approval.
446#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
447struct AgentState {
448    messages: Vec<Message>,
449    iteration: u32,
450    log: Vec<ToolLogEntry>,
451    usage: Usage,
452    /// Calls awaiting approval.
453    pending: Vec<ToolCall>,
454    /// Tools already asked once to be called again with their required arguments.
455    #[serde(default, skip_serializing_if = "Vec::is_empty")]
456    reasked: Vec<String>,
457    /// Answer text streamed so far (preambles of tool-calling turns).
458    #[serde(default, skip_serializing_if = "String::is_empty")]
459    answer: String,
460    /// Skills loaded in this run: their granted tools are offered to the model.
461    #[cfg(feature = "skills")]
462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
463    loaded_skills: Vec<String>,
464    /// This run reads learned notes: a skill it loads is told they still apply.
465    #[cfg(all(feature = "skills", feature = "learning"))]
466    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
467    has_notes: bool,
468    /// What the context guard learned and removed in this run.
469    #[cfg(feature = "context")]
470    #[serde(default, skip_serializing_if = "ContextState::is_empty")]
471    context: ContextState,
472}
473
474/// Why the loop ended.
475#[derive(Clone, Debug, PartialEq, Eq)]
476enum StopReason {
477    /// The model answered without calling tools.
478    Completed,
479    /// The iteration limit forced a final answer without tools.
480    MaxIterations,
481    /// The final answer was cut off by the output token limit.
482    Length,
483    /// The provider ended the turn with a reason graphrt does not recognize.
484    Unrecognized(String),
485}
486
487impl StopReason {
488    fn as_str(&self) -> String {
489        match self {
490            StopReason::Completed => "completed".into(),
491            StopReason::MaxIterations => "max_iterations".into(),
492            StopReason::Length => "length".into(),
493            StopReason::Unrecognized(reason) => format!("finish:{reason}"),
494        }
495    }
496}
497
498/// The `agent` node.
499#[derive(Debug)]
500pub struct AgentNode {
501    config: AgentConfig,
502    refs: Vec<(String, String)>,
503    /// Parsed `tool_context`.
504    tool_context: Vec<ProviderContext>,
505    /// Parsed `learning`.
506    #[cfg(feature = "learning")]
507    learning: Option<Learning>,
508    /// Parsed `context_window`.
509    #[cfg(feature = "context")]
510    context: ContextWindow,
511}
512
513/// Whether `context_window` asks for the guard, which this build does not have.
514#[cfg(not(feature = "context"))]
515pub(crate) fn asks_for_context_guard(raw: Option<&Json>) -> bool {
516    !matches!(raw, None | Some(Json::Null | Json::Bool(false))) && raw.and_then(Json::as_str) != Some("off")
517}
518
519/// One provider's `tool_context`: provider name and `(name, template)` pairs.
520type ProviderContext = (String, Vec<(String, Template)>);
521
522/// Parse `tool_context`: every provider must appear in `tools`, every value
523/// must be a non-empty name mapped to a template string.
524fn parse_tool_context(
525    doc: &NodeDoc,
526    raw: &serde_json::Map<String, Json>,
527    refs: &[(String, String)],
528) -> Result<Vec<ProviderContext>, ConfigError> {
529    let mut parsed = Vec::with_capacity(raw.len());
530    for (provider, values) in raw {
531        if !refs.iter().any(|(p, _)| p == provider) {
532            return Err(ConfigError::new(
533                doc,
534                format!("tool_context provider `{provider}` is not used by any entry of `tools`"),
535            ));
536        }
537        let Json::Object(values) = values else {
538            return Err(ConfigError::new(doc, format!("tool_context `{provider}` must map names to templates")));
539        };
540        let mut templates = Vec::with_capacity(values.len());
541        for (name, value) in values {
542            let (false, Json::String(text)) = (name.is_empty(), value) else {
543                return Err(ConfigError::new(
544                    doc,
545                    format!("tool_context `{provider}.{name}` must be a non-empty name with a template string"),
546                ));
547            };
548            templates.push((name.clone(), Template::parse(text)));
549        }
550        parsed.push((provider.clone(), templates));
551    }
552    Ok(parsed)
553}
554
555impl AgentNode {
556    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
557        let config: AgentConfig = parse_config(doc)?;
558        if config.max_iterations == 0 || config.max_iterations > MAX_ITERATIONS_LIMIT {
559            return Err(ConfigError::new(doc, format!("max_iterations must be between 1 and {MAX_ITERATIONS_LIMIT}")));
560        }
561        let refs = config
562            .tools
563            .iter()
564            .map(|r| {
565                r.split()
566                    .ok_or_else(|| ConfigError::new(doc, format!("invalid tool reference {r:?}; use `provider/name`")))
567            })
568            .collect::<Result<Vec<_>, _>>()?;
569        let tool_context = parse_tool_context(doc, &config.tool_context, &refs)?;
570        // Without the feature the field is still read, so that a workflow that
571        // relies on skills fails here instead of running without them.
572        #[cfg(not(feature = "skills"))]
573        if !config.skills.is_empty() {
574            return Err(ConfigError::new(doc, "`skills` needs a build with skill support (cargo feature `skills`)"));
575        }
576        #[cfg(not(feature = "learning"))]
577        if config.learning.is_some() {
578            return Err(ConfigError::new(
579                doc,
580                "`learning` needs a build with self learning support (cargo feature `learning`)",
581            ));
582        }
583        #[cfg(feature = "learning")]
584        let learning = parse_learning(doc, config.learning.as_ref())?;
585        #[cfg(not(feature = "context"))]
586        if asks_for_context_guard(config.context_window.as_ref()) {
587            return Err(ConfigError::new(
588                doc,
589                "`context_window` needs a build with the context guard (cargo feature `context`)",
590            ));
591        }
592        #[cfg(feature = "context")]
593        let context = ContextWindow::parse(doc, config.context_window.as_ref())?;
594        Ok(Self {
595            config,
596            refs,
597            tool_context,
598            #[cfg(feature = "learning")]
599            learning,
600            #[cfg(feature = "context")]
601            context,
602        })
603    }
604
605    /// Resolve tool references against the registry and attach the agent's
606    /// skills, assigning unique exposed names. Returns the tools and the skill
607    /// catalog for the system prompt (empty without skills).
608    async fn bind_tools(&self, ctx: &NodeContext) -> Result<(Vec<BoundTool>, String), NodeError> {
609        if self.refs.is_empty() && self.config.skills.is_empty() {
610            return Ok((Vec::new(), String::new()));
611        }
612        let mut binder = Binder::default();
613        if !self.refs.is_empty() {
614            let registry = ctx.require_service::<ToolRegistry>("tool registry (graphrt_core::tool::ToolRegistry)")?;
615            for (provider, name) in &self.refs {
616                let runtime = registry
617                    .get(provider)
618                    .cloned()
619                    .ok_or_else(|| NodeError::fatal("tool_not_found", format!("unknown tool provider `{provider}`")))?;
620                binder.bind_registered(provider, name, &runtime, Origin::Agent).await?;
621            }
622        }
623        #[cfg(feature = "skills")]
624        let catalog = self.attach_skills(ctx, &mut binder).await?;
625        #[cfg(not(feature = "skills"))]
626        let catalog = String::new();
627        let mut bound = binder.bound;
628        self.attach_tool_context(ctx, &mut bound)?;
629        Ok((bound, catalog))
630    }
631
632    /// Attach the skills of `skills`: bind the skill tools and the tools the
633    /// owner granted to each skill. Returns the catalog for the system prompt.
634    ///
635    /// A granted tool that is not available in this host (its plugin was
636    /// removed, say) is left out and reported as `skill_tool_unavailable`: the
637    /// skill still loads, it just cannot use that tool.
638    #[cfg(feature = "skills")]
639    async fn attach_skills(&self, ctx: &NodeContext, binder: &mut Binder) -> Result<String, NodeError> {
640        if self.config.skills.is_empty() {
641            return Ok(String::new());
642        }
643        let skills = ctx.require_service::<Skills>("skill source (graphrt_core::skill::Skills)")?;
644        let attached =
645            skills.0.attach(&self.config.skills).await.map_err(|e| NodeError::fatal(e.kind, e.to_string()))?;
646        if attached.is_empty() {
647            return Ok(String::new());
648        }
649        if binder.bound.iter().any(|b| b.provider == SKILL_PROVIDER) {
650            return Err(NodeError::fatal(
651                "skill_provider_conflict",
652                format!("an agent that uses skills cannot also list tools of a provider named `{SKILL_PROVIDER}`"),
653            ));
654        }
655        let specs = attached.runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?;
656        binder.bind_specs(SKILL_PROVIDER, "*", &specs, &attached.runtime, Origin::SkillTool)?;
657        let registry = ctx.service::<ToolRegistry>();
658        for grant in &attached.grants {
659            let bound = match registry.and_then(|r| r.get(&grant.provider)) {
660                Some(runtime) => {
661                    binder.bind_registered(&grant.provider, &grant.tool, runtime, Origin::Grant(grant)).await.is_ok()
662                }
663                None => false,
664            };
665            if !bound {
666                ctx.progress(
667                    "skill_tool_unavailable",
668                    Value::from_json(json!({
669                        "skill": grant.skill, "tool": format!("{}/{}", grant.provider, grant.tool),
670                    })),
671                );
672            }
673        }
674        Ok(attached.catalog)
675    }
676
677    /// Render `tool_context` (secrets exposed) for each configured provider and
678    /// share it with that provider's bound tools. Fails when a provider does not
679    /// accept secrets: silently dropping the values would hide a misconfiguration.
680    fn attach_tool_context(&self, ctx: &NodeContext, bound: &mut [BoundTool]) -> Result<(), NodeError> {
681        for (provider, templates) in &self.tool_context {
682            let Some(first) = bound.iter().find(|b| &b.provider == provider) else { continue };
683            if !first.runtime.accepts_secrets() {
684                return Err(NodeError::fatal(
685                    "tool_context_denied",
686                    format!(
687                        "tool provider `{provider}` does not accept a tool context (a plugin needs \
688                         `permissions.secrets` and must be trusted, e.g. `--trust-plugin {provider}`)"
689                    ),
690                ));
691            }
692            let mut context = ToolCallContext::default();
693            for (name, template) in templates {
694                let value = template.render_exposed(&ctx.pool);
695                // A missing variable renders empty: leave the name out so the tool can refuse.
696                if value.is_empty() {
697                    continue;
698                }
699                ctx.observe_secret(&value);
700                context.secrets.insert(name.clone(), value);
701            }
702            let context = Arc::new(context);
703            for tool in bound.iter_mut().filter(|b| &b.provider == provider) {
704                tool.context = Some(Arc::clone(&context));
705            }
706        }
707        Ok(())
708    }
709
710    fn needs_approval(&self, tool: &BoundTool) -> bool {
711        tool.asks_first()
712            || self.config.require_approval.iter().any(|r| {
713                r == "*" || *r == tool.exposed || *r == tool.name || *r == format!("{}/{}", tool.provider, tool.name)
714            })
715    }
716
717    fn call_needs_approval(&self, tools: &[BoundTool], call: &ToolCall) -> bool {
718        bound_tool(tools, call).is_some_and(|t| self.needs_approval(t))
719    }
720
721    /// The approved lessons this run reads, as a section for the system
722    /// prompt (empty without `learning` or without lessons).
723    #[cfg(feature = "learning")]
724    async fn lesson_notes(&self, ctx: &NodeContext) -> Result<String, NodeError> {
725        let Some(learning) = &self.learning else { return Ok(String::new()) };
726        let lessons = ctx.require_service::<Lessons>("lesson source (graphrt_core::learning::Lessons)")?;
727        let user = learning.user.as_ref().map(|user| user.render(&ctx.pool)).filter(|user| !user.trim().is_empty());
728        let scope = LessonScope { agent: learning.agent.clone(), user };
729        let notes = lessons.0.notes(&scope).await.map_err(|e| NodeError::fatal(e.kind, e.to_string()))?;
730        if !notes.is_empty() {
731            ctx.progress("lessons_applied", Value::from_json(json!({"agent": scope.agent, "ids": notes.ids})));
732        }
733        Ok(notes.text)
734    }
735
736    /// The conversation a run starts with. Each of `sections` (the skill
737    /// catalog, the learned notes) follows the instruction in the system
738    /// message. Without an instruction they are the whole system message.
739    /// `images` are the vision inputs of the user message.
740    fn initial_state(
741        &self,
742        ctx: &NodeContext,
743        sections: &[&str],
744        images: Vec<ContentPart>,
745    ) -> Result<AgentState, NodeError> {
746        let cfg = &self.config;
747        let pool = &ctx.pool;
748        let mut messages = Vec::new();
749        let mut system = cfg.instruction.as_ref().map(|instruction| instruction.render(pool)).unwrap_or_default();
750        for section in sections.iter().filter(|section| !section.is_empty()) {
751            if !system.trim().is_empty() {
752                system.push_str("\n\n");
753            }
754            system.push_str(section);
755        }
756        if !system.trim().is_empty() {
757            messages.push(Message::system(system));
758        }
759        if let Some(memory) = &cfg.memory {
760            messages.extend(memory.history(pool)?);
761        }
762        let query = cfg.query.render(pool);
763        if query.trim().is_empty() && images.is_empty() {
764            if messages.iter().all(|m| m.role == Role::System) {
765                return Err(NodeError::invalid_input("agent query is empty"));
766            }
767        } else {
768            let mut user = Message::user(query);
769            user.content.extend(images);
770            messages.push(user);
771        }
772        Ok(AgentState { messages, ..AgentState::default() })
773    }
774
775    /// Apply the host's decisions to the pending calls. Returns the calls that
776    /// still have no decision.
777    async fn apply_decisions(
778        &self,
779        ctx: &NodeContext,
780        state: &mut AgentState,
781        tools: &[BoundTool],
782        input: Option<&Value>,
783    ) -> Vec<ToolCall> {
784        let decisions = Approvals::from_input(input);
785        let mut approved = Vec::new();
786        let mut undecided = Vec::new();
787        for call in std::mem::take(&mut state.pending) {
788            match decisions.decision(&call.id) {
789                Some(true) => approved.push(call),
790                Some(false) => self.deny(ctx, state, tools, &call, decisions.reason.as_deref()),
791                None => undecided.push(call),
792            }
793        }
794        self.run_calls(ctx, state, tools, approved).await;
795        undecided
796    }
797
798    async fn execute(&self, ctx: NodeContext) -> NodeResult {
799        let (tools, skill_catalog) = self.bind_tools(&ctx).await?;
800        let model = model_for(&ctx, &self.config.model)?;
801        let mut state = match &ctx.resume {
802            Some(resume) => {
803                let mut state: AgentState = serde_json::from_value(resume.state.clone())
804                    .map_err(|e| NodeError::fatal("invalid_resume_state", e.to_string()))?;
805                let undecided = self.apply_decisions(&ctx, &mut state, &tools, resume.input.as_ref()).await;
806                if !undecided.is_empty() {
807                    state.pending = undecided;
808                    return self.pause(&state, &tools);
809                }
810                state
811            }
812            None => {
813                #[cfg(feature = "learning")]
814                let notes = self.lesson_notes(&ctx).await?;
815                #[cfg(not(feature = "learning"))]
816                let notes = String::new();
817                #[cfg(feature = "vision-preparer")]
818                let images = self.config.vision.prepared_image_parts(&ctx).await?;
819                #[cfg(not(feature = "vision-preparer"))]
820                let images = self.config.vision.image_parts(&ctx.pool)?;
821                #[allow(unused_mut)]
822                let mut state = self.initial_state(&ctx, &[&skill_catalog, &notes], images)?;
823                #[cfg(all(feature = "skills", feature = "learning"))]
824                {
825                    state.has_notes = !notes.is_empty();
826                }
827                state
828            }
829        };
830        let (final_text, stop) = loop {
831            state.iteration += 1;
832            let offer =
833                TurnTools { offered: !tools.is_empty(), final_turn: state.iteration >= self.config.max_iterations };
834            let mut turn = self.model_turn(&ctx, model.as_ref(), &mut state, &tools, offer).await?;
835            if offer.callable() && turn.response.tool_calls.is_empty() {
836                read_calls_written_as_text(&mut turn, &state, &tools);
837            }
838            if !offer.callable() || turn.response.tool_calls.is_empty() {
839                break self.answer_turn(&ctx, &mut state, turn, offer);
840            }
841            self.tool_turn(&ctx, &mut state, &tools, turn).await;
842            if !state.pending.is_empty() {
843                return self.pause(&state, &tools);
844            }
845        };
846        Ok(agent_outputs(state, final_text, &stop))
847    }
848
849    /// Ask the model for the next turn (streaming per `stream_tool_turns`) and
850    /// add its usage to the state.
851    async fn model_turn(
852        &self,
853        ctx: &NodeContext,
854        model: &dyn ChatModel,
855        state: &mut AgentState,
856        tools: &[BoundTool],
857        offer: TurnTools,
858    ) -> Result<Turn, NodeError> {
859        let cfg = &self.config;
860        if let Some(keep) = cfg.keep_tool_images {
861            prune_tool_images(&mut state.messages, keep);
862        }
863        // Tools stay declared on the final turn: the history may contain tool calls,
864        // which providers only accept alongside tool definitions.
865        // A tool granted through a skill appears once that skill was loaded.
866        let specs: Vec<ToolSpec> = if offer.offered {
867            tools.iter().filter(|t| t.offered(state)).map(|t| t.spec.clone()).collect()
868        } else {
869            Vec::new()
870        };
871        let request = |messages: Vec<Message>, tools: Vec<ToolSpec>| -> Result<ChatRequest, NodeError> {
872            let mut request = cfg.model.request(messages, &ctx.pool)?;
873            if offer.offered {
874                request.tools = tools;
875                request.tool_choice = Some(if offer.callable() { ToolChoice::Auto } else { ToolChoice::None });
876            }
877            Ok(request)
878        };
879        ctx.progress(
880            "agent_step",
881            Value::from_json(json!({"iteration": state.iteration, "tools_enabled": offer.callable()})),
882        );
883        let plan = TurnPlan {
884            live: cfg.stream_tool_turns || !offer.callable(),
885            stop_at_tool_call: offer.callable(),
886            separate: !state.answer.is_empty(),
887        };
888        #[cfg(not(feature = "context"))]
889        let (response, streamed) = stream_turn(ctx, model, request(state.messages.clone(), specs)?, plan).await?;
890        #[cfg(feature = "context")]
891        let (response, streamed) = {
892            // The fields of the state the guard reads and changes, borrowed apart.
893            let AgentState { messages, context, usage, log, .. } = state;
894            let shown = pinned_results(log, messages);
895            let pinned: Vec<(&str, &str)> = shown.iter().map(|(id, text)| (*id, text.as_str())).collect();
896            let scope = crate::context::Scope { pinned: &pinned, tail: 0 };
897            let mut guard = self.context.session(ctx, model, &cfg.model, scope);
898            loop {
899                let estimate = guard.fit(context, messages, &specs, usage).await?;
900                let turn = request(context.request_messages(messages), specs.clone())?;
901                match stream_turn(ctx, model, turn, plan).await {
902                    Ok(done) => {
903                        guard.observe(context, estimate, &done.0.usage);
904                        break done;
905                    }
906                    // A turn the provider refused for its size is trimmed and sent
907                    // once more. Any other error, and a second refusal, end the turn.
908                    Err(error) => guard.refused(context, messages, &specs, error, usage).await?,
909                }
910            }
911        };
912        state.usage.add(&response.usage);
913        // A content-filtered or malformed turn is an error, never an empty "completed" answer.
914        let finish = check_finish(&response)?;
915        Ok(Turn { response, streamed, finish, live: plan.live })
916    }
917
918    /// A turn without tool calls ends the loop: its text completes the answer.
919    fn answer_turn(
920        &self,
921        ctx: &NodeContext,
922        state: &mut AgentState,
923        mut turn: Turn,
924        offer: TurnTools,
925    ) -> (String, StopReason) {
926        let response = turn.response;
927        if !turn.live && !response.text.is_empty() {
928            ctx.chunk_shared(StreamField::Text.shared(), response.text.clone());
929            turn.streamed = response.text.len();
930        }
931        let stop = if response.finish_reason == Some(FinishReason::Length) {
932            StopReason::Length
933        } else if let FinishCheck::Unknown(reason) = turn.finish {
934            StopReason::Unrecognized(reason)
935        } else if offer.offered && offer.final_turn {
936            StopReason::MaxIterations
937        } else {
938            StopReason::Completed
939        };
940        state.messages.push(Message::assistant(response.text.clone()));
941        (final_answer(std::mem::take(&mut state.answer), response.text, turn.streamed), stop)
942    }
943
944    /// A turn with tool calls: keep its preamble, then reject, run or hold
945    /// (in `state.pending`, for approval) each call.
946    async fn tool_turn(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], turn: Turn) {
947        let response = turn.response;
948        if !response.text.trim().is_empty() {
949            ctx.progress(
950                "agent_thought",
951                Value::from_json(
952                    json!({"iteration": state.iteration, "text": response.text, "streamed": turn.streamed > 0}),
953                ),
954            );
955        }
956        commit_preamble(&mut state.answer, &response.text, turn.streamed);
957        state.messages.push(replayable_message(&response));
958        let runnable = self.runnable_calls(state, tools, response.tool_calls);
959        let (gated, free): (Vec<ToolCall>, Vec<ToolCall>) =
960            runnable.into_iter().partition(|c| self.call_needs_approval(tools, c));
961        self.run_calls(ctx, state, tools, free).await;
962        state.pending = gated;
963    }
964
965    /// The calls that can run. Calls past `max_tool_calls_per_turn` and calls
966    /// with malformed arguments get an error result for the model instead.
967    fn runnable_calls(&self, state: &mut AgentState, tools: &[BoundTool], mut calls: Vec<ToolCall>) -> Vec<ToolCall> {
968        if let Some(limit) = self.config.max_tool_calls_per_turn
969            && calls.len() > limit
970        {
971            for call in calls.split_off(limit) {
972                self.record(state, tools, &call, ToolOutput::error("rejected: too many tool calls in one turn"));
973            }
974        }
975        let mut runnable = Vec::with_capacity(calls.len());
976        for call in calls {
977            // Never offered in this run so far: the model was not shown this
978            // tool, so the call did not come from its tool list.
979            if bound_tool(tools, &call).is_some_and(|tool| !tool.offered(state)) {
980                let message = "error: this tool belongs to a skill that is not loaded. Load the skill first.";
981                self.record(state, tools, &call, ToolOutput::error(message));
982                continue;
983            }
984            match call.arguments_json() {
985                Ok(arguments) => {
986                    let mut call = call;
987                    let Some(tool) = bound_tool(tools, &call) else {
988                        runnable.push(call);
989                        continue;
990                    };
991                    // Arguments in the type the tool's schema asks for ("400" for an integer).
992                    let fitted = tool_call_repair::fit_to_schema(Json::Object(arguments), &tool.spec.parameters);
993                    call.arguments = fitted.to_string();
994                    let missing = match &fitted {
995                        Json::Object(fitted) => tool_call_repair::missing_required(fitted, &tool.spec.parameters),
996                        _ => Vec::new(),
997                    };
998                    // A required argument left out: the model is asked once to call again with it.
999                    if !missing.is_empty() && !state.reasked.contains(&call.name) {
1000                        state.reasked.push(call.name.clone());
1001                        let message = format!(
1002                            "error: this call leaves out {} it needs: {}. Call `{}` again with every required argument.",
1003                            if missing.len() == 1 { "an argument" } else { "arguments" },
1004                            missing.join(", "),
1005                            call.name
1006                        );
1007                        self.record(state, tools, &call, ToolOutput::error(message));
1008                        continue;
1009                    }
1010                    runnable.push(call);
1011                }
1012                Err(e) => {
1013                    let message = format!("error: {e}. Call the tool again with a valid JSON object.");
1014                    self.record(state, tools, &call, ToolOutput::error(message));
1015                }
1016            }
1017        }
1018        runnable
1019    }
1020
1021    fn pause(&self, state: &AgentState, tools: &[BoundTool]) -> NodeResult {
1022        let calls: Vec<Json> = state
1023            .pending
1024            .iter()
1025            .map(|c| json!({"id": c.id, "name": c.name, "arguments": log_arguments(c, tools)}))
1026            .collect();
1027        let saved = serde_json::to_value(state)
1028            .map_err(|e| NodeError::fatal("agent_state", format!("cannot save agent state: {e}")))?;
1029        Ok(NodeOutcome::Paused(PauseRequest {
1030            kind: "tool_approval".to_owned(),
1031            data: Value::from_json(json!({"calls": calls})),
1032            state: saved,
1033        }))
1034    }
1035
1036    fn deny(
1037        &self,
1038        ctx: &NodeContext,
1039        state: &mut AgentState,
1040        tools: &[BoundTool],
1041        call: &ToolCall,
1042        reason: Option<&str>,
1043    ) {
1044        let text = match reason {
1045            Some(r) if !r.is_empty() => format!("The user did not approve this tool call: {r}"),
1046            _ => "The user did not approve this tool call.".to_owned(),
1047        };
1048        ctx.progress("tool_denied", Value::from_json(json!({"id": call.id, "name": call.name})));
1049        self.record(state, tools, call, ToolOutput::error(text));
1050    }
1051
1052    /// A tool result as the model, the `tool_calls` output and the captured
1053    /// `tool_result` progress all see it: the tool's context masked, cut to
1054    /// `max_tool_output_chars`, and a note in place of images that fail
1055    /// [`check_images`].
1056    ///
1057    /// A tool may echo its context (e.g. an upstream error repeating the JWT):
1058    /// the model, the outputs and the progress events must never see it. Masking
1059    /// comes first so a cut through the secret cannot leave its prefix behind.
1060    /// Every consumer takes the text from here, so none can skip the masking.
1061    fn visible_result(&self, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) -> VisibleResult {
1062        let bound = bound_tool(tools, call);
1063        let scrubbed = bound.map_or(Cow::Borrowed(output.text.as_str()), |b| scrub_context(&output.text, b.context()));
1064        let mut text = truncate(&scrubbed, self.config.max_tool_output_chars);
1065        let images = match check_images(&output.images) {
1066            Ok(()) => output.images,
1067            Err(e) => {
1068                let note = format!("[images dropped: {e}]");
1069                text = if text.is_empty() { note } else { format!("{text}\n{note}") };
1070                Vec::new()
1071            }
1072        };
1073        // A failed tool shows nothing: its data is no answer the person should see.
1074        let ui = if output.is_error {
1075            Vec::new()
1076        } else {
1077            graphrt_core::ui::collect_ui_blocks(&output.data).iter().map(Value::to_json).collect()
1078        };
1079        VisibleResult {
1080            text,
1081            images,
1082            ui,
1083            #[cfg(feature = "tool-files")]
1084            files: returned_files(&output.data, output.is_error),
1085            is_error: output.is_error,
1086        }
1087    }
1088
1089    /// Append a tool result to the conversation and the log.
1090    fn record(&self, state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) {
1091        let result = self.visible_result(tools, call, output);
1092        push_result(state, tools, call, result);
1093    }
1094
1095    async fn run_calls(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], calls: Vec<ToolCall>) {
1096        if calls.is_empty() {
1097            return;
1098        }
1099        for call in &calls {
1100            ctx.progress(
1101                "tool_call",
1102                Value::from_json(json!({"id": call.id, "name": call.name, "arguments": log_arguments(call, tools)})),
1103            );
1104        }
1105        let outputs = self.call_tools(tools, &calls).await;
1106        let capture = ctx.captures_content();
1107        for (call, output) in calls.iter().zip(outputs) {
1108            // The tool's own image count, including images the result drops.
1109            let offered_images = output.images.len();
1110            let result = self.visible_result(tools, call, output);
1111            let mut data =
1112                json!({"id": call.id, "name": call.name, "is_error": result.is_error, "images": offered_images});
1113            if capture && let Some(fields) = data.as_object_mut() {
1114                fields.insert("result".to_owned(), Json::String(result.text.clone()));
1115            }
1116            ctx.progress("tool_result", Value::from_json(data));
1117            push_result(state, tools, call, result);
1118        }
1119    }
1120
1121    /// Run `calls` concurrently or one after another, per `parallel_tool_calls`.
1122    async fn call_tools(&self, tools: &[BoundTool], calls: &[ToolCall]) -> Vec<ToolOutput> {
1123        if self.config.parallel_tool_calls {
1124            return futures::future::join_all(calls.iter().map(|c| call_tool(tools, c))).await;
1125        }
1126        let mut outputs = Vec::with_capacity(calls.len());
1127        for call in calls {
1128            outputs.push(call_tool(tools, call).await);
1129        }
1130        outputs
1131    }
1132}
1133
1134/// A tool result after [`AgentNode::visible_result`]: safe to show to the model and the host.
1135struct VisibleResult {
1136    text: String,
1137    images: Vec<ToolImage>,
1138    /// UI blocks the tool returned in its data; never sent to the model.
1139    ui: Vec<Json>,
1140    /// Files the tool returned in its data; never sent to the model.
1141    #[cfg(feature = "tool-files")]
1142    files: Vec<Json>,
1143    is_error: bool,
1144}
1145
1146/// Append a visible tool result to the conversation and the log.
1147fn push_result(state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, result: VisibleResult) {
1148    let bound = bound_tool(tools, call);
1149    #[allow(unused_mut)]
1150    let mut shown = result.text.clone();
1151    #[cfg(feature = "skills")]
1152    if !result.is_error
1153        && let Some(skill) = loaded_skill(bound, call)
1154    {
1155        // The skill is the newest text the model reads, and a model then tends to
1156        // follow it alone. The notes in the system message are named again.
1157        #[cfg(feature = "learning")]
1158        if state.has_notes {
1159            shown.push_str(NOTES_STILL_APPLY);
1160        }
1161        if !state.loaded_skills.contains(&skill) {
1162            state.loaded_skills.push(skill);
1163        }
1164    }
1165    state.messages.push(Message::tool_with_images(call.id.clone(), shown, result.images.iter().map(ToolImage::to_url)));
1166    state.log.push(ToolLogEntry {
1167        id: call.id.clone(),
1168        name: call.name.clone(),
1169        provider: bound.map(|b| b.provider.clone()).unwrap_or_default(),
1170        tool: bound.map(|b| b.name.clone()).unwrap_or_default(),
1171        arguments: log_arguments(call, tools),
1172        result: result.text,
1173        is_error: result.is_error,
1174        images: result.images.len(),
1175        ui: result.ui,
1176        #[cfg(feature = "tool-files")]
1177        files: result.files,
1178    });
1179}
1180
1181/// Follows the content of a loaded skill when the run also reads learned notes.
1182/// Without it a model that has just read a skill follows the skill alone: measured
1183/// with a small hosted model, an approved note was followed in 3 of 12 runs, and in
1184/// 12 of 12 with this sentence, the skill's own steps kept in both.
1185#[cfg(all(feature = "skills", feature = "learning"))]
1186const NOTES_STILL_APPLY: &str = "\nThis skill adds to your instructions and does not replace them: the learned notes in \
1187your instructions still apply. Keep every step of the skill, including how it says to end the reply.";
1188
1189/// The skill a call loads: the `name` argument of the skill tool `load_skill`.
1190/// Only the skill tools bound by [`AgentNode::attach_skills`] count, never a
1191/// registry provider that happens to use the same names.
1192#[cfg(feature = "skills")]
1193fn loaded_skill(bound: Option<&BoundTool>, call: &ToolCall) -> Option<String> {
1194    bound.filter(|tool| tool.skill_tool && tool.name == LOAD_SKILL_TOOL)?;
1195    let arguments = call.arguments_json().ok()?;
1196    arguments.get("name").and_then(Json::as_str).map(str::to_owned)
1197}
1198
1199/// Whether a turn offers tools, and whether it is the last one the iteration limit allows.
1200#[derive(Clone, Copy, Debug)]
1201struct TurnTools {
1202    offered: bool,
1203    final_turn: bool,
1204}
1205
1206impl TurnTools {
1207    /// The model may call tools: they are offered and this is not the forced final turn.
1208    fn callable(self) -> bool {
1209        self.offered && !self.final_turn
1210    }
1211}
1212
1213/// One model turn: the response, how many leading bytes of its text were
1214/// already streamed, its finish check, and whether it streamed live.
1215struct Turn {
1216    response: ChatResponse,
1217    streamed: usize,
1218    finish: FinishCheck,
1219    live: bool,
1220}
1221
1222/// The assistant message of a tool turn as it is kept in the history. Malformed
1223/// arguments are never replayed to the provider: the history keeps `{}` and
1224/// the tool result explains the problem to the model.
1225fn replayable_message(response: &ChatResponse) -> Message {
1226    let mut assistant = response.to_message();
1227    for call in &mut assistant.tool_calls {
1228        if call.arguments_json().is_err() {
1229            call.arguments = "{}".to_owned();
1230        }
1231    }
1232    assistant
1233}
1234
1235/// The tool results the context guard must leave alone, as the id of the
1236/// call and the text the model was shown: the instructions of the skills
1237/// loaded in this run. Their tools stay on offer, so the model must keep the
1238/// text that says how to use them. A skill that was loaded twice is listed
1239/// once, where it was loaded last.
1240#[cfg(feature = "context")]
1241fn pinned_results<'a>(log: &'a [ToolLogEntry], messages: &[Message]) -> Vec<(&'a str, String)> {
1242    #[cfg(feature = "skills")]
1243    let pinned = {
1244        let mut pinned: Vec<(&str, String)> = Vec::new();
1245        let loads = log.iter().filter(|e| e.provider == SKILL_PROVIDER && e.tool == LOAD_SKILL_TOOL && !e.is_error);
1246        for entry in loads {
1247            pinned.retain(|(_, text)| shown_skill(text) != entry.result);
1248            pinned.push((&entry.id, shown_text(entry, messages)));
1249        }
1250        pinned
1251    };
1252    #[cfg(not(feature = "skills"))]
1253    let pinned = {
1254        let _ = (log, messages);
1255        Vec::new()
1256    };
1257    pinned
1258}
1259
1260/// The text of a skill without the sentence the agent may add after it.
1261#[cfg(all(feature = "context", feature = "skills"))]
1262fn shown_skill(text: &str) -> &str {
1263    #[cfg(feature = "learning")]
1264    let text = text.strip_suffix(NOTES_STILL_APPLY).unwrap_or(text);
1265    text
1266}
1267
1268/// What the model was shown for `entry`: its result, or its result with the
1269/// sentence [`push_result`] adds when learned notes apply.
1270#[cfg(all(feature = "context", feature = "skills"))]
1271fn shown_text(entry: &ToolLogEntry, messages: &[Message]) -> String {
1272    #[cfg(feature = "learning")]
1273    {
1274        let with_notes = format!("{}{NOTES_STILL_APPLY}", entry.result);
1275        let shown = messages.iter().any(|message| {
1276            message.role == Role::Tool
1277                && message.tool_call_id.as_deref() == Some(entry.id.as_str())
1278                && message.text() == with_notes
1279        });
1280        if shown {
1281            return with_notes;
1282        }
1283    }
1284    let _ = messages;
1285    entry.result.clone()
1286}
1287
1288/// The node outputs of a finished loop.
1289fn agent_outputs(state: AgentState, final_text: String, stop: &StopReason) -> NodeOutcome {
1290    let log: Vec<Value> = state
1291        .log
1292        .iter()
1293        .map(|e| {
1294            Value::from_json(json!({
1295                "name": e.name, "provider": e.provider, "tool": e.tool,
1296                "arguments": e.arguments, "result": e.result, "is_error": e.is_error, "images": e.images,
1297            }))
1298        })
1299        .collect();
1300    let ui: Vec<Value> = state.log.iter().flat_map(|e| e.ui.iter().cloned().map(Value::from_json)).collect();
1301    let output =
1302        NodeOutput::new().with("text", final_text).with("tool_calls", Value::from(log)).with("ui", Value::from(ui));
1303    #[cfg(feature = "tool-files")]
1304    let output = output.with("files", Value::array(produced_files(&state.log)));
1305    // Present only when the model was not sent everything.
1306    #[cfg(feature = "context")]
1307    let output = match state.context.report() {
1308        Some(report) => output.with("context", Value::from_json(report)),
1309        None => output,
1310    };
1311    output
1312        .with("iterations", i64::from(state.iteration))
1313        .with("stopped_reason", stop.as_str())
1314        .with("usage", usage_value(&state.usage))
1315        .usage(state.usage)
1316        .into()
1317}
1318
1319/// The files in a tool's structured result, as JSON for the saved loop state.
1320/// A failed tool produced nothing the person should be handed.
1321#[cfg(feature = "tool-files")]
1322fn returned_files(data: &Value, is_error: bool) -> Vec<Json> {
1323    if is_error {
1324        return Vec::new();
1325    }
1326    collect_files(data).into_iter().map(|file| Value::File(file).to_json()).collect()
1327}
1328
1329/// The files of every tool result, in call order. A file returned more than once
1330/// (written, then overwritten) appears once, where it was returned last.
1331#[cfg(feature = "tool-files")]
1332fn produced_files(log: &[ToolLogEntry]) -> Vec<Value> {
1333    // The log is this node's own state (never model or tool JSON), so its file objects are trusted.
1334    let files: Vec<Value> =
1335        log.iter().flat_map(|entry| entry.files.iter().cloned().map(Value::from_json_trusted)).collect();
1336    let identity =
1337        |value: &Value| value.as_file().map(|file| (file.reference.clone(), file.url.clone(), file.name.clone()));
1338    let mut unique: Vec<Value> = Vec::with_capacity(files.len());
1339    for file in files {
1340        unique.retain(|earlier| identity(earlier) != identity(&file));
1341        unique.push(file);
1342    }
1343    unique
1344}
1345
1346/// The tools a `provider/name` reference selects from the provider's listing:
1347/// all of them for `*`, else the one named (an error when it is missing).
1348fn select_specs<'a>(specs: &'a [ToolSpec], provider: &str, name: &str) -> Result<Vec<&'a ToolSpec>, NodeError> {
1349    if name == "*" {
1350        return Ok(specs.iter().collect());
1351    }
1352    let spec = specs
1353        .iter()
1354        .find(|s| s.name == name)
1355        .ok_or_else(|| NodeError::fatal("tool_not_found", format!("provider `{provider}` has no tool `{name}`")))?;
1356    Ok(vec![spec])
1357}
1358
1359/// The bound tool a call names (by its exposed, possibly de-duplicated name).
1360fn bound_tool<'a>(tools: &'a [BoundTool], call: &ToolCall) -> Option<&'a BoundTool> {
1361    tools.iter().find(|t| t.exposed == call.name)
1362}
1363
1364/// A turn without tool calls whose text holds calls written out as JSON (a small model's
1365/// `{"name": "resize", "parameters": {...}}`) gets those calls, when they name offered tools.
1366/// Text not yet streamed loses the written calls; text already shown stays as it was.
1367fn read_calls_written_as_text(turn: &mut Turn, state: &AgentState, tools: &[BoundTool]) {
1368    let offered: Vec<&str> =
1369        tools.iter().filter(|tool| tool.offered(state)).map(|tool| tool.exposed.as_str()).collect();
1370    let prefix = format!("text_call_{}_", state.iteration);
1371    let Some((calls, rest)) = tool_call_repair::calls_written_as_text(&turn.response.text, &offered, &prefix) else {
1372        return;
1373    };
1374    if turn.streamed == 0 {
1375        turn.response.text = rest;
1376    }
1377    turn.response.tool_calls = calls;
1378}
1379
1380/// How one model turn streams.
1381#[derive(Clone, Copy, Debug)]
1382struct TurnPlan {
1383    /// Stream text and reasoning as they arrive (otherwise nothing is streamed).
1384    live: bool,
1385    /// Stop streaming text at the turn's first tool-call fragment.
1386    stop_at_tool_call: bool,
1387    /// Earlier turns streamed text: send [`PREAMBLE_SEPARATOR`] before this turn's first text.
1388    separate: bool,
1389}
1390
1391/// Run one turn. Returns the response and how many leading bytes of its text
1392/// were streamed on field `text` (always whole deltas, so a char boundary).
1393/// Deltas are moved into chunks, never copied.
1394async fn stream_turn(
1395    ctx: &NodeContext,
1396    model: &dyn ChatModel,
1397    request: ChatRequest,
1398    plan: TurnPlan,
1399) -> Result<(ChatResponse, usize), NodeError> {
1400    if !plan.live {
1401        return Ok((invoke(ctx, model, request, StreamMode::Off).await?, 0));
1402    }
1403    let stream = model.chat(request).await?;
1404    let mut streamed = 0;
1405    let mut text_closed = false;
1406    let mut separator_pending = plan.separate;
1407    let response = collect(stream, |delta| match delta {
1408        ChatDelta::ToolCall { .. } => text_closed |= plan.stop_at_tool_call,
1409        ChatDelta::Text(text) if !text.is_empty() && !text_closed => {
1410            if std::mem::take(&mut separator_pending) {
1411                ctx.chunk_shared(StreamField::Text.shared(), PREAMBLE_SEPARATOR);
1412            }
1413            streamed += text.len();
1414            ctx.chunk_shared(StreamField::Text.shared(), text);
1415        }
1416        ChatDelta::Reasoning(text) if !text.is_empty() => ctx.chunk_shared(StreamField::Reasoning.shared(), text),
1417        _ => {}
1418    })
1419    .await?;
1420    Ok((response, streamed))
1421}
1422
1423/// Append the streamed part of a tool-calling turn's text to the answer,
1424/// mirroring what [`stream_turn`] sent (separator included).
1425fn commit_preamble(answer: &mut String, text: &str, streamed: usize) {
1426    let Some(preamble) = text.get(..streamed).filter(|p| !p.is_empty()) else { return };
1427    if !answer.is_empty() {
1428        answer.push_str(PREAMBLE_SEPARATOR);
1429    }
1430    answer.push_str(preamble);
1431}
1432
1433/// The `text` output: streamed preambles, then the final turn's text (which
1434/// is always streamed whole). Without preambles the final text is moved as is.
1435fn final_answer(mut answer: String, text: String, streamed: usize) -> String {
1436    if answer.is_empty() {
1437        return text;
1438    }
1439    commit_preamble(&mut answer, &text, streamed);
1440    answer
1441}
1442
1443/// Replace the images of all but the last `keep` image-bearing tool results
1444/// with a text placeholder, so a screenshot loop does not resend every
1445/// screenshot on every turn.
1446fn prune_tool_images(messages: &mut [Message], keep: usize) {
1447    let mut seen = 0;
1448    for message in messages.iter_mut().rev().filter(|m| m.role == Role::Tool) {
1449        let count = message.images().count();
1450        if count == 0 {
1451            continue;
1452        }
1453        seen += 1;
1454        if seen <= keep {
1455            continue;
1456        }
1457        let note = if count == 1 {
1458            "[1 image removed from history]".to_owned()
1459        } else {
1460            format!("[{count} images removed from history]")
1461        };
1462        let text = message.text();
1463        let text = if text.is_empty() { note } else { format!("{text}\n{note}") };
1464        message.content = vec![ContentPart::Text { text }];
1465    }
1466}
1467
1468/// Arguments as shown in logs and approval requests: the parsed object, or the
1469/// raw text when it is not valid JSON (so nothing is hidden from the reader),
1470/// with the tool's context values masked.
1471fn log_arguments(call: &ToolCall, tools: &[BoundTool]) -> Json {
1472    let mut arguments = match call.arguments_json() {
1473        Ok(map) => Json::Object(map),
1474        Err(_) => Json::String(call.arguments.clone()),
1475    };
1476    if let Some(tool) = bound_tool(tools, call)
1477        && !tool.context().is_empty()
1478    {
1479        scrub_json(&mut arguments, tool.context());
1480    }
1481    arguments
1482}
1483
1484/// `text` with every value of `context` masked. Borrows when there is nothing to mask.
1485fn scrub_context<'a>(text: &'a str, context: &ToolCallContext) -> Cow<'a, str> {
1486    if context.is_empty() {
1487        return Cow::Borrowed(text);
1488    }
1489    let values: Vec<&str> = context.secrets.values().map(String::as_str).collect();
1490    redact_secrets(text, &values)
1491}
1492
1493/// Mask the values of `context` in every string of `value`.
1494fn scrub_json(value: &mut Json, context: &ToolCallContext) {
1495    match value {
1496        Json::String(text) => {
1497            if let Cow::Owned(scrubbed) = scrub_context(text, context) {
1498                *text = scrubbed;
1499            }
1500        }
1501        Json::Array(items) => items.iter_mut().for_each(|item| scrub_json(item, context)),
1502        Json::Object(map) => map.values_mut().for_each(|item| scrub_json(item, context)),
1503        _ => {}
1504    }
1505}
1506
1507async fn call_tool(tools: &[BoundTool], call: &ToolCall) -> ToolOutput {
1508    let Some(tool) = bound_tool(tools, call) else {
1509        return ToolOutput::error(format!("error: unknown tool `{}`", call.name));
1510    };
1511    let arguments = match call.arguments_json() {
1512        Ok(map) => Json::Object(map),
1513        Err(e) => return ToolOutput::error(format!("error: {e}")),
1514    };
1515    match tool.runtime.call(&tool.name, arguments, tool.context()).await {
1516        Ok(output) => output,
1517        Err(e) => ToolOutput::error(format!("error: {e}")),
1518    }
1519}
1520
1521/// Host decision for paused tool calls.
1522#[derive(Debug, Default)]
1523struct Approvals {
1524    all: Option<bool>,
1525    per_call: HashMap<String, bool>,
1526    reason: Option<String>,
1527}
1528
1529impl Approvals {
1530    /// Recognized forms: `true`/`false`, `{"approved": bool}`,
1531    /// `{"approvals": {"<call id>": bool}}` (both may be combined, per-call wins),
1532    /// plus an optional `reason`. Anything else decides nothing.
1533    fn from_input(input: Option<&Value>) -> Self {
1534        let mut out = Self::default();
1535        match input {
1536            Some(Value::Bool(b)) => out.all = Some(*b),
1537            Some(Value::Object(map)) => {
1538                out.all = map.get("approved").and_then(Value::as_bool);
1539                if let Some(Value::Object(per)) = map.get("approvals") {
1540                    for (id, v) in per.iter() {
1541                        if let Some(b) = v.as_bool() {
1542                            out.per_call.insert(id.clone(), b);
1543                        }
1544                    }
1545                }
1546                out.reason = map.get("reason").and_then(Value::as_str).map(str::to_owned);
1547            }
1548            _ => {}
1549        }
1550        out
1551    }
1552
1553    /// `Some(true)` approved, `Some(false)` denied, `None` no decision yet.
1554    fn decision(&self, id: &str) -> Option<bool> {
1555        self.per_call.get(id).copied().or(self.all)
1556    }
1557}
1558
1559/// Model-safe tool name: `[A-Za-z0-9_-]{1,64}`, unique within the run.
1560fn unique_name(name: &str, provider: &str, used: &mut HashSet<String>) -> String {
1561    let clean = |s: &str| -> String {
1562        let mut out: String = s
1563            .chars()
1564            .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
1565            .take(64)
1566            .collect();
1567        if out.is_empty() {
1568            out.push_str("tool");
1569        }
1570        out
1571    };
1572    let mut candidate = clean(name);
1573    if used.contains(&candidate) {
1574        candidate = clean(&format!("{provider}_{name}"));
1575    }
1576    let base = candidate.clone();
1577    let mut n = 2;
1578    while used.contains(&candidate) {
1579        let suffix = format!("_{n}");
1580        let keep = 64usize.saturating_sub(suffix.len());
1581        candidate = format!("{}{suffix}", base.chars().take(keep).collect::<String>());
1582        n += 1;
1583    }
1584    used.insert(candidate.clone());
1585    candidate
1586}
1587
1588fn truncate(text: &str, max_chars: usize) -> String {
1589    if max_chars == 0 || text.chars().count() <= max_chars {
1590        return text.to_owned();
1591    }
1592    let mut out: String = text.chars().take(max_chars).collect();
1593    out.push_str("\n[truncated]");
1594    out
1595}
1596
1597impl Node for AgentNode {
1598    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
1599        Box::pin(self.execute(ctx))
1600    }
1601
1602    fn inputs(&self) -> Vec<Selector> {
1603        let cfg = &self.config;
1604        let mut out: Vec<Selector> = cfg.query.selectors().cloned().collect();
1605        if let Some(i) = &cfg.instruction {
1606            out.extend(i.selectors().cloned());
1607        }
1608        if let Some(memory) = &cfg.memory {
1609            out.extend(memory.selectors());
1610        }
1611        out.extend(cfg.vision.selectors());
1612        out.extend(cfg.model.selectors());
1613        out.extend(self.tool_context.iter().flat_map(|(_, t)| t).flat_map(|(_, t)| t.selectors().cloned()));
1614        #[cfg(feature = "learning")]
1615        if let Some(user) = self.learning.as_ref().and_then(|learning| learning.user.as_ref()) {
1616            out.extend(user.selectors().cloned());
1617        }
1618        #[cfg(feature = "context")]
1619        out.extend(self.context.selectors());
1620        out
1621    }
1622}
1623
1624/// Factory for the node registry.
1625pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
1626    Ok(Arc::new(AgentNode::from_doc(doc)?))
1627}
1628
1629#[cfg(test)]
1630mod tests {
1631    use super::*;
1632    use crate::mock::MockModel;
1633    use crate::registry::ModelRegistry;
1634    use crate::types::Role;
1635    use graphrt_core::event::Event;
1636    use graphrt_core::node::Resume;
1637    use graphrt_core::tool::ToolError;
1638    use graphrt_core::{Services, VariablePool};
1639    use std::sync::Mutex;
1640
1641    /// Tools: `add {a, b}` and `fail {}`.
1642    #[derive(Debug, Default)]
1643    struct MathTools {
1644        calls: Mutex<Vec<String>>,
1645    }
1646
1647    impl ToolRuntime for MathTools {
1648        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1649            Box::pin(async {
1650                Ok(vec![
1651                    ToolSpec {
1652                        name: "add".into(),
1653                        description: "add numbers".into(),
1654                        parameters: json!({"type": "object"}),
1655                    },
1656                    ToolSpec {
1657                        name: "fail".into(),
1658                        description: "always fails".into(),
1659                        parameters: json!({"type": "object"}),
1660                    },
1661                ])
1662            })
1663        }
1664
1665        fn call<'a>(
1666            &'a self,
1667            name: &'a str,
1668            arguments: Json,
1669            _context: &'a ToolCallContext,
1670        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1671            self.calls.lock().unwrap().push(name.to_owned());
1672            Box::pin(async move {
1673                match name {
1674                    "add" => {
1675                        let a = arguments["a"].as_i64().unwrap_or(0);
1676                        let b = arguments["b"].as_i64().unwrap_or(0);
1677                        Ok(ToolOutput::text((a + b).to_string()))
1678                    }
1679                    _ => Err(ToolError { tool: name.to_owned(), message: "broken".into() }),
1680                }
1681            })
1682        }
1683    }
1684
1685    /// Tools: `screenshot {}` (one PNG), `bad_image {}` (an unsupported type).
1686    #[derive(Debug, Default)]
1687    struct ScreenTools;
1688
1689    impl ToolRuntime for ScreenTools {
1690        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1691            let spec = |name: &str| ToolSpec { name: name.into(), description: "d".into(), parameters: json!({}) };
1692            Box::pin(
1693                async move { Ok(vec![spec("screenshot"), spec("bad_image"), spec("chart"), spec("broken_chart")]) },
1694            )
1695        }
1696
1697        fn call<'a>(
1698            &'a self,
1699            name: &'a str,
1700            _arguments: Json,
1701            _context: &'a ToolCallContext,
1702        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1703            Box::pin(async move {
1704                Ok(match name {
1705                    "screenshot" => ToolOutput::text("800x600").with_image(ToolImage::png("aGVsbG8=")),
1706                    "chart" => ToolOutput {
1707                        text: "Chart shown".into(),
1708                        data: Value::from_json(json!({"$ui": "chart", "version": 1, "type": "bar"})),
1709                        ..ToolOutput::default()
1710                    },
1711                    "broken_chart" => {
1712                        ToolOutput { data: Value::from_json(json!({"$ui": "chart"})), ..ToolOutput::error("bad chart") }
1713                    }
1714                    _ => ToolOutput::text("odd")
1715                        .with_image(ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() }),
1716                })
1717            })
1718        }
1719    }
1720
1721    struct Setup {
1722        model: Arc<MockModel>,
1723        tools: Arc<MathTools>,
1724        events: Arc<Mutex<Vec<Event>>>,
1725    }
1726
1727    fn setup(responses: Vec<Vec<crate::ChatDelta>>) -> Setup {
1728        Setup {
1729            model: Arc::new(MockModel::new(responses)),
1730            tools: Arc::new(MathTools::default()),
1731            events: Arc::default(),
1732        }
1733    }
1734
1735    fn ctx(s: &Setup) -> NodeContext {
1736        let mut tool_registry = ToolRegistry::new();
1737        tool_registry.add("math", Arc::clone(&s.tools) as Arc<dyn ToolRuntime>);
1738        tool_registry.add("screen", Arc::new(ScreenTools) as Arc<dyn ToolRuntime>);
1739        let services = Services::new()
1740            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
1741            .with(tool_registry);
1742        let mut pool = VariablePool::new();
1743        pool.insert("sys", "query", Value::from("what is 2+3?"));
1744        let events = Arc::clone(&s.events);
1745        NodeContext::for_test("agent", pool)
1746            .with_services(Arc::new(services))
1747            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
1748    }
1749
1750    fn agent(extra: Json) -> AgentNode {
1751        let mut config = json!({
1752            "model": {"provider": "openai", "name": "gpt"},
1753            "instruction": "You are a calculator.",
1754            "tools": ["math/*"],
1755        });
1756        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
1757            c.extend(e);
1758        }
1759        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1760    }
1761
1762    fn completed(r: NodeResult) -> NodeOutput {
1763        match r.unwrap() {
1764            NodeOutcome::Completed(o) => o,
1765            NodeOutcome::Paused(p) => panic!("unexpected pause: {p:?}"),
1766        }
1767    }
1768
1769    #[tokio::test]
1770    async fn ui_blocks_of_tool_results_become_the_ui_output_but_never_reach_the_model() {
1771        let s = setup(vec![
1772            MockModel::tool_calls(&[("c1", "chart", "{}"), ("c2", "broken_chart", "{}")]),
1773            MockModel::text("Here is your chart."),
1774        ]);
1775        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
1776        let ui = out.outputs["ui"].as_array().unwrap().to_vec();
1777        assert_eq!(ui.len(), 1, "only the successful tool's block: {ui:?}");
1778        assert_eq!(graphrt_core::ui::ui_block_kind(&ui[0]), Some("chart"));
1779        let log = out.outputs["tool_calls"].to_json();
1780        assert!(!log.to_string().contains("$ui"), "the log does not repeat the blocks: {log}");
1781        let second = &s.model.requests()[1].messages;
1782        assert!(!format!("{second:?}").contains("$ui"), "blocks are not sent to the model");
1783    }
1784
1785    #[tokio::test]
1786    async fn loops_until_answer() {
1787        let s = setup(vec![
1788            MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#), ("c2", "fail", "{}")]),
1789            MockModel::text("The answer is 5."),
1790        ]);
1791        let out = completed(agent(json!({})).run(ctx(&s)).await);
1792        assert_eq!(out.outputs["text"], Value::from("The answer is 5."));
1793        assert_eq!(out.outputs["iterations"], Value::Int(2));
1794        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1795        assert_eq!(log.len(), 2);
1796        assert_eq!(log[0].get_path(&["result"]), Some(Value::from("5")));
1797        assert_eq!(log[1].get_path(&["is_error"]), Some(Value::Bool(true)));
1798        assert_eq!(out.usage.unwrap().total_tokens, 4);
1799
1800        let requests = s.model.requests();
1801        assert_eq!(requests[0].tools.len(), 2);
1802        let second = &requests[1].messages;
1803        assert_eq!(second[0].role, Role::System);
1804        assert_eq!(second[2].tool_calls.len(), 2);
1805        assert_eq!(second[3].tool_call_id.as_deref(), Some("c1"));
1806        assert_eq!(second[3].text(), "5");
1807        assert!(second[4].text().contains("broken"));
1808
1809        let progress: Vec<String> = s
1810            .events
1811            .lock()
1812            .unwrap()
1813            .iter()
1814            .filter_map(|e| match e {
1815                Event::NodeProgress { name, .. } => Some(name.clone()),
1816                _ => None,
1817            })
1818            .collect();
1819        assert_eq!(progress, ["agent_step", "tool_call", "tool_call", "tool_result", "tool_result", "agent_step"]);
1820    }
1821
1822    /// Tool `image_resize {path*, max_width* (integer), overwrite (boolean)}` that records
1823    /// the arguments it got.
1824    #[derive(Debug, Default)]
1825    struct ImageTools {
1826        arguments: Mutex<Vec<Json>>,
1827    }
1828
1829    impl ToolRuntime for ImageTools {
1830        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1831            Box::pin(async {
1832                Ok(vec![ToolSpec {
1833                    name: "image_resize".into(),
1834                    description: "resize a picture".into(),
1835                    parameters: json!({
1836                        "type": "object",
1837                        "properties": {
1838                            "path": {"type": "string"},
1839                            "max_width": {"type": "integer", "description": "Largest width in pixels"},
1840                            "overwrite": {"type": "boolean"}
1841                        },
1842                        "required": ["path", "max_width"]
1843                    }),
1844                }])
1845            })
1846        }
1847
1848        fn call<'a>(
1849            &'a self,
1850            _name: &'a str,
1851            arguments: Json,
1852            _context: &'a ToolCallContext,
1853        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1854            self.arguments.lock().unwrap().push(arguments.clone());
1855            Box::pin(async move {
1856                Ok(match arguments["max_width"].as_i64() {
1857                    Some(width) => ToolOutput::text(format!("resized to {width} px")),
1858                    None => ToolOutput::error("invalid arguments: max_width must be an integer"),
1859                })
1860            })
1861        }
1862    }
1863
1864    fn image_ctx(model: &Arc<MockModel>, tools: &Arc<ImageTools>) -> NodeContext {
1865        let mut tool_registry = ToolRegistry::new();
1866        tool_registry.add("image", Arc::clone(tools) as Arc<dyn ToolRuntime>);
1867        let services = Services::new()
1868            .with(ModelRegistry::new().with("openai", Arc::clone(model) as Arc<dyn crate::ChatModel>))
1869            .with(tool_registry);
1870        let mut pool = VariablePool::new();
1871        pool.insert("sys", "query", Value::from("make it 400 px wide"));
1872        NodeContext::for_test("agent", pool).with_services(Arc::new(services))
1873    }
1874
1875    fn image_agent() -> AgentNode {
1876        let config = json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["image/*"]});
1877        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1878    }
1879
1880    #[tokio::test]
1881    async fn arguments_are_put_into_the_types_the_tool_asks_for() {
1882        let model = Arc::new(MockModel::new(vec![
1883            MockModel::tool_calls(&[(
1884                "c1",
1885                "image_resize",
1886                r#"{"path": "a.png", "width": "400", "overwrite": "false"}"#,
1887            )]),
1888            MockModel::text("Done."),
1889        ]));
1890        let tools = Arc::new(ImageTools::default());
1891
1892        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
1893
1894        assert_eq!(out.outputs["text"], Value::from("Done."));
1895        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400, "overwrite": false})]);
1896    }
1897
1898    #[tokio::test]
1899    async fn a_call_written_as_text_is_made() {
1900        let written =
1901            "Sure.\n```json\n{\"name\": \"resize\", \"parameters\": {\"path\": \"a.png\", \"max_width\": 400}}\n```";
1902        let model = Arc::new(MockModel::new(vec![MockModel::text(written), MockModel::text("Resized to 400 px.")]));
1903        let tools = Arc::new(ImageTools::default());
1904
1905        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
1906
1907        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400})]);
1908        assert_eq!(out.outputs["iterations"], Value::Int(2));
1909        let second = &model.requests()[1].messages;
1910        let assistant = second.iter().find(|message| !message.tool_calls.is_empty()).unwrap();
1911        assert_eq!(assistant.tool_calls[0].name, "image_resize");
1912        assert!(out.outputs["text"].as_str().unwrap().ends_with("Resized to 400 px."));
1913    }
1914
1915    #[tokio::test]
1916    async fn a_call_without_a_required_argument_is_asked_again_once() {
1917        let model = Arc::new(MockModel::new(vec![
1918            MockModel::tool_calls(&[("c1", "image_resize", r#"{"path": "a.png"}"#)]),
1919            MockModel::tool_calls(&[("c2", "image_resize", r#"{"path": "a.png"}"#)]),
1920            MockModel::text("I could not resize it."),
1921        ]));
1922        let tools = Arc::new(ImageTools::default());
1923
1924        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
1925
1926        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
1927        let first_result = log[0].get_path(&["result"]).unwrap();
1928        assert!(first_result.as_str().unwrap().contains("`max_width` (Largest width in pixels)"), "{first_result:?}");
1929        // Asked once; the second call reaches the tool, which answers for itself.
1930        assert_eq!(tools.arguments.lock().unwrap().len(), 1);
1931        assert!(log[1].get_path(&["result"]).unwrap().as_str().unwrap().contains("invalid arguments"));
1932    }
1933
1934    const JWT: &str = "eyJhbGciOiJIUzI1NiJ9.user-token";
1935
1936    /// Tool `whoami {}` that echoes its context (as a careless upstream error would).
1937    #[derive(Debug)]
1938    struct VaultTools {
1939        accepts: bool,
1940        contexts: Mutex<Vec<ToolCallContext>>,
1941    }
1942
1943    impl VaultTools {
1944        fn new(accepts: bool) -> Arc<Self> {
1945            Arc::new(Self { accepts, contexts: Mutex::default() })
1946        }
1947    }
1948
1949    impl ToolRuntime for VaultTools {
1950        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
1951            let spec = ToolSpec { name: "whoami".into(), description: "d".into(), parameters: json!({}) };
1952            Box::pin(async move { Ok(vec![spec]) })
1953        }
1954
1955        fn call<'a>(
1956            &'a self,
1957            _name: &'a str,
1958            _arguments: Json,
1959            context: &'a ToolCallContext,
1960        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
1961            self.contexts.lock().unwrap().push(context.clone());
1962            let token = context.secret("user_jwt").unwrap_or("none").to_owned();
1963            Box::pin(async move { Ok(ToolOutput::text(format!("rejected token {token}"))) })
1964        }
1965
1966        fn accepts_secrets(&self) -> bool {
1967            self.accepts
1968        }
1969    }
1970
1971    fn vault_ctx(s: &Setup, vault: &Arc<VaultTools>) -> NodeContext {
1972        let mut registry = ToolRegistry::new();
1973        registry.add("vault", Arc::clone(vault) as Arc<dyn ToolRuntime>);
1974        let services = Services::new()
1975            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
1976            .with(registry);
1977        let mut pool = VariablePool::new();
1978        pool.insert("sys", "query", Value::from("who am I?"));
1979        pool.insert("start", "user_jwt", Value::Secret(Arc::from(JWT)));
1980        let events = Arc::clone(&s.events);
1981        NodeContext::for_test("agent", pool)
1982            .with_services(Arc::new(services))
1983            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
1984    }
1985
1986    fn vault_agent(extra: Json) -> AgentNode {
1987        let mut config = json!({
1988            "model": {"provider": "openai", "name": "gpt"},
1989            "tools": ["vault/whoami"],
1990            "tool_context": {"vault": {"user_jwt": "{{#start.user_jwt#}}", "missing": "{{#start.nope#}}"}},
1991        });
1992        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
1993            c.extend(e);
1994        }
1995        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
1996    }
1997
1998    #[tokio::test]
1999    async fn tool_context_reaches_the_tool_but_nothing_else() {
2000        let s = setup(vec![
2001            MockModel::tool_calls(&[("c1", "whoami", &format!(r#"{{"echo":"{JWT}"}}"#))]),
2002            MockModel::text("done"),
2003        ]);
2004        let vault = VaultTools::new(true);
2005        let secrets = Arc::new(graphrt_core::redact::SecretSet::new());
2006        let ctx = vault_ctx(&s, &vault).with_secret_values(Arc::clone(&secrets));
2007        let node = vault_agent(json!({}));
2008        let out = completed(node.run(ctx).await);
2009
2010        let contexts = vault.contexts.lock().unwrap().clone();
2011        assert_eq!(contexts.len(), 1);
2012        assert_eq!(contexts[0].secret("user_jwt"), Some(JWT));
2013        assert_eq!(contexts[0].secret("missing"), None, "empty renders are left out");
2014
2015        // Not in the model's history, the outputs or any event.
2016        let requests = s.model.requests();
2017        assert_eq!(requests[1].messages.last().unwrap().text(), "rejected token ******");
2018        // (The model's own arguments stay in its history as it wrote them.)
2019        let tool_messages: Vec<_> = requests[1].messages.iter().filter(|m| m.role == Role::Tool).collect();
2020        assert!(!format!("{tool_messages:?}").contains(JWT));
2021        assert!(!serde_json::to_string(&out.outputs).unwrap().contains(JWT));
2022        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
2023        assert!(!events.contains(JWT), "{events}");
2024        // Registered with the run so later node errors are scrubbed too.
2025        assert_eq!(secrets.scrub(&format!("bad {JWT}")), "bad ******");
2026        assert!(node.inputs().iter().any(|sel| sel.to_string() == "start.user_jwt"));
2027    }
2028
2029    #[tokio::test]
2030    async fn captured_tool_results_never_carry_the_tool_context() {
2031        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
2032        let vault = VaultTools::new(true);
2033        let base = vault_ctx(&s, &vault);
2034        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2035        completed(vault_agent(json!({})).run(base.with_services(Arc::new(services))).await);
2036        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("rejected token ******")));
2037        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
2038        assert!(!events.contains(JWT), "{events}");
2039    }
2040
2041    #[tokio::test]
2042    async fn tool_results_are_masked_before_they_are_cut() {
2043        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
2044        let vault = VaultTools::new(true);
2045        let base = vault_ctx(&s, &vault);
2046        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2047        // The cut falls inside the echoed token: masking afterwards would miss its prefix.
2048        let limit = "rejected token ".len() + 12;
2049        let node = vault_agent(json!({"max_tool_output_chars": limit}));
2050        completed(node.run(base.with_services(Arc::new(services))).await);
2051        let token_prefix = &JWT[..12];
2052        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
2053        assert!(!events.contains(token_prefix), "{events}");
2054        let requests = s.model.requests();
2055        assert!(!format!("{:?}", requests[1].messages).contains(token_prefix));
2056    }
2057
2058    #[tokio::test]
2059    async fn tool_context_is_sent_again_after_approval() {
2060        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
2061        let vault = VaultTools::new(true);
2062        let node = vault_agent(json!({"require_approval": ["*"]}));
2063        let paused = match node.run(vault_ctx(&s, &vault)).await.unwrap() {
2064            NodeOutcome::Paused(p) => p,
2065            NodeOutcome::Completed(_) => panic!("expected a pause"),
2066        };
2067        assert!(!paused.state.to_string().contains(JWT), "the snapshot state never holds the context");
2068        let resume = Resume { state: paused.state, input: Some(Value::Bool(true)) };
2069        completed(node.run(vault_ctx(&s, &vault).with_resume(Some(resume))).await);
2070        assert_eq!(vault.contexts.lock().unwrap()[0].secret("user_jwt"), Some(JWT));
2071    }
2072
2073    #[tokio::test]
2074    async fn tool_context_needs_a_provider_that_accepts_secrets() {
2075        let s = setup(vec![MockModel::text("unused")]);
2076        let vault = VaultTools::new(false);
2077        let error = vault_agent(json!({})).run(vault_ctx(&s, &vault)).await.unwrap_err();
2078        assert_eq!(error.kind, "tool_context_denied");
2079        assert!(vault.contexts.lock().unwrap().is_empty());
2080    }
2081
2082    #[test]
2083    fn tool_context_providers_must_be_used() {
2084        let config = json!({
2085            "model": {"provider": "openai", "name": "gpt"},
2086            "tools": ["math/add"],
2087            "tool_context": {"vault": {"user_jwt": "x"}},
2088        });
2089        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
2090        assert!(error.to_string().contains("`vault` is not used"), "{error}");
2091        for bad in [json!({"math": {"jwt": 1}}), json!({"math": {"": "x"}}), json!({"math": "x"})] {
2092            let config =
2093                json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["math/add"], "tool_context": bad});
2094            assert!(AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).is_err());
2095        }
2096    }
2097
2098    fn tool_results(s: &Setup) -> Vec<Value> {
2099        let events = s.events.lock().unwrap();
2100        let results = events.iter().filter_map(|e| match e {
2101            Event::NodeProgress { name, data, .. } if name == "tool_result" => Some(data.clone()),
2102            _ => None,
2103        });
2104        results.collect()
2105    }
2106
2107    #[tokio::test]
2108    async fn tool_results_carry_text_only_when_the_host_captures_content() {
2109        let responses = || vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")];
2110        let s = setup(responses());
2111        completed(agent(json!({})).run(ctx(&s)).await);
2112        assert_eq!(tool_results(&s)[0].get_path(&["result"]), None);
2113
2114        let s = setup(responses());
2115        let base = ctx(&s);
2116        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2117        completed(agent(json!({})).run(base.with_services(Arc::new(services))).await);
2118        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("5")));
2119    }
2120
2121    #[tokio::test]
2122    async fn tool_images_reach_the_model() {
2123        let s = setup(vec![MockModel::tool_calls(&[("c1", "screenshot", "{}")]), MockModel::text("a login form")]);
2124        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2125        let requests = s.model.requests();
2126        let result = &requests[1].messages[3];
2127        assert_eq!(result.role, Role::Tool);
2128        assert_eq!(result.text(), "800x600");
2129        assert_eq!(
2130            result.images().cloned().collect::<Vec<_>>(),
2131            vec![ContentPart::Image { url: "data:image/png;base64,aGVsbG8=".into(), detail: None }]
2132        );
2133        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2134        assert_eq!(log[0].get_path(&["images"]), Some(Value::Int(1)));
2135        let reported = s.events.lock().unwrap().iter().find_map(|e| match e {
2136            Event::NodeProgress { name, data, .. } if name == "tool_result" => data.get_path(&["images"]),
2137            _ => None,
2138        });
2139        assert_eq!(reported, Some(Value::Int(1)));
2140    }
2141
2142    #[tokio::test]
2143    async fn invalid_tool_images_are_dropped_with_a_note() {
2144        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
2145        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2146        let result = &s.model.requests()[1].messages[3];
2147        assert_eq!(result.images().count(), 0);
2148        assert!(
2149            result.text().starts_with("odd\n[images dropped: image #0: image media type `image/bmp`"),
2150            "{}",
2151            result.text()
2152        );
2153    }
2154
2155    #[tokio::test]
2156    async fn captured_tool_result_text_matches_what_the_model_sees() {
2157        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
2158        let base = ctx(&s);
2159        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2160        let out = completed(agent(json!({"tools": ["screen/*"]})).run(base.with_services(Arc::new(services))).await);
2161        let seen_by_model = s.model.requests()[1].messages[3].text();
2162        assert!(seen_by_model.contains("[images dropped:"), "{seen_by_model}");
2163        let reported = tool_results(&s)[0].get_path(&["result"]);
2164        assert_eq!(reported, Some(Value::from(seen_by_model.clone())), "progress event");
2165        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2166        assert_eq!(log[0].get_path(&["result"]), Some(Value::from(seen_by_model)), "tool_calls output");
2167    }
2168
2169    #[tokio::test]
2170    async fn keep_tool_images_prunes_older_screenshots() {
2171        let s = setup(vec![
2172            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
2173            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
2174            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
2175            MockModel::text("done"),
2176        ]);
2177        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": 2})).run(ctx(&s)).await);
2178        let last = s.model.requests().last().cloned().unwrap();
2179        let results: Vec<&Message> = last.messages.iter().filter(|m| m.role == Role::Tool).collect();
2180        assert_eq!(results.iter().map(|m| m.images().count()).collect::<Vec<_>>(), [0, 1, 1]);
2181        assert_eq!(results[0].text(), "800x600\n[1 image removed from history]");
2182        // The second request still had every image (only two existed).
2183        let second = &s.model.requests()[2];
2184        assert_eq!(second.messages.iter().map(|m| m.images().count()).sum::<usize>(), 2);
2185    }
2186
2187    fn four_screenshots() -> Vec<Vec<crate::ChatDelta>> {
2188        vec![
2189            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
2190            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
2191            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
2192            MockModel::tool_calls(&[("c4", "screenshot", "{}")]),
2193            MockModel::text("done"),
2194        ]
2195    }
2196
2197    fn images_per_tool_result(s: &Setup) -> Vec<usize> {
2198        let last = s.model.requests().last().cloned().unwrap();
2199        last.messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.images().count()).collect()
2200    }
2201
2202    #[tokio::test]
2203    async fn keep_tool_images_defaults_to_the_last_three() {
2204        let s = setup(four_screenshots());
2205        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2206        assert_eq!(images_per_tool_result(&s), [0, 1, 1, 1]);
2207    }
2208
2209    #[tokio::test]
2210    async fn keep_tool_images_null_keeps_every_image() {
2211        let s = setup(four_screenshots());
2212        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": null})).run(ctx(&s)).await);
2213        assert_eq!(images_per_tool_result(&s), [1, 1, 1, 1]);
2214    }
2215
2216    #[tokio::test]
2217    async fn last_iteration_keeps_tools_but_forbids_calls() {
2218        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), MockModel::text("2")]);
2219        let out = completed(agent(json!({"max_iterations": 2})).run(ctx(&s)).await);
2220        assert_eq!(out.outputs["text"], Value::from("2"));
2221        assert_eq!(out.outputs["stopped_reason"], Value::from("max_iterations"));
2222        let requests = s.model.requests();
2223        assert_eq!(requests[0].tool_choice, Some(ToolChoice::Auto));
2224        assert!(!requests[1].tools.is_empty(), "tool definitions stay for the history's tool calls");
2225        assert_eq!(requests[1].tool_choice, Some(ToolChoice::None));
2226    }
2227
2228    fn text_chunks(s: &Setup) -> Vec<String> {
2229        s.events
2230            .lock()
2231            .unwrap()
2232            .iter()
2233            .filter_map(|e| match e {
2234                Event::NodeChunk { field, chunk, .. } if field.as_ref() == "text" => Some(chunk.clone()),
2235                _ => None,
2236            })
2237            .collect()
2238    }
2239
2240    fn thought(s: &Setup) -> Option<Value> {
2241        s.events.lock().unwrap().iter().find_map(|e| match e {
2242            Event::NodeProgress { name, data, .. } if name == "agent_thought" => Some(data.clone()),
2243            _ => None,
2244        })
2245    }
2246
2247    fn tokens(pieces: &[&str]) -> Vec<crate::ChatDelta> {
2248        let mut out: Vec<crate::ChatDelta> = pieces.iter().map(|p| crate::ChatDelta::Text((*p).into())).collect();
2249        out.push(crate::ChatDelta::Finish(FinishReason::Stop));
2250        out
2251    }
2252
2253    #[tokio::test]
2254    async fn final_answer_streams_token_by_token() {
2255        let s =
2256            setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), tokens(&["It", " is", " 5", "."])]);
2257        let out = completed(agent(json!({})).run(ctx(&s)).await);
2258        // One chunk per provider delta, on a turn that was still allowed to call tools.
2259        assert_eq!(text_chunks(&s), ["It", " is", " 5", "."]);
2260        assert_eq!(out.outputs["text"], Value::from("It is 5."));
2261        assert_eq!(s.model.requests()[1].tool_choice, Some(ToolChoice::Auto));
2262    }
2263
2264    #[tokio::test]
2265    async fn preamble_before_a_tool_call_is_streamed_and_kept_in_the_answer() {
2266        let mut first = tokens(&["Let me", " check."]);
2267        first.pop();
2268        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
2269        let s = setup(vec![first, tokens(&["It is", " 5."])]);
2270        let out = completed(agent(json!({})).run(ctx(&s)).await);
2271        let chunks = text_chunks(&s);
2272        assert_eq!(chunks, ["Let me", " check.", "\n\n", "It is", " 5."]);
2273        assert_eq!(out.outputs["text"], Value::from(chunks.concat().as_str()));
2274        let thought = thought(&s).unwrap();
2275        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
2276        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(true)));
2277        // The history keeps each turn separate: the preamble belongs to the tool-call turn.
2278        let second = &s.model.requests()[1].messages;
2279        assert_eq!(second[2].text(), "Let me check.");
2280        assert_eq!(second[2].tool_calls.len(), 1);
2281    }
2282
2283    #[tokio::test]
2284    async fn tool_call_fragments_and_later_text_are_never_streamed() {
2285        use crate::ChatDelta::{Finish, Text, ToolCall};
2286        let first = vec![
2287            Text("A".into()),
2288            ToolCall { index: 0, id: Some("c1".into()), name: Some("add".into()), arguments: r#"{"a":"#.into() },
2289            Text("B".into()),
2290            ToolCall { index: 0, id: None, name: None, arguments: "1}".into() },
2291            Finish(FinishReason::ToolCalls),
2292        ];
2293        let s = setup(vec![first, MockModel::text("done")]);
2294        let out = completed(agent(json!({})).run(ctx(&s)).await);
2295        assert_eq!(text_chunks(&s), ["A", "\n\n", "done"]);
2296        assert_eq!(out.outputs["text"], Value::from("A\n\ndone"));
2297        assert_eq!(thought(&s).unwrap().get_path(&["text"]), Some(Value::from("AB")));
2298        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
2299    }
2300
2301    #[tokio::test]
2302    async fn stream_tool_turns_false_buffers_tool_turns() {
2303        let mut first = vec![crate::ChatDelta::Text("Let me check.".into())];
2304        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
2305        let s = setup(vec![first, tokens(&["It is", " 5."])]);
2306        let out = completed(agent(json!({"stream_tool_turns": false})).run(ctx(&s)).await);
2307        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
2308        assert_eq!(text_chunks(&s), ["It is 5."]);
2309        assert_eq!(out.outputs["text"], Value::from("It is 5."));
2310        let thought = thought(&s).unwrap();
2311        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
2312        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(false)));
2313    }
2314
2315    #[tokio::test]
2316    async fn forced_final_turn_streams_token_by_token() {
2317        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), tokens(&["=", "2"])]);
2318        let out = completed(agent(json!({"max_iterations": 2, "stream_tool_turns": false})).run(ctx(&s)).await);
2319        assert_eq!(text_chunks(&s), ["=", "2"]);
2320        assert_eq!(out.outputs["text"], Value::from("=2"));
2321    }
2322
2323    #[tokio::test]
2324    async fn preamble_survives_a_tool_approval_pause() {
2325        let mut first = vec![crate::ChatDelta::Text("Checking.".into())];
2326        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
2327        let s = setup(vec![first, MockModel::text("4")]);
2328        let node = agent(json!({"require_approval": ["add"]}));
2329        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
2330        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
2331        let resumed =
2332            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
2333        let out = completed(node.run(resumed).await);
2334        assert_eq!(out.outputs["text"], Value::from("Checking.\n\n4"));
2335        assert_eq!(text_chunks(&s), ["Checking.", "\n\n", "4"]);
2336    }
2337
2338    #[tokio::test]
2339    async fn malformed_arguments_are_reported_back_to_the_model() {
2340        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"#)]), MockModel::text("sorry")]);
2341        let out = completed(agent(json!({})).run(ctx(&s)).await);
2342        assert!(s.tools.calls.lock().unwrap().is_empty(), "malformed calls never run");
2343        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2344        assert_eq!(log[0].get_path(&["arguments"]), Some(Value::from(r#"{"a":2,"#)));
2345        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
2346        let second = &s.model.requests()[1];
2347        assert_eq!(second.messages[2].tool_calls[0].arguments, "{}", "history never replays malformed JSON");
2348        assert!(second.messages[3].text().contains("invalid JSON arguments"));
2349    }
2350
2351    #[tokio::test]
2352    async fn per_turn_limit_rejects_extra_calls() {
2353        let s = setup(vec![
2354            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
2355            MockModel::text("ok"),
2356        ]);
2357        let out =
2358            completed(agent(json!({"max_tool_calls_per_turn": 1, "parallel_tool_calls": false})).run(ctx(&s)).await);
2359        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
2360        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2361        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
2362    }
2363
2364    #[tokio::test]
2365    async fn approval_pauses_and_resumes() {
2366        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]), MockModel::text("4")]);
2367        let node = agent(json!({"tools": [{"provider": "math", "name": "add"}], "require_approval": ["math/add"]}));
2368        let paused = match node.run(ctx(&s)).await.unwrap() {
2369            NodeOutcome::Paused(p) => p,
2370            NodeOutcome::Completed(_) => panic!("expected pause"),
2371        };
2372        assert_eq!(paused.kind, "tool_approval");
2373        assert_eq!(paused.data.get_path(&["calls", "0", "name"]), Some(Value::from("add")));
2374        assert!(s.tools.calls.lock().unwrap().is_empty(), "nothing runs before approval");
2375
2376        // The saved state survives serialization (snapshots store it as JSON).
2377        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
2378        let resumed =
2379            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
2380        let out = completed(node.run(resumed).await);
2381        assert_eq!(out.outputs["text"], Value::from("4"));
2382        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
2383    }
2384
2385    #[tokio::test]
2386    async fn denied_calls_are_reported_to_the_model() {
2387        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", "{}")]), MockModel::text("fine")]);
2388        let node = agent(json!({"require_approval": ["*"]}));
2389        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
2390        let input = Value::from_json(json!({"approvals": {"c1": false}, "reason": "not now"}));
2391        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
2392        assert_eq!(out.outputs["text"], Value::from("fine"));
2393        assert!(s.tools.calls.lock().unwrap().is_empty());
2394        let last_request = s.model.requests().pop().unwrap();
2395        assert!(last_request.messages.iter().any(|m| m.text().contains("not now")));
2396    }
2397
2398    #[tokio::test]
2399    async fn only_gated_calls_wait_for_approval() {
2400        let s = setup(vec![
2401            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "fail", "{}")]),
2402            MockModel::text("done"),
2403        ]);
2404        let node = agent(json!({"require_approval": ["math/fail"]}));
2405        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
2406        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"], "ungated calls run immediately");
2407        assert_eq!(p.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
2408        assert!(p.data.get_path(&["calls", "1"]).is_none());
2409
2410        // No decision (or one that is not understood) keeps the run paused.
2411        for input in [None, Some(Value::from("yes")), Some(Value::from_json(json!({"approved": "true"})))] {
2412            let resumed = ctx(&s).with_resume(Some(Resume { state: p.state.clone(), input }));
2413            assert!(matches!(node.run(resumed).await.unwrap(), NodeOutcome::Paused(_)));
2414        }
2415        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
2416
2417        let input = Value::from_json(json!({"approvals": {"c2": true}}));
2418        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
2419        assert_eq!(out.outputs["text"], Value::from("done"));
2420        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add", "fail"]);
2421    }
2422
2423    #[tokio::test]
2424    async fn per_call_decisions_can_arrive_in_steps() {
2425        let s = setup(vec![
2426            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
2427            MockModel::text("ok"),
2428        ]);
2429        let node = agent(json!({"require_approval": ["*"], "parallel_tool_calls": false}));
2430        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
2431        let input = Value::from_json(json!({"approvals": {"c1": true}}));
2432        let NodeOutcome::Paused(p2) =
2433            node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await.unwrap()
2434        else {
2435            panic!("c2 is still undecided")
2436        };
2437        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
2438        assert_eq!(p2.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
2439        let input = Value::from_json(json!({"approved": false}));
2440        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p2.state, input: Some(input) }))).await);
2441        assert_eq!(out.outputs["text"], Value::from("ok"));
2442        assert_eq!(s.tools.calls.lock().unwrap().len(), 1, "c2 was denied");
2443    }
2444
2445    /// Tool `page {}`: a long result, like a fetched web page.
2446    #[cfg(feature = "context")]
2447    #[derive(Debug, Default)]
2448    struct PageTools {
2449        calls: Mutex<usize>,
2450    }
2451
2452    #[cfg(feature = "context")]
2453    impl ToolRuntime for PageTools {
2454        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
2455            let spec = ToolSpec { name: "page".into(), description: "fetch a page".into(), parameters: json!({}) };
2456            Box::pin(async move { Ok(vec![spec]) })
2457        }
2458
2459        fn call<'a>(
2460            &'a self,
2461            _name: &'a str,
2462            _arguments: Json,
2463            _context: &'a ToolCallContext,
2464        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
2465            let n = {
2466                let mut calls = self.calls.lock().unwrap();
2467                *calls += 1;
2468                *calls
2469            };
2470            Box::pin(async move { Ok(ToolOutput::text(format!("page {n}: {}", "lorem ".repeat(3_500)))) })
2471        }
2472    }
2473
2474    /// A context with the `page` and `math` tools and a model that fetches
2475    /// `pages` pages, one per turn, before the rest of its script.
2476    #[cfg(feature = "context")]
2477    fn page_ctx(pages: usize) -> (Setup, Arc<PageTools>, impl Fn() -> NodeContext) {
2478        let s = setup((1..=pages).map(|n| MockModel::tool_calls(&[(&format!("p{n}"), "page", "{}")])).collect());
2479        let page_tools = Arc::new(PageTools::default());
2480        let (model, tools, events) = (Arc::clone(&s.model), Arc::clone(&s.tools), Arc::clone(&s.events));
2481        let pages = Arc::clone(&page_tools);
2482        let ctx = move || {
2483            let mut tool_registry = ToolRegistry::new();
2484            tool_registry.add("math", Arc::clone(&tools) as Arc<dyn ToolRuntime>);
2485            tool_registry.add("web", Arc::clone(&pages) as Arc<dyn ToolRuntime>);
2486            let services = Services::new()
2487                .with(ModelRegistry::new().with("openai", Arc::clone(&model) as Arc<dyn crate::ChatModel>))
2488                .with(tool_registry);
2489            let mut pool = VariablePool::new();
2490            pool.insert("sys", "query", Value::from("read the pages"));
2491            let events = Arc::clone(&events);
2492            NodeContext::for_test("agent", pool)
2493                .with_services(Arc::new(services))
2494                .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
2495        };
2496        (s, page_tools, ctx)
2497    }
2498
2499    #[cfg(feature = "context")]
2500    fn page_agent(extra: Json) -> AgentNode {
2501        let mut config = json!({"tools": ["web/*", "math/*"], "max_iterations": 30});
2502        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
2503            c.extend(e);
2504        }
2505        agent(config)
2506    }
2507
2508    /// Every tool result of a request has its call in the assistant message
2509    /// before its run of results, and every call has its result.
2510    #[cfg(feature = "context")]
2511    fn assert_request_pairs(messages: &[Message]) {
2512        let mut open: Vec<String> = Vec::new();
2513        for message in messages {
2514            if message.role == Role::Tool {
2515                let id = message.tool_call_id.clone().unwrap();
2516                assert!(open.contains(&id), "result {id} without its call");
2517                open.retain(|other| other != &id);
2518            } else {
2519                assert!(open.is_empty(), "calls without results: {open:?}");
2520                open = message.tool_calls.iter().map(|call| call.id.clone()).collect();
2521            }
2522        }
2523        assert!(open.is_empty(), "calls without results: {open:?}");
2524    }
2525
2526    #[cfg(feature = "context")]
2527    fn progress_named(events: &Mutex<Vec<Event>>, wanted: &str) -> Vec<Json> {
2528        events
2529            .lock()
2530            .unwrap()
2531            .iter()
2532            .filter_map(|e| match e {
2533                Event::NodeProgress { name, data, .. } if name == wanted => Some(data.to_json()),
2534                _ => None,
2535            })
2536            .collect()
2537    }
2538
2539    #[cfg(feature = "context")]
2540    fn too_long(window: u64, sent: u64) -> crate::LlmError {
2541        crate::LlmError::ContextLength(format!(
2542            "This model's maximum context length is {window} tokens. However, your messages resulted in {sent} tokens."
2543        ))
2544    }
2545
2546    #[cfg(feature = "context")]
2547    #[tokio::test]
2548    async fn a_turn_refused_for_its_size_is_trimmed_and_sent_again() {
2549        let (s, pages, ctx) = page_ctx(6);
2550        s.model.push_error(too_long(20_000, 36_500));
2551        s.model.push(MockModel::text("done"));
2552        let out = completed(page_agent(json!({})).run(ctx()).await);
2553        assert_eq!(out.outputs["text"], Value::from("done"));
2554        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
2555        // The outputs say that the model was not sent everything.
2556        assert_eq!(
2557            out.outputs["context"].to_json(),
2558            json!({"removed_messages": 8, "placeholders": 0, "cut_results": 1, "summarized": false, "unsummarized_messages": 0})
2559        );
2560        assert_eq!(*pages.calls.lock().unwrap(), 6, "no tool ran twice");
2561        // Six tool turns, the refused turn and the same turn again.
2562        let requests = s.model.requests();
2563        assert_eq!(requests.len(), 8);
2564        let (refused, retried) = (&requests[6], &requests[7]);
2565        assert!(crate::context::estimate_messages(&retried.messages) < 15_000);
2566        assert!(
2567            crate::context::estimate_messages(&refused.messages) > 30_000,
2568            "nothing was trimmed before the provider refused"
2569        );
2570        assert_request_pairs(&retried.messages);
2571        assert_eq!(retried.messages[0], refused.messages[0], "the system message is unchanged");
2572        let user = retried.messages.iter().find(|m| m.role == Role::User).unwrap().text();
2573        assert!(user.ends_with("read the pages"), "the request stays");
2574        assert!(user.starts_with("[Context note, written by the runtime. 8 earlier message(s)"), "{user}");
2575        assert_eq!(retried.tools, refused.tools);
2576        let trims = progress_named(&s.events, "context_trimmed");
2577        assert_eq!(trims.len(), 1);
2578        assert_eq!(trims[0]["reason"], "provider_limit");
2579        // The `tool_calls` output still has every result in full.
2580        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2581        assert_eq!(log.len(), 6);
2582        assert!(log[0].get_path(&["result"]).unwrap().to_text().len() > 20_000);
2583    }
2584
2585    #[cfg(feature = "context")]
2586    #[tokio::test]
2587    async fn a_second_refusal_fails_the_node_with_the_same_kind() {
2588        let (s, pages, ctx) = page_ctx(6);
2589        s.model.push_error(too_long(20_000, 36_500));
2590        s.model.push_error(too_long(20_000, 21_000));
2591        s.model.push(MockModel::text("never reached"));
2592        let error = page_agent(json!({})).run(ctx()).await.unwrap_err();
2593        assert_eq!(error.kind, "model_context_length");
2594        assert!(!error.retryable);
2595        assert!(error.message.contains("21000 tokens"), "the provider's own words: {}", error.message);
2596        assert!(error.message.contains("already trimmed the conversation and sent it again"), "{}", error.message);
2597        assert_eq!(s.model.requests().len(), 8, "sent again once, not in a loop");
2598        assert_eq!(*pages.calls.lock().unwrap(), 6);
2599    }
2600
2601    #[cfg(feature = "context")]
2602    #[tokio::test]
2603    async fn off_fails_on_the_first_refusal_as_before() {
2604        let (s, _, ctx) = page_ctx(6);
2605        s.model.push_error(too_long(20_000, 36_500));
2606        s.model.push(MockModel::text("never reached"));
2607        let error = page_agent(json!({"context_window": "off"})).run(ctx()).await.unwrap_err();
2608        assert_eq!(error.kind, "model_context_length");
2609        assert_eq!(s.model.requests().len(), 7);
2610        assert!(progress_named(&s.events, "context_trimmed").is_empty());
2611    }
2612
2613    #[cfg(feature = "context")]
2614    #[tokio::test]
2615    async fn a_run_that_fits_is_sent_exactly_as_before() {
2616        let (s, _, ctx) = page_ctx(3);
2617        s.model.push(MockModel::text("done"));
2618        let guarded = completed(page_agent(json!({})).run(ctx()).await);
2619        let with_guard = s.model.requests();
2620        let (s, _, ctx) = page_ctx(3);
2621        s.model.push(MockModel::text("done"));
2622        let plain = completed(page_agent(json!({"context_window": "off"})).run(ctx()).await);
2623        assert_eq!(with_guard, s.model.requests());
2624        assert_eq!(guarded.outputs, plain.outputs);
2625        assert!(!guarded.outputs.contains_key("context"), "nothing was trimmed, so there is nothing to say");
2626        assert!(progress_named(&s.events, "context_trimmed").is_empty());
2627    }
2628
2629    #[cfg(feature = "context")]
2630    #[tokio::test]
2631    async fn a_set_limit_keeps_every_request_under_it() {
2632        let (s, pages, ctx) = page_ctx(12);
2633        s.model.push(MockModel::text("done"));
2634        let node = page_agent(json!({"context_window": {"max_tokens": 40_000}}));
2635        let out = completed(node.run(ctx()).await);
2636        assert_eq!(out.outputs["text"], Value::from("done"));
2637        assert_eq!(*pages.calls.lock().unwrap(), 12);
2638        for (turn, request) in s.model.requests().iter().enumerate() {
2639            let size =
2640                crate::context::estimate_messages(&request.messages) + crate::context::estimate_tools(&request.tools);
2641            assert!(size <= 40_000, "turn {turn}: {size}");
2642            assert_request_pairs(&request.messages);
2643        }
2644        // Old results became placeholders, their calls are still in the conversation.
2645        let last = s.model.requests().pop().unwrap();
2646        let placeholders =
2647            last.messages.iter().filter(|m| m.text().starts_with("[tool result removed to save context")).count();
2648        assert!(placeholders >= 3, "{placeholders}");
2649        assert!(last.messages.iter().any(|m| m.text() == "read the pages"), "nothing was removed, so no note");
2650        let trims = progress_named(&s.events, "context_trimmed");
2651        assert!(!trims.is_empty() && trims.len() < 6, "trimmed in large steps, not on every turn: {}", trims.len());
2652        assert!(trims.iter().all(|trim| trim["reason"] == "budget"));
2653        // The result says so too, not only the events.
2654        let Value::Object(context) = &out.outputs["context"] else { panic!("no context output: {:?}", out.outputs) };
2655        assert!(context["placeholders"].to_json().as_u64().unwrap() >= 3);
2656    }
2657
2658    #[cfg(feature = "context")]
2659    #[tokio::test]
2660    async fn a_window_one_run_learned_is_used_by_the_next_run() {
2661        // One registry for both runs, as a host keeps it.
2662        let (s, pages, _) = page_ctx(6);
2663        let registry = ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>);
2664        let (tools, events) = (Arc::clone(&s.tools), Arc::clone(&s.events));
2665        let ctx = move || {
2666            let mut tool_registry = ToolRegistry::new();
2667            tool_registry.add("math", Arc::clone(&tools) as Arc<dyn ToolRuntime>);
2668            tool_registry.add("web", Arc::clone(&pages) as Arc<dyn ToolRuntime>);
2669            let mut pool = VariablePool::new();
2670            pool.insert("sys", "query", Value::from("read the pages"));
2671            let events = Arc::clone(&events);
2672            NodeContext::for_test("agent", pool)
2673                .with_services(Arc::new(Services::new().with(registry.clone()).with(tool_registry)))
2674                .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
2675        };
2676        s.model.push_error(too_long(20_000, 36_500));
2677        s.model.push(MockModel::text("done"));
2678        completed(page_agent(json!({})).run(ctx()).await);
2679        let first_run = s.model.requests().len();
2680        s.events.lock().unwrap().clear();
2681        // The second run reads as many pages, and no refusal is queued: it
2682        // trims before sending, from what the first run learned.
2683        for n in 1..=6 {
2684            s.model.push(MockModel::tool_calls(&[(&format!("q{n}"), "page", "{}")]));
2685        }
2686        s.model.push(MockModel::text("done again"));
2687        let out = completed(page_agent(json!({})).run(ctx()).await);
2688        assert_eq!(out.outputs["text"], Value::from("done again"));
2689        let requests = s.model.requests();
2690        assert_eq!(requests.len() - first_run, 7, "no request of the second run was refused");
2691        for request in &requests[first_run..] {
2692            let size =
2693                crate::context::estimate_messages(&request.messages) + crate::context::estimate_tools(&request.tools);
2694            assert!(size < 20_000, "{size}");
2695        }
2696        let trims = progress_named(&s.events, "context_trimmed");
2697        assert!(!trims.is_empty() && trims.iter().all(|trim| trim["reason"] == "budget"), "{trims:?}");
2698    }
2699
2700    #[cfg(feature = "context")]
2701    #[tokio::test]
2702    async fn what_the_guard_learned_survives_a_pause() {
2703        let (s, _, ctx) = page_ctx(6);
2704        s.model.push_error(too_long(20_000, 36_500));
2705        s.model.push(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
2706        s.model.push(MockModel::tool_calls(&[("p7", "page", "{}")]));
2707        s.model.push(MockModel::text("done"));
2708        let node = page_agent(json!({"require_approval": ["math/add"]}));
2709        let NodeOutcome::Paused(paused) = node.run(ctx()).await.unwrap() else { panic!("expected pause") };
2710        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
2711        assert_eq!(state["context"]["window"], 20_000);
2712        let trimmed =
2713            ["removed", "placeholders", "cut"].iter().map(|k| state["context"][k].as_u64().unwrap_or(0)).sum::<u64>();
2714        assert!(trimmed > 0, "the refusal trimmed something: {}", state["context"]);
2715        // The call that waits for approval was not trimmed away.
2716        let pending_id = paused.data.get_path(&["calls", "0", "id"]).unwrap().to_text();
2717        assert!(state["messages"].to_string().contains(&format!(r#""id":"{pending_id}""#)));
2718
2719        let resume = Resume { state, input: Some(Value::from_json(json!({"approved": true}))) };
2720        let out = completed(node.run(ctx().with_resume(Some(resume))).await);
2721        assert_eq!(out.outputs["text"], Value::from("done"));
2722        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
2723        // After the resume the loop still knows the window: no request is refused or oversized.
2724        for request in s.model.requests().iter().skip(7) {
2725            assert!(crate::context::estimate_messages(&request.messages) <= 15_000);
2726            assert_request_pairs(&request.messages);
2727        }
2728    }
2729
2730    #[cfg(feature = "context")]
2731    #[tokio::test]
2732    async fn the_note_is_added_to_each_request_once_and_never_stored() {
2733        let (s, _, ctx) = page_ctx(6);
2734        s.model.push_error(too_long(20_000, 36_500));
2735        s.model.push(MockModel::text("Pages one to four were about lorem."));
2736        // Two more tool turns after the trim, then a call that pauses the run.
2737        s.model.push(MockModel::tool_calls(&[("a1", "add", r#"{"a":1,"b":1}"#)]));
2738        s.model.push(MockModel::tool_calls(&[("a2", "add", r#"{"a":2,"b":2}"#)]));
2739        s.model.push(MockModel::tool_calls(&[("c1", "fail", "{}")]));
2740        let node = page_agent(json!({"require_approval": ["math/fail"], "context_window": "summarize"}));
2741        let NodeOutcome::Paused(paused) = node.run(ctx()).await.unwrap() else { panic!("expected pause") };
2742        // Every request after the trim carries the note exactly once, in front of the request.
2743        let requests = s.model.requests();
2744        assert_eq!(requests.len(), 11);
2745        for request in requests.iter().skip(8) {
2746            let text: String = request.messages.iter().map(Message::text).collect();
2747            assert_eq!(text.matches("[Context note").count(), 1);
2748            assert_eq!(text.matches("[End of context note]").count(), 1);
2749            let user = request.messages.iter().find(|m| m.role == Role::User).unwrap().text();
2750            assert!(user.contains("Pages one to four were about lorem.") && user.ends_with("read the pages"));
2751        }
2752        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
2753        // The summary and the count are in the saved state. The note itself is not in any stored message.
2754        assert_eq!(state["context"]["summary"], "Pages one to four were about lorem.");
2755        assert!(state["context"]["removed"].as_u64().unwrap() > 0);
2756        assert!(!state["messages"].to_string().contains("Context note"));
2757
2758        let (s3, _, ctx3) = page_ctx(0);
2759        s3.model.push(MockModel::text("done"));
2760        let resume = Resume { state, input: Some(Value::from_json(json!({"approved": true}))) };
2761        let out = completed(node.run(ctx3().with_resume(Some(resume))).await);
2762        assert_eq!(out.outputs["text"], Value::from("done"));
2763        assert_eq!(out.outputs["context"].get_path(&["summarized"]), Some(Value::Bool(true)));
2764        // After the resume the summary is still what the model is told.
2765        let request = s3.model.requests().pop().unwrap();
2766        let user = request.messages.iter().find(|m| m.role == Role::User).unwrap().text();
2767        assert_eq!(user.matches("Pages one to four were about lorem.").count(), 1);
2768    }
2769
2770    #[cfg(all(feature = "context", feature = "skills"))]
2771    #[test]
2772    fn the_instructions_of_loaded_skills_are_pinned() {
2773        let entry = |id: &str, provider: &str, tool: &str, result: &str, is_error: bool| ToolLogEntry {
2774            id: id.into(),
2775            name: tool.into(),
2776            provider: provider.into(),
2777            tool: tool.into(),
2778            arguments: json!({}),
2779            result: result.into(),
2780            is_error,
2781            images: 0,
2782            ui: Vec::new(),
2783            #[cfg(feature = "tool-files")]
2784            files: Vec::new(),
2785        };
2786        let log = vec![
2787            entry("call_0", SKILL_PROVIDER, LOAD_SKILL_TOOL, "refund rules", false),
2788            entry("call_0", SKILL_PROVIDER, LOAD_SKILL_TOOL, "no such skill", true),
2789            entry("call_0", "web", "page", "a page", false),
2790            entry("call_0", "web", LOAD_SKILL_TOOL, "not a skill", false),
2791            entry("call_1", SKILL_PROVIDER, LOAD_SKILL_TOOL, "shipping rules", false),
2792            // The same skill again: only where it was loaded last.
2793            entry("call_2", SKILL_PROVIDER, LOAD_SKILL_TOOL, "refund rules", false),
2794        ];
2795        let pinned = pinned_results(&log, &[]);
2796        assert_eq!(pinned, [("call_1", "shipping rules".to_owned()), ("call_2", "refund rules".to_owned())]);
2797
2798        // With learned notes the model was shown a sentence more: that is the text to keep.
2799        #[cfg(feature = "learning")]
2800        {
2801            let messages = vec![
2802                Message::tool("call_1", "shipping rules"),
2803                Message::tool("call_2", format!("refund rules{NOTES_STILL_APPLY}")),
2804            ];
2805            let pinned = pinned_results(&log, &messages);
2806            assert_eq!(
2807                pinned,
2808                [("call_1", "shipping rules".to_owned()), ("call_2", format!("refund rules{NOTES_STILL_APPLY}"))]
2809            );
2810            // And the trim leaves exactly that message alone.
2811            let mut conversation = vec![Message::system("s"), Message::user("q")];
2812            for (id, text) in [("call_2", messages[1].text()), ("call_3", "r".repeat(40_000))] {
2813                conversation.push(Message {
2814                    tool_calls: vec![ToolCall { id: id.into(), name: "t".into(), arguments: "{}".into() }],
2815                    ..Message::assistant("")
2816                });
2817                conversation.push(Message::tool(id, text));
2818            }
2819            conversation.push(Message::user("next"));
2820            conversation.push(Message::assistant("ok"));
2821            let borrowed: Vec<(&str, &str)> = pinned.iter().map(|(id, text)| (*id, text.as_str())).collect();
2822            let scope = crate::context::Scope { pinned: &borrowed, tail: 0 };
2823            let keep = crate::context::Keep { tool_results: 0, turns: 1 };
2824            crate::context::trim(&mut conversation, 100, 100, keep, scope);
2825            assert!(conversation.iter().any(|m| m.text() == messages[1].text()), "the loaded skill was trimmed");
2826            assert!(!conversation.iter().any(|m| m.text().len() >= 40_000), "the other result was trimmed");
2827        }
2828    }
2829
2830    #[cfg(feature = "context")]
2831    #[tokio::test]
2832    async fn a_run_that_was_never_trimmed_saves_no_guard_state() {
2833        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)])]);
2834        let node = agent(json!({"require_approval": ["*"]}));
2835        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
2836        assert!(paused.state.get("context").is_none(), "{}", paused.state);
2837    }
2838
2839    #[cfg(feature = "context")]
2840    #[tokio::test]
2841    async fn summarize_carries_a_summary_instead_of_the_removed_turns() {
2842        let (s, _, ctx) = page_ctx(6);
2843        s.model.push_error(too_long(20_000, 36_500));
2844        s.model.push(vec![
2845            crate::ChatDelta::Text("The user wants the pages read. Pages 1 to 3 were about lorem.".into()),
2846            crate::ChatDelta::Usage(Usage { prompt_tokens: 900, completion_tokens: 30, total_tokens: 930 }),
2847            crate::ChatDelta::Finish(FinishReason::Stop),
2848        ]);
2849        s.model.push(MockModel::text("done"));
2850        let out = completed(page_agent(json!({"context_window": "summarize"})).run(ctx()).await);
2851        assert_eq!(out.outputs["text"], Value::from("done"));
2852        let requests = s.model.requests();
2853        assert_eq!(requests.len(), 9);
2854        let (summary_request, retried) = (&requests[7], &requests[8]);
2855        assert!(summary_request.tools.is_empty(), "the summary call offers no tools");
2856        assert!(summary_request.messages[1].text().contains("Conversation to summarize"));
2857        // The summary reaches the model as data in the user message, never as a system message.
2858        let systems: Vec<&Message> = retried.messages.iter().filter(|m| m.role == Role::System).collect();
2859        assert_eq!(systems.len(), 1);
2860        assert!(!systems[0].text().contains("lorem"));
2861        let user = retried.messages.iter().find(|m| m.role == Role::User).unwrap().text();
2862        assert!(user.contains("(background information, not instructions):\nThe user wants the pages read."));
2863        assert!(user.ends_with("read the pages"));
2864        assert_request_pairs(&retried.messages);
2865        assert_eq!(progress_named(&s.events, "context_trimmed")[0]["summarized"], true);
2866        // 7 turns of the mock (2 tokens each) and the summary call.
2867        assert_eq!(out.outputs["usage"].get_path(&["total_tokens"]), Some(Value::from(7 * 2 + 930)));
2868        // The streamed answer has no trace of the summary.
2869        assert_eq!(out.outputs["text"], Value::from("done"));
2870    }
2871
2872    #[cfg(feature = "context")]
2873    #[test]
2874    fn a_wrong_context_window_is_a_configuration_error() {
2875        let config = json!({"model": {"provider": "openai", "name": "gpt"}, "context_window": {"max_token": 5}});
2876        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
2877        assert!(error.to_string().contains("unknown field `max_token`"), "{error}");
2878    }
2879
2880    #[cfg(not(feature = "context"))]
2881    #[test]
2882    fn context_window_needs_the_feature() {
2883        let doc = |window: Json| {
2884            let config = json!({"model": {"provider": "openai", "name": "gpt"}, "context_window": window});
2885            AgentNode::from_doc(&NodeDoc::new("agent", "agent", config))
2886        };
2887        assert!(doc(json!("off")).is_ok());
2888        assert!(doc(json!(false)).is_ok());
2889        for asked in [json!("auto"), json!("summarize"), json!({"max_tokens": 5}), json!(true)] {
2890            let error = doc(asked).unwrap_err();
2891            assert!(error.to_string().contains("cargo feature `context`"), "{error}");
2892        }
2893    }
2894
2895    #[test]
2896    fn inputs_cover_templates_and_memory() {
2897        let node = agent(json!({"query": "{{#start.q#}}", "instruction": "{{#env.persona#}}", "memory": {}}));
2898        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
2899        for expected in ["start.q", "env.persona", "sys.history", "sys.query"] {
2900            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
2901        }
2902    }
2903
2904    #[tokio::test]
2905    async fn unknown_provider_is_fatal() {
2906        let s = setup(vec![]);
2907        let err = agent(json!({"tools": ["nope/x"]})).run(ctx(&s)).await.unwrap_err();
2908        assert!(!err.retryable);
2909        assert_eq!(err.kind, "tool_not_found");
2910    }
2911
2912    #[cfg(not(feature = "learning"))]
2913    #[test]
2914    fn learning_without_learning_support_is_a_configuration_error() {
2915        let doc =
2916            NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "learning": {"agent": "x"}}));
2917        let error = AgentNode::from_doc(&doc).unwrap_err().to_string();
2918        assert!(error.contains("cargo feature `learning`"), "{error}");
2919    }
2920
2921    #[cfg(not(feature = "skills"))]
2922    #[test]
2923    fn listing_skills_without_skill_support_is_a_configuration_error() {
2924        let doc = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "skills": ["report"]}));
2925        let error = AgentNode::from_doc(&doc).unwrap_err().to_string();
2926        assert!(error.contains("cargo feature `skills`"), "{error}");
2927        let empty = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "skills": []}));
2928        assert!(AgentNode::from_doc(&empty).is_ok());
2929    }
2930
2931    #[test]
2932    fn config_validation_and_names() {
2933        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "tools": ["no-slash"]}));
2934        assert!(AgentNode::from_doc(&bad).is_err());
2935        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "max_iterations": 0}));
2936        assert!(AgentNode::from_doc(&bad).is_err());
2937        let mut used = HashSet::new();
2938        assert_eq!(unique_name("search", "web", &mut used), "search");
2939        assert_eq!(unique_name("search", "docs", &mut used), "docs_search");
2940        assert_eq!(unique_name("search", "docs", &mut used), "docs_search_2");
2941        assert_eq!(unique_name("a.b/c", "p", &mut used), "a_b_c");
2942    }
2943
2944    /// Tools: `export {name}` (returns a file), `export_failed {}` (an error that carries one).
2945    #[cfg(feature = "tool-files")]
2946    #[derive(Debug, Default)]
2947    struct ExportTools;
2948
2949    #[cfg(feature = "tool-files")]
2950    fn exported(name: &str) -> Value {
2951        Value::from(graphrt_core::value::File {
2952            marker: true,
2953            name: name.to_owned(),
2954            transfer: graphrt_core::value::FileTransfer::ToolFile,
2955            reference: Some(format!("workspace:outputs/{name}")),
2956            ..Default::default()
2957        })
2958    }
2959
2960    #[cfg(feature = "tool-files")]
2961    impl ToolRuntime for ExportTools {
2962        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
2963            let spec = |name: &str| ToolSpec { name: name.into(), description: "d".into(), parameters: json!({}) };
2964            Box::pin(async move { Ok(vec![spec("export"), spec("export_failed")]) })
2965        }
2966
2967        fn call<'a>(
2968            &'a self,
2969            name: &'a str,
2970            arguments: Json,
2971            _context: &'a ToolCallContext,
2972        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
2973            Box::pin(async move {
2974                let file = exported(arguments["name"].as_str().unwrap_or("out.csv"));
2975                let data = Value::object([("file", file)]);
2976                Ok(match name {
2977                    "export" => ToolOutput { text: "written".into(), data, ..ToolOutput::default() },
2978                    _ => ToolOutput { text: "disk full".into(), data, is_error: true, ..ToolOutput::default() },
2979                })
2980            })
2981        }
2982    }
2983
2984    #[cfg(feature = "tool-files")]
2985    fn export_ctx(s: &Setup) -> NodeContext {
2986        let mut registry = ToolRegistry::new();
2987        registry.add("export", Arc::new(ExportTools) as Arc<dyn ToolRuntime>);
2988        let services = Services::new()
2989            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
2990            .with(registry);
2991        let mut pool = VariablePool::new();
2992        pool.insert("sys", "query", Value::from("export the report"));
2993        NodeContext::for_test("agent", pool).with_services(Arc::new(services))
2994    }
2995
2996    #[cfg(feature = "tool-files")]
2997    #[tokio::test]
2998    async fn files_returned_by_tools_become_the_files_output() {
2999        let s = setup(vec![
3000            MockModel::tool_calls(&[
3001                ("c1", "export", r#"{"name":"a.csv"}"#),
3002                ("c2", "export", r#"{"name":"b.md"}"#),
3003                ("c3", "export_failed", r#"{"name":"lost.txt"}"#),
3004            ]),
3005            // The same file again: it is listed once, in its last position.
3006            MockModel::tool_calls(&[("c4", "export", r#"{"name":"a.csv"}"#)]),
3007            MockModel::text("done"),
3008        ]);
3009        let out = completed(agent(json!({"tools": ["export/*"]})).run(export_ctx(&s)).await);
3010        let files = out.outputs["files"].as_array().unwrap().to_vec();
3011        let names: Vec<&str> = files.iter().map(|f| f.as_file().unwrap().name.as_str()).collect();
3012        assert_eq!(names, ["b.md", "a.csv"]);
3013        assert_eq!(files[0].as_file().unwrap().reference.as_deref(), Some("workspace:outputs/b.md"));
3014        // The model saw the tool's text only: no file object, no reference.
3015        let seen = serde_json::to_string(&s.model.requests()[1].messages).unwrap();
3016        assert!(seen.contains("written") && !seen.contains("workspace:"), "{seen}");
3017    }
3018
3019    #[cfg(feature = "tool-files")]
3020    #[tokio::test]
3021    async fn an_agent_without_file_tools_has_an_empty_files_output() {
3022        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")]);
3023        let out = completed(agent(json!({})).run(ctx(&s)).await);
3024        assert_eq!(out.outputs["files"], Value::array([]));
3025    }
3026
3027    #[cfg(feature = "tool-files")]
3028    #[tokio::test]
3029    async fn files_survive_a_pause_for_approval() {
3030        let s = setup(vec![
3031            MockModel::tool_calls(&[("c1", "export", r#"{"name":"a.csv"}"#)]),
3032            MockModel::tool_calls(&[("c2", "export_failed", "{}")]),
3033            MockModel::text("done"),
3034        ]);
3035        let node = agent(json!({"tools": ["export/*"], "require_approval": ["export/export_failed"]}));
3036        let NodeOutcome::Paused(pause) = node.run(export_ctx(&s)).await.unwrap() else { panic!("expected a pause") };
3037        // The saved state is JSON: the file must come back as a file after resuming.
3038        let state = serde_json::from_str::<Json>(&serde_json::to_string(&pause.state).unwrap()).unwrap();
3039        let input = Some(Value::from_json(json!({"approved": true})));
3040        let resumed = export_ctx(&s).with_resume(Some(Resume { state, input }));
3041        let out = completed(node.run(resumed).await);
3042        let files = out.outputs["files"].as_array().unwrap().to_vec();
3043        assert_eq!(files.len(), 1);
3044        assert_eq!(files[0].as_file().unwrap().name, "a.csv");
3045    }
3046}