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