build: move the claw to rhema 0.5.0

The 0.5.0 line renames what the claw imports and deletes what it
wrapped. The autonomous agent is rhema-rsd now, driver and handler
trait included, so every import moves with the name. The MCP bridge is
gone outright: no crate, no socket, no generated bash functions. The
claw's mcp module stops proxying. It names the client's config file and
media directory in the shell env, runs `mcp prompt` once, and renders
that text as the prompt section. A session with no client on PATH
advertises no servers, which is the 0.5 rule.

The config follows. `host_agent.mcp_servers` is gone, `config.mcp` is
the client's rendered section, and the bare `claw mcp` subcommand gives
way to the standalone `mcp` binary. Secrets leave the OS keyring for
the encrypted file store the frontends write. The keyring is copied
into that store once, under the service name the claw used, so a
deployment that predates the file keeps its logins. rusqlite follows
rhema-identity to 0.43, because the framework links libsqlite3-sys 0.40
and two `links = "sqlite3"` packages cannot share a graph.

The image carries the toolbox the sessions' habits assume: ripgrep, fd,
jq, sd, python3, yq (the Go v4, not Debian's), the mcp client, and
lightpanda. Each release binary is pinned by version and by the
checksum of every arch's artifact, and the boot report inventories
them, so a session knows what it has. gob was already there.

0.5.0 is tagged but not on crates.io, since publishing is retried with
0.5.1, so the workspace carries a `[patch.crates-io]` onto the tag and
the lock pins its rev. Deleting the block and running `cargo update` is
the whole follow-up once 0.5.1 lands. The claw's own version travels
with the framework: the workspace and the chart become 0.5.0.

fmt, clippy with -D warnings over all features and targets, the
workspace tests, and the doc build pass.
This commit is contained in:
vhaudiquet committed 2026-11-27 18:18:45 +01:00
1 parent 9e3890c568
commit 9ac559616c
30 files changed
+1183 -848

No files matched your search

+17 -19
View File
@@ -1,6 +1,6 @@
[package]
name = "rhema-claw"
description = "The resident agent daemon: forge watches and the chat HTTP surface, the first consumer of rhema-autonomous-agent"
description = "The resident agent daemon: forge watches and the chat HTTP surface, the first consumer of rhema-rsd"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
@@ -29,37 +29,36 @@ 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.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"
rhema-bash = "0.5.0"
rhema-prompt = "0.5.0"
rhema-host-agent = "0.5.0"
rhema-config = "0.5.0"
rhema-core = "0.5.0"
# The bounded request view over the claw sessions, on by default here
rhema-transcript = "0.4.2"
rhema-transcript = "0.5.0"
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.2"
rhema-rsd = "0.4.2"
rhema-identity = "0.5.0"
rhema-rsd = { version = "0.5.0", features = ["driver"] }
# 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 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"
rhema-sandbox = "0.5.0"
rhema-sandbox-http = "0.5.0"
rhema-sandbox-ssh = "0.5.0"
# The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw ->
# 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.2"
rhema-memory = "0.5.0"
# The shared ModelCard the backend registry's listings return
rhema-provider = "0.4.2"
rhema-provider-registry = "0.4.2"
rhema-provider = "0.5.0"
rhema-provider-registry = "0.5.0"
# Args for the two-flag binary surface
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
@@ -78,13 +77,12 @@ axum = { workspace = true }
tokio-stream = { workspace = true }
# The watch table: a second connection to the same SQLite file as the
# dispatcher's store — the two-connections pattern rhema-rsd's tests use
rusqlite = { version = "0.40", features = ["bundled"] }
rusqlite = { version = "0.43", features = ["bundled"] }
# RFC3339 parsing for schedule_task's `at`
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.2"
[dev-dependencies]
tempfile = "3"
@@ -96,7 +94,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.2", features = ["mock"] }
rhema-core = { version = "0.5.0", features = ["mock"] }
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "sync", "time"] }
[lints]
+25 -14
View File
@@ -18,7 +18,7 @@ model calls like any other).
```sh
rhema-claw # serve on 127.0.0.1:7799 (config: listen)
rhema-claw --once # one detect + one dispatch pass, then exit
claw mcp servers # the MCP meta surface (see rhema-mcp)
mcp list # the MCP client's own surface (a shell command)
```
### Coding jobs: the `coding_agent` tool
@@ -360,19 +360,30 @@ phone app, no CORS anywhere.
The image is the daemon plus what the agent's shell needs: `bash` and
`git` (the shell is load-bearing, the agent clones in its workspaces),
`curl` for a turn that fetches a URL, and `gob` for a command that
outlives the turn. The agent starts a build or a dev server with `gob
add` and reads its logs and ports on a later one. The chart runs
exactly one replica, the claw is single-node by design: one SQLite
store, one dispatcher. Single-node is what makes restarts instant: at
boot the daemon releases every lease the previous process left —
outright, not at the dead lease's TTL — so a turn an update cut
mid-flight answers its next message instead of stalling behind a ghost
(the committed tool call revives at the top of that next dispatch). The
cut turn is released as superseded on the way, so a thread it never
finished reads as aborted instead of wearing the outcome of the turn
before it. Nothing re-runs it: the mention was drained before the turn
ran, and the thread waits for the next activity.
`curl` for a turn that fetches a URL, `gob` for a command that
outlives the turn (the agent starts a build or a dev server with `gob
add` and reads its logs and ports on a later one), and the toolbox its
habits assume — `rg`, `fd`, `jq`, `yq` (the Go v4, not Debian's v3),
`sd`, `python3`. `lightpanda` is the headless browser a turn fetches
and renders pages with, and `mcp` is the MCP client the sessions call
as a shell command: its config file is the one the coding agent's
settings page writes, and without the binary a session's prompt
advertises no MCP servers at all. Every pinned binary is verified
against its release checksum at build time, and the environment report
the daemon writes at boot lists each of these as present, so a session
knows what it has.
The chart runs exactly one replica, the claw is single-node by
design: one SQLite store, one dispatcher. Single-node is what makes
restarts instant: at boot the daemon releases every lease the previous
process left — outright, not at the dead lease's TTL — so a turn an
update cut mid-flight answers its next message instead of stalling
behind a ghost (the committed tool call revives at the top of that next
dispatch). The cut turn is released as superseded on the way, so a
thread it never finished reads as aborted instead of wearing the
outcome of the turn before it. Nothing re-runs it: the mention was
drained before the turn ran, and the thread waits for the next
activity.
The store and workspaces live on a PVC, `claw.yaml` in a ConfigMap (db
and workspace paths are pinned to the mounted volume), credentials in
a Secret, and the bearer token is the `token` value, required since
+1 -16
View File
@@ -45,22 +45,7 @@ what it is for. The arguments are the JSON schema a call must satisfy.
{% if mcp %}
## MCP servers
Available MCP servers:
{% for server in mcp %}- {{ server.name }} (server: {{ server.server }}): {{ server.description }}
{% endfor %}
MCP servers are reachable through bash commands (**not** direct tool calls).
Usage:
{{ mcp[0].name }} --help # a server's tools
{{ mcp[0].name }} <tool> --help # one tool's arguments
{{ mcp[0].name }} <tool> --schema # one tool's exact input JSON
{{ mcp[0].name }} --flag value # a call; --prop_json for nested values
{{ mcp[0].name }} --json - <<'EOF' ... EOF # nested payloads: heredoc, no quoting
mcp servers | mcp tools <server> | mcp call <server> <tool> <json>
{{ mcp }}
{% endif %}
{% if memory %}
+1 -1
View File
@@ -641,9 +641,9 @@ fn seed_llama_model(backend: &mut Backend, config: &crate::config::ClawConfig) {
#[cfg(test)]
mod tests {
use super::*;
use rhema_autonomous_agent::async_trait;
use rhema_config::secrets::SecretStore as _;
use rhema_core::{EventSink, Message, ModelOutput, ModelRequest, Role, StopReason, Usage};
use rhema_rsd::async_trait;
/// A minimal scripted stand-in: registry tests never complete a turn.
struct Stub;
+21 -23
View File
@@ -216,10 +216,10 @@ pub enum Surface {
/// the model schedules its own wakes to — and `onboarding`, the offer
/// the template's `{% if %}` shows only while a file is unwritten, and
/// only on a chat surface: a forge dispatch is nobody's first
/// conversation. `mcp` renders the wired servers' section, empty on a
/// surface with none; the memory section renders only when the roster
/// actually carries the memory tools, so a forge prompt never
/// documents tools it does not have. Fallible on purpose — a store
/// conversation. `mcp` is the client's `mcp prompt` output, rendered
/// verbatim, absent on a surface with no client; the memory section
/// renders only when the roster actually carries the memory tools, so
/// a forge prompt never documents tools it does not have. Fallible on purpose — a store
/// that cannot be read surfaces loudly instead of rendering a prompt
/// without it, and a template that cannot render fails the dispatch
/// before any model call.
@@ -231,7 +231,7 @@ pub fn render_system(
bootstrap: &Bootstrap,
tools: &[ToolSpec],
vision: Option<&str>,
mcp: &[rhema_config::mcp::McpServerLine],
mcp: Option<&str>,
surface: Surface,
) -> Result<String, BootstrapError> {
let soul = bootstrap.load(BootstrapKind::Soul)?;
@@ -453,7 +453,7 @@ mod tests {
&bootstrap,
&tools,
None,
&[],
None,
Surface::Chat,
)
.expect("renders");
@@ -477,7 +477,7 @@ mod tests {
&bootstrap,
&[],
None,
&[],
None,
Surface::Forge,
)
.expect("renders");
@@ -511,7 +511,7 @@ mod tests {
&bootstrap,
&memory,
None,
&[],
None,
Surface::Chat,
)
.expect("renders");
@@ -522,7 +522,7 @@ mod tests {
&bootstrap,
&[],
None,
&[],
None,
Surface::Forge,
)
.expect("renders");
@@ -534,13 +534,9 @@ mod tests {
}
#[test]
fn the_wired_mcp_servers_render_their_section() {
fn the_wired_mcp_prompt_renders_its_section() {
let (_dir, bootstrap) = store();
let mcp = [rhema_config::mcp::McpServerLine {
name: "acme-mcp".to_owned(),
server: "acme".to_owned(),
description: "the acme tools".to_owned(),
}];
let mcp = "acme: the acme tools\n acme create_issue --json '{\"project\": \"ENG\"}'";
let prompt = render_system(
DEFAULT_SYSTEM_MD,
"github:issue:acme/widgets#7",
@@ -548,13 +544,15 @@ mod tests {
&bootstrap,
&[],
None,
&mcp,
Some(mcp),
Surface::Forge,
)
.expect("renders");
assert!(prompt.contains("## MCP servers"), "{prompt}");
assert!(prompt.contains("acme: the acme tools"), "{prompt}");
// The client's text lands verbatim, quotes and braces included:
// the template escapes nothing in a markdown source.
assert!(
prompt.contains("- acme-mcp (server: acme): the acme tools"),
prompt.contains(r#"acme create_issue --json '{"project": "ENG"}'"#),
"{prompt}"
);
let bare = render_system(
@@ -564,11 +562,11 @@ mod tests {
&bootstrap,
&[],
None,
&[],
None,
Surface::Chat,
)
.expect("renders");
assert!(!bare.contains("## MCP servers"), "{bare}");
assert!(!bare.contains("acme:"), "{bare}");
}
#[test]
@@ -588,7 +586,7 @@ mod tests {
&bootstrap,
&[],
None,
&[],
None,
Surface::Chat,
)
.expect("renders");
@@ -618,7 +616,7 @@ mod tests {
&bootstrap,
&[],
None,
&[],
None,
Surface::Chat,
)
.expect("renders");
@@ -652,7 +650,7 @@ mod tests {
&bootstrap,
&tools,
None,
&[],
None,
Surface::Chat,
)
.expect("renders");
+6 -4
View File
@@ -154,10 +154,12 @@ pub struct ClawConfig {
/// open on its interface; set it when the port is reachable from
/// anywhere but loopback. `/healthz` stays open either way.
pub token: Option<String>,
/// MCP server names held back from the claw's agents — the
/// off switch (the global `mcp.yaml` is the claw's config scope;
/// there are no profiles here). The wiring step filters before
/// anything spawns and the prompt carries only what survives.
/// MCP server names held back from the claw's agents — the off
/// switch for the client's config file (`~/.config/rhema/mcp/config.json`;
/// the claw reads the reference layout, there are no profiles
/// here). The names ride the shell as `MCP_DISABLED`, and the
/// client filters `list` and `prompt` by them, so neither the
/// prompt nor a session's shell sees a muted server.
#[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
pub disabled_mcp_servers: std::collections::BTreeSet<String>,
/// The scoped agent token the client tools hold: it answers only
+4 -4
View File
@@ -25,11 +25,11 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use rhema_autonomous_agent::{Driver, Source, SourceError};
use rhema_rsd::{
DispatchError, Dispatcher, DispatcherConfig, Outcome, ResourceKey, SqliteStore, StoreError,
SystemClock,
};
use rhema_rsd::{Driver, Source, SourceError};
use crate::config::{ClawConfig, ConfigError};
use crate::extension::{ExtensionDeps, Extensions, Lanes};
@@ -784,9 +784,9 @@ mod tests {
release: tokio::sync::Semaphore,
}
#[rhema_autonomous_agent::async_trait]
impl rhema_autonomous_agent::Handler for GatedHandler {
async fn handle(&self, _ctx: &mut rhema_autonomous_agent::SessionContext) -> Outcome {
#[rhema_rsd::async_trait]
impl rhema_rsd::Handler for GatedHandler {
async fn handle(&self, _ctx: &mut rhema_rsd::SessionContext) -> Outcome {
self.runs.fetch_add(1, Ordering::SeqCst);
self.started.add_permits(1);
let _ = self.release.acquire().await;
+20 -1
View File
@@ -22,7 +22,26 @@ use rhema_memory::record::format_utc;
/// The tools the report inventories, in report order. The list is what
/// v1's resident workflow reaches for; absence of any entry is ordinary.
const TOOLS: &[&str] = &["git", "cargo", "rustc", "docker", "node", "npm", "python3"];
const TOOLS: &[&str] = &[
// The general toolchains.
"git",
"cargo",
"rustc",
"docker",
"node",
"npm",
"python3",
// The agent's own toolbox: the image ships these, and a session that
// does not know they are there reaches for grep and sed instead.
"rg",
"fd",
"jq",
"yq",
"sd",
"gob",
"mcp",
"lightpanda",
];
/// The per-command budget: long enough for a cold `--version`, short
/// enough that a hung probe cannot stall a boot past it.
+1 -1
View File
@@ -32,11 +32,11 @@
use std::path::PathBuf;
use std::sync::Arc;
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::Source;
use rhema_rsd::{Dispatcher, ResourceKey, SystemClock};
use crate::consents::WaitBridge;
+1 -1
View File
@@ -22,7 +22,6 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_forge_integration::forge_key_fn;
use rhema_forge_integration::triage::{self, Role, Triage};
use rhema_forge_integration::{
@@ -31,6 +30,7 @@ use rhema_forge_integration::{
};
use rhema_identity::{IdentityStore, SecretKind};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn, SystemClock};
use rhema_rsd::{Source, SourceError, async_trait};
use crate::watch_store::{AccountWatchRecord, ClawStore, SCOPE_ACCOUNT, SCOPE_REPO, WatchRecord};
use rhema_forge_integration::{ForgeKind, resolve_token};
+5 -5
View File
@@ -26,7 +26,6 @@ use std::sync::{Arc, Mutex, PoisonError};
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, Surface};
use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore;
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
use rhema_forge_integration::ForgeKind;
@@ -37,6 +36,7 @@ use rhema_forge_integration::{
};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_identity::IdentityStore;
use rhema_rsd::{Handler, SessionContext, async_trait};
use rhema_rsd::{InboxItem, Outcome, ResourceKey};
use tokio::sync::OnceCell;
@@ -438,7 +438,7 @@ impl ClawHandler {
// and MCP documentation render here from the same wired values;
// a remote sandbox wires neither.
let mut vision = None;
let mut mcp = Vec::new();
let mut mcp = None;
match &self.sandbox {
Some(sandbox) if sandbox.is_remote() => {
config.tools = Some(Arc::new(ShellTools::with_executor(
@@ -450,7 +450,7 @@ impl ClawHandler {
crate::vision::apply(&mut config);
crate::mcp::apply(&mut config);
vision = config.vision.clone();
mcp = config.mcp_servers.clone();
mcp = config.mcp.clone();
}
}
let mut specs = ShellTools::builtin_specs();
@@ -465,7 +465,7 @@ impl ClawHandler {
&self.bootstrap,
&specs,
vision.as_deref(),
&mcp,
mcp.as_deref(),
Surface::Forge,
)
.map_err(|err| format!("cannot render the forge system prompt for {key}: {err}"))?,
@@ -844,7 +844,7 @@ pub(crate) fn final_text(message: &Message) -> Option<String> {
.iter()
.filter_map(|content| match content {
Content::Text(text) => Some(text.as_str()),
Content::ToolCall(_) | Content::ToolResult(_) | Content::Image(_) => None,
_ => None,
})
.collect::<Vec<_>>()
.join("");
+1 -1
View File
@@ -41,11 +41,11 @@ use axum::response::{IntoResponse, Response};
use axum::routing::put;
use axum::routing::{delete, get, post};
use axum::{Router, middleware};
use rhema_autonomous_agent::Driver;
use rhema_claw_tools_contract::Auth;
use rhema_claw_tools_contract::CONTRACT_HEADER;
use rhema_claw_tools_contract::CONTRACT_VERSION;
use rhema_core::ImageMediaType;
use rhema_rsd::Driver;
use rhema_rsd::{
Conflict, DispatchError, Dispatcher, IngestResult, KeyRecord, KeyState, Outcome, ResourceKey,
SqliteStore, Store,
+35 -29
View File
@@ -79,7 +79,6 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
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,
@@ -88,6 +87,7 @@ use rhema_core::{
};
use rhema_memory::{MemoryResolver, MemoryStore, Scope};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use rhema_rsd::{Handler, SessionContext};
use serde_json::{Value, json};
use crate::abort::{AbortGuard, AbortRegistry};
@@ -308,9 +308,16 @@ impl InteractiveHandler {
// results. Local shells only — the interactive handler's
// executor is this host's by construction.
let vision = rhema_bash::vision::wire(std::env::var_os("BASH_ENV"));
let tools = Arc::new(match vision {
Some(wiring) => ShellTools::with_env(&workspace, &wiring.shell_env),
None => ShellTools::new(&workspace),
// The MCP env rides the same shell: the client's config path,
// its media directory, and the muted names. No init file, the
// model calls the installed client directly.
let mut env = vision
.map(|wiring| wiring.shell_env.clone())
.unwrap_or_default();
env.extend(crate::mcp::env());
let tools = Arc::new(match env.is_empty() {
true => ShellTools::new(&workspace),
false => ShellTools::with_env(&workspace, &env),
});
tools.install_approval(Arc::new(AllowAll));
let bootstrap_resolver =
@@ -383,7 +390,7 @@ impl InteractiveHandler {
&self.bootstrap,
&resolver.specs(),
vision,
&[],
crate::mcp::section().as_deref(),
crate::bootstrap::Surface::Chat,
)
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
@@ -887,7 +894,7 @@ fn final_text(message: &Message) -> Option<String> {
.iter()
.filter_map(|content| match content {
Content::Text(text) => Some(text.as_str()),
Content::ToolCall(_) | Content::ToolResult(_) | Content::Image(_) => None,
_ => None,
})
.collect::<Vec<_>>()
.join("");
@@ -1323,8 +1330,8 @@ mod tests {
#[tokio::test]
async fn an_embedded_arrival_migrates_at_the_fold() {
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
dispatcher
.ingest(user_event(
key.as_str(),
@@ -1364,8 +1371,8 @@ mod tests {
#[tokio::test]
async fn a_staged_chip_rides_its_payload_beside_the_question() {
let (recorder, hub, dispatcher, handler, key, _workspace) = paste_env();
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
dispatcher
.ingest(user_event(
key.as_str(),
@@ -1461,7 +1468,7 @@ mod tests {
&handler.bootstrap,
&specs,
None,
&[],
None,
crate::bootstrap::Surface::Chat,
)
.expect("renders");
@@ -1817,8 +1824,8 @@ mod tests {
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
let outcomes = driver.run_once().await.expect("the run happens");
assert_eq!(outcomes, vec![RsdOutcome::Handled]);
@@ -1906,8 +1913,8 @@ mod tests {
dispatcher
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
// The pass runs off the test task; the first generation parks
// in the gate once it is in flight — and a round's inbox drain
@@ -2059,8 +2066,8 @@ mod tests {
dispatcher
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
// The pass runs off the test task; the generation parks in the
// gate once it is in flight — the turn the abort cuts.
@@ -2167,7 +2174,7 @@ mod tests {
}
}
#[rhema_autonomous_agent::async_trait]
#[rhema_rsd::async_trait]
impl rhema_core::ModelProvider for GatedProvider {
async fn complete(
&self,
@@ -2241,8 +2248,8 @@ mod tests {
Arc::new(VolatileStore::new()),
));
register_user(&dispatcher);
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
let key = Key::from("interactive:web");
let png = base64::engine::general_purpose::STANDARD.encode(b"\x89PNG-fake");
let jpeg = base64::engine::general_purpose::STANDARD.encode(b"\xff\xd8jpeg");
@@ -2388,8 +2395,8 @@ mod tests {
Arc::new(VolatileStore::new()),
));
register_user(&dispatcher);
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
let key = Key::from("interactive:web");
// Dispatch 1: the model saves through the chain's memory tools.
@@ -2494,8 +2501,8 @@ mod tests {
Arc::new(VolatileStore::new()),
));
register_user(&dispatcher);
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
let key = Key::from("interactive:web");
// Dispatch 1: the model writes SOUL.md through the chain. A key
@@ -2580,7 +2587,7 @@ mod tests {
dispatcher
.ingest(user_event(key.as_str(), "hello", &[], &[]))
.expect("ingests");
let driver = rhema_autonomous_agent::Driver::new(dispatcher, Arc::new(handler));
let driver = rhema_rsd::Driver::new(dispatcher, Arc::new(handler));
driver.run_once().await.expect("the run happens");
let record = backing
@@ -2665,8 +2672,7 @@ mod tests {
Arc::new(rhema_rsd::SystemClock),
tasks(),
);
let driver =
rhema_autonomous_agent::Driver::new(dispatcher.clone(), handler).with_holder("test");
let driver = rhema_rsd::Driver::new(dispatcher.clone(), handler).with_holder("test");
// The event shape TaskScheduler::detect delivers: the prompt is
// the payload's `prompt`, the key is the task's.
@@ -2790,8 +2796,8 @@ mod tests {
Arc::new(rhema_rsd::SystemClock),
tasks(),
);
let driver = rhema_autonomous_agent::Driver::new(dispatcher.clone(), Arc::new(handler))
.with_holder("test");
let driver =
rhema_rsd::Driver::new(dispatcher.clone(), Arc::new(handler)).with_holder("test");
let key = Key::from("interactive:web");
// The evening's work, in the chat session.
+3 -3
View File
@@ -25,11 +25,11 @@
use std::num::NonZeroU32;
use std::sync::Arc;
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
use rhema_bash::{AllowAll, ShellTools};
use rhema_core::{Event as ModelEvent, EventSink};
use rhema_host_agent::{HostAgent, HostAgentConfig};
use rhema_rsd::{Dispatcher, Event, KeyFn, Outcome, ResourceKey};
use rhema_rsd::{Handler, SessionContext, Source, SourceError, async_trait};
use crate::backends::BackendRegistry;
use crate::handler::final_text;
@@ -415,8 +415,8 @@ impl EventSink for JobSink {
mod tests {
use super::*;
use crate::backends::Backend;
use rhema_autonomous_agent::Driver;
use rhema_core::{Message as CoreMessage, MockProvider, ModelOutput, Role, StopReason, Usage};
use rhema_rsd::Driver;
use rhema_rsd::{DispatcherConfig, KeyState, SqliteStore, SystemClock};
/// A registry whose only backend is the scripted mock.
@@ -443,7 +443,7 @@ mod tests {
/// abort interrupts, released only by the drop.
struct ParkingProvider;
#[rhema_autonomous_agent::async_trait]
#[rhema_rsd::async_trait]
impl rhema_core::ModelProvider for ParkingProvider {
async fn complete(
&self,
+1 -1
View File
@@ -1,5 +1,5 @@
//! `rhema-claw` — the resident agent daemon: forge watches plus the chat
//! HTTP surface, the first consumer of `rhema-autonomous-agent`.
//! HTTP surface, the first consumer of `rhema-rsd`.
//!
//! The spec invariants this crate exists to keep (specs/
//! rhema-framework-v1.md): detection is deterministic code, never the
+19 -24
View File
@@ -33,10 +33,9 @@ struct Args {
#[arg(long)]
mock: bool,
/// The MCP meta surface, the flat flags' first subcommand:
/// `claw mcp servers | tools | schema | call`. The rest goes to
/// the MCP CLI verbatim, which reads the bridge env the init
/// file set; outside a wired agent shell it exits 4 silently.
/// The hidden passthroughs the agent shell's macros exec
/// (`__vision`). The MCP client is the standalone `mcp` binary on
/// PATH; the daemon does not dispatch it.
#[command(subcommand)]
command: Option<Command>,
}
@@ -44,12 +43,6 @@ struct Args {
/// The claw's subcommands.
#[derive(Debug, clap::Subcommand)]
enum Command {
/// The MCP meta surface, passed through to `rhema_mcp::cli`.
Mcp {
/// The CLI's own argv, passed through untouched.
#[arg(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<std::ffi::OsString>,
},
/// The vision CLI the agent shell's `see` macro execs: stages the
/// piped bytes (or the named files) into the session's staging
/// directory. Outside a wired shell it exits 4 with a hint.
@@ -63,15 +56,7 @@ enum Command {
#[tokio::main]
async fn main() {
// The MCP CLI owns the process when dispatched: its exit code is
// ours, its stdout/stderr contract is the caller's output.
let args = Args::parse();
if let Some(Command::Mcp { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1);
argv.push(std::ffi::OsString::from("mcp"));
argv.extend(rest.iter().cloned());
std::process::exit(rhema_mcp::cli::run(&argv));
}
if let Some(Command::Vision { args: rest }) = &args.command {
let mut argv = Vec::with_capacity(rest.len() + 1);
argv.push(std::ffi::OsString::from(rhema_bash::vision::MODE));
@@ -206,13 +191,23 @@ fn resolve_backends(config: &ClawConfig) -> Result<Arc<rhema_claw::BackendRegist
.collect::<Vec<_>>()
};
let env = |name: &str| std::env::var(name).ok();
// The daemon only reads the stored rhema config, keychain tier
// included; it never writes it, so no migration runs here — the
// file's logins belong to the frontends. In a container the
// keychain is unreachable and the literal tier serves.
let secrets = rhema_config::secrets::KeyringSecretStore::named("claw");
// The daemon only reads the stored rhema config; it never writes
// it, so no migration runs here — the file's logins belong to the
// frontends. The secrets are the encrypted file store the current
// frontends write; the old OS keyring is copied into it once, under
// the service name the claw used, for a deployment that predates
// the file.
let home = rhema_config::Home::discover().map_err(rhema_claw::ConfigError::Stored)?;
let secrets = home.secret_store();
let imported = stored.import_legacy_secrets(
&rhema_config::secrets::KeyringSecretReader::named("claw"),
secrets.as_ref(),
);
if imported > 0 {
eprintln!("· copied {imported} key(s) from the OS keyring into the encrypted store");
}
let backends =
rhema_claw::backends::discover(config, &profile, &env, &claw_rows, Some(&secrets));
rhema_claw::backends::discover(config, &profile, &env, &claw_rows, Some(secrets.as_ref()));
// The config's provider/model pair seeds the active backend when it
// names one. When it does not, the seed is the first credential
// discovery actually found — never a hardcoded default kind, and
+134 -62
View File
@@ -1,105 +1,177 @@
//! The claw's MCP wiring: one bridge for the daemon process, its env
//! merged into every coding-agent session the claw runs — chat turns
//! and `coding_agent` jobs alike. The global `mcp.yaml` is the
//! claw's config scope (there are no profiles here); the off switch
//! is the claw config's `disabled_mcp_servers`.
//! The claw's MCP wiring: the prompt section and the shell env the
//! standalone `mcp` client reads. Since 0.5.0 the client and its config
//! live where the session's shell runs, so the daemon names the config
//! file and lets the client describe what it holds.
//!
//! A host session reads `~/.config/rhema/mcp/config.json` and stages
//! media under `~/.cache/rhema/mcp/media`. The config's
//! `disabled_mcp_servers` rides along as `MCP_DISABLED`, which the
//! client filters at `list` and `prompt` time.
#![forbid(unsafe_code)]
use std::collections::BTreeSet;
use std::sync::{Arc, OnceLock};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use rhema_host_agent::HostAgentConfig;
use crate::config::ClawConfig;
/// What one wiring produced, held for the process.
struct Wired {
wiring: Arc<rhema_mcp::Wiring>,
disabled: BTreeSet<String>,
/// The env map layered over every session's shell.
env: BTreeMap<String, String>,
/// The `mcp prompt` output, `None` when the client is missing or
/// the file holds no servers.
prompt: Option<String>,
}
static WIRED: OnceLock<Option<Wired>> = OnceLock::new();
/// The MCP directory pair for the reference layout: the config file
/// and the media staging directory.
fn places(home: &rhema_config::Home) -> (PathBuf, PathBuf) {
(
home.config.join("mcp").join("config.json"),
home.cache.join("mcp").join("media"),
)
}
/// Runs `mcp prompt` against one config, the synchronous host probe.
/// `None` when the client is missing, the file holds no servers, or
/// the command fails: a machine without the client advertises no
/// section rather than a command that fails at the model's first use.
fn probe(env: &BTreeMap<String, String>) -> Option<String> {
let program = std::env::var("MCP_BIN").unwrap_or_else(|_| "mcp".to_owned());
let output = std::process::Command::new(program)
.arg("prompt")
.envs(env)
// The terminal's resume token stops here: a prompt renderer has
// no business minting a resume record for it.
.env_remove(rhema_bash::exec::OSC7577_TOKEN)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8_lossy(&output.stdout).trim().to_owned();
(!text.is_empty()).then_some(text)
}
/// The daemon's wiring, established at first use and never re-read:
/// the claw is single-instance, its servers are stateful across
/// calls, and a rewire mid-process would orphan running sessions'
/// socket paths. `None` when nothing is configured, everything is
/// muted, or the config file cannot load.
/// the claw is single-instance and a rewire mid-process would change
/// the shell env under running sessions. `None` when the config file
/// is absent or the client answers nothing.
fn wired() -> Option<&'static Wired> {
WIRED
.get_or_init(|| {
let claw = ClawConfig::load_from(&ClawConfig::default_path().ok()?).ok()?;
let mcp = rhema_config::mcp::McpConfig::load();
if mcp.servers.is_empty() {
let home = rhema_config::Home::discover().ok()?;
let (config, media) = places(&home);
if !config.is_file() {
return None;
}
let dir = std::env::temp_dir().join(format!("rhema-claw-mcp-{}", std::process::id()));
std::fs::create_dir_all(&dir).ok()?;
// The init chain: the vision wiring first, this one
// second — `BASH_ENV` names ours, whose inheritance guard
// sources the vision file, which sources the process's own.
let inherited = crate::vision::init_path().or_else(|| std::env::var_os("BASH_ENV"));
let wiring =
rhema_mcp::wire(&mcp, &claw.disabled_mcp_servers, &dir, "claw", inherited).ok()?;
for notice in &wiring.notices {
eprintln!("· {notice}");
let _ = std::fs::create_dir_all(&media);
let mut env = BTreeMap::from([
(
"MCP_CONFIG".to_owned(),
config.to_string_lossy().into_owned(),
),
(
"MCP_MEDIA_DIR".to_owned(),
media.to_string_lossy().into_owned(),
),
("MCP_DISABLED".to_owned(), join(&claw.disabled_mcp_servers)),
]);
// The installer's install directory, so the client this
// daemon probes is the one the model's shell resolves.
if let Some(path) = std::env::var_os("PATH") {
let bin_dir = std::env::var("MCP_BIN")
.ok()
.map(PathBuf::from)
.and_then(|bin| bin.parent().map(Path::to_path_buf))
.unwrap_or_else(|| home.home.join(".local/bin"));
env.insert("PATH".to_owned(), prepend(&bin_dir, &path));
}
if wiring.lines.is_empty() {
// Everything muted: drop the wiring (its own Drop
// stops the bridge) and record the answer as none.
drop(wiring);
return None;
}
Some(Wired {
wiring: Arc::new(wiring),
disabled: claw.disabled_mcp_servers,
})
let prompt = probe(&env);
Some(Wired { env, prompt })
})
.as_ref()
}
/// Layers the wiring onto one agent config: the shell env map (the
/// init file, the socket, the token), the prompt's `mcp` lines, and
/// the persisted off switch. A frontend without wiring changes
/// nothing.
/// The `MCP_DISABLED` spelling: the client reads a comma-separated list.
fn join(disabled: &BTreeSet<String>) -> String {
disabled.iter().cloned().collect::<Vec<_>>().join(",")
}
/// Prepends the client's install directory to `PATH`.
fn prepend(dir: &Path, base: &std::ffi::OsStr) -> String {
let dir = dir.to_string_lossy();
match base.is_empty() {
true => dir.into_owned(),
false => format!("{dir}:{}", base.to_string_lossy()),
}
}
/// The `mcp prompt` section for a frontend that renders its own
/// template (the interactive handler's low-level agent).
pub(crate) fn section() -> Option<String> {
wired().and_then(|wired| wired.prompt.clone())
}
/// The shell env a frontend that builds its own `ShellTools` layers on.
pub(crate) fn env() -> BTreeMap<String, String> {
wired().map(|wired| wired.env.clone()).unwrap_or_default()
}
/// Layers the wiring onto one agent config: the shell env map and the
/// prompt's `mcp` section. A frontend without a config file or a
/// client changes nothing.
pub(crate) fn apply(config: &mut HostAgentConfig) {
let Some(wired) = wired() else {
return;
};
config.shell_env.extend(wired.wiring.shell_env.clone());
config.mcp_servers = wired.wiring.lines.clone();
config.disabled_mcp_servers = wired.disabled.clone();
config.shell_env.extend(wired.env.clone());
config.mcp = wired.prompt.clone();
}
use crate::config::ClawConfig;
#[cfg(test)]
mod tests {
use super::*;
/// A first `apply` is indistinguishable from a second: the
/// extension must be idempotent at the level the agent sees (the
/// wiring map's values are constants, so extending twice is the
/// same map).
#[test]
fn apply_without_any_wiring_leaves_the_config_alone() {
fn join_reads_as_the_client_expects() {
let set = BTreeSet::from(["b".to_owned(), "a".to_owned()]);
assert_eq!(join(&set), "a,b");
assert_eq!(join(&BTreeSet::new()), "");
}
#[test]
fn prepend_keeps_the_base_path() {
let base = std::ffi::OsStr::new("/usr/bin");
assert_eq!(prepend(Path::new("/opt/kit"), base), "/opt/kit:/usr/bin");
assert_eq!(
prepend(Path::new("/opt/kit"), std::ffi::OsStr::new("")),
"/opt/kit"
);
}
/// A first `apply` is indistinguishable from a second: the map's
/// values are constants, so extending twice is the same map.
#[test]
fn apply_twice_is_apply_once() {
let mut config = HostAgentConfig::new(
rhema_core::mock::MockProvider::new([]),
"m",
std::path::Path::new("/tmp"),
Path::new("/tmp"),
rhema_bash::AllowAll,
);
let before = config.shell_env.clone();
apply(&mut config);
// The wiring only appears when the machine's global mcp.yaml
// has servers; a bare environment must not invent any.
let after_has_mcp_vars = config
.shell_env
.keys()
.any(|key| key.starts_with("RHEMA_MCP"));
if after_has_mcp_vars {
assert!(config.shell_env.len() > before.len());
} else {
assert_eq!(config.shell_env, before, "no wiring, no change");
}
let once = config.shell_env.clone();
let section = config.mcp.clone();
apply(&mut config);
assert_eq!(config.shell_env, once);
assert_eq!(config.mcp, section);
}
}
+3
View File
@@ -400,6 +400,7 @@ impl ClawShell {
),
cwd: root.clone().into(),
timeout: PROBE_TIMEOUT,
env: std::collections::BTreeMap::new(),
},
cancelled,
&mut sink,
@@ -460,6 +461,7 @@ impl ShellExecutor for ClawShell {
command: request.command,
cwd: root,
timeout: request.timeout,
env: request.env,
},
cancelled,
progress,
@@ -812,6 +814,7 @@ mod tests {
command: "echo hi".to_owned(),
cwd: Path::new(REMOTE_WORKSPACE).to_path_buf(),
timeout: Duration::from_secs(5),
env: std::collections::BTreeMap::new(),
},
&cancelled,
&mut sink,
+1 -1
View File
@@ -23,8 +23,8 @@
use std::sync::Arc;
use rhema_autonomous_agent::{Source, SourceError, async_trait};
use rhema_rsd::{Clock, Dispatcher, Event, KeyFn};
use rhema_rsd::{Source, SourceError, async_trait};
use serde_json::json;
use crate::interactive::passthrough_key_fn;
+1 -1
View File
@@ -81,7 +81,7 @@ pub fn events(session: &CoreSession, last: Option<&Outcome>, leased: bool) -> Ve
});
}
Content::ToolResult(result) => push_result(&mut out, &calls, result),
Content::Image(_) => {}
_ => {}
}
}
if said.is_some() {
+1 -11
View File
@@ -2,10 +2,7 @@
//! env merged into every coding-agent session the claw runs — chat
//! turns and `coding_agent` jobs alike. There is no config gate: the
//! `see` macro is a shell affordance, not a server, so it wires
//! whenever the daemon's agents run local shells. `apply` must run
//! before [`crate::mcp::apply`]: the MCP init file bakes this one in
//! as its literal predecessor, so `BASH_ENV` has to name the MCP file
//! last.
//! whenever the daemon's agents run local shells.
#![forbid(unsafe_code)]
@@ -20,13 +17,6 @@ pub(crate) fn wired() -> Option<&'static Arc<rhema_bash::vision::Wiring>> {
rhema_bash::vision::wire(std::env::var_os("BASH_ENV"))
}
/// The init file a later provisioner chains through — `None` when the
/// vision wiring itself failed, in which case the chain falls back to
/// the process's own `BASH_ENV`.
pub(crate) fn init_path() -> Option<std::ffi::OsString> {
wired().map(|wiring| std::ffi::OsString::from(wiring.init_path.display().to_string()))
}
/// Layers the wiring onto one agent config: the shell env map (the
/// init file, the binary, the staging directory) and the prompt's
/// vision section. A frontend without wiring changes nothing.
+4 -2
View File
@@ -197,7 +197,7 @@ impl GatedProvider {
}
}
#[rhema_autonomous_agent::async_trait]
#[rhema_rsd::async_trait]
impl rhema_core::ModelProvider for GatedProvider {
async fn complete(
&self,
@@ -216,7 +216,7 @@ impl rhema_core::ModelProvider for GatedProvider {
}
}
#[rhema_autonomous_agent::async_trait]
#[rhema_rsd::async_trait]
impl rhema_core::ModelProvider for RecordingProvider {
async fn complete(
&self,
@@ -2361,6 +2361,8 @@ async fn model_listings_carry_the_vision_flag_only_when_known() {
supports_vision: vision,
generation_methods: vec!["generateContent".to_owned()],
pricing: None,
family: None,
release_date: None,
};
let cards = vec![
card("claude-sonnet-4-5", Some(true)),