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