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    /// Notes the agent saves and finds again in later runs: `auto`, `off` or
232    /// `{agent, user, recall, write}` (see `crate::memory`). Needs the cargo
233    /// feature `memory` and a `graphrt_core::memory::Memories` service. Kept as
234    /// raw JSON, like `learning`.
235    #[serde(default)]
236    pub long_term_memory: Option<Json>,
237    /// Workflows the model may start as child runs: `[{workflow, description,
238    /// handoff?}]` (see `crate::subagents`). Needs the cargo feature
239    /// `subagents` and a host that links the workflows. Raw JSON, like `learning`.
240    #[serde(default)]
241    pub subagents: Option<Json>,
242    /// Child runs at the same time (default 4).
243    #[serde(default)]
244    pub max_parallel_subagents: Option<usize>,
245    /// Child runs in one run of this node (default 16).
246    #[serde(default)]
247    pub max_subagent_calls: Option<usize>,
248    /// Tools called again when an attempt was cut while they ran (a retry, a
249    /// resumed preempt): `provider/name`, the name the model sees, `provider/*`
250    /// or `*`. The recall of the agent's own memory and the skill tools are
251    /// always. Any other cut call is not repeated.
252    #[serde(default)]
253    pub retry_safe_tools: Vec<String>,
254}
255
256/// `learning` of the `agent` node: whose lessons a run reads.
257#[cfg(feature = "learning")]
258#[derive(Clone, Debug)]
259struct Learning {
260    /// The agent the lessons belong to.
261    agent: String,
262    /// The user the run is for (a template, for example `{{#sys.user_id#}}`).
263    /// Lessons of that user are added to the lessons of the agent as a whole.
264    /// Without it, or when it renders empty, only the agent's lessons are read.
265    user: Option<Template>,
266}
267
268/// Parse `learning`: `{agent: <name>, user?: <template>}`. Any other key is an
269/// error, so a misspelled `user` cannot silently widen what a run reads.
270#[cfg(feature = "learning")]
271fn parse_learning(doc: &NodeDoc, raw: Option<&Json>) -> Result<Option<Learning>, ConfigError> {
272    let Some(raw) = raw.filter(|raw| !raw.is_null()) else { return Ok(None) };
273    let invalid = |why: &str| ConfigError::new(doc, format!("learning: {why}"));
274    let fields = raw.as_object().ok_or_else(|| invalid("expected `{agent, user}`"))?;
275    if let Some(unknown) = fields.keys().find(|key| !matches!(key.as_str(), "agent" | "user")) {
276        return Err(invalid(&format!("unknown field `{unknown}`")));
277    }
278    let agent = fields.get("agent").and_then(Json::as_str).filter(|agent| !agent.is_empty());
279    let agent = agent.ok_or_else(|| invalid("`agent` must be the name of the agent the lessons belong to"))?;
280    let user = match fields.get("user") {
281        None | Some(Json::Null) => None,
282        Some(Json::String(template)) => Some(Template::parse(template)),
283        Some(_) => return Err(invalid("`user` must be a template string")),
284    };
285    Ok(Some(Learning { agent: agent.to_owned(), user }))
286}
287
288/// A tool bound for one run.
289#[derive(Clone, Debug)]
290struct BoundTool {
291    /// Name exposed to the model (unique, provider-safe characters).
292    exposed: String,
293    provider: String,
294    name: String,
295    runtime: Arc<dyn ToolRuntime>,
296    spec: ToolSpec,
297    /// Rendered `tool_context` of the provider, shared by its tools.
298    context: Option<Arc<ToolCallContext>>,
299    /// Skills that grant this tool. Empty for the agent's own tools. Otherwise
300    /// the tool is offered only once one of these skills was loaded in the run.
301    #[cfg(feature = "skills")]
302    gates: Vec<String>,
303    /// A skill grant that asks first: every call waits for approval.
304    #[cfg(feature = "skills")]
305    ask: bool,
306    /// One of the skill tools themselves (never set for a registry provider,
307    /// whatever its name), so only they can mark a skill as loaded.
308    #[cfg(feature = "skills")]
309    skill_tool: bool,
310}
311
312impl BoundTool {
313    fn context(&self) -> &ToolCallContext {
314        self.context.as_deref().unwrap_or(ToolCallContext::empty())
315    }
316
317    /// The same tool was selected a second time.
318    ///
319    /// A tool the agent lists itself stays as the agent configured it. A tool
320    /// granted by several skills opens with any of them and asks first if any
321    /// of the grants does.
322    #[cfg_attr(not(feature = "skills"), allow(clippy::unused_self, clippy::needless_pass_by_ref_mut))]
323    fn bound_again(&mut self, origin: Origin<'_>) {
324        #[cfg(feature = "skills")]
325        if let (false, Origin::Grant(grant)) = (self.gates.is_empty(), origin) {
326            self.gates.push(grant.skill.clone());
327            self.ask |= grant.ask;
328        }
329        #[cfg(not(feature = "skills"))]
330        let _ = origin;
331    }
332
333    /// Whether the model may see and call this tool given the skills loaded so far.
334    #[cfg(feature = "skills")]
335    fn offered(&self, state: &AgentState) -> bool {
336        self.gates.is_empty() || self.gates.iter().any(|gate| state.loaded_skills.contains(gate))
337    }
338
339    /// Without skill support every bound tool is one of the agent's own.
340    #[cfg(not(feature = "skills"))]
341    #[allow(clippy::unused_self)]
342    fn offered(&self, _state: &AgentState) -> bool {
343        true
344    }
345
346    /// Whether a skill grant makes every call of this tool wait for approval.
347    #[cfg(feature = "skills")]
348    fn asks_first(&self) -> bool {
349        self.ask
350    }
351
352    #[cfg(not(feature = "skills"))]
353    #[allow(clippy::unused_self)]
354    fn asks_first(&self) -> bool {
355        false
356    }
357}
358
359/// The tools of one run, with what came with them.
360#[derive(Default)]
361struct BoundTools {
362    tools: Vec<BoundTool>,
363    /// The skill catalog for the system prompt (empty without skills).
364    catalog: String,
365    #[cfg(feature = "memory")]
366    memory: crate::memory::RunMemory,
367}
368
369/// Where a tool being bound comes from.
370#[derive(Clone, Copy)]
371enum Origin<'a> {
372    /// Listed in the agent's own `tools`.
373    Agent,
374    /// One of the skill tools (`load_skill`, `read_skill_file`).
375    #[cfg(feature = "skills")]
376    SkillTool,
377    /// Granted to a skill by the owner.
378    #[cfg(feature = "skills")]
379    Grant(&'a SkillToolGrant),
380    /// Keeps the lifetime in use in builds without skills.
381    #[cfg(not(feature = "skills"))]
382    #[allow(dead_code)]
383    Unused(std::marker::PhantomData<&'a ()>),
384}
385
386/// Collects the tools of one run, giving each a unique exposed name.
387#[derive(Default)]
388struct Binder {
389    listings: HashMap<String, Vec<ToolSpec>>,
390    bound: Vec<BoundTool>,
391    used: HashSet<String>,
392}
393
394impl Binder {
395    /// Bind `name` (or `*`) of a registry provider, listing the provider once.
396    async fn bind_registered(
397        &mut self,
398        provider: &str,
399        name: &str,
400        runtime: &Arc<dyn ToolRuntime>,
401        origin: Origin<'_>,
402    ) -> Result<(), NodeError> {
403        // The listing is taken out while it is read, so binding can borrow `self`.
404        let specs = match self.listings.remove(provider) {
405            Some(specs) => specs,
406            None => runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?,
407        };
408        let result = self.bind_specs(provider, name, &specs, runtime, origin);
409        self.listings.insert(provider.to_owned(), specs);
410        result
411    }
412
413    fn bind_specs(
414        &mut self,
415        provider: &str,
416        name: &str,
417        specs: &[ToolSpec],
418        runtime: &Arc<dyn ToolRuntime>,
419        origin: Origin<'_>,
420    ) -> Result<(), NodeError> {
421        for spec in select_specs(specs, provider, name)? {
422            if let Some(existing) = self.bound.iter_mut().find(|b| b.provider == provider && b.name == spec.name) {
423                existing.bound_again(origin);
424                continue;
425            }
426            let exposed = unique_name(&spec.name, provider, &mut self.used);
427            #[cfg(feature = "skills")]
428            let (gates, ask) = match origin {
429                Origin::Grant(grant) => (vec![grant.skill.clone()], grant.ask),
430                Origin::Agent | Origin::SkillTool => (Vec::new(), false),
431            };
432            self.bound.push(BoundTool {
433                exposed: exposed.clone(),
434                provider: provider.to_owned(),
435                name: spec.name.clone(),
436                runtime: Arc::clone(runtime),
437                spec: ToolSpec {
438                    name: exposed,
439                    description: spec.description.clone(),
440                    parameters: spec.parameters.clone(),
441                },
442                context: None,
443                #[cfg(feature = "skills")]
444                gates,
445                #[cfg(feature = "skills")]
446                ask,
447                #[cfg(feature = "skills")]
448                skill_tool: matches!(origin, Origin::SkillTool),
449            });
450        }
451        Ok(())
452    }
453}
454
455/// One executed (or rejected) tool call.
456#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
457struct ToolLogEntry {
458    id: String,
459    name: String,
460    provider: String,
461    tool: String,
462    /// Parsed arguments, or the raw text when the model sent malformed JSON.
463    arguments: Json,
464    result: String,
465    is_error: bool,
466    /// Images sent to the model with the result.
467    #[serde(default)]
468    images: usize,
469    /// UI blocks in the tool's structured result (see [`graphrt_core::ui`]), for the host.
470    #[serde(default, skip_serializing_if = "Vec::is_empty")]
471    ui: Vec<Json>,
472    /// Files in the tool's structured result (see [`collect_files`]), for the host.
473    #[cfg(feature = "tool-files")]
474    #[serde(default, skip_serializing_if = "Vec::is_empty")]
475    files: Vec<Json>,
476}
477
478/// Persistable loop state, used to pause for tool approval.
479#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
480struct AgentState {
481    messages: Vec<Message>,
482    iteration: u32,
483    log: Vec<ToolLogEntry>,
484    usage: Usage,
485    /// Calls awaiting approval.
486    pending: Vec<ToolCall>,
487    /// Tools already asked once to be called again with their required arguments.
488    #[serde(default, skip_serializing_if = "Vec::is_empty")]
489    reasked: Vec<String>,
490    /// Answer text streamed so far (preambles of tool-calling turns).
491    #[serde(default, skip_serializing_if = "String::is_empty")]
492    answer: String,
493    /// Skills loaded in this run: their granted tools are offered to the model.
494    #[cfg(feature = "skills")]
495    #[serde(default, skip_serializing_if = "Vec::is_empty")]
496    loaded_skills: Vec<String>,
497    /// This run reads learned notes: a skill it loads is told they still apply.
498    #[cfg(all(feature = "skills", feature = "learning"))]
499    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
500    has_notes: bool,
501    /// What the context guard learned and removed in this run.
502    #[cfg(feature = "context")]
503    #[serde(default, skip_serializing_if = "ContextState::is_empty")]
504    context: ContextState,
505    /// The memory of this node run: attached again on resume, never saved.
506    #[cfg(feature = "memory")]
507    #[serde(skip)]
508    memory: crate::memory::RunMemory,
509    /// Child runs of `subagents`: how many were started, those that wait.
510    #[cfg(feature = "subagents")]
511    #[serde(default, skip_serializing_if = "crate::subagents::ChildState::is_empty")]
512    children: crate::subagents::ChildState,
513    /// Calls running when the checkpoint was kept: an attempt that restores
514    /// it does not know their outcome.
515    #[serde(default, skip_serializing_if = "Vec::is_empty")]
516    started: Vec<ToolCall>,
517    /// Calls of the turn that had not started yet (one after another, or
518    /// children after the plain calls): an attempt that restores runs them.
519    #[serde(default, skip_serializing_if = "Vec::is_empty")]
520    queued: Vec<ToolCall>,
521    /// Tokens and cost of the last model turn, to tell whether the budget
522    /// affords another one.
523    #[serde(default, skip_serializing_if = "is_zero")]
524    last_turn_tokens: u64,
525    #[serde(default, skip_serializing_if = "is_zero")]
526    last_turn_cost: u64,
527    /// A mark of the start over that happened because the checkpoint of an
528    /// earlier attempt could not be read: it is in the idempotency keys, so
529    /// the new turns' calls never take the keys of the earlier ones.
530    #[serde(default, skip_serializing_if = "Option::is_none")]
531    restart: Option<String>,
532    /// The mark of a start over that applies once the approved calls of the
533    /// resume ran (they keep the keys they had).
534    #[serde(default, skip_serializing_if = "Option::is_none")]
535    restart_next: Option<String>,
536    /// The run was told once that this model has no price.
537    #[serde(skip)]
538    price_reported: bool,
539}
540
541#[allow(clippy::trivially_copy_pass_by_ref)]
542fn is_zero(value: &u64) -> bool {
543    *value == 0
544}
545
546/// Why the loop ended.
547#[derive(Clone, Debug, PartialEq, Eq)]
548enum StopReason {
549    /// The model answered without calling tools.
550    Completed,
551    /// The iteration limit forced a final answer without tools.
552    MaxIterations,
553    /// The final answer was cut off by the output token limit.
554    Length,
555    /// The provider ended the turn with a reason graphrt does not recognize.
556    Unrecognized(String),
557    /// A `subagents` entry with `handoff: true` answered for this agent.
558    #[cfg(feature = "subagents")]
559    Handoff,
560    /// The run's token or cost budget did not afford another tool turn: the
561    /// last turn answered without tools.
562    Budget,
563}
564
565impl StopReason {
566    fn as_str(&self) -> String {
567        match self {
568            StopReason::Completed => "completed".into(),
569            StopReason::MaxIterations => "max_iterations".into(),
570            StopReason::Length => "length".into(),
571            StopReason::Unrecognized(reason) => format!("finish:{reason}"),
572            #[cfg(feature = "subagents")]
573            StopReason::Handoff => "handoff".into(),
574            StopReason::Budget => "budget".into(),
575        }
576    }
577}
578
579/// The `agent` node.
580#[derive(Debug)]
581pub struct AgentNode {
582    config: AgentConfig,
583    refs: Vec<(String, String)>,
584    /// Parsed `tool_context`.
585    tool_context: Vec<ProviderContext>,
586    /// Parsed `learning`.
587    #[cfg(feature = "learning")]
588    learning: Option<Learning>,
589    /// Parsed `context_window`.
590    #[cfg(feature = "context")]
591    context: ContextWindow,
592    /// Parsed `long_term_memory`.
593    #[cfg(feature = "memory")]
594    memory: Option<crate::memory::LongTermMemory>,
595    /// Parsed `subagents`.
596    #[cfg(feature = "subagents")]
597    subagents: Option<crate::subagents::Subagents>,
598}
599
600/// Whether `context_window` asks for the guard, which this build does not have.
601#[cfg(not(feature = "context"))]
602pub(crate) fn asks_for_context_guard(raw: Option<&Json>) -> bool {
603    !matches!(raw, None | Some(Json::Null | Json::Bool(false))) && raw.and_then(Json::as_str) != Some("off")
604}
605
606/// One provider's `tool_context`: provider name and `(name, template)` pairs.
607type ProviderContext = (String, Vec<(String, Template)>);
608
609/// Parse `tool_context`: every provider must appear in `tools`, every value
610/// must be a non-empty name mapped to a template string.
611fn parse_tool_context(
612    doc: &NodeDoc,
613    raw: &serde_json::Map<String, Json>,
614    refs: &[(String, String)],
615) -> Result<Vec<ProviderContext>, ConfigError> {
616    let mut parsed = Vec::with_capacity(raw.len());
617    for (provider, values) in raw {
618        if !refs.iter().any(|(p, _)| p == provider) {
619            return Err(ConfigError::new(
620                doc,
621                format!("tool_context provider `{provider}` is not used by any entry of `tools`"),
622            ));
623        }
624        let Json::Object(values) = values else {
625            return Err(ConfigError::new(doc, format!("tool_context `{provider}` must map names to templates")));
626        };
627        let mut templates = Vec::with_capacity(values.len());
628        for (name, value) in values {
629            let (false, Json::String(text)) = (name.is_empty(), value) else {
630                return Err(ConfigError::new(
631                    doc,
632                    format!("tool_context `{provider}.{name}` must be a non-empty name with a template string"),
633                ));
634            };
635            templates.push((name.clone(), Template::parse(text)));
636        }
637        parsed.push((provider.clone(), templates));
638    }
639    Ok(parsed)
640}
641
642impl AgentNode {
643    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
644        let config: AgentConfig = parse_config(doc)?;
645        if config.max_iterations == 0 || config.max_iterations > MAX_ITERATIONS_LIMIT {
646            return Err(ConfigError::new(doc, format!("max_iterations must be between 1 and {MAX_ITERATIONS_LIMIT}")));
647        }
648        let refs = config
649            .tools
650            .iter()
651            .map(|r| {
652                r.split()
653                    .ok_or_else(|| ConfigError::new(doc, format!("invalid tool reference {r:?}; use `provider/name`")))
654            })
655            .collect::<Result<Vec<_>, _>>()?;
656        let tool_context = parse_tool_context(doc, &config.tool_context, &refs)?;
657        // Without the feature the field is still read, so that a workflow that
658        // relies on skills fails here instead of running without them.
659        #[cfg(not(feature = "skills"))]
660        if !config.skills.is_empty() {
661            return Err(ConfigError::new(doc, "`skills` needs a build with skill support (cargo feature `skills`)"));
662        }
663        #[cfg(not(feature = "learning"))]
664        if config.learning.is_some() {
665            return Err(ConfigError::new(
666                doc,
667                "`learning` needs a build with self learning support (cargo feature `learning`)",
668            ));
669        }
670        #[cfg(feature = "learning")]
671        let learning = parse_learning(doc, config.learning.as_ref())?;
672        #[cfg(not(feature = "context"))]
673        if asks_for_context_guard(config.context_window.as_ref()) {
674            return Err(ConfigError::new(
675                doc,
676                "`context_window` needs a build with the context guard (cargo feature `context`)",
677            ));
678        }
679        #[cfg(feature = "context")]
680        let context = ContextWindow::parse(doc, config.context_window.as_ref())?;
681        #[cfg(not(feature = "memory"))]
682        if !matches!(config.long_term_memory, None | Some(Json::Null | Json::Bool(false)))
683            && config.long_term_memory.as_ref().and_then(Json::as_str) != Some("off")
684        {
685            return Err(ConfigError::new(
686                doc,
687                "`long_term_memory` needs a build with memory support (cargo feature `memory`)",
688            ));
689        }
690        #[cfg(feature = "memory")]
691        let memory = crate::memory::parse(doc, config.long_term_memory.as_ref())?;
692        #[cfg(feature = "memory")]
693        if memory.is_some() && refs.iter().any(|(provider, _)| provider == crate::memory::MEMORY_PROVIDER) {
694            return Err(ConfigError::new(
695                doc,
696                "an agent with `long_term_memory` cannot also list tools of a provider named `memory`",
697            ));
698        }
699        #[cfg(not(feature = "subagents"))]
700        if config.subagents.as_ref().and_then(Json::as_array).is_some_and(|list| !list.is_empty()) {
701            return Err(ConfigError::new(doc, "`subagents` needs a build with subagents (cargo feature `subagents`)"));
702        }
703        #[cfg(feature = "subagents")]
704        let subagents = crate::subagents::parse(
705            doc,
706            config.subagents.as_ref(),
707            config.max_parallel_subagents,
708            config.max_subagent_calls,
709        )?;
710        #[cfg(feature = "subagents")]
711        if subagents.is_some() && refs.iter().any(|(provider, _)| provider == crate::subagents::SUBAGENT_PROVIDER) {
712            return Err(ConfigError::new(
713                doc,
714                "an agent with `subagents` cannot also list tools of a provider named `subagents`",
715            ));
716        }
717        Ok(Self {
718            config,
719            refs,
720            tool_context,
721            #[cfg(feature = "learning")]
722            learning,
723            #[cfg(feature = "context")]
724            context,
725            #[cfg(feature = "memory")]
726            memory,
727            #[cfg(feature = "subagents")]
728            subagents,
729        })
730    }
731
732    /// Resolve tool references against the registry and attach the agent's
733    /// skills, assigning unique exposed names. Returns the tools and the skill
734    /// catalog for the system prompt (empty without skills).
735    async fn bind_tools(&self, ctx: &NodeContext) -> Result<BoundTools, NodeError> {
736        #[cfg(feature = "memory")]
737        let with_memory = self.memory.is_some();
738        #[cfg(not(feature = "memory"))]
739        let with_memory = false;
740        #[cfg(feature = "subagents")]
741        let with_children = self.subagents.is_some();
742        #[cfg(not(feature = "subagents"))]
743        let with_children = false;
744        if self.refs.is_empty() && self.config.skills.is_empty() && !with_memory && !with_children {
745            return Ok(BoundTools::default());
746        }
747        let mut binder = Binder::default();
748        if !self.refs.is_empty() {
749            let registry = ctx.require_service::<ToolRegistry>("tool registry (graphrt_core::tool::ToolRegistry)")?;
750            for (provider, name) in &self.refs {
751                let runtime = registry
752                    .get(provider)
753                    .cloned()
754                    .ok_or_else(|| NodeError::fatal("tool_not_found", format!("unknown tool provider `{provider}`")))?;
755                binder.bind_registered(provider, name, &runtime, Origin::Agent).await?;
756            }
757        }
758        #[cfg(feature = "skills")]
759        let catalog = self.attach_skills(ctx, &mut binder).await?;
760        #[cfg(not(feature = "skills"))]
761        let catalog = String::new();
762        #[cfg(feature = "memory")]
763        let memory = match &self.memory {
764            Some(config) => {
765                let (memory, runtime) = crate::memory::RunMemory::attach(ctx, config, &self.config.model)?;
766                let specs = runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?;
767                binder.bind_specs(crate::memory::MEMORY_PROVIDER, "*", &specs, &runtime, Origin::Agent)?;
768                memory
769            }
770            None => crate::memory::RunMemory::default(),
771        };
772        #[cfg(feature = "subagents")]
773        if let Some(config) = &self.subagents {
774            let specs = crate::subagents::specs(ctx, config)?;
775            let runtime: Arc<dyn ToolRuntime> = Arc::new(crate::subagents::NotDirectly);
776            binder.bind_specs(crate::subagents::SUBAGENT_PROVIDER, "*", &specs, &runtime, Origin::Agent)?;
777        }
778        let mut bound = binder.bound;
779        self.attach_tool_context(ctx, &mut bound)?;
780        #[cfg(feature = "memory")]
781        {
782            let names: Vec<(String, String)> = bound
783                .iter()
784                .filter(|b| b.provider == crate::memory::MEMORY_PROVIDER)
785                .map(|b| (b.exposed.clone(), b.name.clone()))
786                .collect();
787            let secrets: Vec<String> =
788                bound.iter().filter_map(|b| b.context.as_ref()).flat_map(|c| c.secrets.values().cloned()).collect();
789            memory.bound(names, secrets);
790        }
791        Ok(BoundTools {
792            tools: bound,
793            catalog,
794            #[cfg(feature = "memory")]
795            memory,
796        })
797    }
798
799    /// Attach the skills of `skills`: bind the skill tools and the tools the
800    /// owner granted to each skill. Returns the catalog for the system prompt.
801    ///
802    /// A granted tool that is not available in this host (its plugin was
803    /// removed, say) is left out and reported as `skill_tool_unavailable`: the
804    /// skill still loads, it just cannot use that tool.
805    #[cfg(feature = "skills")]
806    async fn attach_skills(&self, ctx: &NodeContext, binder: &mut Binder) -> Result<String, NodeError> {
807        if self.config.skills.is_empty() {
808            return Ok(String::new());
809        }
810        let skills = ctx.require_service::<Skills>("skill source (graphrt_core::skill::Skills)")?;
811        let attached =
812            skills.0.attach(&self.config.skills).await.map_err(|e| NodeError::fatal(e.kind, e.to_string()))?;
813        if attached.is_empty() {
814            return Ok(String::new());
815        }
816        if binder.bound.iter().any(|b| b.provider == SKILL_PROVIDER) {
817            return Err(NodeError::fatal(
818                "skill_provider_conflict",
819                format!("an agent that uses skills cannot also list tools of a provider named `{SKILL_PROVIDER}`"),
820            ));
821        }
822        let specs = attached.runtime.list().await.map_err(|e| NodeError::new("tool", e.to_string()))?;
823        binder.bind_specs(SKILL_PROVIDER, "*", &specs, &attached.runtime, Origin::SkillTool)?;
824        let registry = ctx.service::<ToolRegistry>();
825        for grant in &attached.grants {
826            // The name the agent's own workflows are bound under is never granted.
827            #[cfg(feature = "subagents")]
828            if grant.provider == crate::subagents::SUBAGENT_PROVIDER {
829                ctx.progress(
830                    "skill_tool_unavailable",
831                    Value::from_json(
832                        json!({"skill": grant.skill, "tool": format!("{}/{}", grant.provider, grant.tool)}),
833                    ),
834                );
835                continue;
836            }
837            let bound = match registry.and_then(|r| r.get(&grant.provider)) {
838                Some(runtime) => {
839                    binder.bind_registered(&grant.provider, &grant.tool, runtime, Origin::Grant(grant)).await.is_ok()
840                }
841                None => false,
842            };
843            if !bound {
844                ctx.progress(
845                    "skill_tool_unavailable",
846                    Value::from_json(json!({
847                        "skill": grant.skill, "tool": format!("{}/{}", grant.provider, grant.tool),
848                    })),
849                );
850            }
851        }
852        Ok(attached.catalog)
853    }
854
855    /// Render `tool_context` (secrets exposed) for each configured provider and
856    /// share it with that provider's bound tools. Fails when a provider does not
857    /// accept secrets: silently dropping the values would hide a misconfiguration.
858    fn attach_tool_context(&self, ctx: &NodeContext, bound: &mut [BoundTool]) -> Result<(), NodeError> {
859        for (provider, templates) in &self.tool_context {
860            let Some(first) = bound.iter().find(|b| &b.provider == provider) else { continue };
861            if !first.runtime.accepts_secrets() {
862                return Err(NodeError::fatal(
863                    "tool_context_denied",
864                    format!(
865                        "tool provider `{provider}` does not accept a tool context (a plugin needs \
866                         `permissions.secrets` and must be trusted, e.g. `--trust-plugin {provider}`)"
867                    ),
868                ));
869            }
870            let mut context = ToolCallContext::default();
871            for (name, template) in templates {
872                let value = template.render_exposed(&ctx.pool);
873                // A missing variable renders empty: leave the name out so the tool can refuse.
874                if value.is_empty() {
875                    continue;
876                }
877                ctx.observe_secret(&value);
878                context.secrets.insert(name.clone(), value);
879            }
880            let context = Arc::new(context);
881            for tool in bound.iter_mut().filter(|b| &b.provider == provider) {
882                tool.context = Some(Arc::clone(&context));
883            }
884        }
885        Ok(())
886    }
887
888    fn needs_approval(&self, tool: &BoundTool) -> bool {
889        tool.asks_first()
890            || self.config.require_approval.iter().any(|r| {
891                r == "*" || *r == tool.exposed || *r == tool.name || *r == format!("{}/{}", tool.provider, tool.name)
892            })
893    }
894
895    fn call_needs_approval(&self, tools: &[BoundTool], call: &ToolCall) -> bool {
896        bound_tool(tools, call).is_some_and(|t| self.needs_approval(t))
897    }
898
899    /// Whether a call cut while it ran may be made again: a read only built in
900    /// tool, or one the owner listed in `retry_safe_tools`.
901    fn retry_safe(&self, tool: &BoundTool) -> bool {
902        // Read only tools of this crate, known by where they come from: the
903        // recall of the agent's own memory (a reserved provider) and the skill
904        // tools. Registry providers are trusted by the owner's list only.
905        #[allow(unused_mut)]
906        let mut read_only = false;
907        #[cfg(feature = "memory")]
908        {
909            read_only |= tool.provider == crate::memory::MEMORY_PROVIDER && tool.name == "recall";
910        }
911        #[cfg(feature = "skills")]
912        {
913            read_only |= tool.skill_tool;
914        }
915        read_only
916            || self.config.retry_safe_tools.iter().any(|r| {
917                r == "*"
918                    || *r == tool.exposed
919                    || *r == format!("{}/{}", tool.provider, tool.name)
920                    || *r == format!("{}/*", tool.provider)
921            })
922    }
923
924    /// Keep `state` as the checkpoint of this execution (nothing outside an
925    /// engine). A state that cannot be encoded is not kept: the next attempt
926    /// then starts over, as before checkpoints.
927    fn save(ctx: &NodeContext, state: &AgentState) {
928        if !ctx.keeps_checkpoints() {
929            return;
930        }
931        match serde_json::to_value(state) {
932            Ok(value) => ctx.checkpoint(value),
933            Err(error) => {
934                eprintln!("agent {}: checkpoint not kept: {error}", ctx.node_id);
935                ctx.progress("checkpoint_skipped", Value::from_json(json!({"error": error.to_string()})));
936            }
937        }
938    }
939
940    /// The calls an interrupted attempt had started: a safe one runs again, one
941    /// that needs approval waits for it again, any other gets a result saying
942    /// it was not repeated.
943    async fn settle_interrupted(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool]) {
944        let started = std::mem::take(&mut state.started);
945        // Calls that never started run now, as they would have.
946        let mut again = std::mem::take(&mut state.queued);
947        if started.is_empty() && again.is_empty() {
948            return;
949        }
950        for call in started {
951            let tool = bound_tool(tools, &call);
952            ctx.progress("tool_interrupted", Value::from_json(json!({"id": call.id, "name": call.name})));
953            if tool.is_some_and(|t| self.needs_approval(t)) {
954                state.pending.push(call);
955            } else if tool.is_some_and(|t| self.retry_safe(t)) {
956                again.push(call);
957            } else {
958                let message = "interrupted: this call was started and its outcome is unknown. It was not repeated.";
959                self.record(state, tools, &call, ToolOutput::error(message));
960            }
961        }
962        // In the order the model made them (a few calls: a plain pass, no sort).
963        let order: Vec<String> = state
964            .messages
965            .iter()
966            .rev()
967            .find(|m| !m.tool_calls.is_empty())
968            .map(|m| m.tool_calls.iter().map(|c| c.id.clone()).collect())
969            .unwrap_or_default();
970        let mut ordered = Vec::with_capacity(again.len());
971        for id in &order {
972            if let Some(at) = again.iter().position(|call| call.id == *id) {
973                ordered.push(again.swap_remove(at));
974            }
975        }
976        ordered.append(&mut again);
977        self.run_calls(ctx, state, tools, ordered).await;
978    }
979
980    /// The cost of `usage` in micro units at the price the providers file
981    /// gives this agent's model, 0 without one.
982    fn cost_of(&self, ctx: &NodeContext, state: &mut AgentState, usage: &Usage) -> u64 {
983        let model = &self.config.model;
984        crate::nodes::common::price_of(ctx, model, usage).unwrap_or_else(|| {
985            if !state.price_reported {
986                state.price_reported = crate::nodes::common::report_missing_price(ctx, model);
987            }
988            0
989        })
990    }
991
992    /// Whether the run's budget affords another tool turn like the last one
993    /// and the answer after it (two such turns).
994    fn budget_affords_another_turn(ctx: &NodeContext, state: &AgentState) -> bool {
995        let Some(budget) = ctx.budget() else { return true };
996        let tokens = budget.remaining_tokens().is_none_or(|left| left > state.last_turn_tokens.saturating_mul(2));
997        let cost = budget.remaining_cost_micros().is_none_or(|left| left > state.last_turn_cost.saturating_mul(2));
998        tokens && cost
999    }
1000
1001    /// The approved lessons this run reads, as a section for the system
1002    /// prompt (empty without `learning` or without lessons).
1003    #[cfg(feature = "learning")]
1004    async fn lesson_notes(&self, ctx: &NodeContext) -> Result<String, NodeError> {
1005        let Some(learning) = &self.learning else { return Ok(String::new()) };
1006        let lessons = ctx.require_service::<Lessons>("lesson source (graphrt_core::learning::Lessons)")?;
1007        let user = learning.user.as_ref().map(|user| user.render(&ctx.pool)).filter(|user| !user.trim().is_empty());
1008        let scope = LessonScope { agent: learning.agent.clone(), user };
1009        let notes = lessons.0.notes(&scope).await.map_err(|e| NodeError::fatal(e.kind, e.to_string()))?;
1010        if !notes.is_empty() {
1011            ctx.progress("lessons_applied", Value::from_json(json!({"agent": scope.agent, "ids": notes.ids})));
1012        }
1013        Ok(notes.text)
1014    }
1015
1016    /// The conversation a run starts with. Each of `sections` (the skill
1017    /// catalog, the learned notes) follows the instruction in the system
1018    /// message. Without an instruction they are the whole system message.
1019    /// `images` are the vision inputs of the user message.
1020    fn initial_state(
1021        &self,
1022        ctx: &NodeContext,
1023        sections: &[&str],
1024        images: Vec<ContentPart>,
1025    ) -> Result<AgentState, NodeError> {
1026        let cfg = &self.config;
1027        let pool = &ctx.pool;
1028        let mut messages = Vec::new();
1029        let mut system = cfg.instruction.as_ref().map(|instruction| instruction.render(pool)).unwrap_or_default();
1030        for section in sections.iter().filter(|section| !section.is_empty()) {
1031            if !system.trim().is_empty() {
1032                system.push_str("\n\n");
1033            }
1034            system.push_str(section);
1035        }
1036        if !system.trim().is_empty() {
1037            messages.push(Message::system(system));
1038        }
1039        if let Some(memory) = &cfg.memory {
1040            messages.extend(memory.history(pool)?);
1041        }
1042        let query = cfg.query.render(pool);
1043        if query.trim().is_empty() && images.is_empty() {
1044            if messages.iter().all(|m| m.role == Role::System) {
1045                return Err(NodeError::invalid_input("agent query is empty"));
1046            }
1047        } else {
1048            let mut user = Message::user(query);
1049            user.content.extend(images);
1050            messages.push(user);
1051        }
1052        Ok(AgentState { messages, ..AgentState::default() })
1053    }
1054
1055    /// Apply the host's decisions to the pending calls. Returns the calls that
1056    /// still have no decision.
1057    async fn apply_decisions(
1058        &self,
1059        ctx: &NodeContext,
1060        state: &mut AgentState,
1061        tools: &[BoundTool],
1062        input: Option<&Value>,
1063    ) -> Vec<ToolCall> {
1064        let decisions = Approvals::from_input(input);
1065        let mut approved = Vec::new();
1066        let mut undecided = Vec::new();
1067        for call in std::mem::take(&mut state.pending) {
1068            match decisions.decision(&call.id) {
1069                Some(true) => approved.push(call),
1070                Some(false) => self.deny(ctx, state, tools, &call, decisions.reason.as_deref()),
1071                None => undecided.push(call),
1072            }
1073        }
1074        // Still pending while the approved ones run, so a checkpoint keeps them.
1075        state.pending.clone_from(&undecided);
1076        self.run_calls(ctx, state, tools, approved).await;
1077        undecided
1078    }
1079
1080    async fn execute(&self, ctx: NodeContext) -> NodeResult {
1081        let mut bound = self.bind_tools(&ctx).await?;
1082        let (tools, skill_catalog) = (std::mem::take(&mut bound.tools), std::mem::take(&mut bound.catalog));
1083        let model = model_for(&ctx, &self.config.model)?;
1084        // An earlier attempt of this execution was cut (a retry, a resumed
1085        // preempt): go on from its last turn. Newer than a resume state.
1086        let mut restarted = false;
1087        if let Some(saved) = ctx.checkpointed().and_then(|saved| match Self::restore_state(&bound, saved) {
1088            Ok(state) => Some(state),
1089            // From another version of this node: start over, as without checkpoints.
1090            Err(error) => {
1091                eprintln!("agent {}: checkpoint not read, the loop starts over: {}", ctx.node_id, error.message);
1092                ctx.progress("checkpoint_skipped", Value::from_json(json!({"error": error.message})));
1093                restarted = true;
1094                None
1095            }
1096        }) {
1097            let mut state = saved;
1098            ctx.progress("checkpoint_restored", Value::from_json(json!({"iteration": state.iteration})));
1099            self.settle_interrupted(&ctx, &mut state, &tools).await;
1100            // A start over whose approved calls ran in this attempt.
1101            if let Some(mark) = state.restart_next.take() {
1102                state.restart = Some(mark);
1103            }
1104            #[cfg(feature = "subagents")]
1105            if let Some(error) = state.children.stopped.take() {
1106                return Err(error);
1107            }
1108            if Self::must_pause(&state) {
1109                return self.pause(&state, &tools);
1110            }
1111            #[cfg(feature = "subagents")]
1112            if let Some(text) = state.children.handoff.take() {
1113                return Ok(finished(&ctx, state, text, &StopReason::Handoff));
1114            }
1115            return self.run_loop(&ctx, model, &tools, state).await;
1116        }
1117        let state = match &ctx.resume {
1118            Some(resume) => {
1119                let mut state = Self::restore_state(&bound, resume.state.clone())?;
1120                if restarted {
1121                    state.restart_next = Some(restart_mark(&ctx));
1122                }
1123                // Kept at once: a cut while children resume or approved calls run
1124                // goes on from here instead of from turn 1. Its pending calls ask
1125                // for approval again, and approved calls are marked started.
1126                Self::save(&ctx, &state);
1127                // Children that waited go on first, each where it stopped.
1128                #[cfg(feature = "subagents")]
1129                if let Some(config) = &self.subagents
1130                    && !state.children.paused.is_empty()
1131                {
1132                    let mut children = std::mem::take(&mut state.children);
1133                    let done = config.resume(&ctx, &mut children).await;
1134                    if let Some(error) = children.stopped.take() {
1135                        return Err(error);
1136                    }
1137                    state.children = children;
1138                    self.record_children(&ctx, &mut state, &tools, done);
1139                }
1140                let undecided = self.apply_decisions(&ctx, &mut state, &tools, resume.input.as_ref()).await;
1141                // Started over from the paused state: the approved calls kept their
1142                // keys, the turns from here on get new ones.
1143                if let Some(mark) = state.restart_next.take() {
1144                    state.restart = Some(mark);
1145                }
1146                #[cfg(feature = "subagents")]
1147                if let Some(error) = state.children.stopped.take() {
1148                    return Err(error);
1149                }
1150                if !undecided.is_empty() {
1151                    state.pending = undecided;
1152                }
1153                // With the decisions and the children's results in it: a cut from
1154                // here on goes on from this state, not from the one paused.
1155                Self::save(&ctx, &state);
1156                if Self::must_pause(&state) {
1157                    return self.pause(&state, &tools);
1158                }
1159                // A handoff child that finished on resume answers now: no model turn first.
1160                #[cfg(feature = "subagents")]
1161                if let Some(text) = state.children.handoff.take() {
1162                    return Ok(finished(&ctx, state, text, &StopReason::Handoff));
1163                }
1164                state
1165            }
1166            None => {
1167                #[cfg(feature = "learning")]
1168                let notes = self.lesson_notes(&ctx).await?;
1169                #[cfg(not(feature = "learning"))]
1170                let notes = String::new();
1171                #[cfg(feature = "vision-preparer")]
1172                let images = self.config.vision.prepared_image_parts(&ctx).await?;
1173                #[cfg(not(feature = "vision-preparer"))]
1174                let images = self.config.vision.image_parts(&ctx.pool)?;
1175                #[allow(unused_mut)]
1176                let mut state = self.initial_state(&ctx, &[&skill_catalog, &notes], images)?;
1177                if restarted {
1178                    state.restart = Some(restart_mark(&ctx));
1179                }
1180                #[cfg(all(feature = "skills", feature = "learning"))]
1181                {
1182                    state.has_notes = !notes.is_empty();
1183                }
1184                #[cfg(feature = "memory")]
1185                if bound.memory.is_attached() {
1186                    if self.memory.as_ref().is_some_and(crate::memory::LongTermMemory::recalls) {
1187                        bound.memory.recall_into(&ctx, &mut state.messages).await?;
1188                    }
1189                    state.memory = bound.memory.clone();
1190                    state.memory.read_all(&state.messages);
1191                }
1192                state
1193            }
1194        };
1195        self.run_loop(&ctx, model, &tools, state).await
1196    }
1197
1198    /// The agent loop from `state` on: model turns and tool turns until an answer.
1199    async fn run_loop(
1200        &self,
1201        ctx: &NodeContext,
1202        model: Arc<dyn ChatModel>,
1203        tools: &[BoundTool],
1204        mut state: AgentState,
1205    ) -> NodeResult {
1206        let (final_text, stop) = loop {
1207            state.iteration += 1;
1208            // Nothing left: no answer is affordable, the run stops here.
1209            ctx.check_budget()?;
1210            // A budget that does not afford another tool turn and the answer
1211            // after it gets one more turn without tools: an answer from what
1212            // the agent has.
1213            let budget_low = !tools.is_empty() && !Self::budget_affords_another_turn(ctx, &state);
1214            if budget_low {
1215                ctx.progress("budget", Value::from_json(json!({"iteration": state.iteration, "final_turn": true})));
1216            }
1217            let offer = TurnTools {
1218                offered: !tools.is_empty(),
1219                final_turn: state.iteration >= self.config.max_iterations || budget_low,
1220                answer_for_budget: budget_low,
1221            };
1222            let mut turn = self.model_turn(ctx, model.as_ref(), &mut state, tools, offer).await?;
1223            if offer.callable() && turn.response.tool_calls.is_empty() {
1224                read_calls_written_as_text(&mut turn, &state, tools);
1225            }
1226            if !offer.callable() || turn.response.tool_calls.is_empty() {
1227                let (text, stop) = self.answer_turn(ctx, &mut state, turn, offer);
1228                let stop = if budget_low && stop == StopReason::MaxIterations { StopReason::Budget } else { stop };
1229                break (text, stop);
1230            }
1231            self.tool_turn(ctx, &mut state, tools, turn).await;
1232            #[cfg(feature = "subagents")]
1233            if let Some(error) = state.children.stopped.take() {
1234                return Err(error);
1235            }
1236            if Self::must_pause(&state) {
1237                return self.pause(&state, tools);
1238            }
1239            // A handoff: the child answered for this agent.
1240            #[cfg(feature = "subagents")]
1241            if let Some(text) = state.children.handoff.take() {
1242                break (text, StopReason::Handoff);
1243            }
1244        };
1245        Ok(finished(ctx, state, final_text, &stop))
1246    }
1247
1248    /// The state saved by a pause or a checkpoint, with this attempt's memory attached.
1249    #[cfg_attr(not(feature = "memory"), allow(unused_variables))]
1250    fn restore_state(bound: &BoundTools, saved: Json) -> Result<AgentState, NodeError> {
1251        #[allow(unused_mut)]
1252        let mut state: AgentState =
1253            serde_json::from_value(saved).map_err(|e| NodeError::fatal("invalid_resume_state", e.to_string()))?;
1254        #[cfg(feature = "memory")]
1255        {
1256            bound.memory.count_writes(memory_writes(&state.log));
1257            state.memory = bound.memory.clone();
1258            state.memory.read_all(&state.messages);
1259        }
1260        Ok(state)
1261    }
1262
1263    /// Ask the model for the next turn (streaming per `stream_tool_turns`) and
1264    /// add its usage to the state.
1265    async fn model_turn(
1266        &self,
1267        ctx: &NodeContext,
1268        model: &dyn ChatModel,
1269        state: &mut AgentState,
1270        tools: &[BoundTool],
1271        offer: TurnTools,
1272    ) -> Result<Turn, NodeError> {
1273        let cfg = &self.config;
1274        // Everything this turn spends (a context summary too) is charged with it.
1275        let usage_before = state.usage;
1276        if let Some(keep) = cfg.keep_tool_images {
1277            prune_tool_images(&mut state.messages, keep);
1278        }
1279        // Tools stay declared on the final turn: the history may contain tool calls,
1280        // which providers only accept alongside tool definitions.
1281        // A tool granted through a skill appears once that skill was loaded.
1282        let specs: Vec<ToolSpec> = if offer.offered {
1283            tools.iter().filter(|t| t.offered(state)).map(|t| t.spec.clone()).collect()
1284        } else {
1285            Vec::new()
1286        };
1287        let request = |messages: Vec<Message>, tools: Vec<ToolSpec>| -> Result<ChatRequest, NodeError> {
1288            let mut request = cfg.model.request(messages, &ctx.pool)?;
1289            if offer.offered {
1290                request.tools = tools;
1291                request.tool_choice = Some(if offer.callable() { ToolChoice::Auto } else { ToolChoice::None });
1292            }
1293            Ok(request)
1294        };
1295        ctx.progress(
1296            "agent_step",
1297            Value::from_json(json!({"iteration": state.iteration, "tools_enabled": offer.callable()})),
1298        );
1299        let plan = TurnPlan {
1300            live: cfg.stream_tool_turns || !offer.callable(),
1301            stop_at_tool_call: offer.callable(),
1302            separate: !state.answer.is_empty(),
1303        };
1304        #[cfg(not(feature = "context"))]
1305        let (response, streamed) = stream_turn(ctx, model, request(state.messages.clone(), specs)?, plan).await?;
1306        #[cfg(feature = "context")]
1307        let outcome: Result<(ChatResponse, usize), NodeError> = 'turn: {
1308            // The fields of the state the guard reads and changes, borrowed apart.
1309            let AgentState { messages, context, usage, log, .. } = state;
1310            let shown = pinned_results(log, messages);
1311            let pinned: Vec<(&str, &str)> = shown.iter().map(|(id, text)| (*id, text.as_str())).collect();
1312            let scope = crate::context::Scope { pinned: &pinned, tail: 0 };
1313            let mut guard = self.context.session(ctx, model, &cfg.model, scope);
1314            loop {
1315                let estimate = match guard.fit(context, messages, &specs, usage).await {
1316                    Ok(estimate) => estimate,
1317                    Err(error) => break 'turn Err(error),
1318                };
1319                let turn = match request(context.request_messages(messages), specs.clone()) {
1320                    Ok(turn) => turn,
1321                    Err(error) => break 'turn Err(error),
1322                };
1323                match stream_turn(ctx, model, turn, plan).await {
1324                    Ok(done) => {
1325                        guard.observe(context, estimate, &done.0.usage);
1326                        break 'turn Ok(done);
1327                    }
1328                    // A turn the provider refused for its size is trimmed and sent
1329                    // once more. Any other error, and a second refusal, end the turn.
1330                    Err(error) => {
1331                        if let Err(error) = guard.refused(context, messages, &specs, error, usage).await {
1332                            break 'turn Err(error);
1333                        }
1334                    }
1335                }
1336            }
1337        };
1338        #[cfg(feature = "context")]
1339        let (response, streamed) = match outcome {
1340            Ok(done) => done,
1341            Err(error) => {
1342                // A summary made for the turn was paid for, even when the turn failed.
1343                let spent = usage_since(&state.usage, &usage_before);
1344                if !spent.is_zero() {
1345                    // Past a limit the budget stops the run itself: the turn's own error is the answer.
1346                    let cost = self.cost_of(ctx, state, &spent);
1347                    let _limit_reached = ctx.charge(&spent, cost).is_err();
1348                }
1349                return Err(error);
1350            }
1351        };
1352        state.usage.add(&response.usage);
1353        let spent = usage_since(&state.usage, &usage_before);
1354        let cost = self.cost_of(ctx, state, &spent);
1355        state.last_turn_tokens = spent.billable_tokens();
1356        state.last_turn_cost = cost;
1357        if offer.answer_for_budget {
1358            // The answer the budget asked for is kept, even when it passes the limit.
1359            ctx.charge_final(&spent, cost);
1360        } else {
1361            ctx.charge(&spent, cost)?;
1362        }
1363        // A content-filtered or malformed turn is an error, never an empty "completed" answer.
1364        let finish = check_finish(&response)?;
1365        Ok(Turn { response, streamed, finish, live: plan.live })
1366    }
1367
1368    /// A turn without tool calls ends the loop: its text completes the answer.
1369    fn answer_turn(
1370        &self,
1371        ctx: &NodeContext,
1372        state: &mut AgentState,
1373        mut turn: Turn,
1374        offer: TurnTools,
1375    ) -> (String, StopReason) {
1376        let response = turn.response;
1377        if !turn.live && !response.text.is_empty() {
1378            ctx.chunk_shared(StreamField::Text.shared(), response.text.clone());
1379            turn.streamed = response.text.len();
1380        }
1381        let stop = if response.finish_reason == Some(FinishReason::Length) {
1382            StopReason::Length
1383        } else if let FinishCheck::Unknown(reason) = turn.finish {
1384            StopReason::Unrecognized(reason)
1385        } else if offer.offered && offer.final_turn {
1386            StopReason::MaxIterations
1387        } else {
1388            StopReason::Completed
1389        };
1390        state.messages.push(Message::assistant(response.text.clone()));
1391        (final_answer(std::mem::take(&mut state.answer), response.text, turn.streamed), stop)
1392    }
1393
1394    /// A turn with tool calls: keep its preamble, then reject, run or hold
1395    /// (in `state.pending`, for approval) each call.
1396    async fn tool_turn(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], turn: Turn) {
1397        let response = turn.response;
1398        if !response.text.trim().is_empty() {
1399            ctx.progress(
1400                "agent_thought",
1401                Value::from_json(
1402                    json!({"iteration": state.iteration, "text": response.text, "streamed": turn.streamed > 0}),
1403                ),
1404            );
1405        }
1406        commit_preamble(&mut state.answer, &response.text, turn.streamed);
1407        state.messages.push(replayable_message(&response));
1408        let runnable = self.runnable_calls(state, tools, response.tool_calls);
1409        let (gated, free): (Vec<ToolCall>, Vec<ToolCall>) =
1410            runnable.into_iter().partition(|c| self.call_needs_approval(tools, c));
1411        state.pending = gated;
1412        self.run_calls(ctx, state, tools, free).await;
1413    }
1414
1415    /// The calls that can run. Calls past `max_tool_calls_per_turn` and calls
1416    /// with malformed arguments get an error result for the model instead.
1417    fn runnable_calls(&self, state: &mut AgentState, tools: &[BoundTool], mut calls: Vec<ToolCall>) -> Vec<ToolCall> {
1418        if let Some(limit) = self.config.max_tool_calls_per_turn
1419            && calls.len() > limit
1420        {
1421            for call in calls.split_off(limit) {
1422                self.record(state, tools, &call, ToolOutput::error("rejected: too many tool calls in one turn"));
1423            }
1424        }
1425        let mut runnable = Vec::with_capacity(calls.len());
1426        for call in calls {
1427            // Never offered in this run so far: the model was not shown this
1428            // tool, so the call did not come from its tool list.
1429            if bound_tool(tools, &call).is_some_and(|tool| !tool.offered(state)) {
1430                let message = "error: this tool belongs to a skill that is not loaded. Load the skill first.";
1431                self.record(state, tools, &call, ToolOutput::error(message));
1432                continue;
1433            }
1434            match call.arguments_json() {
1435                Ok(arguments) => {
1436                    let mut call = call;
1437                    let Some(tool) = bound_tool(tools, &call) else {
1438                        runnable.push(call);
1439                        continue;
1440                    };
1441                    // Arguments in the type the tool's schema asks for ("400" for an integer).
1442                    let fitted = tool_call_repair::fit_to_schema(Json::Object(arguments), &tool.spec.parameters);
1443                    call.arguments = fitted.to_string();
1444                    let missing = match &fitted {
1445                        Json::Object(fitted) => tool_call_repair::missing_required(fitted, &tool.spec.parameters),
1446                        _ => Vec::new(),
1447                    };
1448                    // A required argument left out: the model is asked once to call again with it.
1449                    if !missing.is_empty() && !state.reasked.contains(&call.name) {
1450                        state.reasked.push(call.name.clone());
1451                        let message = format!(
1452                            "error: this call leaves out {} it needs: {}. Call `{}` again with every required argument.",
1453                            if missing.len() == 1 { "an argument" } else { "arguments" },
1454                            missing.join(", "),
1455                            call.name
1456                        );
1457                        self.record(state, tools, &call, ToolOutput::error(message));
1458                        continue;
1459                    }
1460                    runnable.push(call);
1461                }
1462                Err(e) => {
1463                    let message = format!("error: {e}. Call the tool again with a valid JSON object.");
1464                    self.record(state, tools, &call, ToolOutput::error(message));
1465                }
1466            }
1467        }
1468        runnable
1469    }
1470
1471    fn pause(&self, state: &AgentState, tools: &[BoundTool]) -> NodeResult {
1472        let calls: Vec<Json> = state
1473            .pending
1474            .iter()
1475            .map(|c| json!({"id": c.id, "name": c.name, "arguments": log_arguments(c, tools)}))
1476            .collect();
1477        let saved = serde_json::to_value(state)
1478            .map_err(|e| NodeError::fatal("agent_state", format!("cannot save agent state: {e}")))?;
1479        #[allow(unused_mut)]
1480        let mut data = json!({"calls": calls});
1481        // Only children wait: the nodes inside them reported why, this node passes it on.
1482        #[allow(unused_mut)]
1483        let mut kind = "tool_approval".to_owned();
1484        #[cfg(feature = "subagents")]
1485        if !state.children.paused.is_empty() {
1486            if state.pending.is_empty() {
1487                kind = graphrt_core::node::CHILD_PAUSE.to_owned();
1488            }
1489            if let Some(fields) = data.as_object_mut() {
1490                fields.insert("children".to_owned(), json!(state.children.reasons()));
1491            }
1492        }
1493        Ok(NodeOutcome::Paused(PauseRequest { kind, data: Value::from_json(data), state: saved }))
1494    }
1495
1496    /// Whether the loop must pause: calls wait for approval, or children wait.
1497    fn must_pause(state: &AgentState) -> bool {
1498        #[cfg(feature = "subagents")]
1499        if !state.children.paused.is_empty() {
1500            return true;
1501        }
1502        !state.pending.is_empty()
1503    }
1504
1505    fn deny(
1506        &self,
1507        ctx: &NodeContext,
1508        state: &mut AgentState,
1509        tools: &[BoundTool],
1510        call: &ToolCall,
1511        reason: Option<&str>,
1512    ) {
1513        let text = match reason {
1514            Some(r) if !r.is_empty() => format!("The user did not approve this tool call: {r}"),
1515            _ => "The user did not approve this tool call.".to_owned(),
1516        };
1517        ctx.progress("tool_denied", Value::from_json(json!({"id": call.id, "name": call.name})));
1518        self.record(state, tools, call, ToolOutput::error(text));
1519    }
1520
1521    /// A tool result as the model, the `tool_calls` output and the captured
1522    /// `tool_result` progress all see it: the tool's context masked, cut to
1523    /// `max_tool_output_chars`, and a note in place of images that fail
1524    /// [`check_images`].
1525    ///
1526    /// A tool may echo its context (e.g. an upstream error repeating the JWT):
1527    /// the model, the outputs and the progress events must never see it. Masking
1528    /// comes first so a cut through the secret cannot leave its prefix behind.
1529    /// Every consumer takes the text from here, so none can skip the masking.
1530    fn visible_result(&self, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) -> VisibleResult {
1531        let bound = bound_tool(tools, call);
1532        let scrubbed = bound.map_or(Cow::Borrowed(output.text.as_str()), |b| scrub_context(&output.text, b.context()));
1533        let mut text = truncate(&scrubbed, self.config.max_tool_output_chars);
1534        let images = match check_images(&output.images) {
1535            Ok(()) => output.images,
1536            Err(e) => {
1537                let note = format!("[images dropped: {e}]");
1538                text = if text.is_empty() { note } else { format!("{text}\n{note}") };
1539                Vec::new()
1540            }
1541        };
1542        // A failed tool shows nothing: its data is no answer the person should see.
1543        let ui = if output.is_error {
1544            Vec::new()
1545        } else {
1546            graphrt_core::ui::collect_ui_blocks(&output.data).iter().map(Value::to_json).collect()
1547        };
1548        VisibleResult {
1549            text,
1550            images,
1551            ui,
1552            #[cfg(feature = "tool-files")]
1553            files: returned_files(&output.data, output.is_error),
1554            is_error: output.is_error,
1555        }
1556    }
1557
1558    /// Append a tool result to the conversation and the log.
1559    fn record(&self, state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, output: ToolOutput) {
1560        let result = self.visible_result(tools, call, output);
1561        push_result(state, tools, call, result);
1562    }
1563
1564    async fn run_calls(&self, ctx: &NodeContext, state: &mut AgentState, tools: &[BoundTool], calls: Vec<ToolCall>) {
1565        if calls.is_empty() {
1566            return;
1567        }
1568        // The turn is kept with the calls that run now marked as started and
1569        // the others queued: an attempt cut while they run knows which
1570        // outcomes it does not know, and runs what never started.
1571        state.queued.clone_from(&calls);
1572        // What the model read before these calls decides where a saved note came from.
1573        #[cfg(feature = "memory")]
1574        state.memory.observe(&state.messages, &calls);
1575        for call in &calls {
1576            ctx.progress(
1577                "tool_call",
1578                Value::from_json(json!({"id": call.id, "name": call.name, "arguments": log_arguments(call, tools)})),
1579            );
1580        }
1581        // The same for every attempt of a call, different for every other call:
1582        // the turn is in it because providers number calls per turn.
1583        let key = match &state.restart {
1584            None => format!("{}:{}", ctx.idempotency_key(), state.iteration),
1585            Some(mark) => format!("{}:r{mark}.{}", ctx.idempotency_key(), state.iteration),
1586        };
1587        #[cfg(feature = "subagents")]
1588        let (children, calls): (Vec<ToolCall>, Vec<ToolCall>) = match &self.subagents {
1589            Some(_) => calls.into_iter().partition(|call| {
1590                bound_tool(tools, call).is_some_and(|b| b.provider == crate::subagents::SUBAGENT_PROVIDER)
1591            }),
1592            None => (Vec::new(), calls),
1593        };
1594        if self.config.parallel_tool_calls {
1595            Self::start_calls(ctx, state, &calls);
1596            let outputs = futures::future::join_all(calls.iter().map(|c| call_tool(tools, c, &key))).await;
1597            self.finish_calls(ctx, state, tools, &calls, outputs);
1598        } else {
1599            // One after another: each result is kept as soon as it is in.
1600            for call in calls {
1601                Self::start_calls(ctx, state, std::slice::from_ref(&call));
1602                let output = call_tool(tools, &call, &key).await;
1603                self.finish_calls(ctx, state, tools, std::slice::from_ref(&call), vec![output]);
1604            }
1605        }
1606        #[cfg(feature = "subagents")]
1607        if let Some(config) = &self.subagents
1608            && !children.is_empty()
1609        {
1610            let with_workflow: Vec<(ToolCall, String)> = children
1611                .iter()
1612                .map(|call| (call.clone(), bound_tool(tools, call).map(|b| b.name.clone()).unwrap_or_default()))
1613                .collect();
1614            Self::start_calls(ctx, state, &children);
1615            let mut child_state = std::mem::take(&mut state.children);
1616            let done = config.run(ctx, &mut child_state, with_workflow).await;
1617            state.children = child_state;
1618            // A child that paused waits in `state.children`, not in `started`.
1619            state.started.retain(|started| !children.iter().any(|c| c.id == started.id));
1620            self.record_children(ctx, state, tools, done);
1621        }
1622        #[cfg(feature = "memory")]
1623        state.memory.flush_events(ctx);
1624        state.started.clear();
1625        state.queued.clear();
1626        Self::save(ctx, state);
1627    }
1628
1629    /// Move `calls` from the queue to the started calls, and keep the turn.
1630    fn start_calls(ctx: &NodeContext, state: &mut AgentState, calls: &[ToolCall]) {
1631        state.queued.retain(|queued| !calls.iter().any(|c| c.id == queued.id));
1632        state.started.extend(calls.iter().cloned());
1633        Self::save(ctx, state);
1634    }
1635
1636    /// Record the results of `calls` and keep the turn without them in `started`.
1637    fn finish_calls(
1638        &self,
1639        ctx: &NodeContext,
1640        state: &mut AgentState,
1641        tools: &[BoundTool],
1642        calls: &[ToolCall],
1643        outputs: Vec<ToolOutput>,
1644    ) {
1645        self.record_outputs(ctx, state, tools, calls, outputs);
1646        state.started.retain(|started| !calls.iter().any(|c| c.id == started.id));
1647        Self::save(ctx, state);
1648    }
1649
1650    /// Show the results of `calls` to the host and add them to the conversation.
1651    fn record_outputs(
1652        &self,
1653        ctx: &NodeContext,
1654        state: &mut AgentState,
1655        tools: &[BoundTool],
1656        calls: &[ToolCall],
1657        outputs: Vec<ToolOutput>,
1658    ) {
1659        let capture = ctx.captures_content();
1660        for (call, output) in calls.iter().zip(outputs) {
1661            // The tool's own image count, including images the result drops.
1662            let offered_images = output.images.len();
1663            let result = self.visible_result(tools, call, output);
1664            let mut data =
1665                json!({"id": call.id, "name": call.name, "is_error": result.is_error, "images": offered_images});
1666            if capture && let Some(fields) = data.as_object_mut() {
1667                fields.insert("result".to_owned(), Json::String(result.text.clone()));
1668            }
1669            ctx.progress("tool_result", Value::from_json(data));
1670            push_result(state, tools, call, result);
1671        }
1672    }
1673
1674    /// Add the results of children that finished on resume.
1675    #[cfg(feature = "subagents")]
1676    fn record_children(
1677        &self,
1678        ctx: &NodeContext,
1679        state: &mut AgentState,
1680        tools: &[BoundTool],
1681        done: Vec<crate::subagents::Done>,
1682    ) {
1683        let (calls, outputs): (Vec<ToolCall>, Vec<ToolOutput>) = done
1684            .into_iter()
1685            .filter_map(|d| match d {
1686                crate::subagents::Done::Result(call, output) => Some((call, output)),
1687                crate::subagents::Done::Paused => None,
1688            })
1689            .unzip();
1690        self.record_outputs(ctx, state, tools, &calls, outputs);
1691    }
1692}
1693
1694/// A tool result after [`AgentNode::visible_result`]: safe to show to the model and the host.
1695struct VisibleResult {
1696    text: String,
1697    images: Vec<ToolImage>,
1698    /// UI blocks the tool returned in its data; never sent to the model.
1699    ui: Vec<Json>,
1700    /// Files the tool returned in its data; never sent to the model.
1701    #[cfg(feature = "tool-files")]
1702    files: Vec<Json>,
1703    is_error: bool,
1704}
1705
1706/// Append a visible tool result to the conversation and the log.
1707fn push_result(state: &mut AgentState, tools: &[BoundTool], call: &ToolCall, result: VisibleResult) {
1708    let bound = bound_tool(tools, call);
1709    // Read now, before a trim can replace it: where a later note came from depends on it.
1710    #[cfg(feature = "memory")]
1711    state.memory.read_result(bound.is_some_and(|b| b.provider == crate::memory::MEMORY_PROVIDER), &result.text);
1712    #[allow(unused_mut)]
1713    let mut shown = result.text.clone();
1714    #[cfg(feature = "skills")]
1715    if !result.is_error
1716        && let Some(skill) = loaded_skill(bound, call)
1717    {
1718        // The skill is the newest text the model reads, and a model then tends to
1719        // follow it alone. The notes in the system message are named again.
1720        #[cfg(feature = "learning")]
1721        if state.has_notes {
1722            shown.push_str(NOTES_STILL_APPLY);
1723        }
1724        if !state.loaded_skills.contains(&skill) {
1725            state.loaded_skills.push(skill);
1726        }
1727    }
1728    state.messages.push(Message::tool_with_images(call.id.clone(), shown, result.images.iter().map(ToolImage::to_url)));
1729    state.log.push(ToolLogEntry {
1730        id: call.id.clone(),
1731        name: call.name.clone(),
1732        provider: bound.map(|b| b.provider.clone()).unwrap_or_default(),
1733        tool: bound.map(|b| b.name.clone()).unwrap_or_default(),
1734        arguments: log_arguments(call, tools),
1735        result: result.text,
1736        is_error: result.is_error,
1737        images: result.images.len(),
1738        ui: result.ui,
1739        #[cfg(feature = "tool-files")]
1740        files: result.files,
1741    });
1742}
1743
1744/// Follows the content of a loaded skill when the run also reads learned notes.
1745/// Without it a model that has just read a skill follows the skill alone: measured
1746/// with a small hosted model, an approved note was followed in 3 of 12 runs, and in
1747/// 12 of 12 with this sentence, the skill's own steps kept in both.
1748#[cfg(all(feature = "skills", feature = "learning"))]
1749const NOTES_STILL_APPLY: &str = "\nThis skill adds to your instructions and does not replace them: the learned notes in \
1750your instructions still apply. Keep every step of the skill, including how it says to end the reply.";
1751
1752/// The skill a call loads: the `name` argument of the skill tool `load_skill`.
1753/// Only the skill tools bound by [`AgentNode::attach_skills`] count, never a
1754/// registry provider that happens to use the same names.
1755#[cfg(feature = "skills")]
1756fn loaded_skill(bound: Option<&BoundTool>, call: &ToolCall) -> Option<String> {
1757    bound.filter(|tool| tool.skill_tool && tool.name == LOAD_SKILL_TOOL)?;
1758    let arguments = call.arguments_json().ok()?;
1759    arguments.get("name").and_then(Json::as_str).map(str::to_owned)
1760}
1761
1762/// Whether a turn offers tools, and whether it is the last one the iteration limit allows.
1763#[derive(Clone, Copy, Debug)]
1764struct TurnTools {
1765    offered: bool,
1766    final_turn: bool,
1767    /// The budget ran low: this is the answer it leaves room for.
1768    answer_for_budget: bool,
1769}
1770
1771impl TurnTools {
1772    /// The model may call tools: they are offered and this is not the forced final turn.
1773    fn callable(self) -> bool {
1774        self.offered && !self.final_turn
1775    }
1776}
1777
1778/// One model turn: the response, how many leading bytes of its text were
1779/// already streamed, its finish check, and whether it streamed live.
1780struct Turn {
1781    response: ChatResponse,
1782    streamed: usize,
1783    finish: FinishCheck,
1784    live: bool,
1785}
1786
1787/// The assistant message of a tool turn as it is kept in the history. Malformed
1788/// arguments are never replayed to the provider: the history keeps `{}` and
1789/// the tool result explains the problem to the model.
1790fn replayable_message(response: &ChatResponse) -> Message {
1791    let mut assistant = response.to_message();
1792    for call in &mut assistant.tool_calls {
1793        if call.arguments_json().is_err() {
1794            call.arguments = "{}".to_owned();
1795        }
1796    }
1797    assistant
1798}
1799
1800/// Characters of a tool call's arguments and result in a [`turn_digest`].
1801#[cfg(feature = "memory")]
1802const DIGEST_ARGUMENTS_CHARS: usize = 200;
1803#[cfg(feature = "memory")]
1804const DIGEST_RESULT_CHARS: usize = 300;
1805/// Characters of a whole [`turn_digest`].
1806#[cfg(feature = "memory")]
1807const DIGEST_CHARS: usize = 2_000;
1808
1809/// What the tools did in this run, short enough to send with the next turn
1810/// of a conversation (output `turn_digest`): per call the tool, its
1811/// arguments and the start of its result, from what the model saw, with the
1812/// run's secrets masked. Memory tools are left out: what they return is
1813/// recalled again when it matters. `None` when no tool was called.
1814#[cfg(feature = "memory")]
1815fn turn_digest(log: &[ToolLogEntry], secrets: Option<&graphrt_core::redact::SecretSet>) -> Option<String> {
1816    // Secrets are masked before anything is cut, so no part of one survives a cut.
1817    let scrub = |text: &str| -> String {
1818        match secrets {
1819            Some(secrets) => secrets.scrub(text).into_owned(),
1820            None => text.to_owned(),
1821        }
1822    };
1823    let cut = |text: &str, max: usize| -> String {
1824        let text = scrub(text);
1825        let flat: String = text.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
1826        match flat.char_indices().nth(max) {
1827            Some((at, _)) => format!("{}...", flat.get(..at).unwrap_or_default()),
1828            None => flat,
1829        }
1830    };
1831    let mut digest = String::new();
1832    for entry in log.iter().filter(|e| e.provider != crate::memory::MEMORY_PROVIDER) {
1833        let arguments = cut(&entry.arguments.to_string(), DIGEST_ARGUMENTS_CHARS);
1834        let line = match entry.is_error {
1835            true => format!("- {}({arguments}) failed: {}\n", entry.name, cut(&entry.result, DIGEST_RESULT_CHARS)),
1836            false => format!("- {}({arguments}) returned: {}\n", entry.name, cut(&entry.result, DIGEST_RESULT_CHARS)),
1837        };
1838        if digest.chars().count() + line.chars().count() > DIGEST_CHARS {
1839            digest.push_str("- (more calls left out)\n");
1840            break;
1841        }
1842        digest.push_str(&line);
1843    }
1844    if digest.is_empty() {
1845        return None;
1846    }
1847    // Once more over the whole: a secret could also be split across a name and its arguments.
1848    Some(scrub(digest.trim_end()))
1849}
1850
1851/// Notes saved earlier in this node run, from its tool log.
1852#[cfg(feature = "memory")]
1853fn memory_writes(log: &[ToolLogEntry]) -> usize {
1854    log.iter().filter(|e| e.provider == crate::memory::MEMORY_PROVIDER && e.tool == "remember" && !e.is_error).count()
1855}
1856
1857/// The tool results the context guard must leave alone, as the id of the
1858/// call and the text the model was shown: the instructions of the skills
1859/// loaded in this run. Their tools stay on offer, so the model must keep the
1860/// text that says how to use them. A skill that was loaded twice is listed
1861/// once, where it was loaded last.
1862#[cfg(feature = "context")]
1863fn pinned_results<'a>(log: &'a [ToolLogEntry], messages: &[Message]) -> Vec<(&'a str, String)> {
1864    #[cfg(feature = "skills")]
1865    let pinned = {
1866        let mut pinned: Vec<(&str, String)> = Vec::new();
1867        let loads = log.iter().filter(|e| e.provider == SKILL_PROVIDER && e.tool == LOAD_SKILL_TOOL && !e.is_error);
1868        for entry in loads {
1869            pinned.retain(|(_, text)| shown_skill(text) != entry.result);
1870            pinned.push((&entry.id, shown_text(entry, messages)));
1871        }
1872        pinned
1873    };
1874    #[cfg(not(feature = "skills"))]
1875    let pinned = {
1876        let _ = (log, messages);
1877        Vec::new()
1878    };
1879    pinned
1880}
1881
1882/// The text of a skill without the sentence the agent may add after it.
1883#[cfg(all(feature = "context", feature = "skills"))]
1884fn shown_skill(text: &str) -> &str {
1885    #[cfg(feature = "learning")]
1886    let text = text.strip_suffix(NOTES_STILL_APPLY).unwrap_or(text);
1887    text
1888}
1889
1890/// What the model was shown for `entry`: its result, or its result with the
1891/// sentence [`push_result`] adds when learned notes apply.
1892#[cfg(all(feature = "context", feature = "skills"))]
1893fn shown_text(entry: &ToolLogEntry, messages: &[Message]) -> String {
1894    #[cfg(feature = "learning")]
1895    {
1896        let with_notes = format!("{}{NOTES_STILL_APPLY}", entry.result);
1897        let shown = messages.iter().any(|message| {
1898            message.role == Role::Tool
1899                && message.tool_call_id.as_deref() == Some(entry.id.as_str())
1900                && message.text() == with_notes
1901        });
1902        if shown {
1903            return with_notes;
1904        }
1905    }
1906    let _ = messages;
1907    entry.result.clone()
1908}
1909
1910/// The outcome of a finished loop: its outputs, and the digest of its tool
1911/// activity for the conversation's memory (feature `memory`).
1912fn finished(ctx: &NodeContext, state: AgentState, text: String, stop: &StopReason) -> NodeOutcome {
1913    #[cfg(feature = "memory")]
1914    let digest = turn_digest(&state.log, ctx.secret_values().as_deref());
1915    #[cfg(not(feature = "memory"))]
1916    let _ = ctx;
1917    let outcome = agent_outputs(state, text, stop);
1918    #[cfg(feature = "memory")]
1919    let outcome = match (outcome, digest) {
1920        (NodeOutcome::Completed(output), Some(digest)) => NodeOutcome::Completed(output.with("turn_digest", digest)),
1921        (outcome, _) => outcome,
1922    };
1923    outcome
1924}
1925
1926/// A mark of one start over, different for every one (the time, and the
1927/// attempt within it).
1928fn restart_mark(ctx: &NodeContext) -> String {
1929    format!("{:x}-{}", ctx.clock.now_ms(), ctx.attempt)
1930}
1931
1932/// What `now` holds beyond `before`.
1933fn usage_since(now: &Usage, before: &Usage) -> Usage {
1934    Usage {
1935        prompt_tokens: now.prompt_tokens.saturating_sub(before.prompt_tokens),
1936        completion_tokens: now.completion_tokens.saturating_sub(before.completion_tokens),
1937        total_tokens: now.total_tokens.saturating_sub(before.total_tokens),
1938    }
1939}
1940
1941/// The node outputs of a finished loop.
1942fn agent_outputs(state: AgentState, final_text: String, stop: &StopReason) -> NodeOutcome {
1943    let log: Vec<Value> = state
1944        .log
1945        .iter()
1946        .map(|e| {
1947            Value::from_json(json!({
1948                "name": e.name, "provider": e.provider, "tool": e.tool,
1949                "arguments": e.arguments, "result": e.result, "is_error": e.is_error, "images": e.images,
1950            }))
1951        })
1952        .collect();
1953    let ui: Vec<Value> = state.log.iter().flat_map(|e| e.ui.iter().cloned().map(Value::from_json)).collect();
1954    let output =
1955        NodeOutput::new().with("text", final_text).with("tool_calls", Value::from(log)).with("ui", Value::from(ui));
1956    #[cfg(feature = "tool-files")]
1957    let output = output.with("files", Value::array(produced_files(&state.log)));
1958    // Present only when the model was not sent everything.
1959    #[cfg(feature = "context")]
1960    let output = match state.context.report() {
1961        Some(report) => output.with("context", Value::from_json(report)),
1962        None => output,
1963    };
1964    output
1965        .with("iterations", i64::from(state.iteration))
1966        .with("stopped_reason", stop.as_str())
1967        .with("usage", usage_value(&state.usage))
1968        .usage(state.usage)
1969        .into()
1970}
1971
1972/// The files in a tool's structured result, as JSON for the saved loop state.
1973/// A failed tool produced nothing the person should be handed.
1974#[cfg(feature = "tool-files")]
1975fn returned_files(data: &Value, is_error: bool) -> Vec<Json> {
1976    if is_error {
1977        return Vec::new();
1978    }
1979    collect_files(data).into_iter().map(|file| Value::File(file).to_json()).collect()
1980}
1981
1982/// The files of every tool result, in call order. A file returned more than once
1983/// (written, then overwritten) appears once, where it was returned last.
1984#[cfg(feature = "tool-files")]
1985fn produced_files(log: &[ToolLogEntry]) -> Vec<Value> {
1986    // The log is this node's own state (never model or tool JSON), so its file objects are trusted.
1987    let files: Vec<Value> =
1988        log.iter().flat_map(|entry| entry.files.iter().cloned().map(Value::from_json_trusted)).collect();
1989    let identity =
1990        |value: &Value| value.as_file().map(|file| (file.reference.clone(), file.url.clone(), file.name.clone()));
1991    let mut unique: Vec<Value> = Vec::with_capacity(files.len());
1992    for file in files {
1993        unique.retain(|earlier| identity(earlier) != identity(&file));
1994        unique.push(file);
1995    }
1996    unique
1997}
1998
1999/// The tools a `provider/name` reference selects from the provider's listing:
2000/// all of them for `*`, else the one named (an error when it is missing).
2001fn select_specs<'a>(specs: &'a [ToolSpec], provider: &str, name: &str) -> Result<Vec<&'a ToolSpec>, NodeError> {
2002    if name == "*" {
2003        return Ok(specs.iter().collect());
2004    }
2005    let spec = specs
2006        .iter()
2007        .find(|s| s.name == name)
2008        .ok_or_else(|| NodeError::fatal("tool_not_found", format!("provider `{provider}` has no tool `{name}`")))?;
2009    Ok(vec![spec])
2010}
2011
2012/// The bound tool a call names (by its exposed, possibly de-duplicated name).
2013fn bound_tool<'a>(tools: &'a [BoundTool], call: &ToolCall) -> Option<&'a BoundTool> {
2014    tools.iter().find(|t| t.exposed == call.name)
2015}
2016
2017/// A turn without tool calls whose text holds calls written out as JSON (a small model's
2018/// `{"name": "resize", "parameters": {...}}`) gets those calls, when they name offered tools;
2019/// one that holds a call written as a command (`resize --max-width 400 uploads/a.png`) gets
2020/// that call, when the command's name and every argument are the tool's own.
2021/// Text not yet streamed loses the written calls; text already shown stays as it was.
2022fn read_calls_written_as_text(turn: &mut Turn, state: &AgentState, tools: &[BoundTool]) {
2023    let offered: Vec<&str> =
2024        tools.iter().filter(|tool| tool.offered(state)).map(|tool| tool.exposed.as_str()).collect();
2025    let prefix = format!("text_call_{}_", state.iteration);
2026    let written = tool_call_repair::calls_written_as_text(&turn.response.text, &offered, &prefix).or_else(|| {
2027        let schemas: Vec<(&str, &Json)> = tools
2028            .iter()
2029            .filter(|tool| tool.offered(state))
2030            .map(|tool| (tool.exposed.as_str(), &tool.spec.parameters))
2031            .collect();
2032        tool_call_repair::command_written_as_text(&turn.response.text, &schemas, &prefix)
2033            .map(|(call, rest)| (vec![call], rest))
2034    });
2035    let Some((calls, rest)) = written else {
2036        return;
2037    };
2038    if turn.streamed == 0 {
2039        turn.response.text = rest;
2040    }
2041    turn.response.tool_calls = calls;
2042}
2043
2044/// How one model turn streams.
2045#[derive(Clone, Copy, Debug)]
2046struct TurnPlan {
2047    /// Stream text and reasoning as they arrive (otherwise nothing is streamed).
2048    live: bool,
2049    /// Stop streaming text at the turn's first tool-call fragment.
2050    stop_at_tool_call: bool,
2051    /// Earlier turns streamed text: send [`PREAMBLE_SEPARATOR`] before this turn's first text.
2052    separate: bool,
2053}
2054
2055/// Run one turn. Returns the response and how many leading bytes of its text
2056/// were streamed on field `text` (always whole deltas, so a char boundary).
2057/// Deltas are moved into chunks, never copied.
2058async fn stream_turn(
2059    ctx: &NodeContext,
2060    model: &dyn ChatModel,
2061    request: ChatRequest,
2062    plan: TurnPlan,
2063) -> Result<(ChatResponse, usize), NodeError> {
2064    if !plan.live {
2065        return Ok((invoke(ctx, model, request, StreamMode::Off).await?, 0));
2066    }
2067    let stream = model.chat(request).await?;
2068    let mut streamed = 0;
2069    let mut text_closed = false;
2070    let mut separator_pending = plan.separate;
2071    let response = collect(stream, |delta| match delta {
2072        ChatDelta::ToolCall { .. } => text_closed |= plan.stop_at_tool_call,
2073        ChatDelta::Text(text) if !text.is_empty() && !text_closed => {
2074            if std::mem::take(&mut separator_pending) {
2075                ctx.chunk_shared(StreamField::Text.shared(), PREAMBLE_SEPARATOR);
2076            }
2077            streamed += text.len();
2078            ctx.chunk_shared(StreamField::Text.shared(), text);
2079        }
2080        ChatDelta::Reasoning(text) if !text.is_empty() => ctx.chunk_shared(StreamField::Reasoning.shared(), text),
2081        _ => {}
2082    })
2083    .await?;
2084    Ok((response, streamed))
2085}
2086
2087/// Append the streamed part of a tool-calling turn's text to the answer,
2088/// mirroring what [`stream_turn`] sent (separator included).
2089fn commit_preamble(answer: &mut String, text: &str, streamed: usize) {
2090    let Some(preamble) = text.get(..streamed).filter(|p| !p.is_empty()) else { return };
2091    if !answer.is_empty() {
2092        answer.push_str(PREAMBLE_SEPARATOR);
2093    }
2094    answer.push_str(preamble);
2095}
2096
2097/// The `text` output: streamed preambles, then the final turn's text (which
2098/// is always streamed whole). Without preambles the final text is moved as is.
2099fn final_answer(mut answer: String, text: String, streamed: usize) -> String {
2100    if answer.is_empty() {
2101        return text;
2102    }
2103    commit_preamble(&mut answer, &text, streamed);
2104    answer
2105}
2106
2107/// Replace the images of all but the last `keep` image-bearing tool results
2108/// with a text placeholder, so a screenshot loop does not resend every
2109/// screenshot on every turn.
2110fn prune_tool_images(messages: &mut [Message], keep: usize) {
2111    let mut seen = 0;
2112    for message in messages.iter_mut().rev().filter(|m| m.role == Role::Tool) {
2113        let count = message.images().count();
2114        if count == 0 {
2115            continue;
2116        }
2117        seen += 1;
2118        if seen <= keep {
2119            continue;
2120        }
2121        let note = if count == 1 {
2122            "[1 image removed from history]".to_owned()
2123        } else {
2124            format!("[{count} images removed from history]")
2125        };
2126        let text = message.text();
2127        let text = if text.is_empty() { note } else { format!("{text}\n{note}") };
2128        message.content = vec![ContentPart::Text { text }];
2129    }
2130}
2131
2132/// Arguments as shown in logs and approval requests: the parsed object, or the
2133/// raw text when it is not valid JSON (so nothing is hidden from the reader),
2134/// with the tool's context values masked.
2135fn log_arguments(call: &ToolCall, tools: &[BoundTool]) -> Json {
2136    let mut arguments = match call.arguments_json() {
2137        Ok(map) => Json::Object(map),
2138        Err(_) => Json::String(call.arguments.clone()),
2139    };
2140    if let Some(tool) = bound_tool(tools, call)
2141        && !tool.context().is_empty()
2142    {
2143        scrub_json(&mut arguments, tool.context());
2144    }
2145    arguments
2146}
2147
2148/// `text` with every value of `context` masked. Borrows when there is nothing to mask.
2149fn scrub_context<'a>(text: &'a str, context: &ToolCallContext) -> Cow<'a, str> {
2150    if context.is_empty() {
2151        return Cow::Borrowed(text);
2152    }
2153    let values: Vec<&str> = context.secrets.values().map(String::as_str).collect();
2154    redact_secrets(text, &values)
2155}
2156
2157/// Mask the values of `context` in every string of `value`.
2158fn scrub_json(value: &mut Json, context: &ToolCallContext) {
2159    match value {
2160        Json::String(text) => {
2161            if let Cow::Owned(scrubbed) = scrub_context(text, context) {
2162                *text = scrubbed;
2163            }
2164        }
2165        Json::Array(items) => items.iter_mut().for_each(|item| scrub_json(item, context)),
2166        Json::Object(map) => map.values_mut().for_each(|item| scrub_json(item, context)),
2167        _ => {}
2168    }
2169}
2170
2171/// Run one call. `key` is the node execution's idempotency key with the turn:
2172/// the call gets `<key>:<call id>`, the same for every attempt of the call.
2173async fn call_tool(tools: &[BoundTool], call: &ToolCall, key: &str) -> ToolOutput {
2174    let Some(tool) = bound_tool(tools, call) else {
2175        return ToolOutput::error(format!("error: unknown tool `{}`", call.name));
2176    };
2177    let arguments = match call.arguments_json() {
2178        Ok(map) => Json::Object(map),
2179        Err(e) => return ToolOutput::error(format!("error: {e}")),
2180    };
2181    let mut context = tool.context().clone();
2182    context.idempotency_key = Some(format!("{key}:{}", call.id));
2183    match tool.runtime.call(&tool.name, arguments, &context).await {
2184        Ok(output) => output,
2185        Err(e) => ToolOutput::error(format!("error: {e}")),
2186    }
2187}
2188
2189/// Host decision for paused tool calls.
2190#[derive(Debug, Default)]
2191struct Approvals {
2192    all: Option<bool>,
2193    per_call: HashMap<String, bool>,
2194    reason: Option<String>,
2195}
2196
2197impl Approvals {
2198    /// Recognized forms: `true`/`false`, `{"approved": bool}`,
2199    /// `{"approvals": {"<call id>": bool}}` (both may be combined, per-call wins),
2200    /// plus an optional `reason`. Anything else decides nothing.
2201    fn from_input(input: Option<&Value>) -> Self {
2202        let mut out = Self::default();
2203        match input {
2204            Some(Value::Bool(b)) => out.all = Some(*b),
2205            Some(Value::Object(map)) => {
2206                out.all = map.get("approved").and_then(Value::as_bool);
2207                if let Some(Value::Object(per)) = map.get("approvals") {
2208                    for (id, v) in per.iter() {
2209                        if let Some(b) = v.as_bool() {
2210                            out.per_call.insert(id.clone(), b);
2211                        }
2212                    }
2213                }
2214                out.reason = map.get("reason").and_then(Value::as_str).map(str::to_owned);
2215            }
2216            _ => {}
2217        }
2218        out
2219    }
2220
2221    /// `Some(true)` approved, `Some(false)` denied, `None` no decision yet.
2222    fn decision(&self, id: &str) -> Option<bool> {
2223        self.per_call.get(id).copied().or(self.all)
2224    }
2225}
2226
2227/// Model-safe tool name: `[A-Za-z0-9_-]{1,64}`, unique within the run.
2228fn unique_name(name: &str, provider: &str, used: &mut HashSet<String>) -> String {
2229    let clean = |s: &str| -> String {
2230        let mut out: String = s
2231            .chars()
2232            .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' })
2233            .take(64)
2234            .collect();
2235        if out.is_empty() {
2236            out.push_str("tool");
2237        }
2238        out
2239    };
2240    let mut candidate = clean(name);
2241    if used.contains(&candidate) {
2242        candidate = clean(&format!("{provider}_{name}"));
2243    }
2244    let base = candidate.clone();
2245    let mut n = 2;
2246    while used.contains(&candidate) {
2247        let suffix = format!("_{n}");
2248        let keep = 64usize.saturating_sub(suffix.len());
2249        candidate = format!("{}{suffix}", base.chars().take(keep).collect::<String>());
2250        n += 1;
2251    }
2252    used.insert(candidate.clone());
2253    candidate
2254}
2255
2256fn truncate(text: &str, max_chars: usize) -> String {
2257    if max_chars == 0 || text.chars().count() <= max_chars {
2258        return text.to_owned();
2259    }
2260    let mut out: String = text.chars().take(max_chars).collect();
2261    out.push_str("\n[truncated]");
2262    out
2263}
2264
2265impl Node for AgentNode {
2266    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
2267        Box::pin(self.execute(ctx))
2268    }
2269
2270    /// The loop charges the budget per model turn and keeps a checkpoint per turn.
2271    fn tracks_turns(&self) -> bool {
2272        true
2273    }
2274
2275    fn inputs(&self) -> Vec<Selector> {
2276        let cfg = &self.config;
2277        let mut out: Vec<Selector> = cfg.query.selectors().cloned().collect();
2278        if let Some(i) = &cfg.instruction {
2279            out.extend(i.selectors().cloned());
2280        }
2281        if let Some(memory) = &cfg.memory {
2282            out.extend(memory.selectors());
2283        }
2284        out.extend(cfg.vision.selectors());
2285        out.extend(cfg.model.selectors());
2286        out.extend(self.tool_context.iter().flat_map(|(_, t)| t).flat_map(|(_, t)| t.selectors().cloned()));
2287        #[cfg(feature = "learning")]
2288        if let Some(user) = self.learning.as_ref().and_then(|learning| learning.user.as_ref()) {
2289            out.extend(user.selectors().cloned());
2290        }
2291        #[cfg(feature = "context")]
2292        out.extend(self.context.selectors());
2293        out
2294    }
2295}
2296
2297/// Factory for the node registry.
2298pub fn factory(doc: &NodeDoc) -> Result<Arc<dyn Node>, ConfigError> {
2299    Ok(Arc::new(AgentNode::from_doc(doc)?))
2300}
2301
2302#[cfg(test)]
2303mod tests {
2304    use super::*;
2305    use crate::mock::MockModel;
2306    use crate::registry::ModelRegistry;
2307    use crate::types::Role;
2308    use graphrt_core::event::Event;
2309    use graphrt_core::node::Resume;
2310    use graphrt_core::tool::ToolError;
2311    use graphrt_core::{Services, VariablePool};
2312    use std::sync::Mutex;
2313
2314    /// Tools: `add {a, b}` and `fail {}`.
2315    #[derive(Debug, Default)]
2316    struct MathTools {
2317        calls: Mutex<Vec<String>>,
2318    }
2319
2320    impl ToolRuntime for MathTools {
2321        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
2322            Box::pin(async {
2323                Ok(vec![
2324                    ToolSpec {
2325                        name: "add".into(),
2326                        description: "add numbers".into(),
2327                        parameters: json!({"type": "object"}),
2328                    },
2329                    ToolSpec {
2330                        name: "fail".into(),
2331                        description: "always fails".into(),
2332                        parameters: json!({"type": "object"}),
2333                    },
2334                ])
2335            })
2336        }
2337
2338        fn call<'a>(
2339            &'a self,
2340            name: &'a str,
2341            arguments: Json,
2342            _context: &'a ToolCallContext,
2343        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
2344            self.calls.lock().unwrap().push(name.to_owned());
2345            Box::pin(async move {
2346                match name {
2347                    "add" => {
2348                        let a = arguments["a"].as_i64().unwrap_or(0);
2349                        let b = arguments["b"].as_i64().unwrap_or(0);
2350                        Ok(ToolOutput::text((a + b).to_string()))
2351                    }
2352                    _ => Err(ToolError { tool: name.to_owned(), message: "broken".into() }),
2353                }
2354            })
2355        }
2356    }
2357
2358    /// Tools: `screenshot {}` (one PNG), `bad_image {}` (an unsupported type).
2359    #[derive(Debug, Default)]
2360    struct ScreenTools;
2361
2362    impl ToolRuntime for ScreenTools {
2363        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
2364            let spec = |name: &str| ToolSpec { name: name.into(), description: "d".into(), parameters: json!({}) };
2365            Box::pin(
2366                async move { Ok(vec![spec("screenshot"), spec("bad_image"), spec("chart"), spec("broken_chart")]) },
2367            )
2368        }
2369
2370        fn call<'a>(
2371            &'a self,
2372            name: &'a str,
2373            _arguments: Json,
2374            _context: &'a ToolCallContext,
2375        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
2376            Box::pin(async move {
2377                Ok(match name {
2378                    "screenshot" => ToolOutput::text("800x600").with_image(ToolImage::png("aGVsbG8=")),
2379                    "chart" => ToolOutput {
2380                        text: "Chart shown".into(),
2381                        data: Value::from_json(json!({"$ui": "chart", "version": 1, "type": "bar"})),
2382                        ..ToolOutput::default()
2383                    },
2384                    "broken_chart" => {
2385                        ToolOutput { data: Value::from_json(json!({"$ui": "chart"})), ..ToolOutput::error("bad chart") }
2386                    }
2387                    _ => ToolOutput::text("odd")
2388                        .with_image(ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() }),
2389                })
2390            })
2391        }
2392    }
2393
2394    struct Setup {
2395        model: Arc<MockModel>,
2396        tools: Arc<MathTools>,
2397        events: Arc<Mutex<Vec<Event>>>,
2398    }
2399
2400    fn setup(responses: Vec<Vec<crate::ChatDelta>>) -> Setup {
2401        Setup {
2402            model: Arc::new(MockModel::new(responses)),
2403            tools: Arc::new(MathTools::default()),
2404            events: Arc::default(),
2405        }
2406    }
2407
2408    fn ctx(s: &Setup) -> NodeContext {
2409        let mut tool_registry = ToolRegistry::new();
2410        tool_registry.add("math", Arc::clone(&s.tools) as Arc<dyn ToolRuntime>);
2411        tool_registry.add("screen", Arc::new(ScreenTools) as Arc<dyn ToolRuntime>);
2412        let services = Services::new()
2413            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
2414            .with(tool_registry);
2415        let mut pool = VariablePool::new();
2416        pool.insert("sys", "query", Value::from("what is 2+3?"));
2417        let events = Arc::clone(&s.events);
2418        NodeContext::for_test("agent", pool)
2419            .with_services(Arc::new(services))
2420            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
2421    }
2422
2423    fn agent(extra: Json) -> AgentNode {
2424        let mut config = json!({
2425            "model": {"provider": "openai", "name": "gpt"},
2426            "instruction": "You are a calculator.",
2427            "tools": ["math/*"],
2428        });
2429        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
2430            c.extend(e);
2431        }
2432        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
2433    }
2434
2435    fn completed(r: NodeResult) -> NodeOutput {
2436        match r.unwrap() {
2437            NodeOutcome::Completed(o) => o,
2438            NodeOutcome::Paused(p) => panic!("unexpected pause: {p:?}"),
2439        }
2440    }
2441
2442    #[tokio::test]
2443    async fn ui_blocks_of_tool_results_become_the_ui_output_but_never_reach_the_model() {
2444        let s = setup(vec![
2445            MockModel::tool_calls(&[("c1", "chart", "{}"), ("c2", "broken_chart", "{}")]),
2446            MockModel::text("Here is your chart."),
2447        ]);
2448        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2449        let ui = out.outputs["ui"].as_array().unwrap().to_vec();
2450        assert_eq!(ui.len(), 1, "only the successful tool's block: {ui:?}");
2451        assert_eq!(graphrt_core::ui::ui_block_kind(&ui[0]), Some("chart"));
2452        let log = out.outputs["tool_calls"].to_json();
2453        assert!(!log.to_string().contains("$ui"), "the log does not repeat the blocks: {log}");
2454        let second = &s.model.requests()[1].messages;
2455        assert!(!format!("{second:?}").contains("$ui"), "blocks are not sent to the model");
2456    }
2457
2458    #[tokio::test]
2459    async fn loops_until_answer() {
2460        let s = setup(vec![
2461            MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#), ("c2", "fail", "{}")]),
2462            MockModel::text("The answer is 5."),
2463        ]);
2464        let out = completed(agent(json!({})).run(ctx(&s)).await);
2465        assert_eq!(out.outputs["text"], Value::from("The answer is 5."));
2466        assert_eq!(out.outputs["iterations"], Value::Int(2));
2467        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2468        assert_eq!(log.len(), 2);
2469        assert_eq!(log[0].get_path(&["result"]), Some(Value::from("5")));
2470        assert_eq!(log[1].get_path(&["is_error"]), Some(Value::Bool(true)));
2471        assert_eq!(out.usage.unwrap().total_tokens, 4);
2472
2473        let requests = s.model.requests();
2474        assert_eq!(requests[0].tools.len(), 2);
2475        let second = &requests[1].messages;
2476        assert_eq!(second[0].role, Role::System);
2477        assert_eq!(second[2].tool_calls.len(), 2);
2478        assert_eq!(second[3].tool_call_id.as_deref(), Some("c1"));
2479        assert_eq!(second[3].text(), "5");
2480        assert!(second[4].text().contains("broken"));
2481
2482        let progress: Vec<String> = s
2483            .events
2484            .lock()
2485            .unwrap()
2486            .iter()
2487            .filter_map(|e| match e {
2488                Event::NodeProgress { name, .. } => Some(name.clone()),
2489                _ => None,
2490            })
2491            .collect();
2492        assert_eq!(progress, ["agent_step", "tool_call", "tool_call", "tool_result", "tool_result", "agent_step"]);
2493    }
2494
2495    /// Tool `image_resize {path*, max_width* (integer), overwrite (boolean)}` that records
2496    /// the arguments it got.
2497    #[derive(Debug, Default)]
2498    struct ImageTools {
2499        arguments: Mutex<Vec<Json>>,
2500    }
2501
2502    impl ToolRuntime for ImageTools {
2503        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
2504            Box::pin(async {
2505                Ok(vec![ToolSpec {
2506                    name: "image_resize".into(),
2507                    description: "resize a picture".into(),
2508                    parameters: json!({
2509                        "type": "object",
2510                        "properties": {
2511                            "path": {"type": "string"},
2512                            "max_width": {"type": "integer", "description": "Largest width in pixels"},
2513                            "overwrite": {"type": "boolean"}
2514                        },
2515                        "required": ["path", "max_width"]
2516                    }),
2517                }])
2518            })
2519        }
2520
2521        fn call<'a>(
2522            &'a self,
2523            _name: &'a str,
2524            arguments: Json,
2525            _context: &'a ToolCallContext,
2526        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
2527            self.arguments.lock().unwrap().push(arguments.clone());
2528            Box::pin(async move {
2529                Ok(match arguments["max_width"].as_i64() {
2530                    Some(width) => ToolOutput::text(format!("resized to {width} px")),
2531                    None => ToolOutput::error("invalid arguments: max_width must be an integer"),
2532                })
2533            })
2534        }
2535    }
2536
2537    fn image_ctx(model: &Arc<MockModel>, tools: &Arc<ImageTools>) -> NodeContext {
2538        let mut tool_registry = ToolRegistry::new();
2539        tool_registry.add("image", Arc::clone(tools) as Arc<dyn ToolRuntime>);
2540        let services = Services::new()
2541            .with(ModelRegistry::new().with("openai", Arc::clone(model) as Arc<dyn crate::ChatModel>))
2542            .with(tool_registry);
2543        let mut pool = VariablePool::new();
2544        pool.insert("sys", "query", Value::from("make it 400 px wide"));
2545        NodeContext::for_test("agent", pool).with_services(Arc::new(services))
2546    }
2547
2548    fn image_agent() -> AgentNode {
2549        let config = json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["image/*"]});
2550        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
2551    }
2552
2553    #[tokio::test]
2554    async fn arguments_are_put_into_the_types_the_tool_asks_for() {
2555        let model = Arc::new(MockModel::new(vec![
2556            MockModel::tool_calls(&[(
2557                "c1",
2558                "image_resize",
2559                r#"{"path": "a.png", "width": "400", "overwrite": "false"}"#,
2560            )]),
2561            MockModel::text("Done."),
2562        ]));
2563        let tools = Arc::new(ImageTools::default());
2564
2565        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
2566
2567        assert_eq!(out.outputs["text"], Value::from("Done."));
2568        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400, "overwrite": false})]);
2569    }
2570
2571    #[tokio::test]
2572    async fn a_call_written_as_text_is_made() {
2573        let written =
2574            "Sure.\n```json\n{\"name\": \"resize\", \"parameters\": {\"path\": \"a.png\", \"max_width\": 400}}\n```";
2575        let model = Arc::new(MockModel::new(vec![MockModel::text(written), MockModel::text("Resized to 400 px.")]));
2576        let tools = Arc::new(ImageTools::default());
2577
2578        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
2579
2580        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400})]);
2581        assert_eq!(out.outputs["iterations"], Value::Int(2));
2582        let second = &model.requests()[1].messages;
2583        let assistant = second.iter().find(|message| !message.tool_calls.is_empty()).unwrap();
2584        assert_eq!(assistant.tool_calls[0].name, "image_resize");
2585        assert!(out.outputs["text"].as_str().unwrap().ends_with("Resized to 400 px."));
2586    }
2587
2588    #[tokio::test]
2589    async fn a_call_written_as_a_command_is_made() {
2590        let written = "I use this command: `resize --max-width 400 a.png`";
2591        let model = Arc::new(MockModel::new(vec![MockModel::text(written), MockModel::text("Resized to 400 px.")]));
2592        let tools = Arc::new(ImageTools::default());
2593
2594        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
2595
2596        // The written "400" is put into the integer the schema asks for.
2597        assert_eq!(*tools.arguments.lock().unwrap(), [json!({"path": "a.png", "max_width": 400})]);
2598        assert_eq!(out.outputs["iterations"], Value::Int(2));
2599        assert!(out.outputs["text"].as_str().unwrap().ends_with("Resized to 400 px."));
2600    }
2601
2602    #[tokio::test]
2603    async fn a_call_without_a_required_argument_is_asked_again_once() {
2604        let model = Arc::new(MockModel::new(vec![
2605            MockModel::tool_calls(&[("c1", "image_resize", r#"{"path": "a.png"}"#)]),
2606            MockModel::tool_calls(&[("c2", "image_resize", r#"{"path": "a.png"}"#)]),
2607            MockModel::text("I could not resize it."),
2608        ]));
2609        let tools = Arc::new(ImageTools::default());
2610
2611        let out = completed(image_agent().run(image_ctx(&model, &tools)).await);
2612
2613        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2614        let first_result = log[0].get_path(&["result"]).unwrap();
2615        assert!(first_result.as_str().unwrap().contains("`max_width` (Largest width in pixels)"), "{first_result:?}");
2616        // Asked once; the second call reaches the tool, which answers for itself.
2617        assert_eq!(tools.arguments.lock().unwrap().len(), 1);
2618        assert!(log[1].get_path(&["result"]).unwrap().as_str().unwrap().contains("invalid arguments"));
2619    }
2620
2621    const JWT: &str = "eyJhbGciOiJIUzI1NiJ9.user-token";
2622
2623    /// Tool `whoami {}` that echoes its context (as a careless upstream error would).
2624    #[derive(Debug)]
2625    struct VaultTools {
2626        accepts: bool,
2627        contexts: Mutex<Vec<ToolCallContext>>,
2628    }
2629
2630    impl VaultTools {
2631        fn new(accepts: bool) -> Arc<Self> {
2632            Arc::new(Self { accepts, contexts: Mutex::default() })
2633        }
2634    }
2635
2636    impl ToolRuntime for VaultTools {
2637        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
2638            let spec = ToolSpec { name: "whoami".into(), description: "d".into(), parameters: json!({}) };
2639            Box::pin(async move { Ok(vec![spec]) })
2640        }
2641
2642        fn call<'a>(
2643            &'a self,
2644            _name: &'a str,
2645            _arguments: Json,
2646            context: &'a ToolCallContext,
2647        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
2648            self.contexts.lock().unwrap().push(context.clone());
2649            let token = context.secret("user_jwt").unwrap_or("none").to_owned();
2650            Box::pin(async move { Ok(ToolOutput::text(format!("rejected token {token}"))) })
2651        }
2652
2653        fn accepts_secrets(&self) -> bool {
2654            self.accepts
2655        }
2656    }
2657
2658    fn vault_ctx(s: &Setup, vault: &Arc<VaultTools>) -> NodeContext {
2659        let mut registry = ToolRegistry::new();
2660        registry.add("vault", Arc::clone(vault) as Arc<dyn ToolRuntime>);
2661        let services = Services::new()
2662            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
2663            .with(registry);
2664        let mut pool = VariablePool::new();
2665        pool.insert("sys", "query", Value::from("who am I?"));
2666        pool.insert("start", "user_jwt", Value::Secret(Arc::from(JWT)));
2667        let events = Arc::clone(&s.events);
2668        NodeContext::for_test("agent", pool)
2669            .with_services(Arc::new(services))
2670            .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
2671    }
2672
2673    fn vault_agent(extra: Json) -> AgentNode {
2674        let mut config = json!({
2675            "model": {"provider": "openai", "name": "gpt"},
2676            "tools": ["vault/whoami"],
2677            "tool_context": {"vault": {"user_jwt": "{{#start.user_jwt#}}", "missing": "{{#start.nope#}}"}},
2678        });
2679        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
2680            c.extend(e);
2681        }
2682        AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap()
2683    }
2684
2685    #[tokio::test]
2686    async fn tool_context_reaches_the_tool_but_nothing_else() {
2687        let s = setup(vec![
2688            MockModel::tool_calls(&[("c1", "whoami", &format!(r#"{{"echo":"{JWT}"}}"#))]),
2689            MockModel::text("done"),
2690        ]);
2691        let vault = VaultTools::new(true);
2692        let secrets = Arc::new(graphrt_core::redact::SecretSet::new());
2693        let ctx = vault_ctx(&s, &vault).with_secret_values(Arc::clone(&secrets));
2694        let node = vault_agent(json!({}));
2695        let out = completed(node.run(ctx).await);
2696
2697        let contexts = vault.contexts.lock().unwrap().clone();
2698        assert_eq!(contexts.len(), 1);
2699        assert_eq!(contexts[0].secret("user_jwt"), Some(JWT));
2700        assert_eq!(contexts[0].secret("missing"), None, "empty renders are left out");
2701
2702        // Not in the model's history, the outputs or any event.
2703        let requests = s.model.requests();
2704        assert_eq!(requests[1].messages.last().unwrap().text(), "rejected token ******");
2705        // (The model's own arguments stay in its history as it wrote them.)
2706        let tool_messages: Vec<_> = requests[1].messages.iter().filter(|m| m.role == Role::Tool).collect();
2707        assert!(!format!("{tool_messages:?}").contains(JWT));
2708        assert!(!serde_json::to_string(&out.outputs).unwrap().contains(JWT));
2709        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
2710        assert!(!events.contains(JWT), "{events}");
2711        // Registered with the run so later node errors are scrubbed too.
2712        assert_eq!(secrets.scrub(&format!("bad {JWT}")), "bad ******");
2713        assert!(node.inputs().iter().any(|sel| sel.to_string() == "start.user_jwt"));
2714    }
2715
2716    #[tokio::test]
2717    async fn captured_tool_results_never_carry_the_tool_context() {
2718        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
2719        let vault = VaultTools::new(true);
2720        let base = vault_ctx(&s, &vault);
2721        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2722        completed(vault_agent(json!({})).run(base.with_services(Arc::new(services))).await);
2723        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("rejected token ******")));
2724        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
2725        assert!(!events.contains(JWT), "{events}");
2726    }
2727
2728    #[tokio::test]
2729    async fn tool_results_are_masked_before_they_are_cut() {
2730        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
2731        let vault = VaultTools::new(true);
2732        let base = vault_ctx(&s, &vault);
2733        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2734        // The cut falls inside the echoed token: masking afterwards would miss its prefix.
2735        let limit = "rejected token ".len() + 12;
2736        let node = vault_agent(json!({"max_tool_output_chars": limit}));
2737        completed(node.run(base.with_services(Arc::new(services))).await);
2738        let token_prefix = &JWT[..12];
2739        let events = serde_json::to_string(&*s.events.lock().unwrap()).unwrap();
2740        assert!(!events.contains(token_prefix), "{events}");
2741        let requests = s.model.requests();
2742        assert!(!format!("{:?}", requests[1].messages).contains(token_prefix));
2743    }
2744
2745    #[tokio::test]
2746    async fn tool_context_is_sent_again_after_approval() {
2747        let s = setup(vec![MockModel::tool_calls(&[("c1", "whoami", "{}")]), MockModel::text("done")]);
2748        let vault = VaultTools::new(true);
2749        let node = vault_agent(json!({"require_approval": ["*"]}));
2750        let paused = match node.run(vault_ctx(&s, &vault)).await.unwrap() {
2751            NodeOutcome::Paused(p) => p,
2752            NodeOutcome::Completed(_) => panic!("expected a pause"),
2753        };
2754        assert!(!paused.state.to_string().contains(JWT), "the snapshot state never holds the context");
2755        let resume = Resume { state: paused.state, input: Some(Value::Bool(true)) };
2756        completed(node.run(vault_ctx(&s, &vault).with_resume(Some(resume))).await);
2757        assert_eq!(vault.contexts.lock().unwrap()[0].secret("user_jwt"), Some(JWT));
2758    }
2759
2760    #[tokio::test]
2761    async fn tool_context_needs_a_provider_that_accepts_secrets() {
2762        let s = setup(vec![MockModel::text("unused")]);
2763        let vault = VaultTools::new(false);
2764        let error = vault_agent(json!({})).run(vault_ctx(&s, &vault)).await.unwrap_err();
2765        assert_eq!(error.kind, "tool_context_denied");
2766        assert!(vault.contexts.lock().unwrap().is_empty());
2767    }
2768
2769    #[test]
2770    fn tool_context_providers_must_be_used() {
2771        let config = json!({
2772            "model": {"provider": "openai", "name": "gpt"},
2773            "tools": ["math/add"],
2774            "tool_context": {"vault": {"user_jwt": "x"}},
2775        });
2776        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
2777        assert!(error.to_string().contains("`vault` is not used"), "{error}");
2778        for bad in [json!({"math": {"jwt": 1}}), json!({"math": {"": "x"}}), json!({"math": "x"})] {
2779            let config =
2780                json!({"model": {"provider": "openai", "name": "gpt"}, "tools": ["math/add"], "tool_context": bad});
2781            assert!(AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).is_err());
2782        }
2783    }
2784
2785    fn tool_results(s: &Setup) -> Vec<Value> {
2786        let events = s.events.lock().unwrap();
2787        let results = events.iter().filter_map(|e| match e {
2788            Event::NodeProgress { name, data, .. } if name == "tool_result" => Some(data.clone()),
2789            _ => None,
2790        });
2791        results.collect()
2792    }
2793
2794    #[tokio::test]
2795    async fn tool_results_carry_text_only_when_the_host_captures_content() {
2796        let responses = || vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")];
2797        let s = setup(responses());
2798        completed(agent(json!({})).run(ctx(&s)).await);
2799        assert_eq!(tool_results(&s)[0].get_path(&["result"]), None);
2800
2801        let s = setup(responses());
2802        let base = ctx(&s);
2803        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2804        completed(agent(json!({})).run(base.with_services(Arc::new(services))).await);
2805        assert_eq!(tool_results(&s)[0].get_path(&["result"]), Some(Value::from("5")));
2806    }
2807
2808    #[tokio::test]
2809    async fn tool_images_reach_the_model() {
2810        let s = setup(vec![MockModel::tool_calls(&[("c1", "screenshot", "{}")]), MockModel::text("a login form")]);
2811        let out = completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2812        let requests = s.model.requests();
2813        let result = &requests[1].messages[3];
2814        assert_eq!(result.role, Role::Tool);
2815        assert_eq!(result.text(), "800x600");
2816        assert_eq!(
2817            result.images().cloned().collect::<Vec<_>>(),
2818            vec![ContentPart::Image { url: "data:image/png;base64,aGVsbG8=".into(), detail: None }]
2819        );
2820        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2821        assert_eq!(log[0].get_path(&["images"]), Some(Value::Int(1)));
2822        let reported = s.events.lock().unwrap().iter().find_map(|e| match e {
2823            Event::NodeProgress { name, data, .. } if name == "tool_result" => data.get_path(&["images"]),
2824            _ => None,
2825        });
2826        assert_eq!(reported, Some(Value::Int(1)));
2827    }
2828
2829    #[tokio::test]
2830    async fn invalid_tool_images_are_dropped_with_a_note() {
2831        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
2832        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2833        let result = &s.model.requests()[1].messages[3];
2834        assert_eq!(result.images().count(), 0);
2835        assert!(
2836            result.text().starts_with("odd\n[images dropped: image #0: image media type `image/bmp`"),
2837            "{}",
2838            result.text()
2839        );
2840    }
2841
2842    #[tokio::test]
2843    async fn captured_tool_result_text_matches_what_the_model_sees() {
2844        let s = setup(vec![MockModel::tool_calls(&[("c1", "bad_image", "{}")]), MockModel::text("ok")]);
2845        let base = ctx(&s);
2846        let services = (*base.services).clone().with(graphrt_core::node::CaptureContent);
2847        let out = completed(agent(json!({"tools": ["screen/*"]})).run(base.with_services(Arc::new(services))).await);
2848        let seen_by_model = s.model.requests()[1].messages[3].text();
2849        assert!(seen_by_model.contains("[images dropped:"), "{seen_by_model}");
2850        let reported = tool_results(&s)[0].get_path(&["result"]);
2851        assert_eq!(reported, Some(Value::from(seen_by_model.clone())), "progress event");
2852        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
2853        assert_eq!(log[0].get_path(&["result"]), Some(Value::from(seen_by_model)), "tool_calls output");
2854    }
2855
2856    #[tokio::test]
2857    async fn keep_tool_images_prunes_older_screenshots() {
2858        let s = setup(vec![
2859            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
2860            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
2861            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
2862            MockModel::text("done"),
2863        ]);
2864        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": 2})).run(ctx(&s)).await);
2865        let last = s.model.requests().last().cloned().unwrap();
2866        let results: Vec<&Message> = last.messages.iter().filter(|m| m.role == Role::Tool).collect();
2867        assert_eq!(results.iter().map(|m| m.images().count()).collect::<Vec<_>>(), [0, 1, 1]);
2868        assert_eq!(results[0].text(), "800x600\n[1 image removed from history]");
2869        // The second request still had every image (only two existed).
2870        let second = &s.model.requests()[2];
2871        assert_eq!(second.messages.iter().map(|m| m.images().count()).sum::<usize>(), 2);
2872    }
2873
2874    fn four_screenshots() -> Vec<Vec<crate::ChatDelta>> {
2875        vec![
2876            MockModel::tool_calls(&[("c1", "screenshot", "{}")]),
2877            MockModel::tool_calls(&[("c2", "screenshot", "{}")]),
2878            MockModel::tool_calls(&[("c3", "screenshot", "{}")]),
2879            MockModel::tool_calls(&[("c4", "screenshot", "{}")]),
2880            MockModel::text("done"),
2881        ]
2882    }
2883
2884    fn images_per_tool_result(s: &Setup) -> Vec<usize> {
2885        let last = s.model.requests().last().cloned().unwrap();
2886        last.messages.iter().filter(|m| m.role == Role::Tool).map(|m| m.images().count()).collect()
2887    }
2888
2889    #[tokio::test]
2890    async fn keep_tool_images_defaults_to_the_last_three() {
2891        let s = setup(four_screenshots());
2892        completed(agent(json!({"tools": ["screen/*"]})).run(ctx(&s)).await);
2893        assert_eq!(images_per_tool_result(&s), [0, 1, 1, 1]);
2894    }
2895
2896    #[tokio::test]
2897    async fn keep_tool_images_null_keeps_every_image() {
2898        let s = setup(four_screenshots());
2899        completed(agent(json!({"tools": ["screen/*"], "keep_tool_images": null})).run(ctx(&s)).await);
2900        assert_eq!(images_per_tool_result(&s), [1, 1, 1, 1]);
2901    }
2902
2903    #[tokio::test]
2904    async fn last_iteration_keeps_tools_but_forbids_calls() {
2905        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), MockModel::text("2")]);
2906        let out = completed(agent(json!({"max_iterations": 2})).run(ctx(&s)).await);
2907        assert_eq!(out.outputs["text"], Value::from("2"));
2908        assert_eq!(out.outputs["stopped_reason"], Value::from("max_iterations"));
2909        let requests = s.model.requests();
2910        assert_eq!(requests[0].tool_choice, Some(ToolChoice::Auto));
2911        assert!(!requests[1].tools.is_empty(), "tool definitions stay for the history's tool calls");
2912        assert_eq!(requests[1].tool_choice, Some(ToolChoice::None));
2913    }
2914
2915    fn text_chunks(s: &Setup) -> Vec<String> {
2916        s.events
2917            .lock()
2918            .unwrap()
2919            .iter()
2920            .filter_map(|e| match e {
2921                Event::NodeChunk { field, chunk, .. } if field.as_ref() == "text" => Some(chunk.clone()),
2922                _ => None,
2923            })
2924            .collect()
2925    }
2926
2927    fn thought(s: &Setup) -> Option<Value> {
2928        s.events.lock().unwrap().iter().find_map(|e| match e {
2929            Event::NodeProgress { name, data, .. } if name == "agent_thought" => Some(data.clone()),
2930            _ => None,
2931        })
2932    }
2933
2934    fn tokens(pieces: &[&str]) -> Vec<crate::ChatDelta> {
2935        let mut out: Vec<crate::ChatDelta> = pieces.iter().map(|p| crate::ChatDelta::Text((*p).into())).collect();
2936        out.push(crate::ChatDelta::Finish(FinishReason::Stop));
2937        out
2938    }
2939
2940    #[tokio::test]
2941    async fn final_answer_streams_token_by_token() {
2942        let s =
2943            setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), tokens(&["It", " is", " 5", "."])]);
2944        let out = completed(agent(json!({})).run(ctx(&s)).await);
2945        // One chunk per provider delta, on a turn that was still allowed to call tools.
2946        assert_eq!(text_chunks(&s), ["It", " is", " 5", "."]);
2947        assert_eq!(out.outputs["text"], Value::from("It is 5."));
2948        assert_eq!(s.model.requests()[1].tool_choice, Some(ToolChoice::Auto));
2949    }
2950
2951    #[tokio::test]
2952    async fn preamble_before_a_tool_call_is_streamed_and_kept_in_the_answer() {
2953        let mut first = tokens(&["Let me", " check."]);
2954        first.pop();
2955        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
2956        let s = setup(vec![first, tokens(&["It is", " 5."])]);
2957        let out = completed(agent(json!({})).run(ctx(&s)).await);
2958        let chunks = text_chunks(&s);
2959        assert_eq!(chunks, ["Let me", " check.", "\n\n", "It is", " 5."]);
2960        assert_eq!(out.outputs["text"], Value::from(chunks.concat().as_str()));
2961        let thought = thought(&s).unwrap();
2962        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
2963        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(true)));
2964        // The history keeps each turn separate: the preamble belongs to the tool-call turn.
2965        let second = &s.model.requests()[1].messages;
2966        assert_eq!(second[2].text(), "Let me check.");
2967        assert_eq!(second[2].tool_calls.len(), 1);
2968    }
2969
2970    #[tokio::test]
2971    async fn tool_call_fragments_and_later_text_are_never_streamed() {
2972        use crate::ChatDelta::{Finish, Text, ToolCall};
2973        let first = vec![
2974            Text("A".into()),
2975            ToolCall { index: 0, id: Some("c1".into()), name: Some("add".into()), arguments: r#"{"a":"#.into() },
2976            Text("B".into()),
2977            ToolCall { index: 0, id: None, name: None, arguments: "1}".into() },
2978            Finish(FinishReason::ToolCalls),
2979        ];
2980        let s = setup(vec![first, MockModel::text("done")]);
2981        let out = completed(agent(json!({})).run(ctx(&s)).await);
2982        assert_eq!(text_chunks(&s), ["A", "\n\n", "done"]);
2983        assert_eq!(out.outputs["text"], Value::from("A\n\ndone"));
2984        assert_eq!(thought(&s).unwrap().get_path(&["text"]), Some(Value::from("AB")));
2985        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
2986    }
2987
2988    #[tokio::test]
2989    async fn stream_tool_turns_false_buffers_tool_turns() {
2990        let mut first = vec![crate::ChatDelta::Text("Let me check.".into())];
2991        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]));
2992        let s = setup(vec![first, tokens(&["It is", " 5."])]);
2993        let out = completed(agent(json!({"stream_tool_turns": false})).run(ctx(&s)).await);
2994        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
2995        assert_eq!(text_chunks(&s), ["It is 5."]);
2996        assert_eq!(out.outputs["text"], Value::from("It is 5."));
2997        let thought = thought(&s).unwrap();
2998        assert_eq!(thought.get_path(&["text"]), Some(Value::from("Let me check.")));
2999        assert_eq!(thought.get_path(&["streamed"]), Some(Value::Bool(false)));
3000    }
3001
3002    #[tokio::test]
3003    async fn forced_final_turn_streams_token_by_token() {
3004        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#)]), tokens(&["=", "2"])]);
3005        let out = completed(agent(json!({"max_iterations": 2, "stream_tool_turns": false})).run(ctx(&s)).await);
3006        assert_eq!(text_chunks(&s), ["=", "2"]);
3007        assert_eq!(out.outputs["text"], Value::from("=2"));
3008    }
3009
3010    #[tokio::test]
3011    async fn preamble_survives_a_tool_approval_pause() {
3012        let mut first = vec![crate::ChatDelta::Text("Checking.".into())];
3013        first.extend(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
3014        let s = setup(vec![first, MockModel::text("4")]);
3015        let node = agent(json!({"require_approval": ["add"]}));
3016        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
3017        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
3018        let resumed =
3019            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
3020        let out = completed(node.run(resumed).await);
3021        assert_eq!(out.outputs["text"], Value::from("Checking.\n\n4"));
3022        assert_eq!(text_chunks(&s), ["Checking.", "\n\n", "4"]);
3023    }
3024
3025    #[tokio::test]
3026    async fn malformed_arguments_are_reported_back_to_the_model() {
3027        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"#)]), MockModel::text("sorry")]);
3028        let out = completed(agent(json!({})).run(ctx(&s)).await);
3029        assert!(s.tools.calls.lock().unwrap().is_empty(), "malformed calls never run");
3030        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
3031        assert_eq!(log[0].get_path(&["arguments"]), Some(Value::from(r#"{"a":2,"#)));
3032        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
3033        let second = &s.model.requests()[1];
3034        assert_eq!(second.messages[2].tool_calls[0].arguments, "{}", "history never replays malformed JSON");
3035        assert!(second.messages[3].text().contains("invalid JSON arguments"));
3036    }
3037
3038    #[tokio::test]
3039    async fn per_turn_limit_rejects_extra_calls() {
3040        let s = setup(vec![
3041            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
3042            MockModel::text("ok"),
3043        ]);
3044        let out =
3045            completed(agent(json!({"max_tool_calls_per_turn": 1, "parallel_tool_calls": false})).run(ctx(&s)).await);
3046        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
3047        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
3048        assert_eq!(log[0].get_path(&["is_error"]), Some(Value::Bool(true)));
3049    }
3050
3051    #[tokio::test]
3052    async fn approval_pauses_and_resumes() {
3053        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]), MockModel::text("4")]);
3054        let node = agent(json!({"tools": [{"provider": "math", "name": "add"}], "require_approval": ["math/add"]}));
3055        let paused = match node.run(ctx(&s)).await.unwrap() {
3056            NodeOutcome::Paused(p) => p,
3057            NodeOutcome::Completed(_) => panic!("expected pause"),
3058        };
3059        assert_eq!(paused.kind, "tool_approval");
3060        assert_eq!(paused.data.get_path(&["calls", "0", "name"]), Some(Value::from("add")));
3061        assert!(s.tools.calls.lock().unwrap().is_empty(), "nothing runs before approval");
3062
3063        // The saved state survives serialization (snapshots store it as JSON).
3064        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
3065        let resumed =
3066            ctx(&s).with_resume(Some(Resume { state, input: Some(Value::from_json(json!({"approved": true}))) }));
3067        let out = completed(node.run(resumed).await);
3068        assert_eq!(out.outputs["text"], Value::from("4"));
3069        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
3070    }
3071
3072    #[tokio::test]
3073    async fn denied_calls_are_reported_to_the_model() {
3074        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", "{}")]), MockModel::text("fine")]);
3075        let node = agent(json!({"require_approval": ["*"]}));
3076        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
3077        let input = Value::from_json(json!({"approvals": {"c1": false}, "reason": "not now"}));
3078        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
3079        assert_eq!(out.outputs["text"], Value::from("fine"));
3080        assert!(s.tools.calls.lock().unwrap().is_empty());
3081        let last_request = s.model.requests().pop().unwrap();
3082        assert!(last_request.messages.iter().any(|m| m.text().contains("not now")));
3083    }
3084
3085    #[tokio::test]
3086    async fn only_gated_calls_wait_for_approval() {
3087        let s = setup(vec![
3088            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "fail", "{}")]),
3089            MockModel::text("done"),
3090        ]);
3091        let node = agent(json!({"require_approval": ["math/fail"]}));
3092        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
3093        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"], "ungated calls run immediately");
3094        assert_eq!(p.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
3095        assert!(p.data.get_path(&["calls", "1"]).is_none());
3096
3097        // No decision (or one that is not understood) keeps the run paused.
3098        for input in [None, Some(Value::from("yes")), Some(Value::from_json(json!({"approved": "true"})))] {
3099            let resumed = ctx(&s).with_resume(Some(Resume { state: p.state.clone(), input }));
3100            assert!(matches!(node.run(resumed).await.unwrap(), NodeOutcome::Paused(_)));
3101        }
3102        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
3103
3104        let input = Value::from_json(json!({"approvals": {"c2": true}}));
3105        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await);
3106        assert_eq!(out.outputs["text"], Value::from("done"));
3107        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add", "fail"]);
3108    }
3109
3110    #[tokio::test]
3111    async fn per_call_decisions_can_arrive_in_steps() {
3112        let s = setup(vec![
3113            MockModel::tool_calls(&[("c1", "add", r#"{"a":1,"b":1}"#), ("c2", "add", r#"{"a":2,"b":2}"#)]),
3114            MockModel::text("ok"),
3115        ]);
3116        let node = agent(json!({"require_approval": ["*"], "parallel_tool_calls": false}));
3117        let NodeOutcome::Paused(p) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
3118        let input = Value::from_json(json!({"approvals": {"c1": true}}));
3119        let NodeOutcome::Paused(p2) =
3120            node.run(ctx(&s).with_resume(Some(Resume { state: p.state, input: Some(input) }))).await.unwrap()
3121        else {
3122            panic!("c2 is still undecided")
3123        };
3124        assert_eq!(s.tools.calls.lock().unwrap().len(), 1);
3125        assert_eq!(p2.data.get_path(&["calls", "0", "id"]), Some(Value::from("c2")));
3126        let input = Value::from_json(json!({"approved": false}));
3127        let out = completed(node.run(ctx(&s).with_resume(Some(Resume { state: p2.state, input: Some(input) }))).await);
3128        assert_eq!(out.outputs["text"], Value::from("ok"));
3129        assert_eq!(s.tools.calls.lock().unwrap().len(), 1, "c2 was denied");
3130    }
3131
3132    /// Tool `page {}`: a long result, like a fetched web page.
3133    #[cfg(feature = "context")]
3134    #[derive(Debug, Default)]
3135    struct PageTools {
3136        calls: Mutex<usize>,
3137    }
3138
3139    #[cfg(feature = "context")]
3140    impl ToolRuntime for PageTools {
3141        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
3142            let spec = ToolSpec { name: "page".into(), description: "fetch a page".into(), parameters: json!({}) };
3143            Box::pin(async move { Ok(vec![spec]) })
3144        }
3145
3146        fn call<'a>(
3147            &'a self,
3148            _name: &'a str,
3149            _arguments: Json,
3150            _context: &'a ToolCallContext,
3151        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
3152            let n = {
3153                let mut calls = self.calls.lock().unwrap();
3154                *calls += 1;
3155                *calls
3156            };
3157            Box::pin(async move { Ok(ToolOutput::text(format!("page {n}: {}", "lorem ".repeat(3_500)))) })
3158        }
3159    }
3160
3161    /// A context with the `page` and `math` tools and a model that fetches
3162    /// `pages` pages, one per turn, before the rest of its script.
3163    #[cfg(feature = "context")]
3164    fn page_ctx(pages: usize) -> (Setup, Arc<PageTools>, impl Fn() -> NodeContext) {
3165        let s = setup((1..=pages).map(|n| MockModel::tool_calls(&[(&format!("p{n}"), "page", "{}")])).collect());
3166        let page_tools = Arc::new(PageTools::default());
3167        let (model, tools, events) = (Arc::clone(&s.model), Arc::clone(&s.tools), Arc::clone(&s.events));
3168        let pages = Arc::clone(&page_tools);
3169        let ctx = move || {
3170            let mut tool_registry = ToolRegistry::new();
3171            tool_registry.add("math", Arc::clone(&tools) as Arc<dyn ToolRuntime>);
3172            tool_registry.add("web", Arc::clone(&pages) as Arc<dyn ToolRuntime>);
3173            let services = Services::new()
3174                .with(ModelRegistry::new().with("openai", Arc::clone(&model) as Arc<dyn crate::ChatModel>))
3175                .with(tool_registry);
3176            let mut pool = VariablePool::new();
3177            pool.insert("sys", "query", Value::from("read the pages"));
3178            let events = Arc::clone(&events);
3179            NodeContext::for_test("agent", pool)
3180                .with_services(Arc::new(services))
3181                .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
3182        };
3183        (s, page_tools, ctx)
3184    }
3185
3186    #[cfg(feature = "context")]
3187    fn page_agent(extra: Json) -> AgentNode {
3188        let mut config = json!({"tools": ["web/*", "math/*"], "max_iterations": 30});
3189        if let (Some(c), Json::Object(e)) = (config.as_object_mut(), extra) {
3190            c.extend(e);
3191        }
3192        agent(config)
3193    }
3194
3195    /// Every tool result of a request has its call in the assistant message
3196    /// before its run of results, and every call has its result.
3197    #[cfg(feature = "context")]
3198    fn assert_request_pairs(messages: &[Message]) {
3199        let mut open: Vec<String> = Vec::new();
3200        for message in messages {
3201            if message.role == Role::Tool {
3202                let id = message.tool_call_id.clone().unwrap();
3203                assert!(open.contains(&id), "result {id} without its call");
3204                open.retain(|other| other != &id);
3205            } else {
3206                assert!(open.is_empty(), "calls without results: {open:?}");
3207                open = message.tool_calls.iter().map(|call| call.id.clone()).collect();
3208            }
3209        }
3210        assert!(open.is_empty(), "calls without results: {open:?}");
3211    }
3212
3213    #[cfg(feature = "context")]
3214    fn progress_named(events: &Mutex<Vec<Event>>, wanted: &str) -> Vec<Json> {
3215        events
3216            .lock()
3217            .unwrap()
3218            .iter()
3219            .filter_map(|e| match e {
3220                Event::NodeProgress { name, data, .. } if name == wanted => Some(data.to_json()),
3221                _ => None,
3222            })
3223            .collect()
3224    }
3225
3226    #[cfg(feature = "context")]
3227    fn too_long(window: u64, sent: u64) -> crate::LlmError {
3228        crate::LlmError::ContextLength(format!(
3229            "This model's maximum context length is {window} tokens. However, your messages resulted in {sent} tokens."
3230        ))
3231    }
3232
3233    #[cfg(feature = "context")]
3234    #[tokio::test]
3235    async fn a_turn_refused_for_its_size_is_trimmed_and_sent_again() {
3236        let (s, pages, ctx) = page_ctx(6);
3237        s.model.push_error(too_long(20_000, 36_500));
3238        s.model.push(MockModel::text("done"));
3239        let out = completed(page_agent(json!({})).run(ctx()).await);
3240        assert_eq!(out.outputs["text"], Value::from("done"));
3241        assert_eq!(out.outputs["stopped_reason"], Value::from("completed"));
3242        // The outputs say that the model was not sent everything.
3243        assert_eq!(
3244            out.outputs["context"].to_json(),
3245            json!({"removed_messages": 8, "placeholders": 0, "cut_results": 1, "summarized": false, "unsummarized_messages": 0})
3246        );
3247        assert_eq!(*pages.calls.lock().unwrap(), 6, "no tool ran twice");
3248        // Six tool turns, the refused turn and the same turn again.
3249        let requests = s.model.requests();
3250        assert_eq!(requests.len(), 8);
3251        let (refused, retried) = (&requests[6], &requests[7]);
3252        assert!(crate::context::estimate_messages(&retried.messages) < 15_000);
3253        assert!(
3254            crate::context::estimate_messages(&refused.messages) > 30_000,
3255            "nothing was trimmed before the provider refused"
3256        );
3257        assert_request_pairs(&retried.messages);
3258        assert_eq!(retried.messages[0], refused.messages[0], "the system message is unchanged");
3259        let user = retried.messages.iter().find(|m| m.role == Role::User).unwrap().text();
3260        assert!(user.ends_with("read the pages"), "the request stays");
3261        assert!(user.starts_with("[Context note, written by the runtime. 8 earlier message(s)"), "{user}");
3262        assert_eq!(retried.tools, refused.tools);
3263        let trims = progress_named(&s.events, "context_trimmed");
3264        assert_eq!(trims.len(), 1);
3265        assert_eq!(trims[0]["reason"], "provider_limit");
3266        // The `tool_calls` output still has every result in full.
3267        let log = out.outputs["tool_calls"].as_array().unwrap().to_vec();
3268        assert_eq!(log.len(), 6);
3269        assert!(log[0].get_path(&["result"]).unwrap().to_text().len() > 20_000);
3270    }
3271
3272    #[cfg(feature = "context")]
3273    #[tokio::test]
3274    async fn a_second_refusal_fails_the_node_with_the_same_kind() {
3275        let (s, pages, ctx) = page_ctx(6);
3276        s.model.push_error(too_long(20_000, 36_500));
3277        s.model.push_error(too_long(20_000, 21_000));
3278        s.model.push(MockModel::text("never reached"));
3279        let error = page_agent(json!({})).run(ctx()).await.unwrap_err();
3280        assert_eq!(error.kind, "model_context_length");
3281        assert!(!error.retryable);
3282        assert!(error.message.contains("21000 tokens"), "the provider's own words: {}", error.message);
3283        assert!(error.message.contains("already trimmed the conversation and sent it again"), "{}", error.message);
3284        assert_eq!(s.model.requests().len(), 8, "sent again once, not in a loop");
3285        assert_eq!(*pages.calls.lock().unwrap(), 6);
3286    }
3287
3288    #[cfg(feature = "context")]
3289    #[tokio::test]
3290    async fn off_fails_on_the_first_refusal_as_before() {
3291        let (s, _, ctx) = page_ctx(6);
3292        s.model.push_error(too_long(20_000, 36_500));
3293        s.model.push(MockModel::text("never reached"));
3294        let error = page_agent(json!({"context_window": "off"})).run(ctx()).await.unwrap_err();
3295        assert_eq!(error.kind, "model_context_length");
3296        assert_eq!(s.model.requests().len(), 7);
3297        assert!(progress_named(&s.events, "context_trimmed").is_empty());
3298    }
3299
3300    #[cfg(feature = "context")]
3301    #[tokio::test]
3302    async fn a_run_that_fits_is_sent_exactly_as_before() {
3303        let (s, _, ctx) = page_ctx(3);
3304        s.model.push(MockModel::text("done"));
3305        let guarded = completed(page_agent(json!({})).run(ctx()).await);
3306        let with_guard = s.model.requests();
3307        let (s, _, ctx) = page_ctx(3);
3308        s.model.push(MockModel::text("done"));
3309        let plain = completed(page_agent(json!({"context_window": "off"})).run(ctx()).await);
3310        assert_eq!(with_guard, s.model.requests());
3311        assert_eq!(guarded.outputs, plain.outputs);
3312        assert!(!guarded.outputs.contains_key("context"), "nothing was trimmed, so there is nothing to say");
3313        assert!(progress_named(&s.events, "context_trimmed").is_empty());
3314    }
3315
3316    #[cfg(feature = "context")]
3317    #[tokio::test]
3318    async fn a_set_limit_keeps_every_request_under_it() {
3319        let (s, pages, ctx) = page_ctx(12);
3320        s.model.push(MockModel::text("done"));
3321        let node = page_agent(json!({"context_window": {"max_tokens": 40_000}}));
3322        let out = completed(node.run(ctx()).await);
3323        assert_eq!(out.outputs["text"], Value::from("done"));
3324        assert_eq!(*pages.calls.lock().unwrap(), 12);
3325        for (turn, request) in s.model.requests().iter().enumerate() {
3326            let size =
3327                crate::context::estimate_messages(&request.messages) + crate::context::estimate_tools(&request.tools);
3328            assert!(size <= 40_000, "turn {turn}: {size}");
3329            assert_request_pairs(&request.messages);
3330        }
3331        // Old results became placeholders, their calls are still in the conversation.
3332        let last = s.model.requests().pop().unwrap();
3333        let placeholders =
3334            last.messages.iter().filter(|m| m.text().starts_with("[tool result removed to save context")).count();
3335        assert!(placeholders >= 3, "{placeholders}");
3336        assert!(last.messages.iter().any(|m| m.text() == "read the pages"), "nothing was removed, so no note");
3337        let trims = progress_named(&s.events, "context_trimmed");
3338        assert!(!trims.is_empty() && trims.len() < 6, "trimmed in large steps, not on every turn: {}", trims.len());
3339        assert!(trims.iter().all(|trim| trim["reason"] == "budget"));
3340        // The result says so too, not only the events.
3341        let Value::Object(context) = &out.outputs["context"] else { panic!("no context output: {:?}", out.outputs) };
3342        assert!(context["placeholders"].to_json().as_u64().unwrap() >= 3);
3343    }
3344
3345    #[cfg(feature = "context")]
3346    #[tokio::test]
3347    async fn a_window_one_run_learned_is_used_by_the_next_run() {
3348        // One registry for both runs, as a host keeps it.
3349        let (s, pages, _) = page_ctx(6);
3350        let registry = ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>);
3351        let (tools, events) = (Arc::clone(&s.tools), Arc::clone(&s.events));
3352        let ctx = move || {
3353            let mut tool_registry = ToolRegistry::new();
3354            tool_registry.add("math", Arc::clone(&tools) as Arc<dyn ToolRuntime>);
3355            tool_registry.add("web", Arc::clone(&pages) as Arc<dyn ToolRuntime>);
3356            let mut pool = VariablePool::new();
3357            pool.insert("sys", "query", Value::from("read the pages"));
3358            let events = Arc::clone(&events);
3359            NodeContext::for_test("agent", pool)
3360                .with_services(Arc::new(Services::new().with(registry.clone()).with(tool_registry)))
3361                .with_sink(Arc::new(move |e| events.lock().unwrap().push(e)))
3362        };
3363        s.model.push_error(too_long(20_000, 36_500));
3364        s.model.push(MockModel::text("done"));
3365        completed(page_agent(json!({})).run(ctx()).await);
3366        let first_run = s.model.requests().len();
3367        s.events.lock().unwrap().clear();
3368        // The second run reads as many pages, and no refusal is queued: it
3369        // trims before sending, from what the first run learned.
3370        for n in 1..=6 {
3371            s.model.push(MockModel::tool_calls(&[(&format!("q{n}"), "page", "{}")]));
3372        }
3373        s.model.push(MockModel::text("done again"));
3374        let out = completed(page_agent(json!({})).run(ctx()).await);
3375        assert_eq!(out.outputs["text"], Value::from("done again"));
3376        let requests = s.model.requests();
3377        assert_eq!(requests.len() - first_run, 7, "no request of the second run was refused");
3378        for request in &requests[first_run..] {
3379            let size =
3380                crate::context::estimate_messages(&request.messages) + crate::context::estimate_tools(&request.tools);
3381            assert!(size < 20_000, "{size}");
3382        }
3383        let trims = progress_named(&s.events, "context_trimmed");
3384        assert!(!trims.is_empty() && trims.iter().all(|trim| trim["reason"] == "budget"), "{trims:?}");
3385    }
3386
3387    #[cfg(feature = "context")]
3388    #[tokio::test]
3389    async fn what_the_guard_learned_survives_a_pause() {
3390        let (s, _, ctx) = page_ctx(6);
3391        s.model.push_error(too_long(20_000, 36_500));
3392        s.model.push(MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)]));
3393        s.model.push(MockModel::tool_calls(&[("p7", "page", "{}")]));
3394        s.model.push(MockModel::text("done"));
3395        let node = page_agent(json!({"require_approval": ["math/add"]}));
3396        let NodeOutcome::Paused(paused) = node.run(ctx()).await.unwrap() else { panic!("expected pause") };
3397        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
3398        assert_eq!(state["context"]["window"], 20_000);
3399        let trimmed =
3400            ["removed", "placeholders", "cut"].iter().map(|k| state["context"][k].as_u64().unwrap_or(0)).sum::<u64>();
3401        assert!(trimmed > 0, "the refusal trimmed something: {}", state["context"]);
3402        // The call that waits for approval was not trimmed away.
3403        let pending_id = paused.data.get_path(&["calls", "0", "id"]).unwrap().to_text();
3404        assert!(state["messages"].to_string().contains(&format!(r#""id":"{pending_id}""#)));
3405
3406        let resume = Resume { state, input: Some(Value::from_json(json!({"approved": true}))) };
3407        let out = completed(node.run(ctx().with_resume(Some(resume))).await);
3408        assert_eq!(out.outputs["text"], Value::from("done"));
3409        assert_eq!(s.tools.calls.lock().unwrap().as_slice(), ["add"]);
3410        // After the resume the loop still knows the window: no request is refused or oversized.
3411        for request in s.model.requests().iter().skip(7) {
3412            assert!(crate::context::estimate_messages(&request.messages) <= 15_000);
3413            assert_request_pairs(&request.messages);
3414        }
3415    }
3416
3417    #[cfg(feature = "context")]
3418    #[tokio::test]
3419    async fn the_note_is_added_to_each_request_once_and_never_stored() {
3420        let (s, _, ctx) = page_ctx(6);
3421        s.model.push_error(too_long(20_000, 36_500));
3422        s.model.push(MockModel::text("Pages one to four were about lorem."));
3423        // Two more tool turns after the trim, then a call that pauses the run.
3424        s.model.push(MockModel::tool_calls(&[("a1", "add", r#"{"a":1,"b":1}"#)]));
3425        s.model.push(MockModel::tool_calls(&[("a2", "add", r#"{"a":2,"b":2}"#)]));
3426        s.model.push(MockModel::tool_calls(&[("c1", "fail", "{}")]));
3427        let node = page_agent(json!({"require_approval": ["math/fail"], "context_window": "summarize"}));
3428        let NodeOutcome::Paused(paused) = node.run(ctx()).await.unwrap() else { panic!("expected pause") };
3429        // Every request after the trim carries the note exactly once, in front of the request.
3430        let requests = s.model.requests();
3431        assert_eq!(requests.len(), 11);
3432        for request in requests.iter().skip(8) {
3433            let text: String = request.messages.iter().map(Message::text).collect();
3434            assert_eq!(text.matches("[Context note").count(), 1);
3435            assert_eq!(text.matches("[End of context note]").count(), 1);
3436            let user = request.messages.iter().find(|m| m.role == Role::User).unwrap().text();
3437            assert!(user.contains("Pages one to four were about lorem.") && user.ends_with("read the pages"));
3438        }
3439        let state: Json = serde_json::from_str(&paused.state.to_string()).unwrap();
3440        // The summary and the count are in the saved state. The note itself is not in any stored message.
3441        assert_eq!(state["context"]["summary"], "Pages one to four were about lorem.");
3442        assert!(state["context"]["removed"].as_u64().unwrap() > 0);
3443        assert!(!state["messages"].to_string().contains("Context note"));
3444
3445        let (s3, _, ctx3) = page_ctx(0);
3446        s3.model.push(MockModel::text("done"));
3447        let resume = Resume { state, input: Some(Value::from_json(json!({"approved": true}))) };
3448        let out = completed(node.run(ctx3().with_resume(Some(resume))).await);
3449        assert_eq!(out.outputs["text"], Value::from("done"));
3450        assert_eq!(out.outputs["context"].get_path(&["summarized"]), Some(Value::Bool(true)));
3451        // After the resume the summary is still what the model is told.
3452        let request = s3.model.requests().pop().unwrap();
3453        let user = request.messages.iter().find(|m| m.role == Role::User).unwrap().text();
3454        assert_eq!(user.matches("Pages one to four were about lorem.").count(), 1);
3455    }
3456
3457    #[cfg(feature = "memory")]
3458    #[test]
3459    fn the_turn_digest_masks_a_secret_even_where_a_result_is_cut() {
3460        let secret = "s3cr3t-0123456789abcdef";
3461        let secrets = graphrt_core::redact::SecretSet::new();
3462        secrets.observe_plaintext(secret);
3463        // The secret starts just before the cut of 300 characters.
3464        let result = format!("{}{secret} and more", "x".repeat(290));
3465        let entry = |provider: &str| ToolLogEntry {
3466            id: "c1".into(),
3467            name: "fetch".into(),
3468            provider: provider.into(),
3469            tool: "fetch".into(),
3470            arguments: json!({"token": secret}),
3471            result: result.clone(),
3472            is_error: false,
3473            images: 0,
3474            ui: Vec::new(),
3475            #[cfg(feature = "tool-files")]
3476            files: Vec::new(),
3477        };
3478        let digest = turn_digest(&[entry("web"), entry(crate::memory::MEMORY_PROVIDER)], Some(&secrets)).unwrap();
3479        assert!(!digest.contains(&secret[..8]), "{digest}");
3480        assert_eq!(digest.lines().count(), 1, "memory tools are left out: {digest}");
3481        assert!(turn_digest(&[], Some(&secrets)).is_none());
3482    }
3483
3484    #[cfg(all(feature = "context", feature = "skills"))]
3485    #[test]
3486    fn the_instructions_of_loaded_skills_are_pinned() {
3487        let entry = |id: &str, provider: &str, tool: &str, result: &str, is_error: bool| ToolLogEntry {
3488            id: id.into(),
3489            name: tool.into(),
3490            provider: provider.into(),
3491            tool: tool.into(),
3492            arguments: json!({}),
3493            result: result.into(),
3494            is_error,
3495            images: 0,
3496            ui: Vec::new(),
3497            #[cfg(feature = "tool-files")]
3498            files: Vec::new(),
3499        };
3500        let log = vec![
3501            entry("call_0", SKILL_PROVIDER, LOAD_SKILL_TOOL, "refund rules", false),
3502            entry("call_0", SKILL_PROVIDER, LOAD_SKILL_TOOL, "no such skill", true),
3503            entry("call_0", "web", "page", "a page", false),
3504            entry("call_0", "web", LOAD_SKILL_TOOL, "not a skill", false),
3505            entry("call_1", SKILL_PROVIDER, LOAD_SKILL_TOOL, "shipping rules", false),
3506            // The same skill again: only where it was loaded last.
3507            entry("call_2", SKILL_PROVIDER, LOAD_SKILL_TOOL, "refund rules", false),
3508        ];
3509        let pinned = pinned_results(&log, &[]);
3510        assert_eq!(pinned, [("call_1", "shipping rules".to_owned()), ("call_2", "refund rules".to_owned())]);
3511
3512        // With learned notes the model was shown a sentence more: that is the text to keep.
3513        #[cfg(feature = "learning")]
3514        {
3515            let messages = vec![
3516                Message::tool("call_1", "shipping rules"),
3517                Message::tool("call_2", format!("refund rules{NOTES_STILL_APPLY}")),
3518            ];
3519            let pinned = pinned_results(&log, &messages);
3520            assert_eq!(
3521                pinned,
3522                [("call_1", "shipping rules".to_owned()), ("call_2", format!("refund rules{NOTES_STILL_APPLY}"))]
3523            );
3524            // And the trim leaves exactly that message alone.
3525            let mut conversation = vec![Message::system("s"), Message::user("q")];
3526            for (id, text) in [("call_2", messages[1].text()), ("call_3", "r".repeat(40_000))] {
3527                conversation.push(Message {
3528                    tool_calls: vec![ToolCall { id: id.into(), name: "t".into(), arguments: "{}".into() }],
3529                    ..Message::assistant("")
3530                });
3531                conversation.push(Message::tool(id, text));
3532            }
3533            conversation.push(Message::user("next"));
3534            conversation.push(Message::assistant("ok"));
3535            let borrowed: Vec<(&str, &str)> = pinned.iter().map(|(id, text)| (*id, text.as_str())).collect();
3536            let scope = crate::context::Scope { pinned: &borrowed, tail: 0 };
3537            let keep = crate::context::Keep { tool_results: 0, turns: 1 };
3538            crate::context::trim(&mut conversation, 100, 100, keep, scope);
3539            assert!(conversation.iter().any(|m| m.text() == messages[1].text()), "the loaded skill was trimmed");
3540            assert!(!conversation.iter().any(|m| m.text().len() >= 40_000), "the other result was trimmed");
3541        }
3542    }
3543
3544    #[cfg(feature = "context")]
3545    #[tokio::test]
3546    async fn a_run_that_was_never_trimmed_saves_no_guard_state() {
3547        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":2}"#)])]);
3548        let node = agent(json!({"require_approval": ["*"]}));
3549        let NodeOutcome::Paused(paused) = node.run(ctx(&s)).await.unwrap() else { panic!("expected pause") };
3550        assert!(paused.state.get("context").is_none(), "{}", paused.state);
3551    }
3552
3553    #[cfg(feature = "context")]
3554    #[tokio::test]
3555    async fn summarize_carries_a_summary_instead_of_the_removed_turns() {
3556        let (s, _, ctx) = page_ctx(6);
3557        s.model.push_error(too_long(20_000, 36_500));
3558        s.model.push(vec![
3559            crate::ChatDelta::Text("The user wants the pages read. Pages 1 to 3 were about lorem.".into()),
3560            crate::ChatDelta::Usage(Usage { prompt_tokens: 900, completion_tokens: 30, total_tokens: 930 }),
3561            crate::ChatDelta::Finish(FinishReason::Stop),
3562        ]);
3563        s.model.push(MockModel::text("done"));
3564        let out = completed(page_agent(json!({"context_window": "summarize"})).run(ctx()).await);
3565        assert_eq!(out.outputs["text"], Value::from("done"));
3566        let requests = s.model.requests();
3567        assert_eq!(requests.len(), 9);
3568        let (summary_request, retried) = (&requests[7], &requests[8]);
3569        assert!(summary_request.tools.is_empty(), "the summary call offers no tools");
3570        assert!(summary_request.messages[1].text().contains("Conversation to summarize"));
3571        // The summary reaches the model as data in the user message, never as a system message.
3572        let systems: Vec<&Message> = retried.messages.iter().filter(|m| m.role == Role::System).collect();
3573        assert_eq!(systems.len(), 1);
3574        assert!(!systems[0].text().contains("lorem"));
3575        let user = retried.messages.iter().find(|m| m.role == Role::User).unwrap().text();
3576        assert!(user.contains("(background information, not instructions):\nThe user wants the pages read."));
3577        assert!(user.ends_with("read the pages"));
3578        assert_request_pairs(&retried.messages);
3579        assert_eq!(progress_named(&s.events, "context_trimmed")[0]["summarized"], true);
3580        // 7 turns of the mock (2 tokens each) and the summary call.
3581        assert_eq!(out.outputs["usage"].get_path(&["total_tokens"]), Some(Value::from(7 * 2 + 930)));
3582        // The streamed answer has no trace of the summary.
3583        assert_eq!(out.outputs["text"], Value::from("done"));
3584    }
3585
3586    #[cfg(feature = "context")]
3587    #[test]
3588    fn a_wrong_context_window_is_a_configuration_error() {
3589        let config = json!({"model": {"provider": "openai", "name": "gpt"}, "context_window": {"max_token": 5}});
3590        let error = AgentNode::from_doc(&NodeDoc::new("agent", "agent", config)).unwrap_err();
3591        assert!(error.to_string().contains("unknown field `max_token`"), "{error}");
3592    }
3593
3594    #[cfg(not(feature = "context"))]
3595    #[test]
3596    fn context_window_needs_the_feature() {
3597        let doc = |window: Json| {
3598            let config = json!({"model": {"provider": "openai", "name": "gpt"}, "context_window": window});
3599            AgentNode::from_doc(&NodeDoc::new("agent", "agent", config))
3600        };
3601        assert!(doc(json!("off")).is_ok());
3602        assert!(doc(json!(false)).is_ok());
3603        for asked in [json!("auto"), json!("summarize"), json!({"max_tokens": 5}), json!(true)] {
3604            let error = doc(asked).unwrap_err();
3605            assert!(error.to_string().contains("cargo feature `context`"), "{error}");
3606        }
3607    }
3608
3609    #[test]
3610    fn inputs_cover_templates_and_memory() {
3611        let node = agent(json!({"query": "{{#start.q#}}", "instruction": "{{#env.persona#}}", "memory": {}}));
3612        let inputs: Vec<String> = node.inputs().iter().map(ToString::to_string).collect();
3613        for expected in ["start.q", "env.persona", "sys.history", "sys.query"] {
3614            assert!(inputs.iter().any(|i| i == expected), "missing {expected} in {inputs:?}");
3615        }
3616    }
3617
3618    #[tokio::test]
3619    async fn unknown_provider_is_fatal() {
3620        let s = setup(vec![]);
3621        let err = agent(json!({"tools": ["nope/x"]})).run(ctx(&s)).await.unwrap_err();
3622        assert!(!err.retryable);
3623        assert_eq!(err.kind, "tool_not_found");
3624    }
3625
3626    #[cfg(not(feature = "learning"))]
3627    #[test]
3628    fn learning_without_learning_support_is_a_configuration_error() {
3629        let doc =
3630            NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "learning": {"agent": "x"}}));
3631        let error = AgentNode::from_doc(&doc).unwrap_err().to_string();
3632        assert!(error.contains("cargo feature `learning`"), "{error}");
3633    }
3634
3635    #[cfg(not(feature = "skills"))]
3636    #[test]
3637    fn listing_skills_without_skill_support_is_a_configuration_error() {
3638        let doc = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "skills": ["report"]}));
3639        let error = AgentNode::from_doc(&doc).unwrap_err().to_string();
3640        assert!(error.contains("cargo feature `skills`"), "{error}");
3641        let empty = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "skills": []}));
3642        assert!(AgentNode::from_doc(&empty).is_ok());
3643    }
3644
3645    #[test]
3646    fn config_validation_and_names() {
3647        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "tools": ["no-slash"]}));
3648        assert!(AgentNode::from_doc(&bad).is_err());
3649        let bad = NodeDoc::new("a", "agent", json!({"model": {"provider": "p", "name": "m"}, "max_iterations": 0}));
3650        assert!(AgentNode::from_doc(&bad).is_err());
3651        let mut used = HashSet::new();
3652        assert_eq!(unique_name("search", "web", &mut used), "search");
3653        assert_eq!(unique_name("search", "docs", &mut used), "docs_search");
3654        assert_eq!(unique_name("search", "docs", &mut used), "docs_search_2");
3655        assert_eq!(unique_name("a.b/c", "p", &mut used), "a_b_c");
3656    }
3657
3658    /// Tools: `export {name}` (returns a file), `export_failed {}` (an error that carries one).
3659    #[cfg(feature = "tool-files")]
3660    #[derive(Debug, Default)]
3661    struct ExportTools;
3662
3663    #[cfg(feature = "tool-files")]
3664    fn exported(name: &str) -> Value {
3665        Value::from(graphrt_core::value::File {
3666            marker: true,
3667            name: name.to_owned(),
3668            transfer: graphrt_core::value::FileTransfer::ToolFile,
3669            reference: Some(format!("workspace:outputs/{name}")),
3670            ..Default::default()
3671        })
3672    }
3673
3674    #[cfg(feature = "tool-files")]
3675    impl ToolRuntime for ExportTools {
3676        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
3677            let spec = |name: &str| ToolSpec { name: name.into(), description: "d".into(), parameters: json!({}) };
3678            Box::pin(async move { Ok(vec![spec("export"), spec("export_failed")]) })
3679        }
3680
3681        fn call<'a>(
3682            &'a self,
3683            name: &'a str,
3684            arguments: Json,
3685            _context: &'a ToolCallContext,
3686        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
3687            Box::pin(async move {
3688                let file = exported(arguments["name"].as_str().unwrap_or("out.csv"));
3689                let data = Value::object([("file", file)]);
3690                Ok(match name {
3691                    "export" => ToolOutput { text: "written".into(), data, ..ToolOutput::default() },
3692                    _ => ToolOutput { text: "disk full".into(), data, is_error: true, ..ToolOutput::default() },
3693                })
3694            })
3695        }
3696    }
3697
3698    #[cfg(feature = "tool-files")]
3699    fn export_ctx(s: &Setup) -> NodeContext {
3700        let mut registry = ToolRegistry::new();
3701        registry.add("export", Arc::new(ExportTools) as Arc<dyn ToolRuntime>);
3702        let services = Services::new()
3703            .with(ModelRegistry::new().with("openai", Arc::clone(&s.model) as Arc<dyn crate::ChatModel>))
3704            .with(registry);
3705        let mut pool = VariablePool::new();
3706        pool.insert("sys", "query", Value::from("export the report"));
3707        NodeContext::for_test("agent", pool).with_services(Arc::new(services))
3708    }
3709
3710    #[cfg(feature = "tool-files")]
3711    #[tokio::test]
3712    async fn files_returned_by_tools_become_the_files_output() {
3713        let s = setup(vec![
3714            MockModel::tool_calls(&[
3715                ("c1", "export", r#"{"name":"a.csv"}"#),
3716                ("c2", "export", r#"{"name":"b.md"}"#),
3717                ("c3", "export_failed", r#"{"name":"lost.txt"}"#),
3718            ]),
3719            // The same file again: it is listed once, in its last position.
3720            MockModel::tool_calls(&[("c4", "export", r#"{"name":"a.csv"}"#)]),
3721            MockModel::text("done"),
3722        ]);
3723        let out = completed(agent(json!({"tools": ["export/*"]})).run(export_ctx(&s)).await);
3724        let files = out.outputs["files"].as_array().unwrap().to_vec();
3725        let names: Vec<&str> = files.iter().map(|f| f.as_file().unwrap().name.as_str()).collect();
3726        assert_eq!(names, ["b.md", "a.csv"]);
3727        assert_eq!(files[0].as_file().unwrap().reference.as_deref(), Some("workspace:outputs/b.md"));
3728        // The model saw the tool's text only: no file object, no reference.
3729        let seen = serde_json::to_string(&s.model.requests()[1].messages).unwrap();
3730        assert!(seen.contains("written") && !seen.contains("workspace:"), "{seen}");
3731    }
3732
3733    #[cfg(feature = "tool-files")]
3734    #[tokio::test]
3735    async fn an_agent_without_file_tools_has_an_empty_files_output() {
3736        let s = setup(vec![MockModel::tool_calls(&[("c1", "add", r#"{"a":2,"b":3}"#)]), MockModel::text("5")]);
3737        let out = completed(agent(json!({})).run(ctx(&s)).await);
3738        assert_eq!(out.outputs["files"], Value::array([]));
3739    }
3740
3741    #[cfg(feature = "tool-files")]
3742    #[tokio::test]
3743    async fn files_survive_a_pause_for_approval() {
3744        let s = setup(vec![
3745            MockModel::tool_calls(&[("c1", "export", r#"{"name":"a.csv"}"#)]),
3746            MockModel::tool_calls(&[("c2", "export_failed", "{}")]),
3747            MockModel::text("done"),
3748        ]);
3749        let node = agent(json!({"tools": ["export/*"], "require_approval": ["export/export_failed"]}));
3750        let NodeOutcome::Paused(pause) = node.run(export_ctx(&s)).await.unwrap() else { panic!("expected a pause") };
3751        // The saved state is JSON: the file must come back as a file after resuming.
3752        let state = serde_json::from_str::<Json>(&serde_json::to_string(&pause.state).unwrap()).unwrap();
3753        let input = Some(Value::from_json(json!({"approved": true})));
3754        let resumed = export_ctx(&s).with_resume(Some(Resume { state, input }));
3755        let out = completed(node.run(resumed).await);
3756        let files = out.outputs["files"].as_array().unwrap().to_vec();
3757        assert_eq!(files.len(), 1);
3758        assert_eq!(files[0].as_file().unwrap().name, "a.csv");
3759    }
3760}