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