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
//! REPL command and session types for the `.ragsh` interactive language.
//!
//! These types model the RLM/CodeAct loop as data: a [`ReplCommand`] is one
//! step an orchestrator issues, a [`ReplSession`] holds the durable values and
//! command history that step runs against, a [`CapabilityPolicy`] is the
//! allowlist that bounds what a (possibly model-driven) session may invoke, and
//! a [`ReplOutcome`] is the structured, inspectable result fed back into the
//! next step.
//!
//! All public types for the REPL skeleton live here.  Logic (parsing) lives in
//! [`super`]; tests live in `test.rs`.

use std::collections::{HashMap, HashSet, VecDeque};

use serde::{Deserialize, Serialize};

// ── Command model ─────────────────────────────────────────────────────────────

/// The set of commands understood by the `.ragsh` REPL.
///
/// Each variant maps to one command verb.  Serde is derived so that command
/// values can be logged or replayed as JSON.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "command", rename_all = "snake_case")]
pub enum ReplCommand {
    /// Print command help listing all verbs and their signatures.
    Help,

    /// Load a `.rag` blueprint from the given file path into the session.
    Load {
        /// Filesystem path to the `.rag` source file.
        path: String,
    },

    /// Compile a named blueprint that has already been loaded into the session.
    Compile {
        /// Name of the blueprint to compile.
        name: String,
    },

    /// Run a named compiled graph with a JSON-encoded input payload.
    ///
    /// In the skeleton this produces a [`ReplOutcome::Planned`]; live wiring
    /// to the graph runtime is a follow-up milestone.
    Run {
        /// Name of the registered compiled graph.
        graph: String,
        /// JSON-encoded input payload to pass to the graph.
        input: String,
    },

    /// Set a named session variable to a string value.
    ///
    /// The value is stored internally as a [`serde_json::Value::String`].
    /// Use [`ReplSession::set`] directly for richer JSON values.
    Set {
        /// Variable name.
        key: String,
        /// String representation of the value.
        value: String,
    },

    /// Retrieve a named session variable and return its value.
    Get {
        /// Variable name to look up.
        key: String,
    },

    /// Show session information.
    ///
    /// Recognised subjects: `vars`, `graphs`, `status`.
    Show {
        /// The subject to display (`vars`, `graphs`, or `status`).
        what: String,
    },

    /// Invoke a registered capability by name with a JSON argument object.
    ///
    /// In the skeleton this is policy-checked and returned as
    /// [`ReplOutcome::Planned`] rather than executed immediately.
    Call {
        /// Name of the registered capability (must be on the [`CapabilityPolicy`]
        /// allowlist).
        capability: String,
        /// Arbitrary JSON arguments forwarded to the capability.
        args: serde_json::Value,
    },

    /// Exit the REPL session.
    Quit,
}

impl ReplCommand {
    /// Returns the canonical command verb name used in the grammar.
    pub fn name(&self) -> &'static str {
        match self {
            ReplCommand::Help => "help",
            ReplCommand::Load { .. } => "load",
            ReplCommand::Compile { .. } => "compile",
            ReplCommand::Run { .. } => "run",
            ReplCommand::Set { .. } => "set",
            ReplCommand::Get { .. } => "get",
            ReplCommand::Show { .. } => "show",
            ReplCommand::Call { .. } => "call",
            ReplCommand::Quit => "quit",
        }
    }
}

// ── Outcome ───────────────────────────────────────────────────────────────────

/// The result produced by executing a [`ReplCommand`] in a [`ReplSession`].
///
/// Uses adjacent tagging (`tag = "kind", content = "data"`) so that newtype
/// variants containing non-map values (such as `Message` holding a `String`)
/// serialize correctly alongside struct variants like `Planned`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
pub enum ReplOutcome {
    /// A human-readable message from a side-effect-free command.
    Message(String),

    /// A JSON value retrieved from the session namespace.
    Value(serde_json::Value),

    /// The command was policy-checked and recorded; live harness/graph
    /// execution is deferred until the REPL skeleton is wired to a runtime
    /// (milestones R2–R6 in the design document).
    Planned {
        /// Short label of the intended action (e.g. `"graph_run"`).
        action: String,
        /// Structured parameters describing the planned call.
        detail: serde_json::Value,
    },

    /// The session has been asked to terminate.
    Quit,
}

// ── Capability policy ─────────────────────────────────────────────────────────

/// An allowlist that controls which capability names a [`ReplSession`] may
/// invoke.
///
/// By default nothing is allowed.  Use [`CapabilityPolicy::allow`] or
/// [`CapabilityPolicy::from_list`] to grant access.  Attempting to invoke a
/// capability that is not on the list produces a
/// [`crate::error::TinyAgentsError::Capability`] error.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CapabilityPolicy {
    allowed: HashSet<String>,
}

impl CapabilityPolicy {
    /// Create an empty policy (no capabilities allowed).
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a capability name to the allowlist.
    pub fn allow(&mut self, name: impl Into<String>) -> &mut Self {
        self.allowed.insert(name.into());
        self
    }

    /// Returns `true` if the given capability name is on the allowlist.
    pub fn is_allowed(&self, name: &str) -> bool {
        self.allowed.contains(name)
    }

    /// Build a policy from an iterable of allowed names.
    pub fn from_list<I, S>(names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let mut policy = Self::new();
        for name in names {
            policy.allow(name.into());
        }
        policy
    }

    /// Returns the number of capabilities currently on the allowlist.
    pub fn len(&self) -> usize {
        self.allowed.len()
    }

    /// Returns `true` if no capabilities are allowed.
    pub fn is_empty(&self) -> bool {
        self.allowed.is_empty()
    }
}

// ── Session ───────────────────────────────────────────────────────────────────

/// An interactive REPL session holding session variables, a capability policy,
/// and a command history.
///
/// `ReplSession` is the primary entry point for driving the `.ragsh` skeleton
/// — the **line-oriented command REPL** (verbs like `set`/`get`/`run`/`call`
/// parsed from a single line; see the [`repl`](crate::repl) module docs for
/// the grammar).
///
/// # Not to be confused with `repl::session::ReplSession`
///
/// There are two distinct types named `ReplSession` in this crate, gated
/// differently and serving different layers of the `.ragsh` design:
///
/// - **This type** (`repl::ReplSession`, always available) — the
///   line-oriented command skeleton documented here.
/// - [`crate::repl::session::ReplSession`] (feature `repl` only) — the
///   Rhai-backed scripting session: a persistent namespace evaluated one cell
///   (small script) at a time, with capability calls (`model_query`,
///   `tool_call`, `graph_run`, …) wired to live registries.
///
/// Only **this** type is re-exported as `repl::ReplSession`; the scripting
/// session is deliberately *not* re-exported there to avoid shadowing it, and
/// must be reached via `repl::session::ReplSession`. With the `repl` feature
/// enabled, `crate::ReplSession` (the crate-root re-export) resolves to the
/// **scripting** session instead — the crate root and the `repl` module
/// re-export different types under the same final path segment, so always
/// check which path (`crate::ReplSession` vs. `crate::repl::ReplSession`) you
/// actually imported from.
///
/// ## Execution model
///
/// Side-effect-free commands (`Set`, `Get`, `Show`, `Help`, `Quit`) run fully
/// inside `execute`.  Commands that need live harness/graph integration
/// (`Load`, `Compile`, `Run`, `Call`) are policy-checked first — a
/// [`crate::error::TinyAgentsError::Capability`] error is returned immediately
/// if the operation is not on the allowlist — and, when allowed, the method
/// returns [`ReplOutcome::Planned`] describing the intended action without
/// performing it.  The wiring to the live runtime is a follow-up milestone
/// (R2–R6 in the design document).
///
/// ## Example
///
/// ```rust
/// use tinyagents::repl::{ReplSession, CapabilityPolicy, ReplOutcome};
///
/// let policy = CapabilityPolicy::from_list(["my_tool"]);
/// let mut session = ReplSession::new().with_policy(policy);
///
/// session.set("x", serde_json::json!(42));
/// assert_eq!(session.get("x"), Some(&serde_json::json!(42)));
/// ```
pub struct ReplSession {
    /// Session-scoped variables, keyed by name and stored as JSON values.
    variables: HashMap<String, serde_json::Value>,
    /// The capability allowlist governing this session.
    policy: CapabilityPolicy,
    /// Ordered history of the most recent commands submitted to this session
    /// (oldest first). Bounded by the session's history capacity —
    /// [`DEFAULT_HISTORY_CAPACITY`] unless overridden with
    /// [`ReplSession::with_history_capacity`] — with the **oldest** entries
    /// dropped once the cap is reached, so a long-lived session does not grow
    /// without bound (`Call` commands clone their full JSON args into history).
    pub history: VecDeque<ReplCommand>,
    /// Maximum number of retained history entries.
    history_capacity: usize,
}

/// Default cap on [`ReplSession::history`] entries.
///
/// Chosen to comfortably cover interactive and replay sessions while bounding
/// memory in long-lived processes; override per session with
/// [`ReplSession::with_history_capacity`].
pub const DEFAULT_HISTORY_CAPACITY: usize = 1000;

impl ReplSession {
    /// Create a new session with an empty namespace, a deny-all policy, and
    /// the default history capacity ([`DEFAULT_HISTORY_CAPACITY`]).
    pub fn new() -> Self {
        Self {
            variables: HashMap::new(),
            policy: CapabilityPolicy::new(),
            history: VecDeque::new(),
            history_capacity: DEFAULT_HISTORY_CAPACITY,
        }
    }

    /// Replace the session's capability policy, returning the updated session.
    pub fn with_policy(mut self, policy: CapabilityPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Set the maximum number of history entries retained by this session,
    /// returning the updated session.
    ///
    /// Once the cap is reached the **oldest** entry is dropped per new
    /// command. A capacity of `0` disables history recording entirely. Any
    /// existing overflow is trimmed immediately.
    pub fn with_history_capacity(mut self, capacity: usize) -> Self {
        self.history_capacity = capacity;
        while self.history.len() > capacity {
            self.history.pop_front();
        }
        self
    }

    /// Set a session variable to any JSON value.
    pub fn set(&mut self, key: impl Into<String>, value: serde_json::Value) {
        self.variables.insert(key.into(), value);
    }

    /// Get a session variable by name.  Returns `None` if it has not been set.
    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
        self.variables.get(key)
    }

    /// Return a reference to the full variable map.
    pub fn vars(&self) -> &HashMap<String, serde_json::Value> {
        &self.variables
    }

    /// Execute a command against this session and return a [`ReplOutcome`].
    ///
    /// The command is appended to [`ReplSession::history`] before execution
    /// begins; when the history is at capacity the oldest entry is dropped
    /// first (see [`ReplSession::with_history_capacity`]).
    ///
    /// # Errors
    ///
    /// * [`crate::error::TinyAgentsError::Capability`] — the command requires
    ///   a capability that is not on the allowlist.
    /// * [`crate::error::TinyAgentsError::Serialization`] — an internal
    ///   serialization step failed (e.g. serialising variables for `show vars`).
    pub fn execute(&mut self, cmd: ReplCommand) -> crate::error::Result<ReplOutcome> {
        if self.history_capacity > 0 {
            if self.history.len() == self.history_capacity {
                self.history.pop_front();
            }
            self.history.push_back(cmd.clone());
        }

        match cmd {
            ReplCommand::Help => {
                let text = concat!(
                    "Commands:\n",
                    "  help                        — show this help\n",
                    "  load <path>                 — load a .rag blueprint\n",
                    "  compile <name>              — compile a loaded blueprint\n",
                    "  run <graph> <input>         — run a compiled graph\n",
                    "  set <key> <value>           — set a session variable\n",
                    "  get <key>                   — retrieve a session variable\n",
                    "  show <vars|graphs|status>   — show session info\n",
                    "  call <capability> <json>    — invoke a registered capability\n",
                    "  quit                        — exit the session",
                );
                Ok(ReplOutcome::Message(text.to_string()))
            }

            ReplCommand::Quit => Ok(ReplOutcome::Quit),

            ReplCommand::Set { key, value } => {
                self.variables.insert(key, serde_json::Value::String(value));
                Ok(ReplOutcome::Message("ok".to_string()))
            }

            ReplCommand::Get { key } => {
                let val = self
                    .variables
                    .get(&key)
                    .cloned()
                    .unwrap_or(serde_json::Value::Null);
                Ok(ReplOutcome::Value(val))
            }

            ReplCommand::Show { what } => match what.as_str() {
                "vars" => {
                    let map = serde_json::to_value(&self.variables)?;
                    Ok(ReplOutcome::Value(map))
                }
                "graphs" => Ok(ReplOutcome::Message(
                    "(graph registry not yet wired in skeleton)".to_string(),
                )),
                "status" => {
                    let status = serde_json::json!({
                        "variables": self.variables.len(),
                        "history": self.history.len(),
                        "policy_allowed": self.policy.len(),
                    });
                    Ok(ReplOutcome::Value(status))
                }
                other => Ok(ReplOutcome::Message(format!(
                    "unknown show subject `{other}`; recognised subjects: vars, graphs, status"
                ))),
            },

            ReplCommand::Load { path } => {
                self.check_capability("load")?;
                Ok(ReplOutcome::Planned {
                    action: "load".to_string(),
                    detail: serde_json::json!({ "path": path }),
                })
            }

            ReplCommand::Compile { name } => {
                self.check_capability("compile")?;
                Ok(ReplOutcome::Planned {
                    action: "compile".to_string(),
                    detail: serde_json::json!({ "name": name }),
                })
            }

            ReplCommand::Run { graph, input } => {
                self.check_capability("run")?;
                Ok(ReplOutcome::Planned {
                    action: "graph_run".to_string(),
                    detail: serde_json::json!({ "graph": graph, "input": input }),
                })
            }

            ReplCommand::Call { capability, args } => {
                self.check_capability(&capability)?;
                Ok(ReplOutcome::Planned {
                    action: "capability_call".to_string(),
                    detail: serde_json::json!({ "capability": capability, "args": args }),
                })
            }
        }
    }

    // ── Private helpers ───────────────────────────────────────────────────────

    fn check_capability(&self, name: &str) -> crate::error::Result<()> {
        if self.policy.is_allowed(name) {
            Ok(())
        } else {
            Err(crate::error::TinyAgentsError::Capability(format!(
                "capability `{name}` is not in the session allowlist"
            )))
        }
    }
}

impl Default for ReplSession {
    fn default() -> Self {
        Self::new()
    }
}