runifold-tool 0.5.5

Typed, capability-gated tool execution boundary for Runifold
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
use std::{collections::BTreeMap, fmt, fmt::Write as _, sync::Arc};

use futures_util::future::{Either, select};
use jsonschema::{ValidationError, Validator, error::ValidationErrorKind};
use runifold_core::RunContext;
use runifold_model::{ArtifactScope, ArtifactStore, ToolSpec};
use serde_json::Value;

use crate::{
    Tool, ToolContext, ToolDescriptor, ToolError, ToolErrorKind, ToolFuture, ToolOutput,
    ToolRegistrationError,
};

/// Immutable-name registry and capability gate for tools.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ToolLimits {
    /// Maximum serialized invocation input size.
    pub max_input_bytes: usize,
    /// Maximum serialized canonical output size.
    pub max_output_bytes: usize,
}

impl Default for ToolLimits {
    fn default() -> Self {
        Self {
            max_input_bytes: 1024 * 1024,
            max_output_bytes: 8 * 1024 * 1024,
        }
    }
}

#[derive(Clone)]
struct RegisteredTool {
    tool: Arc<dyn Tool>,
    input_validator: Validator,
    output_validator: Validator,
}

/// Immutable-name Tool registry with compiled contracts and bounded I/O.
#[derive(Clone, Default)]
pub struct ToolRegistry {
    tools: BTreeMap<String, RegisteredTool>,
    limits: ToolLimits,
    artifact_store: Option<Arc<dyn ArtifactStore>>,
    artifact_scope: Option<ArtifactScope>,
}

impl ToolRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces the serialized Tool I/O limits.
    #[must_use]
    pub const fn with_limits(mut self, limits: ToolLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Makes an artifact store available to every Tool invocation context.
    #[must_use]
    pub fn with_artifact_store(
        mut self,
        scope: ArtifactScope,
        store: Arc<dyn ArtifactStore>,
    ) -> Self {
        self.artifact_scope = Some(scope);
        self.artifact_store = Some(store);
        self
    }

    /// Registers a tool without replacing an existing name.
    ///
    /// # Errors
    ///
    /// Returns [`ToolRegistrationError`] for blank or duplicate names.
    pub fn register(&mut self, tool: Arc<dyn Tool>) -> Result<(), ToolRegistrationError> {
        let name = tool.descriptor().name.trim();
        if name.is_empty() {
            return Err(ToolRegistrationError::EmptyName);
        }
        if self.tools.contains_key(name) {
            return Err(ToolRegistrationError::DuplicateName(name.into()));
        }
        let input_validator = compile_schema(name, "input", &tool.descriptor().input_schema)?;
        let output_validator = compile_schema(name, "output", &tool.descriptor().output_schema)?;
        self.tools.insert(
            name.into(),
            RegisteredTool {
                tool,
                input_validator,
                output_validator,
            },
        );
        Ok(())
    }

    /// Returns model-facing specifications in deterministic name order.
    pub fn model_specs(&self) -> Vec<ToolSpec> {
        self.tools
            .values()
            .map(|registered| registered.tool.descriptor().model_spec())
            .collect()
    }

    /// Returns the number of registered tools.
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Returns whether no tools are registered.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Returns whether a tool is registered under `name`.
    pub fn contains(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Returns the immutable descriptor registered under `name`.
    pub fn descriptor(&self, name: &str) -> Option<&ToolDescriptor> {
        self.tools
            .get(name)
            .map(|registered| registered.tool.descriptor())
    }

    /// Invokes a registered tool after checking the owning run's explicit
    /// capability grant.
    pub fn invoke<'a>(
        &'a self,
        name: &'a str,
        input: Value,
        run: &'a RunContext,
    ) -> ToolFuture<'a, Result<ToolOutput, ToolError>> {
        Box::pin(async move {
            let registered = self.tools.get(name).ok_or_else(|| {
                ToolError::local(
                    ToolErrorKind::NotFound,
                    format!("tool `{name}` is not registered"),
                )
            })?;
            let descriptor = registered.tool.descriptor();
            if !run.capabilities().contains(descriptor.id) {
                return Err(ToolError::local(
                    ToolErrorKind::CapabilityDenied,
                    format!("run is not granted tool capability `{name}`"),
                ));
            }
            let context = ToolContext::for_run(run)
                .with_artifact_store(self.artifact_scope.clone(), self.artifact_store.clone());
            validate_size(
                "Tool input",
                &input,
                self.limits.max_input_bytes,
                ToolErrorKind::InvalidInput,
            )?;
            registered
                .input_validator
                .validate(&input)
                .map_err(|error| input_validation_error(name, &error))?;
            if context
                .remaining()
                .is_some_and(|remaining| remaining.is_zero())
            {
                return Err(ToolError::local(
                    ToolErrorKind::DeadlineExceeded,
                    "tool invocation deadline already elapsed",
                ));
            }
            let cancellation = context.cancellation().clone();
            match select(
                Box::pin(cancellation.cancelled()),
                Box::pin(registered.tool.invoke(input, context)),
            )
            .await
            {
                Either::Left(_) => Err(ToolError::local(
                    ToolErrorKind::Cancelled,
                    "tool invocation was cancelled",
                )),
                Either::Right((result, _)) => {
                    let output = result?;
                    validate_output(&output, &registered.output_validator, self.limits)?;
                    Ok(output)
                }
            }
        })
    }
}

fn input_validation_error(tool: &str, error: &ValidationError<'_>) -> ToolError {
    let input_path = error.instance_path().to_string();
    let schema_path = error.schema_path().to_string();
    let keyword = error.kind().keyword().to_owned();
    let mut diagnostic = ToolError::local(
        ToolErrorKind::InvalidInput,
        format!(
            "Tool `{tool}` rejected its arguments: input at `{input_path}` violates `{keyword}` at schema `{schema_path}`; call the tool again with corrected arguments and do not guess its result"
        ),
    );
    diagnostic
        .metadata
        .insert("validation.input_path".into(), Value::String(input_path));
    diagnostic
        .metadata
        .insert("validation.schema_path".into(), Value::String(schema_path));
    diagnostic
        .metadata
        .insert("validation.keyword".into(), Value::String(keyword));
    diagnostic
        .metadata
        .insert("tool.name".into(), Value::String(tool.into()));
    if let ValidationErrorKind::Enum { options } = error.kind() {
        diagnostic
            .metadata
            .insert("validation.allowed_values".into(), options.clone());
        let _ = write!(
            diagnostic.message,
            "; allowed values: {}",
            bounded_json(options, 512)
        );
    }
    if is_safe_scalar(error.instance()) {
        diagnostic.metadata.insert(
            "validation.actual_value".into(),
            error.instance().as_ref().clone(),
        );
        let _ = write!(
            diagnostic.message,
            "; received: {}",
            bounded_json(error.instance(), 128)
        );
    }
    diagnostic
}

fn is_safe_scalar(value: &Value) -> bool {
    match value {
        Value::Null | Value::Bool(_) | Value::Number(_) => true,
        Value::String(value) => value.len() <= 64,
        Value::Array(_) | Value::Object(_) => false,
    }
}

fn bounded_json(value: &Value, maximum: usize) -> String {
    let encoded = value.to_string();
    if encoded.len() <= maximum {
        encoded
    } else {
        "<redacted: value exceeds diagnostic limit>".into()
    }
}

fn compile_schema(
    tool: &str,
    direction: &'static str,
    schema: &Value,
) -> Result<Validator, ToolRegistrationError> {
    jsonschema::validator_for(schema).map_err(|error| ToolRegistrationError::InvalidSchema {
        tool: tool.into(),
        direction,
        message: error.to_string(),
    })
}

fn validate_output(
    output: &ToolOutput,
    validator: &Validator,
    limits: ToolLimits,
) -> Result<(), ToolError> {
    if output.content.is_empty() {
        return Err(ToolError::local(
            ToolErrorKind::InvalidOutput,
            "Tool output content cannot be empty",
        ));
    }
    validate_size(
        "Tool output",
        output,
        limits.max_output_bytes,
        ToolErrorKind::InvalidOutput,
    )?;
    if output.is_error {
        return Ok(());
    }
    let instance = output
        .structured_content
        .clone()
        .unwrap_or_else(|| serde_json::to_value(&output.content).unwrap_or(Value::Null));
    validator.validate(&instance).map_err(|error| {
        ToolError::local(
            ToolErrorKind::InvalidOutput,
            format!(
                "Tool output violates its declared schema at `{}`",
                error.schema_path()
            ),
        )
    })
}

fn validate_size<T: serde::Serialize>(
    label: &str,
    value: &T,
    limit: usize,
    kind: ToolErrorKind,
) -> Result<(), ToolError> {
    let size = serde_json::to_vec(value)
        .map_err(|error| {
            ToolError::local(kind.clone(), format!("{label} cannot be encoded: {error}"))
        })?
        .len();
    if size > limit {
        return Err(ToolError::local(
            kind,
            format!("{label} is {size} bytes and exceeds the {limit}-byte limit"),
        ));
    }
    Ok(())
}

impl fmt::Debug for ToolRegistry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ToolRegistry")
            .field("tools", &self.tools.keys().collect::<Vec<_>>())
            .field("limits", &self.limits)
            .field("artifact_store", &self.artifact_store.is_some())
            .field("artifact_scope", &self.artifact_scope)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, sync::Arc};

    use runifold_core::{
        Budget, BudgetTracker, CapabilityId, CapabilitySet, EffectClass, RiskLevel, RunContext,
    };
    use serde_json::{Value, json};

    use crate::{
        Tool, ToolContext, ToolDescriptor, ToolError, ToolErrorKind, ToolFuture, ToolLimits,
        ToolOutput, ToolRegistrationError,
    };

    use super::ToolRegistry;

    #[derive(Debug)]
    struct EchoTool {
        descriptor: ToolDescriptor,
    }

    impl EchoTool {
        fn new(name: &str) -> Self {
            Self {
                descriptor: ToolDescriptor {
                    id: CapabilityId::new(),
                    name: name.into(),
                    version: "1".into(),
                    description: "Echo structured input".into(),
                    input_schema: json!({"type": "object"}),
                    output_schema: json!({"type": "object"}),
                    effect: EffectClass::Pure,
                    risk: RiskLevel::Low,
                    metadata: BTreeMap::new(),
                },
            }
        }
    }

    impl Tool for EchoTool {
        fn descriptor(&self) -> &ToolDescriptor {
            &self.descriptor
        }

        fn invoke(
            &self,
            input: Value,
            _context: ToolContext,
        ) -> ToolFuture<'_, Result<ToolOutput, ToolError>> {
            Box::pin(async move { Ok(ToolOutput::model_visible(input)) })
        }
    }

    #[test]
    fn registry_requires_explicit_capability_grants() {
        let tool = Arc::new(EchoTool::new("echo"));
        let mut registry = ToolRegistry::new();
        registry.register(tool).unwrap();
        let run = RunContext::root(BudgetTracker::new(Budget::default()), CapabilitySet::new());

        let error =
            futures_executor::block_on(registry.invoke("echo", json!({"x": 1}), &run)).unwrap_err();

        assert_eq!(error.kind, ToolErrorKind::CapabilityDenied);
    }

    #[test]
    fn granted_tools_execute_through_the_object_safe_boundary() {
        let tool = Arc::new(EchoTool::new("echo"));
        let mut capabilities = CapabilitySet::new();
        capabilities.grant(tool.descriptor().capability());
        let run = RunContext::root(BudgetTracker::new(Budget::default()), capabilities);
        let mut registry = ToolRegistry::new();
        registry.register(tool).unwrap();

        let output =
            futures_executor::block_on(registry.invoke("echo", json!({"x": 1}), &run)).unwrap();

        assert_eq!(output.structured_content, Some(json!({"x": 1})));
    }

    #[test]
    fn invalid_enum_reports_input_path_allowed_values_and_safe_actual_value() {
        let mut tool = EchoTool::new("market_history");
        tool.descriptor.input_schema = json!({
            "type": "object",
            "properties": {
                "lookback": {"type": "string", "enum": ["1d", "7d", "30d"]}
            },
            "required": ["lookback"]
        });
        let tool = Arc::new(tool);
        let mut capabilities = CapabilitySet::new();
        capabilities.grant(tool.descriptor().capability());
        let run = RunContext::root(BudgetTracker::new(Budget::default()), capabilities);
        let mut registry = ToolRegistry::new();
        registry.register(tool).unwrap();

        let error = futures_executor::block_on(registry.invoke(
            "market_history",
            json!({"lookback": "forever"}),
            &run,
        ))
        .unwrap_err();

        assert_eq!(error.kind, ToolErrorKind::InvalidInput);
        assert_eq!(error.metadata["tool.name"], "market_history");
        assert_eq!(error.metadata["validation.input_path"], "/lookback");
        assert_eq!(error.metadata["validation.keyword"], "enum");
        assert_eq!(error.metadata["validation.actual_value"], "forever");
        assert_eq!(
            error.metadata["validation.allowed_values"],
            json!(["1d", "7d", "30d"])
        );
        assert!(error.message.contains("call the tool again"));
    }

    #[test]
    fn duplicate_names_are_rejected_instead_of_replaced() {
        let mut registry = ToolRegistry::new();
        registry.register(Arc::new(EchoTool::new("echo"))).unwrap();

        let error = registry
            .register(Arc::new(EchoTool::new("echo")))
            .unwrap_err();

        assert_eq!(error, ToolRegistrationError::DuplicateName("echo".into()));
    }

    #[test]
    fn invalid_schemas_fail_during_registration() {
        let mut tool = EchoTool::new("invalid");
        tool.descriptor.input_schema = json!({"type":"not-a-json-schema-type"});
        let error = ToolRegistry::new().register(Arc::new(tool)).unwrap_err();
        assert!(matches!(
            error,
            ToolRegistrationError::InvalidSchema {
                direction: "input",
                ..
            }
        ));
    }

    #[test]
    fn output_contract_and_size_are_enforced_after_execution() {
        let tool = Arc::new(EchoTool::new("bounded"));
        let mut capabilities = CapabilitySet::new();
        capabilities.grant(tool.descriptor().capability());
        let run = RunContext::root(BudgetTracker::new(Budget::default()), capabilities);
        let mut registry = ToolRegistry::new().with_limits(ToolLimits {
            max_input_bytes: 1024,
            max_output_bytes: 32,
        });
        registry.register(tool).unwrap();

        let error = futures_executor::block_on(registry.invoke(
            "bounded",
            json!({"payload":"this output is intentionally larger than the limit"}),
            &run,
        ))
        .unwrap_err();
        assert_eq!(error.kind, ToolErrorKind::InvalidOutput);
    }
}