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