tinyagents 2.1.0

A recursive language-model (RLM) harness for Rust.
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
//! Tool layer for the harness.
//!
//! In the recursive architecture the [`Tool`] trait is the universal call
//! boundary that makes recursion uniform: a tool can be a plain function, but it
//! can equally be an *entire other agent* —
//! [`crate::harness::subagent::SubAgentTool`] implements [`Tool`], so "a model
//! calling a model" is just "a model calling a tool". Everything the agent loop
//! can invoke flows through this layer and its [`ToolRegistry`].
//!
//! See [`types`] for definitions. This module provides constructors and the
//! [`ToolRegistry`] logic for registering and looking up tools by name.

mod schema;
mod types;

use std::sync::Arc;

use serde_json::Value;

use crate::error::{Result, TinyAgentsError};

pub use schema::*;
pub use types::*;

impl ToolSchema {
    /// Creates a tool schema.
    pub fn new(name: impl Into<String>, description: impl Into<String>, parameters: Value) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            parameters,
            format: ToolFormat::Json,
        }
    }

    /// Sets the preferred model-visible tool-call format.
    pub fn with_format(mut self, format: ToolFormat) -> Self {
        self.format = format;
        self
    }

    /// Validates a model-supplied tool call against this tool's schema.
    ///
    /// The harness supports the JSON Schema subset used for model-visible tool
    /// declarations: `type`, object `properties`, `required`,
    /// `additionalProperties: false`, array `items`, and `enum`. Unknown schema
    /// keywords are ignored so providers can still receive richer schemas while
    /// the local execution boundary fails closed for the structural constraints
    /// it understands.
    pub fn validate_call(&self, call: &ToolCall) -> Result<()> {
        if call.name != self.name {
            return Err(TinyAgentsError::Validation(format!(
                "tool call `{}` does not match schema `{}`",
                call.name, self.name
            )));
        }
        validate_schema_value(
            &self.parameters,
            &call.arguments,
            &format!("tool `{}` arguments", self.name),
        )
    }
}

impl ToolFormat {
    /// Returns `true` for the default JSON/function-call format.
    pub fn is_json(&self) -> bool {
        matches!(self, ToolFormat::Json)
    }
}

impl ToolTimeout {
    /// Returns `true` for the default inherited timeout behavior.
    pub fn is_inherit(&self) -> bool {
        matches!(self, ToolTimeout::Inherit)
    }
}

impl ToolDisplay {
    /// Returns `true` when no display metadata is set.
    pub fn is_empty(&self) -> bool {
        self.label.is_none() && self.detail.is_none()
    }

    /// Creates display metadata with optional label and detail fields.
    pub fn new(label: Option<impl Into<String>>, detail: Option<impl Into<String>>) -> Self {
        Self {
            label: label.map(Into::into),
            detail: detail.map(Into::into),
        }
    }

    /// Creates display metadata with only a label.
    pub fn label(label: impl Into<String>) -> Self {
        Self {
            label: Some(label.into()),
            detail: None,
        }
    }

    /// Sets the static display detail.
    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }
}

impl ToolCall {
    /// Creates a tool call with the given id, name, and arguments.
    pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: Value) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            arguments,
            invalid: None,
        }
    }

    /// Creates a tool call the provider could not parse: `raw` (the unparseable
    /// arguments string) is preserved as the arguments value and `reason`
    /// records why parsing failed. The agent loop feeds `reason` back to the
    /// model as an error tool result instead of failing the run.
    pub fn invalid(
        id: impl Into<String>,
        name: impl Into<String>,
        raw: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            arguments: Value::String(raw.into()),
            invalid: Some(reason.into()),
        }
    }

    /// Returns `true` when the model emitted unparseable arguments for this call
    /// (see [`Self::invalid`]).
    pub fn is_invalid(&self) -> bool {
        self.invalid.is_some()
    }
}

impl ToolResult {
    /// Creates a successful textual tool result.
    pub fn text(
        call_id: impl Into<String>,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        Self {
            call_id: call_id.into(),
            name: name.into(),
            content: content.into(),
            raw: None,
            error: None,
            elapsed_ms: 0,
        }
    }

    /// Creates an error tool result, preserving the call id for repair.
    pub fn error(
        call_id: impl Into<String>,
        name: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        let message = message.into();
        Self {
            call_id: call_id.into(),
            name: name.into(),
            content: message.clone(),
            raw: None,
            error: Some(message),
            elapsed_ms: 0,
        }
    }

    /// Returns `true` when the tool reported an error.
    pub fn is_error(&self) -> bool {
        self.error.is_some()
    }
}

impl ToolPolicy {
    /// A classified, side-effect-free read-only policy.
    ///
    /// This is the recommended baseline for pure tools (computation, lookups
    /// against in-memory state) that never touch the filesystem, network, or
    /// money. Being *classified*, it passes strict policy enforcement.
    pub fn read_only() -> Self {
        Self {
            classified: true,
            side_effects: ToolSideEffects {
                read_only: true,
                ..ToolSideEffects::default()
            },
            runtime: ToolRuntime {
                idempotent: true,
                cancelable: true,
                ..ToolRuntime::default()
            },
            access: ToolAccess {
                background_safe: true,
                ..ToolAccess::default()
            },
            display: ToolDisplay::default(),
        }
    }

    /// A classified policy with no side effects declared yet, ready for the
    /// builder methods below.
    pub fn classified() -> Self {
        Self {
            classified: true,
            ..Self::default()
        }
    }

    /// Sets the declared side effects.
    pub fn with_side_effects(mut self, side_effects: ToolSideEffects) -> Self {
        self.classified = true;
        self.side_effects = side_effects;
        self
    }

    /// Sets the declared runtime requirements.
    pub fn with_runtime(mut self, runtime: ToolRuntime) -> Self {
        self.classified = true;
        self.runtime = runtime;
        self
    }

    /// Sets the declared access requirements.
    pub fn with_access(mut self, access: ToolAccess) -> Self {
        self.classified = true;
        self.access = access;
        self
    }

    /// Sets human-facing presentation metadata for timeline/audit use.
    pub fn with_display(mut self, display: ToolDisplay) -> Self {
        self.display = display;
        self
    }

    /// Marks the tool as requiring explicit human approval before each call.
    pub fn requiring_approval(mut self) -> Self {
        self.classified = true;
        self.access.approval_required = true;
        self
    }

    /// Returns `true` when the policy declares any side effect beyond read-only.
    pub fn has_side_effects(&self) -> bool {
        let s = &self.side_effects;
        s.writes_files
            || s.network
            || s.installs_dependencies
            || s.destructive
            || s.external_service
            || s.payment
    }
}

/// Derives a title-cased human-readable label from a raw tool name.
///
/// Common machine prefixes are stripped, and `snake_case` / `kebab-case` names
/// become spaced labels. Degenerate names fall back to the original input so
/// callers never receive an empty label unless the input itself was empty.
pub fn humanize_tool_name(name: &str) -> String {
    let trimmed = name
        .strip_prefix("composio_")
        .or_else(|| name.strip_prefix("mcp_"))
        .unwrap_or(name);

    let mut out = String::with_capacity(trimmed.len());
    let mut capitalize = true;
    for ch in trimmed.chars() {
        if ch == '_' || ch == '-' {
            if !out.is_empty() && !out.ends_with(' ') {
                out.push(' ');
            }
            capitalize = true;
        } else if capitalize {
            out.extend(ch.to_uppercase());
            capitalize = false;
        } else {
            out.push(ch);
        }
    }

    let label = out.trim();
    if label.is_empty() {
        name.to_string()
    } else {
        label.to_string()
    }
}

/// Extracts a compact human-facing detail from common tool argument keys.
///
/// The first recognized scalar value wins, using keys that usually identify the
/// resource being acted on (`path`, `query`, `to`, `url`, and similar). Returns
/// `None` for non-object args, empty values, and complex values.
pub fn context_detail_from_args(args: &Value) -> Option<String> {
    const CONTEXT_KEYS: &[&str] = &[
        "to",
        "recipient",
        "recipient_email",
        "to_email",
        "email",
        "query",
        "q",
        "search",
        "search_query",
        "url",
        "file_path",
        "path",
        "command",
        "cmd",
        "subject",
        "title",
        "channel",
        "channel_id",
        "repo",
        "repository",
        "name",
        "id",
    ];

    let obj = args.as_object()?;
    for key in CONTEXT_KEYS {
        let Some(value) = obj.get(*key) else {
            continue;
        };
        if let Some(rendered) = render_context_value(value) {
            return Some(rendered);
        }
    }
    None
}

fn render_context_value(value: &Value) -> Option<String> {
    const MAX_DETAIL: usize = 80;

    let raw = match value {
        Value::String(s) => s.trim().to_string(),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Array(items) => items
            .iter()
            .filter_map(Value::as_str)
            .collect::<Vec<_>>()
            .join(", "),
        _ => String::new(),
    };
    let raw = raw.split_whitespace().collect::<Vec<_>>().join(" ");
    if raw.is_empty() {
        return None;
    }
    if raw.chars().count() > MAX_DETAIL {
        let truncated: String = raw.chars().take(MAX_DETAIL.saturating_sub(3)).collect();
        Some(format!("{truncated}..."))
    } else {
        Some(raw)
    }
}

impl<State: Send + Sync> ToolRegistry<State> {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self {
            tools: std::collections::HashMap::new(),
        }
    }

    /// Registers a tool under its [`Tool::name`], replacing any existing tool
    /// with the same name.
    pub fn register(&mut self, tool: Arc<dyn Tool<State>>) -> &mut Self {
        self.tools.insert(tool.name().to_owned(), tool);
        self
    }

    /// Looks up a tool by name.
    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool<State>>> {
        self.tools.get(name).cloned()
    }

    /// Returns the registered tool names in sorted order.
    pub fn names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.tools.keys().cloned().collect();
        names.sort();
        names
    }

    /// Returns the schemas of all registered tools, sorted by name.
    pub fn schemas(&self) -> Vec<ToolSchema> {
        let mut schemas: Vec<ToolSchema> = self.tools.values().map(|t| t.schema()).collect();
        schemas.sort_by(|a, b| a.name.cmp(&b.name));
        schemas
    }

    /// Returns a snapshot of every registered tool's [`ToolPolicy`], keyed by
    /// tool name. This is the projection policy-enforcement middleware and audit
    /// logs consume.
    pub fn policies(&self) -> std::collections::HashMap<String, ToolPolicy> {
        self.tools
            .iter()
            .map(|(name, tool)| (name.clone(), tool.policy()))
            .collect()
    }
}

impl<State: Send + Sync> Default for ToolRegistry<State> {
    fn default() -> Self {
        Self::new()
    }
}

fn validate_schema_value(schema: &Value, value: &Value, path: &str) -> Result<()> {
    if schema.is_null() || schema.as_object().is_some_and(|o| o.is_empty()) {
        return Ok(());
    }

    if let Some(enum_values) = schema.get("enum").and_then(Value::as_array)
        && !enum_values.iter().any(|allowed| allowed == value)
    {
        return Err(TinyAgentsError::Validation(format!(
            "{path} must be one of the declared enum values"
        )));
    }

    if let Some(type_spec) = schema.get("type") {
        validate_type_spec(type_spec, value, path)?;
    }

    // Enforce `required` independently of `properties`. A schema may declare
    // required fields without listing per-field property schemas; nesting this
    // check under `properties` would let such schemas fail open, silently
    // accepting calls that omit required arguments.
    if let Some(required) = schema.get("required").and_then(Value::as_array) {
        let object = value.as_object().ok_or_else(|| {
            TinyAgentsError::Validation(format!("{path} must be an object with declared fields"))
        })?;
        for field in required.iter().filter_map(Value::as_str) {
            if !object.contains_key(field) {
                return Err(TinyAgentsError::Validation(format!(
                    "{path}.{field} is required"
                )));
            }
        }
    }

    if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
        let object = value.as_object().ok_or_else(|| {
            TinyAgentsError::Validation(format!("{path} must be an object with declared fields"))
        })?;

        if schema.get("additionalProperties").and_then(Value::as_bool) == Some(false) {
            for field in object.keys() {
                if !properties.contains_key(field) {
                    return Err(TinyAgentsError::Validation(format!(
                        "{path}.{field} is not allowed"
                    )));
                }
            }
        }

        for (field, field_schema) in properties {
            if let Some(field_value) = object.get(field) {
                validate_schema_value(field_schema, field_value, &format!("{path}.{field}"))?;
            }
        }
    }

    if let Some(items_schema) = schema.get("items")
        && let Some(items) = value.as_array()
    {
        for (index, item) in items.iter().enumerate() {
            validate_schema_value(items_schema, item, &format!("{path}[{index}]"))?;
        }
    }

    Ok(())
}

fn validate_type_spec(type_spec: &Value, value: &Value, path: &str) -> Result<()> {
    if let Some(kind) = type_spec.as_str() {
        if json_value_matches_type(value, kind) {
            return Ok(());
        }
        return Err(TinyAgentsError::Validation(format!(
            "{path} must be {kind}, got {}",
            json_value_kind(value)
        )));
    }

    if let Some(kinds) = type_spec.as_array() {
        let allowed: Vec<&str> = kinds.iter().filter_map(Value::as_str).collect();
        if allowed
            .iter()
            .any(|kind| json_value_matches_type(value, kind))
        {
            return Ok(());
        }
        return Err(TinyAgentsError::Validation(format!(
            "{path} must be one of {}, got {}",
            allowed.join(", "),
            json_value_kind(value)
        )));
    }

    Ok(())
}

fn json_value_matches_type(value: &Value, kind: &str) -> bool {
    match kind {
        "null" => value.is_null(),
        "boolean" => value.is_boolean(),
        "object" => value.is_object(),
        "array" => value.is_array(),
        "number" => value.is_number(),
        "integer" => value.as_i64().is_some() || value.as_u64().is_some(),
        "string" => value.is_string(),
        _ => true,
    }
}

fn json_value_kind(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(n) if n.as_i64().is_some() || n.as_u64().is_some() => "integer",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}

#[cfg(test)]
mod schema_test;
#[cfg(test)]
mod test;