refactor(claw): carry the tool seam the 0.4.2 line removed

The 0.4.2 line deletes the resident tool machinery from
rhema-autonomous-agent. The claw was its only consumer, so the
registry, the TOOL.yaml loader, the allowlist, and the resolver chain
now live in `toolkit`, beside the manifests and builtins that feed
them. The shapes do not change; only the owner does.

The compiler marked the rest of the release's edges:

- The resolver seam grew `resolve_streaming`, so the chain returns the
  shell's output as deltas and a filtered registry still answers the
  plain call.
- `ShellExecutor::run` now takes a `RunRequest` and a `ToolProgress`
  sink. The sandbox adapter re-roots the request for the wrapped
  sandbox and relays its `RunOutcome`; `Sandbox::exec` became
  `Sandbox::run`, so the seed probe follows.
- `SandboxError::OutOfMemory` joins the error mapping.
- `rhema_core::paste` left the engine with the display encodings, so
  `paste` here carries the span record, the annotation, and the legacy
  migration. A stash from either line loads unchanged.
- `rhema_bash::exec` no longer re-exports `async_trait`; the tool
  modules import it from the crate.

The dependency pins and both integrations move to 0.4.2 together; the
lock refreshes with them.
This commit is contained in:
vhaudiquet committed 2026-11-24 20:02:46 +01:00
1 parent ea26019f0c
commit 23aea1195d
23 files changed
+2208 -206

No files matched your search

+18 -19
View File
@@ -29,26 +29,25 @@ mock = ["rhema-core/mock"]
# shell, the approval seam, and revive-on-resume (rhema-bash), the
# system-prompt renderer (rhema-prompt), and the driver that turns a
# provider into a host-operating agent (rhema-host-agent)
rhema-bash = "0.4.1"
rhema-prompt = "0.4.1"
rhema-host-agent = "0.4.1"
rhema-autonomous-agent = "0.4.1"
rhema-config = "0.4.1"
rhema-core = "0.4.1"
rhema-bash = "0.4.2"
rhema-prompt = "0.4.2"
rhema-host-agent = "0.4.2"
rhema-autonomous-agent = "0.4.2"
rhema-config = "0.4.2"
rhema-core = "0.4.2"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.4.1"
rhema-transcript = "0.4.2"
rhema-calendar-integration = { path = "../../integrations/rhema-calendar-integration" }
rhema-forge-integration = { path = "../../integrations/rhema-forge-integration" }
# The accounts layer: identities hold the forge tokens the watches poll
# with, and the identity tools manage them over chat
rhema-identity = "0.4.1"
rhema-rsd = "0.4.1"
rhema-identity = "0.4.2"
rhema-rsd = "0.4.2"
# The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box
# The private-key seam: the ssh sandbox carries the key text, not a
# path, so a store-held credential has no file to stage. This rides
# the rhema 0.4.2 release; everything else stays on the 0.4.1 line
# until the lockstep bump.
# speaking the wire protocol over HTTP, or an ssh login on a far box.
# The choice carries an ssh private key as text, so a store-held
# credential has no file to stage; that is the seam the 0.4.2 line adds,
# and the family moves to it together.
rhema-sandbox = "0.4.2"
rhema-sandbox-http = "0.4.2"
rhema-sandbox-ssh = "0.4.2"
@@ -57,10 +56,10 @@ rhema-sandbox-ssh = "0.4.2"
# contract only — never the reverse.
rhema-claw-tools-contract = { path = "../../tools/contract" }
# The resident tier's durable memory: its tools join the resolver chain
rhema-memory = "0.4.1"
rhema-memory = "0.4.2"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.4.1"
rhema-provider-registry = "0.4.1"
rhema-provider = "0.4.2"
rhema-provider-registry = "0.4.2"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -85,7 +84,7 @@ time = { version = "0.3", default-features = false, features = ["parsing"] }
# Inbound chat images ride base64; the dispatch decodes them into the
# attachment store
base64 = "0.23"
rhema-mcp = "0.4.1"
rhema-mcp = "0.4.2"
[dev-dependencies]
tempfile = "3"
@@ -97,7 +96,7 @@ reqwest = { version = "0.13", features = ["json", "stream"] }
bytes = "1"
# The scripted provider for turn-level tests; mirrors rhema-code's mock
# feature without a feature of our own — tests are the only consumer
rhema-core = { version = "0.4.1", features = ["mock"] }
rhema-core = { version = "0.4.2", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+8 -10
View File
@@ -29,7 +29,8 @@ use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_core::{ToolCall, ToolContext, ToolResolver, ToolResult, ToolSpec};
use rhema_identity::{Account, AccountDraft, IdentityStore, Secret, SecretKind};
use serde::Deserialize;
@@ -283,8 +284,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// The identity tool set over the account store and the watch table —
/// specs from the embedded manifests, operations compiled here.
pub fn registry(accounts: Arc<dyn IdentityStore>, watches: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(accounts, watches));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
assert!(
skipped.is_empty(),
"the identity tool manifests must all load: {skipped:?}"
@@ -582,7 +582,7 @@ impl ToolResolver for IdentityExec {
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::ToolOp;
use crate::toolkit::ToolOp;
fn parts() -> (Arc<dyn IdentityStore>, Arc<ClawStore>) {
(
@@ -598,15 +598,13 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin_and_serves_the_registry() {
let (accounts, watches) = parts();
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(accounts, watches),
);
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(accounts, watches));
assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 3);
let (accounts, watches) = parts();
let resolver = registry(accounts, watches)
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver =
registry(accounts, watches).resolver_for(&crate::toolkit::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("identity_list"),
rhema_core::ReplaySafety::Safe
+5 -6
View File
@@ -17,7 +17,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -309,10 +310,8 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, workspace.into(), hub, key),
);
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into(), hub, key));
assert!(
skipped.is_empty(),
"the attach_file tool manifest must load: {skipped:?}"
@@ -327,7 +326,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::Allowlist;
use crate::toolkit::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+5 -5
View File
@@ -26,7 +26,8 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rhema_core::ToolSpec;
use rhema_prompt::render_template;
use serde_json::{Value, json};
@@ -312,8 +313,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// interactive resolver chain composes — its spec from the embedded
/// manifest, the operation compiled here.
pub fn registry(bootstrap: Arc<Bootstrap>) -> ToolRegistry {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(bootstrap));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap));
assert!(
skipped.is_empty(),
"the bootstrap tool manifest must load: {skipped:?}"
@@ -444,7 +444,7 @@ mod tests {
let tools = registry(Arc::new(Bootstrap {
root: bootstrap.root().to_path_buf(),
}))
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive())
.resolver_for(&crate::toolkit::Allowlist::permissive())
.specs();
let prompt = render_system(
DEFAULT_SYSTEM_MD,
@@ -666,7 +666,7 @@ mod tests {
#[tokio::test]
async fn the_tool_writes_through_the_store_and_answers_one_line() {
use rhema_autonomous_agent::Allowlist;
use crate::toolkit::Allowlist;
use rhema_core::{ToolCall, ToolContext};
let (_dir, bootstrap) = store();
+5 -6
View File
@@ -21,7 +21,8 @@ use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rusqlite::params;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -509,10 +510,8 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(consents, bridge, hub, key),
);
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(consents, bridge, hub, key));
assert!(
skipped.is_empty(),
"the ask_secret tool manifest must load: {skipped:?}"
@@ -527,7 +526,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::Allowlist;
use crate::toolkit::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+5 -4
View File
@@ -32,17 +32,18 @@
use std::path::PathBuf;
use std::sync::Arc;
use rhema_autonomous_agent::{Allowlist, Source, ToolRegistry};
use rhema_autonomous_agent::Source;
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_core::ToolResolver;
use rhema_forge_integration::ForgeKind;
use rhema_rsd::{Dispatcher, ResourceKey, SystemClock};
use crate::consents::WaitBridge;
use crate::daemon::ClawError;
use crate::forge::ForgeSource;
use crate::hub::EventHub;
use rhema_calendar_integration::CalendarSource;
use rhema_calendar_integration::CalendarStore;
use rhema_forge_integration::ForgeKind;
use crate::toolkit::{Allowlist, ToolRegistry};
/// The store handles the standard set is assembled over. One struct,
/// so a new extension is a field plus a constructor line, not another
+2 -2
View File
@@ -50,8 +50,8 @@ use crate::sandbox::SandboxState;
/// [`Role`] is the seam it hangs on, a reviewer dispatch deserving a
/// narrower policy than an implementer's — and a policy that refuses the
/// shell refuses the run (see [`ClawHandler::dispatch`]).
fn allowlist() -> rhema_autonomous_agent::Allowlist {
rhema_autonomous_agent::Allowlist::permissive()
fn allowlist() -> crate::toolkit::Allowlist {
crate::toolkit::Allowlist::permissive()
}
/// The coding agent over one watch: a provider, a model, a workspace
+1 -1
View File
@@ -28,11 +28,11 @@
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, PoisonError};
use rhema_core::paste::PasteSpan;
use rhema_rsd::ResourceKey;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
use crate::paste::PasteSpan;
use crate::turn_store::{TurnStore, TurnStoreError};
/// How many events a subscriber may trail by before the oldest drop.
+5 -6
View File
@@ -14,7 +14,8 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -353,10 +354,8 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The identity tool set over `store`: `identity_set` — its spec from
/// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, workspace.into()),
);
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, workspace.into()));
assert!(
skipped.is_empty(),
"the identity_set tool manifest must load: {skipped:?}"
@@ -371,7 +370,7 @@ pub fn registry(store: Arc<IdentityStore>, workspace: impl Into<PathBuf>) -> Too
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::Allowlist;
use crate::toolkit::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+13 -11
View File
@@ -78,7 +78,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use rhema_autonomous_agent::{Allowlist, Handler, ResolverChain, SessionContext, async_trait};
use async_trait::async_trait;
use rhema_autonomous_agent::{Handler, SessionContext};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{
Agent, ChatParams, Content, Event as ModelEvent, EventSink, Image, ImageMediaType, Message,
@@ -96,6 +97,7 @@ use crate::hub::{EventHub, TurnEvent, UserImage};
use crate::notifications::NotificationStore;
use crate::sandbox::SandboxState;
use crate::steer::{SteerGuard, SteerRegistry};
use crate::toolkit::{Allowlist, ResolverChain};
/// The key prefixes of the resident context (see the module docs):
/// `interactive:`, `task:`, `phone:`, and `calendar:`. Forge keys —
@@ -497,8 +499,8 @@ impl InteractiveHandler {
// plain either way before the join, its span
// measured where it lands.
let mut message = [Message::text(Role::User, text.to_owned())];
rhema_core::paste::migrate(&mut message);
let mut spans = rhema_core::paste::spans(&message[0]);
crate::paste::migrate(&mut message);
let mut spans = crate::paste::spans(&message[0]);
let mut composed = match &message[0].content[0] {
Content::Text(text) => text.clone(),
_ => unreachable!("the message was built with one text block"),
@@ -509,9 +511,9 @@ impl InteractiveHandler {
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(rhema_core::paste::normalize)
.map(crate::paste::normalize)
{
let span = rhema_core::paste::PasteSpan {
let span = crate::paste::PasteSpan {
start: composed.len(),
end: composed.len() + paste.len(),
lines: paste.lines().count(),
@@ -538,7 +540,7 @@ impl InteractiveHandler {
}
let base = input.len();
input.push_str(&text);
pastes.extend(spans.into_iter().map(|span| rhema_core::paste::PasteSpan {
pastes.extend(spans.into_iter().map(|span| crate::paste::PasteSpan {
start: span.start + base,
end: span.end + base,
lines: span.lines,
@@ -669,14 +671,14 @@ impl InteractiveHandler {
let framed_len = input.len();
let pastes = pastes
.iter()
.map(|span| rhema_core::paste::PasteSpan {
.map(|span| crate::paste::PasteSpan {
start: span.start + framed_len - recorded_len,
end: span.end + framed_len - recorded_len,
lines: span.lines,
})
.collect::<Vec<_>>();
let mut question = [Message::text_with_images(Role::User, input, core_images)];
rhema_core::paste::annotate(&mut question[0], &pastes);
crate::paste::annotate(&mut question[0], &pastes);
let [turn_input] = question;
let mut turn = Box::pin(run_turn(
&mut agent,
@@ -871,7 +873,7 @@ fn restore_session(stashed: &Value, key: &str) -> Result<Session, String> {
// embedded form in its prompts; the provider must never see
// a mark. One rewrite on the way in, chips survive as the
// span note — the same pass the driver's from_session runs.
rhema_core::paste::migrate(&mut session.history);
crate::paste::migrate(&mut session.history);
Ok(session)
}
}
@@ -1754,8 +1756,8 @@ mod tests {
// The chip rides as the span note: one span, over exactly the
// payload's range, and no mark survives the restore.
assert_eq!(
rhema_core::paste::spans(&session.history[0]).as_slice(),
&[rhema_core::paste::PasteSpan {
crate::paste::spans(&session.history[0]).as_slice(),
&[crate::paste::PasteSpan {
start: "review this:".len(),
end: "review this:".len() + payload.len(),
lines: 3,
+4 -4
View File
@@ -17,7 +17,8 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -41,8 +42,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[(
/// The coding-agent tool set over `store`: one tool, `coding_agent` —
/// its spec from the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<CodingJobStore>) -> ToolRegistry {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the coding_agent tool manifest must load: {skipped:?}"
@@ -227,7 +227,7 @@ fn required<'a>(value: &'a Option<String>, complaint: &str) -> Result<&'a str, S
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::Allowlist;
use crate::toolkit::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+2
View File
@@ -96,6 +96,7 @@ pub mod mock;
pub mod notifications;
pub mod notify_tools;
pub mod openai;
pub mod paste;
pub mod pause;
pub mod phone;
pub mod sandbox;
@@ -104,6 +105,7 @@ pub mod steer;
pub mod task_source;
pub mod task_store;
pub mod task_tools;
pub mod toolkit;
pub mod turn_store;
pub(crate) mod vision;
pub mod watch_store;
+6 -8
View File
@@ -12,7 +12,8 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -33,8 +34,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[("notify", include_str!("../tools/notif
/// The notification tool set over `store`: `notify` — its spec from
/// the embedded manifest, the operation compiled here.
pub fn registry(store: Arc<NotificationStore>) -> ToolRegistry {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the notify tool manifest must load: {skipped:?}"
@@ -102,7 +102,7 @@ mod tests {
async fn call(store: &Arc<NotificationStore>, args: Value) -> rhema_core::ToolResult {
let resolver =
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
resolver
.resolve(
rhema_core::ToolCall {
@@ -118,13 +118,11 @@ mod tests {
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_spec() {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "notify");
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("notify"),
rhema_core::ReplaySafety::Unsafe,
+215
View File
@@ -0,0 +1,215 @@
//! How a prompt carries a pasted payload: plain text plus a span note.
//!
//! A submitted prompt is plain text with each multi-line paste's payload
//! in place, exactly what the model reads, and the message carries a
//! [`PasteSpan`] list under [`CONSUMER`] saying which byte ranges the
//! chat surface draws as chips. No provider, no summarizer, and no other
//! consumer reads that note.
//!
//! `rhema-core` carried this until 0.4.2 moved display encodings out of
//! the engine. One frontend writes the note and the same frontend reads
//! it, so it belongs beside that frontend. The format is unchanged, so a
//! session stashed by either side loads in the other.
//!
//! [`PasteSpan`] replaced an embedded encoding, [`MARK`], payload,
//! [`MARK`], written into the text. Sessions written that way still
//! load. [`migrate`] rewrites one into plain text plus spans before the
//! first provider call.
use rhema_core::{Content, Message, Role};
use serde::{Deserialize, Serialize};
/// The object-replacement character: opens and closes one embedded
/// paste. Two marks always bracket a payload; a lone mark is literal
/// text.
pub const MARK: char = '\u{FFFC}';
/// The annotation key the chat surface records paste spans under on a
/// user message. No engine reads it.
pub const CONSUMER: &str = "rhema-code";
/// One paste's span in a message's plain text: the byte range its chip
/// stands for, and the payload's line count for the chip's label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PasteSpan {
/// Start byte of the payload in the message text.
pub start: usize,
/// End byte of the payload in the message text, exclusive.
pub end: usize,
/// Lines in the payload, the chip's size label.
pub lines: usize,
}
/// The annotation's own shape, `{"pastes": [...]}`.
#[derive(Serialize, Deserialize)]
struct Pastes {
pastes: Vec<PasteSpan>,
}
/// Normalizes text that travels inside an embed or beside marks:
/// carriage returns to newlines, stray marks dropped, the scan must stay
/// unambiguous.
pub fn normalize(text: &str) -> String {
text.replace("\r\n", "\n")
.replace('\r', "\n")
.replace(MARK, "")
}
/// Records `spans` on `message` under [`CONSUMER`], replacing whatever
/// the same consumer left before; an empty list clears the note.
pub fn annotate(message: &mut Message, spans: &[PasteSpan]) {
if spans.is_empty() {
message.annotations.remove(CONSUMER);
return;
}
let value = serde_json::to_value(Pastes {
pastes: spans.to_vec(),
})
.expect("paste spans serialize");
message.annotate(CONSUMER, value);
}
/// The paste spans `message` carries, empty when it has none or when the
/// note is not this consumer's shape.
pub fn spans(message: &Message) -> Vec<PasteSpan> {
message
.annotation(CONSUMER)
.and_then(|value| serde_json::from_value::<Pastes>(value.clone()).ok())
.map(|pastes| pastes.pastes)
.unwrap_or_default()
}
/// Splits legacy embedded text into the plain form and its spans.
fn split_legacy(text: &str) -> (String, Vec<PasteSpan>) {
let mut plain = String::with_capacity(text.len());
let mut spans = Vec::new();
let mut rest = text;
while let Some(start) = rest.find(MARK) {
plain.push_str(&rest[..start]);
let after = &rest[start + MARK.len_utf8()..];
match after.find(MARK) {
Some(end) => {
let payload = &after[..end];
let begin = plain.len();
plain.push_str(payload);
spans.push(PasteSpan {
start: begin,
end: plain.len(),
lines: payload.lines().count(),
});
rest = &after[end + MARK.len_utf8()..];
}
// An unpaired mark is literal text.
None => {
plain.push(MARK);
rest = after;
}
}
}
plain.push_str(rest);
(plain, spans)
}
/// Rewrites the legacy embedded form in `history` into plain text plus
/// [`PasteSpan`] annotations, returning how many messages changed.
/// Sessions written before the annotation existed carry `MARK payload
/// MARK` inside the prompt; a resumed session must not send those marks
/// to a provider. Chips only ever lived in one user text block, so only
/// user messages are considered.
pub fn migrate(history: &mut [Message]) -> usize {
let mut changed = 0;
for message in history.iter_mut() {
if message.role != Role::User {
continue;
}
let mut spans = Vec::new();
let mut touched = false;
for content in message.content.iter_mut() {
if let Content::Text(text) = content
&& text.contains(MARK)
{
let (plain, found) = split_legacy(text);
*text = plain;
spans.extend(found);
touched = true;
}
}
if touched {
annotate(message, &spans);
changed += 1;
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn spans_round_trip_through_the_annotation() {
let mut message = Message::text(Role::User, "look at l1\nl2 this");
assert!(spans(&message).is_empty());
let span = PasteSpan {
start: 8,
end: 13,
lines: 2,
};
annotate(&mut message, &[span]);
assert_eq!(spans(&message), vec![span]);
let json = serde_json::to_value(&message).unwrap();
assert_eq!(json["annotations"]["rhema-code"]["pastes"][0]["lines"], 2);
// Clearing the last span drops the whole note, so an
// annotation-free message keeps the pre-annotation wire shape.
annotate(&mut message, &[]);
assert!(spans(&message).is_empty());
assert!(
serde_json::to_value(&message)
.unwrap()
.get("annotations")
.is_none()
);
}
#[test]
fn migrate_rewrites_the_legacy_form_into_plain_text_and_spans() {
let payload = "l1\nl2\nl3\nl4";
let mut history = vec![
Message::text(Role::User, format!("look at {MARK}{payload}{MARK} this")),
Message::text(Role::Assistant, "on it"),
];
assert_eq!(migrate(&mut history), 1);
assert_eq!(
history[0].content,
Message::text(Role::User, format!("look at {payload} this")).content
);
assert_eq!(
spans(&history[0]),
vec![PasteSpan {
start: 8,
end: 8 + payload.len(),
lines: 4,
}]
);
// Idempotent: the plain form has no marks left to rewrite.
assert_eq!(migrate(&mut history), 0);
assert_eq!(history[1], Message::text(Role::Assistant, "on it"));
}
#[test]
fn an_unpaired_mark_migrates_as_literal_text() {
let mut history = vec![Message::text(Role::User, format!("a{MARK}b"))];
assert_eq!(migrate(&mut history), 1);
assert_eq!(
history[0].content,
Message::text(Role::User, "a\u{FFFC}b").content
);
assert!(spans(&history[0]).is_empty());
}
#[test]
fn normalize_flattens_carriage_returns_and_drops_marks() {
assert_eq!(normalize("p\r\nq\rs"), "p\nq\ns");
assert_eq!(normalize(&format!("a{MARK}b")), "ab");
}
}
+5 -6
View File
@@ -49,7 +49,8 @@ use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use rusqlite::params;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -721,10 +722,8 @@ pub fn registry(
hub: Arc<EventHub>,
key: ResourceKey,
) -> ToolRegistry {
let (tools, skipped) = rhema_autonomous_agent::manifest::builtin_tools(
MANIFESTS,
&builtins(store, consents, bridge, hub, key),
);
let (tools, skipped) =
crate::toolkit::builtin_tools(MANIFESTS, &builtins(store, consents, bridge, hub, key));
assert!(
skipped.is_empty(),
"the phone tool manifest must load: {skipped:?}"
@@ -739,7 +738,7 @@ pub fn registry(
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::Allowlist;
use crate::toolkit::Allowlist;
#[test]
fn the_manifest_loads_against_its_builtin_and_serves_the_registry() {
+27 -20
View File
@@ -26,8 +26,9 @@ use std::time::Duration;
use async_trait::async_trait;
use base64::Engine as _;
use rhema_bash::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_bash::exec::{RunOutcome, ShellError, ShellExecutor, default_executor_with};
use rhema_core::{OutputOnly, ToolProgress};
use rhema_sandbox::{RunRequest, Sandbox, ShellSandbox, WorkspaceSeed};
use rhema_sandbox_http::HttpSandbox;
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize};
@@ -388,16 +389,16 @@ impl ClawShell {
.workspace_for(&self.host_workspace)
.to_string_lossy()
.to_string();
let mut sink = |_line: &str| {};
let mut sink = OutputOnly(|_line: &str| {});
let probe = sandbox
.exec(
ExecRequest {
.run(
RunRequest {
command: format!(
"mkdir -p {}; ls -A {} 2>/dev/null | head -n 1",
shquote(&root),
shquote(&root)
),
cwd: root.clone(),
cwd: root.clone().into(),
timeout: PROBE_TIMEOUT,
},
cancelled,
@@ -432,18 +433,13 @@ impl ClawShell {
impl ShellExecutor for ClawShell {
async fn run(
&self,
command: &str,
cwd: &Path,
timeout: Duration,
request: RunRequest,
cancelled: &AtomicBool,
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
) -> Result<Executed, ShellError> {
progress: &mut dyn ToolProgress,
) -> Result<RunOutcome, ShellError> {
let choice = self.state.choice();
if !choice.is_remote() {
return self
.local
.run(command, cwd, timeout, cancelled, progress)
.await;
return self.local.run(request, cancelled, progress).await;
}
{
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
@@ -459,7 +455,15 @@ impl ShellExecutor for ClawShell {
}
let root = choice.remote_root(&self.host_workspace);
ShellSandbox::new(sandbox)
.run(command, &root, timeout, cancelled, progress)
.run(
RunRequest {
command: request.command,
cwd: root,
timeout: request.timeout,
},
cancelled,
progress,
)
.await
}
}
@@ -469,6 +473,7 @@ impl ShellExecutor for ClawShell {
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
match err {
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
rhema_sandbox::SandboxError::OutOfMemory => ShellError::OutOfMemory,
rhema_sandbox::SandboxError::Unavailable(message)
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
// The error enum is non-exhaustive: an unknown failure is still
@@ -800,12 +805,14 @@ mod tests {
});
let executor = state.executor(dir.path());
let cancelled = AtomicBool::new(false);
let mut sink = |_line: &str| {};
let mut sink = OutputOnly(|_line: &str| {});
let executed = executor
.run(
"echo hi",
Path::new(REMOTE_WORKSPACE),
Duration::from_secs(5),
RunRequest {
command: "echo hi".to_owned(),
cwd: Path::new(REMOTE_WORKSPACE).to_path_buf(),
timeout: Duration::from_secs(5),
},
&cancelled,
&mut sink,
)
+10 -13
View File
@@ -15,7 +15,8 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
use time::OffsetDateTime;
@@ -65,8 +66,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `cancel_task` — specs from the embedded manifests, operations
/// compiled here.
pub fn registry(store: Arc<TaskStore>) -> ToolRegistry {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the task tool manifests must all load: {skipped:?}"
@@ -236,7 +236,7 @@ mod tests {
async fn call(store: &Arc<TaskStore>, name: &str, args: Value) -> rhema_core::ToolResult {
let resolver =
registry(store.clone()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
registry(store.clone()).resolver_for(&crate::toolkit::Allowlist::permissive());
resolver
.resolve(
rhema_core::ToolCall {
@@ -252,8 +252,7 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!(
@@ -271,7 +270,7 @@ mod tests {
let mut covered = Vec::new();
for (source, raw) in MANIFESTS {
covered.push(
rhema_autonomous_agent::manifest::parse(raw)
crate::toolkit::parse_manifest(raw)
.unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin,
);
@@ -286,12 +285,11 @@ mod tests {
#[test]
fn the_registry_serves_the_manifest_specs() {
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
let specs = resolver.specs();
for (name, raw) in MANIFESTS {
let manifest = rhema_autonomous_agent::manifest::parse(raw)
.unwrap_or_else(|err| panic!("{name}: {err}"));
let manifest =
crate::toolkit::parse_manifest(raw).unwrap_or_else(|err| panic!("{name}: {err}"));
let spec = specs
.iter()
.find(|spec| spec.name == *name)
@@ -310,8 +308,7 @@ mod tests {
#[test]
fn replay_safety_comes_from_the_manifest() {
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("list_tasks"),
rhema_core::ReplaySafety::Safe
+680
View File
@@ -0,0 +1,680 @@
//! The resident's toolset: named tools, a `TOOL.yaml` per tool, and the
//! per-run [`ToolResolver`] cut from them.
//!
//! `rhema-core` ships the resolver seam and no registry, on purpose. It
//! ships one primitive, not a framework. Until 0.4.2 the registry, the
//! manifest loader, the allowlist, and the resolver chain rode
//! `rhema-autonomous-agent`, which was never the right home for them. The
//! crate is the lease-driven loop, and it compiles no tool of its own.
//! The claw was the only consumer, so the machinery moved here with the
//! tools it serves.
//!
//! The shape is unchanged. A tool is a folder under `tools/` holding a
//! `TOOL.yaml`: the name the model calls, the description it
//! picks the tool by, the argument schema, the replay classification, and
//! a `run` binding. The code half is a [`ToolOp`] registered under that
//! binding's id, so a tool's static data stops living next to it in Rust
//! string literals and one folder names one tool. [`builtin_tools`]
//! joins the two, [`ToolRegistry`] holds the survivors, and
//! [`ToolRegistry::resolver_for`] cuts the allowlisted view the step
//! engine consumes.
//!
//! A manifest that does not parse, or whose `run.builtin` id has no
//! operation, is skipped rather than fatal, the way an unreadable skill
//! folder is; each family pins its shipped set with a test.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use async_trait::async_trait;
use rhema_core::{
ReplaySafety, ToolCall, ToolContext, ToolProgress, ToolResolver, ToolResult, ToolSpec,
};
use serde::Deserialize;
use serde_json::Value;
use thiserror::Error;
/// Why a tool invocation failed: the message the model reads. The
/// registry turns `Err` into an in-band failure result, a failing tool is
/// a result the model reacts to, never a crashed run, so the message is
/// the error's whole content.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{0}")]
pub struct ToolError(String);
impl ToolError {
/// An error whose message the model reads verbatim.
pub fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
/// The message the model reads.
pub fn message(&self) -> &str {
&self.0
}
}
impl From<String> for ToolError {
fn from(message: String) -> Self {
Self(message)
}
}
impl From<&str> for ToolError {
fn from(message: &str) -> Self {
Self(message.to_owned())
}
}
/// One named tool: the spec the model sees, and the invocation the
/// registry dispatches to.
#[async_trait]
pub trait Tool: Send + Sync {
/// The tool's schema, passed through to the provider's native
/// tool-calling format. The description lives here and nowhere else.
fn spec(&self) -> ToolSpec;
/// Whether a resume may re-execute one of this tool's committed calls
/// that lost its result. [`ReplaySafety::Unsafe`] unless declared
/// otherwise: an unclassified tool is treated as side-effecting.
fn replay_safety(&self) -> ReplaySafety {
ReplaySafety::Unsafe
}
/// Runs the tool. The registry turns `Err` into an in-band failure
/// result carrying the error's message; `Ok` text is the tool's
/// answer.
async fn invoke(&self, args: Value) -> Result<String, ToolError>;
}
/// The static half of a tool, parsed from a `TOOL.yaml`.
#[derive(Debug, Clone, PartialEq)]
pub struct Manifest {
/// Name the model uses to call the tool.
pub name: String,
/// What the tool does; the model picks tools from this.
pub description: String,
/// JSON schema for the call arguments; the empty-object schema when
/// the manifest omits it.
pub parameters: Value,
/// Whether a resume may re-execute a committed call that lost its
/// result; [`ReplaySafety::Unsafe`] when the manifest omits it.
pub replay_safety: ReplaySafety,
/// The `run.builtin` id naming the compiled operation.
pub builtin: String,
}
/// Why a `TOOL.yaml` did not parse into a [`Manifest`].
#[derive(Debug, Error)]
#[error("{0}")]
pub struct ManifestError(String);
/// Parses one `TOOL.yaml`. `parameters` defaults to the empty-object
/// schema and `replay_safety` to [`ReplaySafety::Unsafe`], so a minimal
/// manifest is a name, a description, and a `run` binding.
pub fn parse_manifest(raw: &str) -> Result<Manifest, ManifestError> {
let yaml: ManifestYaml =
serde_yaml::from_str(raw).map_err(|err| ManifestError(err.to_string()))?;
let name = yaml.name.trim().to_owned();
if name.is_empty() {
return Err(ManifestError("no tool name".to_owned()));
}
let description = yaml.description.trim().to_owned();
if description.is_empty() {
return Err(ManifestError(format!("{name}: no description")));
}
let builtin = match yaml.run.kind {
RunKind::Builtin { builtin } => builtin.trim().to_owned(),
};
if builtin.is_empty() {
return Err(ManifestError(format!(
"{name}: run.builtin names no operation"
)));
}
let parameters = match yaml.parameters {
Some(value) => serde_json::to_value(&value)
.map_err(|err| ManifestError(format!("{name}: parameters are not JSON: {err}")))?,
None => serde_json::json!({ "type": "object" }),
};
let replay_safety = yaml
.replay_safety
.map(|replay| match replay {
ReplayYaml::Unsafe => ReplaySafety::Unsafe,
ReplayYaml::Safe => ReplaySafety::Safe,
})
.unwrap_or_default();
Ok(Manifest {
name,
description,
parameters,
replay_safety,
builtin,
})
}
/// The operation half of a manifest-defined tool: run the call. The spec
/// half lives in the tool's `TOOL.yaml`, so an operation carries no
/// schema strings of its own.
#[async_trait]
pub trait ToolOp: Send + Sync {
/// Runs the tool. The registry turns `Err` into an in-band failure
/// result; `Ok` text is the tool's answer.
async fn invoke(&self, args: Value) -> Result<String, ToolError>;
}
/// A [`Tool`] cut from a [`Manifest`] plus its registered operation: the
/// model sees the manifest's spec, and the registry dispatches to the
/// operation.
pub struct ManifestTool {
manifest: Manifest,
op: Arc<dyn ToolOp>,
}
impl ManifestTool {
/// Binds `manifest` to the operation `op`.
pub fn new(manifest: Manifest, op: Arc<dyn ToolOp>) -> Self {
Self { manifest, op }
}
}
#[async_trait]
impl Tool for ManifestTool {
fn spec(&self) -> ToolSpec {
ToolSpec::new(
self.manifest.name.clone(),
self.manifest.description.clone(),
self.manifest.parameters.clone(),
)
}
fn replay_safety(&self) -> ReplaySafety {
self.manifest.replay_safety
}
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
self.op.invoke(args).await
}
}
/// Loads `manifests`: `(source, text)` pairs, `source` naming the
/// manifest in skip reports, against the registered `builtins`. A
/// manifest that does not parse, or whose `run.builtin` id has no
/// operation, is skipped and reported; the survivors are ready to
/// register.
pub fn builtin_tools(
manifests: &[(&str, &str)],
builtins: &BTreeMap<String, Arc<dyn ToolOp>>,
) -> (Vec<Arc<dyn Tool>>, Vec<String>) {
let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
let mut skipped = Vec::new();
for (source, raw) in manifests {
let manifest = match parse_manifest(raw) {
Ok(manifest) => manifest,
Err(err) => {
skipped.push(format!("{source}: {err}"));
continue;
}
};
match builtins.get(&manifest.builtin) {
Some(op) => tools.push(Arc::new(ManifestTool::new(manifest, op.clone()))),
None => skipped.push(format!(
"{source}: no builtin operation for {:?}",
manifest.builtin
)),
}
}
(tools, skipped)
}
/// The tool-permission set one handler run is granted. `None` means
/// permissive, every registered tool, which is the resident tier's
/// standing policy: the HTTP surface is the trust boundary.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Allowlist {
allowed: Option<BTreeSet<String>>,
}
impl Allowlist {
/// Every registered tool is permitted.
pub fn permissive() -> Self {
Self { allowed: None }
}
/// Only the named tools are permitted.
pub fn from_tools(names: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
allowed: Some(names.into_iter().map(Into::into).collect()),
}
}
/// Whether `tool` may be invoked under this allowlist.
pub fn allows(&self, tool: &str) -> bool {
match &self.allowed {
None => true,
Some(allowed) => allowed.contains(tool),
}
}
}
/// The named tool set, from which per-run [`ToolResolver`]s are cut.
#[derive(Default)]
pub struct ToolRegistry {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
impl ToolRegistry {
/// An empty registry.
pub fn new() -> Self {
Self::default()
}
/// Registers a tool under its spec's name; a re-register replaces.
pub fn register(&mut self, tool: Arc<dyn Tool>) {
self.tools.insert(tool.spec().name, tool);
}
/// How many tools are registered.
pub fn len(&self) -> usize {
self.tools.len()
}
/// Whether nothing is registered.
pub fn is_empty(&self) -> bool {
self.tools.is_empty()
}
/// A resolver over the tools `allowlist` permits: the model sees only
/// those specs, and a call for a forbidden or unknown tool comes back
/// as an in-band failure result.
pub fn resolver_for(&self, allowlist: &Allowlist) -> Arc<dyn ToolResolver> {
Arc::new(FilteredResolver {
tools: self
.tools
.iter()
.filter(|(name, _)| allowlist.allows(name))
.map(|(name, tool)| (name.clone(), tool.clone()))
.collect(),
})
}
}
/// One run's view of the registry: the allowlisted slice, as the seam the
/// step engine consumes.
struct FilteredResolver {
tools: BTreeMap<String, Arc<dyn Tool>>,
}
#[async_trait]
impl ToolResolver for FilteredResolver {
fn specs(&self) -> Vec<ToolSpec> {
self.tools.values().map(|tool| tool.spec()).collect()
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
self.tools
.get(name)
.map(|tool| tool.replay_safety())
.unwrap_or(ReplaySafety::Unsafe)
}
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
let Some(tool) = self.tools.get(&call.name) else {
return ToolResult::failure(&call.id, format!("unknown tool: {}", call.name));
};
match tool.invoke(call.args.clone()).await {
Ok(text) => ToolResult::success(&call.id, text),
Err(err) => ToolResult::failure(&call.id, err.message()),
}
}
}
/// Several resolvers behind one seam: specs concatenate in order, and a
/// call is served by the first resolver offering that tool's name. Tool
/// names should be unique across the chain; on a duplicate, the earlier
/// resolver wins and the later one is unreachable for it.
pub struct ResolverChain {
resolvers: Vec<Arc<dyn ToolResolver>>,
}
impl ResolverChain {
/// A chain serving tools from `resolvers`, in order.
pub fn new(resolvers: Vec<Arc<dyn ToolResolver>>) -> Self {
Self { resolvers }
}
/// The resolver offering `name`, if any.
fn owner(&self, name: &str) -> Option<&Arc<dyn ToolResolver>> {
self.resolvers
.iter()
.find(|resolver| resolver.specs().iter().any(|spec| spec.name == name))
}
}
#[async_trait]
impl ToolResolver for ResolverChain {
fn specs(&self) -> Vec<ToolSpec> {
self.resolvers
.iter()
.flat_map(|resolver| resolver.specs())
.collect()
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
self.owner(name)
.map(|resolver| resolver.replay_safety(name))
.unwrap_or(ReplaySafety::Unsafe)
}
async fn resolve(&self, call: ToolCall, ctx: &ToolContext) -> ToolResult {
match self.owner(&call.name) {
Some(resolver) => resolver.resolve(call, ctx).await,
None => ToolResult::failure(&call.id, format!("unknown tool: {}", call.name)),
}
}
/// Streams through the owning resolver: the shell is long, and its
/// live lines are the reason this chain exists as a seam rather than
/// a filter.
async fn resolve_streaming(
&self,
call: ToolCall,
ctx: &ToolContext,
progress: &mut dyn ToolProgress,
) -> ToolResult {
match self.owner(&call.name) {
Some(resolver) => resolver.resolve_streaming(call, ctx, progress).await,
None => ToolResult::failure(&call.id, format!("unknown tool: {}", call.name)),
}
}
}
/// The `TOOL.yaml` body this module reads.
#[derive(Debug, Deserialize)]
struct ManifestYaml {
name: String,
description: String,
#[serde(default)]
parameters: Option<serde_yaml::Value>,
#[serde(default)]
replay_safety: Option<ReplayYaml>,
run: Run,
}
/// The `run` binding: the kind's field name is the variant, so `builtin`
/// names a compiled operation the consumer registered under that id, and
/// a future kind is another variant.
#[derive(Debug, Deserialize)]
struct Run {
#[serde(flatten)]
kind: RunKind,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RunKind {
Builtin { builtin: String },
}
/// The manifest's `replay_safety`, lowercase to read like the yaml it
/// sits in; maps onto [`ReplaySafety`].
#[derive(Debug, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ReplayYaml {
Unsafe,
Safe,
}
#[cfg(test)]
mod tests {
use super::*;
struct Echo;
#[async_trait]
impl ToolOp for Echo {
async fn invoke(&self, args: Value) -> Result<String, ToolError> {
Ok(args.to_string())
}
}
struct Boom;
#[async_trait]
impl ToolOp for Boom {
async fn invoke(&self, _args: Value) -> Result<String, ToolError> {
Err(ToolError::new("exploded"))
}
}
fn builtins() -> BTreeMap<String, Arc<dyn ToolOp>> {
BTreeMap::from([
("test.echo".to_owned(), Arc::new(Echo) as Arc<dyn ToolOp>),
("test.boom".to_owned(), Arc::new(Boom) as Arc<dyn ToolOp>),
])
}
#[test]
fn a_full_manifest_parses() {
let manifest = parse_manifest(
"name: probe\n\
description: |\n\
\x20 Probe the parser.\n\
parameters:\n\
\x20 type: object\n\
\x20 properties:\n\
\x20 path:\n\
\x20 type: string\n\
\x20 required: [path]\n\
replay_safety: safe\n\
run:\n\
\x20 builtin: test.echo\n",
)
.expect("parses");
assert_eq!(manifest.name, "probe");
assert_eq!(manifest.description, "Probe the parser.");
assert_eq!(
manifest.parameters,
serde_json::json!({
"type": "object",
"properties": { "path": { "type": "string" } },
"required": ["path"]
})
);
assert_eq!(manifest.replay_safety, ReplaySafety::Safe);
assert_eq!(manifest.builtin, "test.echo");
}
#[test]
fn omissions_take_defaults() {
let manifest =
parse_manifest("name: probe\ndescription: Probe.\nrun:\n builtin: test.echo\n")
.expect("parses");
assert_eq!(manifest.parameters, serde_json::json!({ "type": "object" }));
assert_eq!(manifest.replay_safety, ReplaySafety::Unsafe);
}
#[test]
fn blank_fields_and_a_missing_run_are_rejected() {
assert!(parse_manifest("description: Probe.\nrun:\n builtin: test.echo\n").is_err());
assert!(
parse_manifest("name: probe\ndescription: \" \"\nrun:\n builtin: test.echo\n")
.is_err()
);
assert!(
parse_manifest("name: probe\ndescription: Probe.\nrun:\n builtin: \" \"\n").is_err()
);
assert!(parse_manifest("name: probe\ndescription: Probe.\n").is_err());
}
#[test]
fn an_unknown_run_kind_is_rejected_not_silently_dropped() {
let err = parse_manifest("name: probe\ndescription: Probe.\nrun:\n exec: ./run.sh\n")
.expect_err("exec is not a binding");
assert!(
err.to_string().contains("did not match any variant"),
"{err}"
);
}
#[test]
fn loading_resolves_builtins_and_reports_skips() {
let manifests = [
(
"probe",
"name: probe\ndescription: Probe.\nrun:\n builtin: test.echo\n",
),
("bad", "name: bad\ndescription: Probe.\n"),
(
"orphan",
"name: orphan\ndescription: Probe.\nrun:\n builtin: test.nope\n",
),
];
let (tools, skipped) = builtin_tools(&manifests, &builtins());
assert_eq!(tools.len(), 1);
assert_eq!(tools[0].spec().name, "probe");
assert_eq!(skipped.len(), 2, "{skipped:?}");
assert!(skipped[0].starts_with("bad:"), "{skipped:?}");
assert!(skipped[1].contains("test.nope"), "{skipped:?}");
}
#[test]
fn a_loaded_tool_registers_under_its_manifest_name_and_classifies() {
let manifests = [(
"probe",
"name: probe\ndescription: Probe.\nreplay_safety: safe\nrun:\n builtin: test.echo\n",
)];
let (tools, skipped) = builtin_tools(&manifests, &builtins());
assert!(skipped.is_empty(), "{skipped:?}");
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
assert_eq!(registry.len(), 1);
let resolver = registry.resolver_for(&Allowlist::permissive());
assert_eq!(resolver.specs()[0].name, "probe");
assert_eq!(
resolver.replay_safety("probe"),
ReplaySafety::Safe,
"the manifest's classification reaches the resolver"
);
assert_eq!(resolver.replay_safety("unknown"), ReplaySafety::Unsafe);
}
fn call(name: &str) -> ToolCall {
ToolCall {
id: "c1".into(),
name: name.into(),
args: serde_json::json!({ "a": 1 }),
provider_data: Value::Null,
}
}
#[tokio::test]
async fn a_filtered_resolver_hides_what_it_forbids_and_fails_a_call_for_it() {
let (tools, _) = builtin_tools(
&[
(
"echo",
"name: echo\ndescription: Echo.\nrun:\n builtin: test.echo\n",
),
(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
),
],
&builtins(),
);
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
let resolver = registry.resolver_for(&Allowlist::from_tools(["echo"]));
let names: Vec<String> = resolver.specs().iter().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["echo".to_owned()]);
let forbidden = resolver
.resolve(call("boom"), &ToolContext::default())
.await;
assert!(forbidden.is_error);
assert_eq!(forbidden.content, "unknown tool: boom");
}
#[tokio::test]
async fn an_operation_error_is_an_in_band_failure_with_its_message() {
let (tools, _) = builtin_tools(
&[(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
)],
&builtins(),
);
let mut registry = ToolRegistry::new();
for tool in tools {
registry.register(tool);
}
let resolver = registry.resolver_for(&Allowlist::permissive());
let result = resolver
.resolve(call("boom"), &ToolContext::default())
.await;
assert!(result.is_error);
assert_eq!(result.content, "exploded");
assert_eq!(result.id, "c1");
}
#[tokio::test]
async fn a_chain_serves_each_name_from_its_own_resolver() {
let (tools, _) = builtin_tools(
&[
(
"echo",
"name: echo\ndescription: Echo.\nreplay_safety: safe\nrun:\n builtin: test.echo\n",
),
(
"boom",
"name: boom\ndescription: Boom.\nrun:\n builtin: test.boom\n",
),
],
&builtins(),
);
let mut left = ToolRegistry::new();
left.register(tools[0].clone());
let mut right = ToolRegistry::new();
right.register(tools[1].clone());
let chain = ResolverChain::new(vec![
left.resolver_for(&Allowlist::permissive()),
right.resolver_for(&Allowlist::permissive()),
]);
let names: Vec<String> = chain.specs().iter().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["echo".to_owned(), "boom".to_owned()]);
assert_eq!(chain.replay_safety("echo"), ReplaySafety::Safe);
assert_eq!(chain.replay_safety("boom"), ReplaySafety::Unsafe);
assert_eq!(
chain
.resolve(call("echo"), &ToolContext::default())
.await
.content,
r#"{"a":1}"#
);
assert!(
chain
.resolve(call("boom"), &ToolContext::default())
.await
.is_error
);
assert_eq!(
chain
.resolve(call("nope"), &ToolContext::default())
.await
.content,
"unknown tool: nope"
);
}
#[test]
fn an_empty_allowlist_permits_nothing() {
let allowlist = Allowlist::from_tools(Vec::<String>::new());
assert!(!allowlist.allows("bash"));
assert_eq!(Allowlist::default(), Allowlist::permissive());
}
}
+10 -12
View File
@@ -14,7 +14,8 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use rhema_autonomous_agent::{ToolError, ToolOp, ToolRegistry, async_trait};
use crate::toolkit::{ToolError, ToolOp, ToolRegistry};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};
@@ -62,8 +63,7 @@ pub const MANIFESTS: &[(&str, &str)] = &[
/// `unwatch_repo`, `list_watches` — specs from the embedded manifests,
/// operations compiled here.
pub fn registry(store: Arc<ClawStore>) -> ToolRegistry {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store));
assert!(
skipped.is_empty(),
"the watch tool manifests must all load: {skipped:?}"
@@ -197,7 +197,7 @@ mod tests {
fn names(registry: &ToolRegistry) -> Vec<String> {
registry
.resolver_for(&rhema_autonomous_agent::Allowlist::permissive())
.resolver_for(&crate::toolkit::Allowlist::permissive())
.specs()
.into_iter()
.map(|spec| spec.name)
@@ -206,8 +206,7 @@ mod tests {
#[test]
fn every_manifest_loads_against_its_builtin() {
let (tools, skipped) =
rhema_autonomous_agent::manifest::builtin_tools(MANIFESTS, &builtins(store()));
let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(store()));
assert!(skipped.is_empty(), "{skipped:?}");
let names: Vec<String> = tools.iter().map(|tool| tool.spec().name).collect();
assert_eq!(
@@ -221,7 +220,7 @@ mod tests {
let mut covered = Vec::new();
for (source, raw) in MANIFESTS {
covered.push(
rhema_autonomous_agent::manifest::parse(raw)
crate::toolkit::parse_manifest(raw)
.unwrap_or_else(|err| panic!("{source}: {err}"))
.builtin,
);
@@ -236,8 +235,7 @@ mod tests {
#[test]
fn replay_safety_comes_from_the_manifest() {
let resolver =
registry(store()).resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = registry(store()).resolver_for(&crate::toolkit::Allowlist::permissive());
assert_eq!(
resolver.replay_safety("list_watches"),
rhema_core::ReplaySafety::Safe
@@ -263,7 +261,7 @@ mod tests {
async fn watch_repo_lands_a_row_and_answers_json() {
let store = store();
let tools = registry(store.clone());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let result = resolver
.resolve(
@@ -303,7 +301,7 @@ mod tests {
async fn a_bad_watch_fails_in_band_with_the_reason() {
let store = store();
let tools = registry(store.clone());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| {
resolver.resolve(
@@ -356,7 +354,7 @@ mod tests {
store.add("github", "acme/widgets", None, "").expect("seed");
store.add("gitlab", "group/prop", None, "").expect("seed");
let tools = registry(store.clone());
let resolver = tools.resolver_for(&rhema_autonomous_agent::Allowlist::permissive());
let resolver = tools.resolver_for(&crate::toolkit::Allowlist::permissive());
let ctx = rhema_core::ToolContext::default();
let call = |name: &str, args: Value| {
resolver.resolve(
+5 -5
View File
@@ -11,7 +11,7 @@ use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use rhema_autonomous_agent::Allowlist;
use rhema_claw::toolkit::Allowlist;
use rhema_claw::watch_tools;
use rhema_claw::{ClawConfig, Daemon};
use rhema_core::{Content, Message, MockProvider, ModelOutput, Role, Session, StopReason, Usage};
@@ -955,10 +955,10 @@ async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() {
.iter()
.find(|message| message.role == Role::User)
.expect("the question is stashed");
assert_eq!(rhema_core::paste::spans(ask).len(), 1);
assert_eq!(rhema_core::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_core::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_core::paste::spans(ask)[0].lines, 2);
assert_eq!(rhema_claw::paste::spans(ask).len(), 1);
assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38);
assert_eq!(rhema_claw::paste::spans(ask)[0].lines, 2);
}
/// A turn nobody watched is still replayable: a client arriving after