graphrt-core 0.12.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! The generic `tool` node and [`NativeTools`], a [`ToolRuntime`] built from
//! Rust closures.
//!
//! The `tool` node calls one tool of a provider registered in the
//! [`ToolRegistry`] service:
//!
//! ```yaml
//! - id: weather
//!   type: tool
//!   provider_id: builtin          # or e.g. "mcp:github"
//!   tool_name: get_weather
//!   tool_parameters:
//!     city:  { type: variable, value: [start, city] }
//!     units: { type: constant, value: metric }
//!     note:  { type: mixed,    value: "asked by {{#sys.user_id#}}" }
//! ```
//!
//! A simpler `arguments` map is also accepted: string values are templates
//! (a lone `{{#a.b#}}` placeholder keeps its typed value), other values are
//! constants.
//!
//! `tool_context` sends per-run values to the tool beside the arguments, for
//! providers that accept them (the workspace tools take the user's directory
//! this way with `--workspace-per-user`):
//!
//! ```yaml
//!   tool_context:
//!     scope: "{{#sys.user_id#}}"
//! ```
//!
//! A tool with a price (`image/generate` with a `per_image` price) gets what
//! the run's cost budget leaves and reports what the call cost: the node
//! charges it to the budget and reports it as `usage.cost_micros`.
//!
//! Outputs: `text` (string), `json` (structured result, or `null`; when the text
//! looks like JSON but does not parse, metadata `json_error` says why), `files`
//! (array, currently always empty), `is_error` (bool) and `error` (the tool's error
//! text, or `null`). A tool-reported error fails the node unless
//! `ignore_tool_errors` is set, in which case `is_error` / `error` let a downstream
//! branch react. `variable` arguments that do not resolve are sent as `null` and
//! listed in metadata `missing_arguments`.

use std::fmt;
use std::future::Future;
use std::sync::Arc;

use futures::future::BoxFuture;
use indexmap::IndexMap;
use serde::Deserialize;

use crate::dsl::NodeDoc;
use crate::node::{ConfigError, Node, NodeContext, NodeError, NodeOutput, NodeResult, Registry, parse_config};
use crate::pool::{Selector, VariablePool};
use crate::template::Template;
use crate::tool::{ToolCallContext, ToolError, ToolOutput, ToolRegistry, ToolRuntime, ToolSpec};
use crate::value::Value;

/// Node kind handled by [`ToolNode`].
pub const KIND: &str = "tool";

/// Register the `tool` node kind.
pub fn register(registry: &mut Registry) {
    registry.register_lazily_described(KIND, descriptor, |doc| {
        ToolNode::from_doc(doc).map(|n| Arc::new(n) as Arc<dyn Node>)
    });
}

/// Catalog descriptor of the `tool` node.
pub fn descriptor() -> crate::catalog::NodeDescriptor {
    use crate::catalog::schema::{nested, object, selector};
    use crate::catalog::{NodeCategory, NodeDescriptor, OutputDescriptor};
    use crate::value::ValueType;

    let parameter = serde_json::json!({
        "oneOf": [
            nested(serde_json::json!({ "type": { "const": "mixed" }, "value": { "type": "string" } }), &["type", "value"]),
            nested(serde_json::json!({ "type": { "const": "variable" }, "value": selector() }), &["type", "value"]),
            nested(serde_json::json!({ "type": { "const": "constant" }, "value": {} }), &["type"])
        ]
    });
    #[allow(unused_mut)]
    let mut properties = serde_json::json!({
        "provider_id": { "type": "string", "minLength": 1 },
        "provider": { "type": "string", "minLength": 1 },
        "provider_name": { "type": "string", "minLength": 1 },
        "tool_name": { "type": "string", "minLength": 1 },
        "tool_parameters": { "type": "object", "additionalProperties": parameter },
        "tool_configurations": { "type": "object" },
        "arguments": { "type": "object" },
        "ignore_tool_errors": { "type": "boolean", "default": false }
    });
    #[cfg(feature = "tool-context")]
    if let Some(fields) = properties.as_object_mut() {
        fields.insert(
            "tool_context".to_owned(),
            serde_json::json!({ "type": "object", "additionalProperties": { "type": "string" } }),
        );
    }
    NodeDescriptor::new(KIND, "Tool", NodeCategory::Integration)
        .describe(
            "Calls one tool from a registered tool provider (native tools, MCP servers, plugins). \
             Arguments: `tool_parameters` (mixed template / variable / constant) override `arguments` \
             (strings are templates) which override `tool_configurations` (constants).",
        )
        .icon("wrench")
        .source("builtin")
        .schema(object(properties, &["tool_name"]))
        .output(OutputDescriptor::new("text", ValueType::String).describe("Text result"))
        .output(OutputDescriptor::new("json", ValueType::Any).describe("Structured result, or the text parsed as JSON"))
        .output(OutputDescriptor::new("files", ValueType::ArrayFile))
        .output(OutputDescriptor::new("is_error", ValueType::Boolean))
        .output(OutputDescriptor::new("error", ValueType::String).describe("Error text when the tool reported one"))
}

/// How one tool argument is produced.
#[derive(Clone, Debug, PartialEq, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum ArgSource {
    /// Text template, rendered against the pool.
    Mixed { value: Template },
    /// Value read from a selector (typed).
    Variable { value: Selector },
    /// Literal value.
    Constant {
        #[serde(default)]
        value: Value,
    },
}

#[derive(Debug, Deserialize)]
struct ToolNodeConfig {
    #[serde(alias = "provider", alias = "provider_name")]
    provider_id: String,
    tool_name: String,
    #[serde(default)]
    tool_parameters: IndexMap<String, ArgSource>,
    /// Constant configuration parameters; lowest precedence.
    #[serde(default)]
    tool_configurations: IndexMap<String, Value>,
    /// Shorthand: strings are templates, everything else a constant.
    #[serde(default)]
    arguments: IndexMap<String, Value>,
    /// Per-run values for the tool (name -> template), never shown in events.
    #[cfg(feature = "tool-context")]
    #[serde(default)]
    tool_context: IndexMap<String, Template>,
    /// When true, a tool-reported error becomes a normal output instead of a node failure.
    #[serde(default)]
    ignore_tool_errors: bool,
}

/// Calls one tool from the [`ToolRegistry`] service.
#[derive(Debug, Clone)]
pub struct ToolNode {
    provider: String,
    tool: String,
    /// Arguments in precedence order (later entries override earlier ones).
    args: Vec<(String, ArgSource)>,
    #[cfg(feature = "tool-context")]
    tool_context: IndexMap<String, Template>,
    ignore_tool_errors: bool,
}

impl ToolNode {
    /// Build from a node document.
    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
        let cfg: ToolNodeConfig = parse_config(doc)?;
        if cfg.provider_id.trim().is_empty() {
            return Err(ConfigError::new(doc, "`provider_id` must not be empty"));
        }
        if cfg.tool_name.trim().is_empty() {
            return Err(ConfigError::new(doc, "`tool_name` must not be empty"));
        }
        let mut args: Vec<(String, ArgSource)> = Vec::new();
        for (k, v) in cfg.tool_configurations {
            args.push((k, ArgSource::Constant { value: v }));
        }
        for (k, v) in cfg.arguments {
            let source = match v {
                Value::String(s) => ArgSource::Mixed { value: Template::parse(&s) },
                other => ArgSource::Constant { value: other },
            };
            args.push((k, source));
        }
        for (k, v) in cfg.tool_parameters {
            args.push((k, v));
        }
        Ok(Self {
            provider: cfg.provider_id,
            tool: cfg.tool_name,
            args,
            #[cfg(feature = "tool-context")]
            tool_context: cfg.tool_context,
            ignore_tool_errors: cfg.ignore_tool_errors,
        })
    }

    /// Resolve arguments. Returns `(plaintext arguments for the call, masked copy for observability)`.
    fn resolve_args(&self, pool: &VariablePool) -> (serde_json::Value, Value) {
        let mut exposed = serde_json::Map::new();
        let mut masked: IndexMap<String, Value> = IndexMap::new();
        for (name, source) in &self.args {
            match source {
                // Text templates: render twice so the observable copy keeps secrets masked.
                ArgSource::Mixed { value } if !matches!(value.parts(), [crate::template::Part::Var(_)]) => {
                    exposed.insert(name.clone(), serde_json::Value::String(value.render_exposed(pool)));
                    masked.insert(name.clone(), Value::from(value.render(pool)));
                }
                _ => {
                    let value = match source {
                        // A lone placeholder keeps the typed value (numbers stay numbers).
                        ArgSource::Mixed { value } => value.resolve(pool),
                        ArgSource::Variable { value } => pool.get_or_null(value),
                        ArgSource::Constant { value } => value.clone(),
                    };
                    exposed.insert(name.clone(), value.to_json_exposed());
                    masked.insert(name.clone(), value);
                }
            }
        }
        (serde_json::Value::Object(exposed), Value::from(masked))
    }

    async fn execute(&self, ctx: NodeContext) -> NodeResult {
        let registry = ctx.require_service::<ToolRegistry>("tool registry")?;
        let runtime = registry
            .get(&self.provider)
            .ok_or_else(|| NodeError::fatal("tool", format!("unknown tool provider `{}`", self.provider)))?
            .clone();
        let (arguments, masked_args) = self.resolve_args(&ctx.pool);
        let missing = self.missing_variables(&ctx.pool);
        #[cfg(feature = "tool-context")]
        let owned_context = self.call_context(&ctx, runtime.accepts_secrets())?;
        #[cfg(feature = "tool-context")]
        let context = &owned_context;
        // Arguments already carry rendered secrets here: the node config is written by the
        // workflow author, not a model.
        #[cfg(not(feature = "tool-context"))]
        let context = ToolCallContext::empty();
        let output =
            runtime.call(&self.tool, arguments, context).await.map_err(|e| NodeError::new("tool", e.to_string()))?;
        // A call the run's budget does not afford stops the run, as a model call
        // would, even with `ignore_tool_errors`.
        #[cfg(feature = "tool-error-types")]
        if output.is_limit_exceeded() {
            return Err(match ctx.budget() {
                Some(budget) => budget.refuse(output.text),
                None => NodeError::fatal(crate::tool::LIMIT_EXCEEDED, output.text),
            });
        }
        if output.is_error && !self.ignore_tool_errors {
            #[cfg(feature = "tool-error-types")]
            let error_type = output.error_type.as_deref().unwrap_or("tool_error");
            #[cfg(not(feature = "tool-error-types"))]
            let error_type = "tool_error";
            return Err(NodeError::fatal(error_type, output.text));
        }
        // Files a native tool returned in its structured result (plugins and MCP servers
        // cannot create file values).
        #[cfg(feature = "tool-files")]
        let files: Vec<Value> = crate::tool::collect_files(&output.data).into_iter().map(Value::File).collect();
        #[cfg(not(feature = "tool-files"))]
        let files: Vec<Value> = Vec::new();
        let (json, json_error) =
            if output.data.is_null() { parse_json_text(&output.text) } else { (output.data, None) };
        // With `ignore_tool_errors`, the failure stays visible to the graph through the
        // `is_error` / `error` outputs so a downstream branch can react to it.
        let error = if output.is_error { Value::from(output.text.as_str()) } else { Value::Null };
        let mut result = NodeOutput::new()
            .with("text", output.text)
            .with("json", json)
            .with("files", Value::array(files))
            .with("is_error", output.is_error)
            .with("error", error)
            .meta("provider", self.provider.as_str())
            .meta("tool", self.tool.as_str())
            .meta("arguments", masked_args);
        if let Some(e) = json_error {
            result = result.meta("json_error", e);
        }
        if !missing.is_empty() {
            result = result.meta("missing_arguments", Value::array(missing.into_iter().map(Value::from)));
        }
        // The engine charges a node's reported usage to the run's budget when it completes.
        #[cfg(feature = "tool-context")]
        if output.cost_micros > 0 {
            result.usage = Some(crate::event::Usage { cost_micros: output.cost_micros, ..Default::default() });
        }
        Ok(result.into())
    }

    /// The per-call context: the rendered `tool_context`, and what the run's
    /// cost budget leaves.
    #[cfg(feature = "tool-context")]
    ///
    /// @throws NodeError - `tool_context_denied` (fatal) when the node sets a
    ///   `tool_context` and the provider does not accept one.
    fn call_context(&self, ctx: &NodeContext, accepts_secrets: bool) -> Result<ToolCallContext, NodeError> {
        let mut context = ToolCallContext {
            remaining_cost_micros: ctx.budget().and_then(crate::budget::RunBudget::remaining_cost_micros),
            ..ToolCallContext::default()
        };
        if self.tool_context.is_empty() {
            return Ok(context);
        }
        if !accepts_secrets {
            return Err(NodeError::fatal(
                "tool_context_denied",
                format!("tool provider `{}` does not accept a tool context", self.provider),
            ));
        }
        for (name, template) in &self.tool_context {
            let value = template.render_exposed(&ctx.pool);
            // A missing variable renders empty: leave the name out so the tool can refuse.
            if value.is_empty() {
                continue;
            }
            ctx.observe_secret(&value);
            context.secrets.insert(name.clone(), value);
        }
        Ok(context)
    }

    /// Selectors of `variable` arguments that do not resolve (sent to the tool as `null`).
    fn missing_variables(&self, pool: &VariablePool) -> Vec<String> {
        self.args
            .iter()
            .filter_map(|(_, source)| match source {
                ArgSource::Variable { value } if pool.get(value).is_none() => Some(value.to_string()),
                _ => None,
            })
            .collect()
    }
}

/// Structured view of a text result when it looks like a JSON object or array.
/// Returns the parse error when it looks like JSON but is not valid.
fn parse_json_text(text: &str) -> (Value, Option<String>) {
    let trimmed = text.trim_start();
    if trimmed.starts_with('{') || trimmed.starts_with('[') {
        return match serde_json::from_slice::<serde_json::Value>(text.as_bytes()) {
            Ok(json) => (Value::from_json(json), None),
            Err(e) => (Value::Null, Some(e.to_string())),
        };
    }
    (Value::Null, None)
}

impl Node for ToolNode {
    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
        Box::pin(self.execute(ctx))
    }

    fn inputs(&self) -> Vec<Selector> {
        let mut out = Vec::new();
        for (_, source) in &self.args {
            match source {
                ArgSource::Mixed { value } => out.extend(value.selectors().cloned()),
                ArgSource::Variable { value } => out.push(value.clone()),
                ArgSource::Constant { .. } => {}
            }
        }
        #[cfg(feature = "tool-context")]
        for template in self.tool_context.values() {
            out.extend(template.selectors().cloned());
        }
        out
    }
}

type ToolFn = Arc<dyn Fn(serde_json::Value) -> BoxFuture<'static, Result<ToolOutput, ToolError>> + Send + Sync>;

/// A [`ToolRuntime`] whose tools are Rust closures.
///
/// ```
/// use graphrt_core::tool::{ToolOutput, ToolSpec};
/// use graphrt_core::tool_node::NativeTools;
///
/// let tools = NativeTools::new().with(
///     ToolSpec {
///         name: "echo".into(),
///         description: "Echo the `text` argument".into(),
///         parameters: serde_json::json!({
///             "type": "object",
///             "properties": { "text": { "type": "string" } },
///             "required": ["text"]
///         }),
///         effects: Vec::new(),
///     },
///     |args| async move { Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default())) },
/// );
/// ```
#[derive(Clone, Default)]
pub struct NativeTools {
    tools: IndexMap<String, (ToolSpec, ToolFn)>,
}

impl fmt::Debug for NativeTools {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NativeTools").field("tools", &self.tools.keys().collect::<Vec<_>>()).finish()
    }
}

impl NativeTools {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add (or replace) a tool.
    pub fn add<F, Fut>(&mut self, spec: ToolSpec, handler: F) -> &mut Self
    where
        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
    {
        let handler: ToolFn = Arc::new(move |args| Box::pin(handler(args)));
        self.tools.insert(spec.name.clone(), (spec, handler));
        self
    }

    /// Builder-style [`NativeTools::add`].
    pub fn with<F, Fut>(mut self, spec: ToolSpec, handler: F) -> Self
    where
        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
    {
        self.add(spec, handler);
        self
    }

    pub fn len(&self) -> usize {
        self.tools.len()
    }

    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }
}

impl ToolRuntime for NativeTools {
    fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
        let specs = self.tools.values().map(|(spec, _)| spec.clone()).collect();
        Box::pin(futures::future::ready(Ok(specs)))
    }

    /// Native handlers take only arguments; the context is not forwarded
    /// (`accepts_secrets` stays `false`).
    fn call<'a>(
        &'a self,
        name: &'a str,
        arguments: serde_json::Value,
        _context: &'a ToolCallContext,
    ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
        let Some((spec, handler)) = self.tools.get(name) else {
            return Box::pin(futures::future::ready(Err(ToolError {
                tool: name.to_owned(),
                message: "unknown tool".to_owned(),
            })));
        };
        if let Err(message) = check_required(&spec.parameters, &arguments) {
            return Box::pin(futures::future::ready(Err(ToolError { tool: name.to_owned(), message })));
        }
        handler(arguments)
    }
}

/// Lightweight argument check: the arguments must be an object containing every
/// property listed in the schema's `required` array. Full JSON Schema validation
/// is left to the tool itself.
fn check_required(schema: &serde_json::Value, arguments: &serde_json::Value) -> Result<(), String> {
    let Some(args) = arguments.as_object() else {
        return Err("arguments must be a JSON object".to_owned());
    };
    let required = schema.get("required").and_then(serde_json::Value::as_array);
    let missing: Vec<&str> = required
        .into_iter()
        .flatten()
        .filter_map(serde_json::Value::as_str)
        .filter(|key| args.get(*key).is_none_or(serde_json::Value::is_null))
        .collect();
    if missing.is_empty() { Ok(()) } else { Err(format!("missing required arguments: {}", missing.join(", "))) }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;
    use crate::node::{NodeOutcome, Services};

    #[derive(Debug, Default)]
    struct Recorder {
        calls: Mutex<Vec<(String, serde_json::Value)>>,
        reply: Option<ToolOutput>,
    }

    impl ToolRuntime for Recorder {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            Box::pin(futures::future::ready(Ok(Vec::new())))
        }
        fn call<'a>(
            &'a self,
            name: &'a str,
            arguments: serde_json::Value,
            _context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            self.calls.lock().unwrap().push((name.to_owned(), arguments));
            let reply = self.reply.clone().unwrap_or_else(|| ToolOutput::text("{\"ok\":true}"));
            Box::pin(futures::future::ready(Ok(reply)))
        }
    }

    fn doc(config: serde_json::Value) -> NodeDoc {
        NodeDoc::new("t", KIND, config)
    }

    fn pool() -> VariablePool {
        let mut p = VariablePool::new();
        p.insert("start", "city", Value::from("Jakarta"));
        p.insert("start", "days", Value::Int(3));
        p.insert("env", "TOKEN", Value::Secret(Arc::from("s3cret")));
        p
    }

    fn ctx_with(runtime: Arc<dyn ToolRuntime>) -> NodeContext {
        let mut reg = ToolRegistry::new();
        reg.add("mock", runtime);
        NodeContext::for_test("t", pool()).with_services(Arc::new(Services::new().with(reg)))
    }

    fn completed(r: NodeResult) -> NodeOutput {
        match r {
            Ok(NodeOutcome::Completed(o)) => o,
            other => panic!("unexpected {other:?}"),
        }
    }

    #[tokio::test]
    async fn resolves_all_argument_kinds() {
        let rec = Arc::new(Recorder::default());
        let node = ToolNode::from_doc(&doc(serde_json::json!({
            "provider_id": "mock",
            "tool_name": "weather",
            "tool_configurations": {"units": "imperial", "lang": "en"},
            "arguments": {"note": "for {{#start.city#}}", "raw": 5},
            "tool_parameters": {
                "city": {"type": "variable", "value": ["start", "city"]},
                "days": {"type": "mixed", "value": "{{#start.days#}}"},
                "units": {"type": "constant", "value": "metric"},
                "auth": {"type": "mixed", "value": "Bearer {{#env.TOKEN#}}"}
            }
        })))
        .unwrap();
        let out = completed(node.run(ctx_with(rec.clone())).await);
        let calls = rec.calls.lock().unwrap();
        let (name, args) = &calls[0];
        assert_eq!(name, "weather");
        assert_eq!(args["city"], "Jakarta");
        assert_eq!(args["days"], 3);
        assert_eq!(args["units"], "metric", "tool_parameters override configurations");
        assert_eq!(args["lang"], "en");
        assert_eq!(args["note"], "for Jakarta");
        assert_eq!(args["raw"], 5);
        assert_eq!(args["auth"], "Bearer s3cret", "tool receives the plaintext secret");
        // Observability metadata never contains the secret.
        let meta = serde_json::to_string(&out.metadata).unwrap();
        assert!(!meta.contains("s3cret"));
        assert_eq!(out.outputs["text"], Value::from("{\"ok\":true}"));
        assert_eq!(out.outputs["json"].get_path(&["ok"]), Some(Value::Bool(true)));
        assert_eq!(out.outputs["files"], Value::array([]));
        assert_eq!(node.inputs().len(), 4); // note, city, days, auth
    }

    #[tokio::test]
    async fn tool_error_fails_unless_ignored() {
        let rec = Arc::new(Recorder { reply: Some(ToolOutput::error("boom")), ..Recorder::default() });
        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x"});
        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
        let err = node.run(ctx_with(rec.clone())).await.unwrap_err();
        assert_eq!(err.kind, "tool_error");
        assert!(!err.retryable);

        let cfg = serde_json::json!({"provider": "mock", "tool_name": "x", "ignore_tool_errors": true});
        let node = ToolNode::from_doc(&doc(cfg)).unwrap();
        let out = completed(node.run(ctx_with(rec)).await);
        assert_eq!(out.outputs["text"], Value::from("boom"));
        assert_eq!(out.outputs["is_error"], Value::Bool(true));
        assert_eq!(out.outputs["error"], Value::from("boom"));
    }

    #[tokio::test]
    async fn successful_call_has_no_error_output() {
        let rec = Arc::new(Recorder { reply: Some(ToolOutput::text("{\"a\": 1")), ..Recorder::default() });
        let node = ToolNode::from_doc(&doc(serde_json::json!({
            "provider": "mock", "tool_name": "x",
            "tool_parameters": {"city": {"type": "variable", "value": ["start", "nope"]}}
        })))
        .unwrap();
        let out = completed(node.run(ctx_with(rec)).await);
        assert_eq!(out.outputs["is_error"], Value::Bool(false));
        assert_eq!(out.outputs["error"], Value::Null);
        // Looks like JSON but is truncated: `json` is null and the reason is recorded.
        assert_eq!(out.outputs["json"], Value::Null);
        assert!(out.metadata.contains_key("json_error"));
        assert_eq!(out.metadata["missing_arguments"], Value::array([Value::from("start.nope")]));
    }

    #[tokio::test]
    async fn missing_provider_or_registry_is_fatal() {
        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "nope", "tool_name": "x"}))).unwrap();
        let err = node.run(ctx_with(Arc::new(Recorder::default()))).await.unwrap_err();
        assert!(!err.retryable);
        let err = node.run(NodeContext::for_test("t", pool())).await.unwrap_err();
        assert_eq!(err.kind, "missing_service");
    }

    /// Keeps the context of every call and answers with a cost.
    #[cfg(feature = "tool-context")]
    #[derive(Debug, Default)]
    struct Priced {
        accepts: bool,
        cost_micros: u64,
        /// Refuse every call with an error of this type.
        #[cfg(feature = "tool-error-types")]
        refusal: Option<&'static str>,
        contexts: Mutex<Vec<ToolCallContext>>,
    }

    #[cfg(feature = "tool-context")]
    impl ToolRuntime for Priced {
        fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>> {
            Box::pin(futures::future::ready(Ok(Vec::new())))
        }
        fn call<'a>(
            &'a self,
            _name: &'a str,
            _arguments: serde_json::Value,
            context: &'a ToolCallContext,
        ) -> BoxFuture<'a, Result<ToolOutput, ToolError>> {
            self.contexts.lock().unwrap().push(context.clone());
            #[cfg(feature = "tool-error-types")]
            if let Some(error_type) = self.refusal {
                return Box::pin(futures::future::ready(Ok(ToolOutput::typed_error(error_type, "refused"))));
            }
            let output = ToolOutput { cost_micros: self.cost_micros, ..ToolOutput::text("made") };
            Box::pin(futures::future::ready(Ok(output)))
        }
        fn accepts_secrets(&self) -> bool {
            self.accepts
        }
    }

    #[cfg(feature = "tool-context")]
    #[tokio::test]
    async fn tool_context_reaches_a_tool_that_accepts_it_and_never_the_events() {
        let priced = Arc::new(Priced { accepts: true, ..Priced::default() });
        let node = ToolNode::from_doc(&doc(serde_json::json!({
            "provider_id": "mock", "tool_name": "x",
            "tool_context": {"scope": "{{#env.TOKEN#}}", "region": "{{#start.city#}}", "empty": "{{#start.nope#}}"}
        })))
        .unwrap();
        let out = completed(node.run(ctx_with(priced.clone())).await);
        let context = priced.contexts.lock().unwrap().pop().unwrap();
        assert_eq!(context.secret("scope"), Some("s3cret"));
        assert_eq!(context.secret("region"), Some("Jakarta"));
        assert_eq!(context.secret("empty"), None, "a value that does not resolve is left out");
        assert_eq!(context.remaining_cost_micros, None, "no budget outside an engine");
        assert!(!serde_json::to_string(&out.metadata).unwrap().contains("s3cret"));
        assert!(out.usage.is_none(), "a free tool reports no usage");
        assert_eq!(node.inputs().len(), 3);

        // A provider that does not take a context is told so, not silently skipped.
        let closed = Arc::new(Priced::default());
        let err = node.run(ctx_with(closed.clone())).await.unwrap_err();
        assert_eq!(err.kind, "tool_context_denied");
        assert!(closed.contexts.lock().unwrap().is_empty());
    }

    #[cfg(feature = "tool-context")]
    #[tokio::test]
    async fn a_priced_tool_learns_the_budget_left_and_reports_its_cost() {
        let priced = Arc::new(Priced { cost_micros: 40_000, ..Priced::default() });
        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "mock", "tool_name": "x"}))).unwrap();
        let budget = Arc::new(crate::budget::RunBudget::limited(None, Some(100_000)));
        budget.charge(&crate::event::Usage::default(), 30_000).unwrap();
        let out = completed(node.run(ctx_with(priced.clone()).with_budget(budget, None)).await);
        assert_eq!(priced.contexts.lock().unwrap()[0].remaining_cost_micros, Some(70_000));
        assert_eq!(out.usage.map(|usage| usage.cost_micros), Some(40_000));
    }

    #[cfg(all(feature = "tool-context", feature = "tool-error-types"))]
    #[tokio::test]
    async fn a_typed_tool_error_fails_the_node_with_its_type() {
        let node = ToolNode::from_doc(&doc(serde_json::json!({"provider_id": "mock", "tool_name": "x"}))).unwrap();
        let pricing = Arc::new(Priced { refusal: Some("price_missing"), ..Priced::default() });
        let err = node.run(ctx_with(pricing)).await.unwrap_err();
        assert_eq!((err.kind.as_str(), err.message.as_str(), err.retryable), ("price_missing", "refused", false));

        // A call the budget does not afford stops the run, even with `ignore_tool_errors`.
        let ignoring = ToolNode::from_doc(&doc(serde_json::json!({
            "provider_id": "mock", "tool_name": "x", "ignore_tool_errors": true
        })))
        .unwrap();
        let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let flag = Arc::clone(&stopped);
        let budget = Arc::new(crate::budget::RunBudget::new(
            None,
            Some(100),
            (0, 0),
            Box::new(move |_| flag.store(true, std::sync::atomic::Ordering::Release)),
        ));
        let refusing = Arc::new(Priced { refusal: Some("limit_exceeded"), ..Priced::default() });
        let err = ignoring.run(ctx_with(refusing.clone()).with_budget(budget, None)).await.unwrap_err();
        assert_eq!(err.kind, "limit_exceeded");
        assert!(stopped.load(std::sync::atomic::Ordering::Acquire), "the run's budget stops the run");
        let err = ignoring.run(ctx_with(refusing)).await.unwrap_err();
        assert_eq!(err.kind, "limit_exceeded", "outside an engine too");

        // Other typed errors are ignored like any tool error.
        let pricing = Arc::new(Priced { refusal: Some("price_missing"), ..Priced::default() });
        let out = completed(ignoring.run(ctx_with(pricing)).await);
        assert_eq!(out.outputs["is_error"], Value::Bool(true));
    }

    #[test]
    fn rejects_invalid_config() {
        assert!(ToolNode::from_doc(&doc(serde_json::json!({"tool_name": "x"}))).is_err());
        assert!(ToolNode::from_doc(&doc(serde_json::json!({"provider_id": " ", "tool_name": "x"}))).is_err());
        let bad_param = serde_json::json!({"provider_id": "p", "tool_name": "x",
            "tool_parameters": {"a": {"type": "variable", "value": ["only"]}}});
        assert!(ToolNode::from_doc(&doc(bad_param)).is_err());
    }

    #[test]
    fn registers_kind() {
        let mut r = Registry::new();
        register(&mut r);
        assert!(r.contains(KIND));
    }

    fn echo_spec() -> ToolSpec {
        ToolSpec {
            name: "echo".into(),
            description: "echo".into(),
            parameters: serde_json::json!({"type": "object", "required": ["text"]}),
            effects: Vec::new(),
        }
    }

    #[tokio::test]
    async fn native_tools_dispatch_and_validate() {
        let tools = NativeTools::new().with(echo_spec(), |args| async move {
            Ok(ToolOutput::text(args["text"].as_str().unwrap_or_default().to_uppercase()))
        });
        assert_eq!(tools.len(), 1);
        assert_eq!(tools.list().await.unwrap()[0].name, "echo");
        let out = tools.call("echo", serde_json::json!({"text": "hi"}), ToolCallContext::empty()).await.unwrap();
        assert_eq!(out.text, "HI");
        let err = tools.call("echo", serde_json::json!({}), ToolCallContext::empty()).await.unwrap_err();
        assert!(err.message.contains("text"));
        assert!(tools.call("echo", serde_json::json!("str"), ToolCallContext::empty()).await.is_err());
        assert!(tools.call("nope", serde_json::json!({}), ToolCallContext::empty()).await.is_err());
    }

    #[tokio::test]
    async fn tool_node_with_native_tools() {
        let tools = NativeTools::new().with(echo_spec(), |args| async move {
            Ok(ToolOutput {
                text: "done".into(),
                data: Value::from_json(args),
                is_error: false,
                ..ToolOutput::default()
            })
        });
        let node = ToolNode::from_doc(&doc(serde_json::json!({
            "provider_id": "mock", "tool_name": "echo", "arguments": {"text": "{{#start.city#}}"}
        })))
        .unwrap();
        let out = completed(node.run(ctx_with(Arc::new(tools))).await);
        assert_eq!(out.outputs["json"].get_path(&["text"]), Some(Value::from("Jakarta")));
    }
}