feat(claw): choose where bash runs, this host or a remote sandbox
The daemon's `bash` always ran on its own host. A deployment that wants the shell isolated, or on a machine with the project's toolchain, had no way to say so, and the web settings had no surface for it. A sandbox choice now persists in the settings table, and the daemon can be seeded from `sandbox` in claw.yaml. `local` keeps the existing shell; `http` wraps `rhema-sandbox-http` in a `ShellSandbox` and gives every handler a `ShellTools` built over it. Chat turns, forge turns, and coding jobs all read the choice per dispatch, so a switch applies on the next turn without a restart. A remote sandbox starts empty. The first command for a workspace probes `/workspace` and, when it is empty, sends the host workspace as a tarball through the protocol's seed route. Later edits stay in the sandbox; the claw does not copy them back. The web settings gain a System > Sandbox page: the two kinds, the URL and a write-only token, a forget-token action, and the effective workspace. `GET /v1/sandbox` never returns the token; `PUT` validates and persists the choice. Tests: the sandbox state and config validation, the HTTP route round trip, and a remote turn that seeds a fresh sandbox and runs its shell there. fmt, clippy with -D warnings, the workspace tests, and the web typecheck and build pass.
This commit is contained in:
1 parent
5dc8402107
commit
1aa8d5578e
20 files changed
+1502
-23
No files matched your search
@@ -40,6 +40,10 @@ rhema-forge-integration = { path = "../../integrations/rhema-forge-integration"
|
||||
# with, and the identity tools manage them over chat
|
||||
rhema-identity = "0.3.0"
|
||||
rhema-rsd = "0.3.0"
|
||||
# The sandbox seam: where `bash` runs, local process or a daemon speaking
|
||||
# the wire protocol over HTTP
|
||||
rhema-sandbox = "0.3.0"
|
||||
rhema-sandbox-http = "0.3.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.
|
||||
@@ -59,6 +63,8 @@ thiserror = { workspace = true }
|
||||
# A daemon: the runtime, the poll sleep, the ctrl-c signal; the driver's
|
||||
# concurrent handler runs share it. `net` is the HTTP listener.
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "signal", "time", "sync", "net"] }
|
||||
# The sandbox executor implements the shell seam
|
||||
async-trait = { workspace = true }
|
||||
# The chat surface: native routes plus SSE, and the OpenAI shim
|
||||
axum = { workspace = true }
|
||||
# Broadcast receivers as SSE bodies
|
||||
|
||||
@@ -69,6 +69,10 @@ listen: 127.0.0.1:7799
|
||||
token: change-me # optional; when set, /v1/* requires it
|
||||
agent_token: change-me-too # the client tools' scoped bearer (rhema-tools)
|
||||
tools_bin: ~/.local/share/rhema-tools/bin # put the client tools on PATH
|
||||
sandbox: # where bash runs; omit for this host
|
||||
kind: http # local (default) or http
|
||||
url: https://box.example:7600 # the sandboxd base URL
|
||||
token: sandbox-secret # the daemon's shared secret, if it has one
|
||||
poll_interval_secs: 120
|
||||
max_turn_steps: 2048 # tool rounds one chat turn may run
|
||||
watches: # a seed: imported while the table is empty
|
||||
@@ -96,6 +100,14 @@ unattended for a long time, so a cap this deep is a runaway guard, not
|
||||
a work timer — a turn that hits it ends with a failed outcome and the
|
||||
conversation intact; a follow-up message keeps going.
|
||||
|
||||
`sandbox` selects where the agent's `bash` runs. Unset or `kind: local`
|
||||
keeps the daemon's own processes. `kind: http` sends commands to a host
|
||||
speaking the sandbox protocol (`rhema-sandboxd`), with `url` and an
|
||||
optional `token`. The settings screen writes the same choice to the
|
||||
settings table, and the next turn reads it; no restart is needed. On
|
||||
first use the claw copies the local workspace into the sandbox's
|
||||
`/workspace`. Later edits stay there; the claw does not copy them back.
|
||||
|
||||
The surface refuses to start on a non-loopback `listen` with no
|
||||
`token`: anything beyond loopback can reach the port, and the bearer
|
||||
token is what stands between it and the agent's tools. Set a token, or
|
||||
@@ -137,6 +149,8 @@ DELETE /v1/consents/{id} deny a pending ask
|
||||
GET /v1/attachments/{id} an attached file's bytes
|
||||
GET /v1/phone/commands?device= the device's queued, unconfirmed commands
|
||||
POST /v1/phone/commands/{id}/result {"ok", "detail"?} — the device's report
|
||||
GET /v1/sandbox where the agent's bash runs
|
||||
PUT /v1/sandbox {"kind","url"?,"token"?}, switch and persist
|
||||
GET /v1/providers the backend instances + the active pair
|
||||
PUT /v1/providers/active {"provider","model"?} — switch, persisted
|
||||
PUT /v1/providers/{id}/credentials add or replace an instance, persisted
|
||||
|
||||
@@ -55,6 +55,9 @@ pub enum ConfigError {
|
||||
"agent_token is the same value as token; the agent token must be its own secret, scoped to the tool routes"
|
||||
)]
|
||||
SameAgentToken,
|
||||
/// The configured sandbox choice cannot run as written.
|
||||
#[error("sandbox: {0}")]
|
||||
Sandbox(String),
|
||||
/// The ingest credential is the same value as the human token or
|
||||
/// the agent token: boot refuses, because the ingest credential's
|
||||
/// safety is that it is write-only and the event door only — a
|
||||
@@ -171,6 +174,10 @@ pub struct ClawConfig {
|
||||
/// Unset closes the door to credentials; the human token can still
|
||||
/// ingest.
|
||||
pub ingest_token: Option<String>,
|
||||
/// Where the agent's `bash` runs: this host when unset, or a
|
||||
/// `rhema-sandboxd` over HTTP. The settings store owns the live
|
||||
/// choice; this seeds it at boot, before the first settings write.
|
||||
pub sandbox: Option<crate::sandbox::SandboxChoice>,
|
||||
}
|
||||
|
||||
impl ClawConfig {
|
||||
@@ -198,6 +205,7 @@ impl Default for ClawConfig {
|
||||
tools_bin: None,
|
||||
ingest_token: None,
|
||||
transcript: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -326,6 +334,12 @@ impl ClawConfig {
|
||||
{
|
||||
return Err(ConfigError::IngestTokenCollision);
|
||||
}
|
||||
if let Some(sandbox) = &self.sandbox {
|
||||
sandbox
|
||||
.clone()
|
||||
.normalized()
|
||||
.map_err(|err| ConfigError::Sandbox(err.to_string()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -422,6 +436,10 @@ model: claude-sonnet-4-5
|
||||
listen: 192.168.1.10:7800
|
||||
token: sekrit
|
||||
ingest_token: door-key
|
||||
sandbox:
|
||||
kind: http
|
||||
url: https://box.example:7600
|
||||
token: sandbox-secret
|
||||
";
|
||||
let config: ClawConfig = serde_yaml::from_str(raw).expect("parses");
|
||||
assert_eq!(config.poll_interval_secs, 30);
|
||||
@@ -438,6 +456,35 @@ ingest_token: door-key
|
||||
config.bootstrap_root.as_deref(),
|
||||
Some(std::path::Path::new("/var/lib/rhema/claw-bootstrap"))
|
||||
);
|
||||
let sandbox = config.sandbox.expect("the sandbox parses");
|
||||
assert_eq!(sandbox.kind, crate::sandbox::SandboxKind::Http);
|
||||
assert_eq!(sandbox.url.as_deref(), Some("https://box.example:7600"));
|
||||
assert_eq!(sandbox.token.as_deref(), Some("sandbox-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_http_sandbox_needs_a_url_at_boot() {
|
||||
let missing = ClawConfig {
|
||||
sandbox: Some(crate::sandbox::SandboxChoice {
|
||||
kind: crate::sandbox::SandboxKind::Http,
|
||||
url: None,
|
||||
token: None,
|
||||
}),
|
||||
..ClawConfig::default()
|
||||
};
|
||||
assert!(
|
||||
matches!(missing.validate(), Err(ConfigError::Sandbox(_))),
|
||||
"a remote sandbox without a URL is refused at boot"
|
||||
);
|
||||
let valid = ClawConfig {
|
||||
sandbox: Some(crate::sandbox::SandboxChoice {
|
||||
kind: crate::sandbox::SandboxKind::Http,
|
||||
url: Some("https://box.example:7600".to_owned()),
|
||||
token: None,
|
||||
}),
|
||||
..ClawConfig::default()
|
||||
};
|
||||
assert!(valid.validate().is_ok(), "a complete remote choice passes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -62,6 +62,9 @@ pub enum ClawError {
|
||||
/// The runtime settings table could not be opened or read.
|
||||
#[error(transparent)]
|
||||
Settings(#[from] crate::settings::SettingsError),
|
||||
/// The sandbox choice could not be loaded or is malformed.
|
||||
#[error(transparent)]
|
||||
Sandbox(#[from] crate::sandbox::SandboxError),
|
||||
/// The notification table could not be opened or read.
|
||||
#[error(transparent)]
|
||||
Notifications(#[from] crate::notifications::NotificationStoreError),
|
||||
@@ -225,6 +228,10 @@ impl Daemon {
|
||||
// The forge handler resolves its watches through the table at
|
||||
// dispatch time, so a watch added mid-run is answerable without a
|
||||
// restart.
|
||||
// The runtime settings table, opened before the handlers so the
|
||||
// sandbox choice and the provider write share one connection.
|
||||
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
|
||||
|
||||
// The client tools' connection, handed to the agent's shell as
|
||||
// environment: the URL the surface answers on, the scoped
|
||||
// agent token (the middleware keeps it to the contract's data
|
||||
@@ -252,6 +259,25 @@ impl Daemon {
|
||||
format!("{}:{inherited}", tools_bin.display()),
|
||||
);
|
||||
}
|
||||
// Where `bash` runs: the stored choice wins, the config seeds a
|
||||
// fresh store. The state is shared by every handler and the
|
||||
// surface, so a switch is live on the next turn.
|
||||
let sandbox = Arc::new(crate::sandbox::SandboxState::load(
|
||||
settings.clone(),
|
||||
config.sandbox.clone(),
|
||||
interactive_workspace.clone(),
|
||||
&tool_env,
|
||||
)?);
|
||||
let sandbox_choice = sandbox.choice();
|
||||
eprintln!(
|
||||
"[claw] sandbox: {}{}",
|
||||
sandbox_choice.kind.as_str(),
|
||||
sandbox_choice
|
||||
.url
|
||||
.as_deref()
|
||||
.map(|url| format!(" ({url})"))
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
let forge_handler = ClawHandler::new(
|
||||
backends.clone(),
|
||||
workspace_root,
|
||||
@@ -259,7 +285,8 @@ impl Daemon {
|
||||
accounts.clone(),
|
||||
config.transcript_enabled(),
|
||||
tool_env.clone(),
|
||||
);
|
||||
)
|
||||
.with_sandbox(sandbox.clone());
|
||||
// Three drivers over one store admit from the same table, so
|
||||
// each owns its slice of the key space: a forge pass must never
|
||||
// pick up a resident or job event (it would fail it, and
|
||||
@@ -292,7 +319,6 @@ impl Daemon {
|
||||
let phone = Arc::new(crate::phone::PhoneStore::open(&db)?);
|
||||
let memory = Arc::new(FileMemoryStore::new(config.memory_path()?)?);
|
||||
let bootstrap = Arc::new(crate::bootstrap::Bootstrap::new(config.bootstrap_dir()?)?);
|
||||
let settings = Arc::new(crate::settings::SettingsStore::open(&db)?);
|
||||
// The identity store shares the settings table and keeps its
|
||||
// images beside the database.
|
||||
let identity = Arc::new(crate::identity::IdentityStore::new(
|
||||
@@ -361,7 +387,8 @@ impl Daemon {
|
||||
extensions.clone(),
|
||||
config.transcript_enabled(),
|
||||
)
|
||||
.with_steer(steer.clone());
|
||||
.with_steer(steer.clone())
|
||||
.with_sandbox(sandbox.clone());
|
||||
let interactive_driver = Arc::new(
|
||||
Driver::new(
|
||||
interactive_dispatcher.clone(),
|
||||
@@ -381,7 +408,8 @@ impl Daemon {
|
||||
notifications.clone(),
|
||||
config.max_turn_steps,
|
||||
config.transcript_enabled(),
|
||||
);
|
||||
)
|
||||
.with_sandbox(sandbox.clone());
|
||||
let jobs_driver = Arc::new(
|
||||
Driver::new(jobs_dispatcher.clone(), Arc::new(jobs_handler))
|
||||
.with_holder("rhema-claw-jobs")
|
||||
@@ -410,6 +438,7 @@ impl Daemon {
|
||||
bridge,
|
||||
attachments,
|
||||
phone,
|
||||
sandbox,
|
||||
config.token.clone(),
|
||||
config.agent_token.clone(),
|
||||
config.ingest_token.clone(),
|
||||
|
||||
@@ -25,7 +25,7 @@ use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use crate::forge::{WatchCredential, record_client, resolve_watch_credential};
|
||||
use crate::watch_store::ClawStore;
|
||||
use rhema_agent_tools::AllowAll;
|
||||
use rhema_agent_tools::{AllowAll, ShellTools};
|
||||
use rhema_autonomous_agent::{Handler, SessionContext, async_trait};
|
||||
use rhema_coding_agent::{CodingAgent, CodingAgentConfig};
|
||||
use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session};
|
||||
@@ -40,6 +40,7 @@ use rhema_rsd::{InboxItem, Outcome, ResourceKey};
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use crate::backends::BackendRegistry;
|
||||
use crate::sandbox::SandboxState;
|
||||
|
||||
/// The handler's tool permissions, resolved deterministically before the
|
||||
/// agent's first step (spec §8) — never by the model, never mid-run. V1
|
||||
@@ -71,6 +72,9 @@ pub struct ClawHandler {
|
||||
/// agent shell: the daemon URL, the scoped agent token, the tools'
|
||||
/// bin dir on PATH. Empty when the config issues no agent token.
|
||||
tool_env: std::collections::BTreeMap<String, String>,
|
||||
/// Where commands run: this host when absent, a remote sandbox when
|
||||
/// the surface selected one. Read per dispatch.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
clients: Mutex<HashMap<String, Arc<WatchClient>>>,
|
||||
}
|
||||
|
||||
@@ -92,10 +96,18 @@ impl ClawHandler {
|
||||
watches,
|
||||
accounts,
|
||||
tool_env,
|
||||
sandbox: None,
|
||||
clients: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the deployment's sandbox choice: a forge turn's commands
|
||||
/// run where it says, seeded from the thread's host workspace.
|
||||
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
|
||||
self.sandbox = Some(sandbox);
|
||||
self
|
||||
}
|
||||
|
||||
/// The forge client a dispatch key answers to:
|
||||
/// `"github:issue:acme/widgets#7"` resolves its watch record from the
|
||||
/// table at dispatch time — the table is the source of truth, not a
|
||||
@@ -346,7 +358,8 @@ impl ClawHandler {
|
||||
}
|
||||
|
||||
/// The config one dispatch's agent runs on: the default coding
|
||||
/// agent's, with the bounded request view when the config has it on.
|
||||
/// agent's, with the bounded request view when the config has it on
|
||||
/// and a remote shell when the sandbox choice says so.
|
||||
/// A forge thread answers for as long as the thread lives; without
|
||||
/// the view its history would ride whole on every step.
|
||||
fn agent_config(
|
||||
@@ -355,15 +368,29 @@ impl ClawHandler {
|
||||
model: &str,
|
||||
workspace: &Path,
|
||||
) -> CodingAgentConfig {
|
||||
let mut config = CodingAgentConfig::new(provider, model, workspace, AllowAll);
|
||||
let display = match &self.sandbox {
|
||||
Some(sandbox) => sandbox.workspace_for(workspace),
|
||||
None => workspace.to_path_buf(),
|
||||
};
|
||||
let mut config = CodingAgentConfig::new(provider, model, &display, AllowAll);
|
||||
// Write the resolved value, not an override: the coding agent's
|
||||
// own default is on now, and the config's `false` must win.
|
||||
config.transcript = self
|
||||
.transcript
|
||||
.then(rhema_transcript::TranscriptSettings::default);
|
||||
config.shell_env = self.tool_env.clone();
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
match &self.sandbox {
|
||||
Some(sandbox) if sandbox.is_remote() => {
|
||||
config.tools = Some(Arc::new(ShellTools::with_executor(
|
||||
display,
|
||||
sandbox.executor(workspace.to_path_buf()),
|
||||
)));
|
||||
}
|
||||
_ => {
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
|
||||
@@ -123,6 +123,9 @@ pub struct ClawState {
|
||||
/// The phone tables: the command queue the device polls and the
|
||||
/// reported state the ingest door feeds.
|
||||
phone: Arc<crate::phone::PhoneStore>,
|
||||
/// Where the agent's `bash` runs: the live choice `/v1/sandbox`
|
||||
/// edits, shared with every handler.
|
||||
sandbox: Arc<crate::sandbox::SandboxState>,
|
||||
token: Option<String>,
|
||||
/// The scoped agent token the client tools hold: a second bearer
|
||||
/// answering only the contract's data routes (see
|
||||
@@ -146,7 +149,7 @@ impl ClawState {
|
||||
/// `agent_token`.
|
||||
#[expect(
|
||||
clippy::too_many_arguments,
|
||||
reason = "eighteen parts, each load-bearing"
|
||||
reason = "twenty-one parts, each load-bearing"
|
||||
)]
|
||||
pub fn new(
|
||||
dispatcher: Arc<Dispatcher>,
|
||||
@@ -167,6 +170,7 @@ impl ClawState {
|
||||
bridge: Arc<crate::consents::WaitBridge>,
|
||||
attachments: Arc<crate::attachments::AttachmentStore>,
|
||||
phone: Arc<crate::phone::PhoneStore>,
|
||||
sandbox: Arc<crate::sandbox::SandboxState>,
|
||||
token: Option<String>,
|
||||
agent_token: Option<String>,
|
||||
ingest_token: Option<String>,
|
||||
@@ -190,6 +194,7 @@ impl ClawState {
|
||||
bridge,
|
||||
attachments,
|
||||
phone,
|
||||
sandbox,
|
||||
token,
|
||||
agent_token,
|
||||
ingest_token,
|
||||
@@ -289,6 +294,11 @@ impl ClawState {
|
||||
pub fn watches(&self) -> &ClawStore {
|
||||
&self.watches
|
||||
}
|
||||
|
||||
/// Where the agent's `bash` runs.
|
||||
pub fn sandbox(&self) -> &crate::sandbox::SandboxState {
|
||||
&self.sandbox
|
||||
}
|
||||
}
|
||||
|
||||
/// The app router: `/healthz` open, `/v1` behind the bearer check when
|
||||
@@ -343,6 +353,7 @@ pub fn router(state: ClawState) -> Router {
|
||||
)
|
||||
.route("/providers/{id}", delete(providers_remove))
|
||||
.route("/providers/{id}/models", get(providers_models))
|
||||
.route("/sandbox", get(sandbox_get).put(sandbox_put))
|
||||
.route(
|
||||
"/chat/completions",
|
||||
post(crate::openai::chat_completions)
|
||||
@@ -1982,6 +1993,63 @@ pub(crate) async fn drain_owned(
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /v1/sandbox`: where the agent's `bash` runs. The token never
|
||||
/// rides the wire: `token_set` says whether one is stored.
|
||||
async fn sandbox_get(State(state): State<ClawState>) -> Json<Value> {
|
||||
Json(sandbox_json(&state))
|
||||
}
|
||||
|
||||
/// The sandbox state as the wire sees it: the shared body of the read
|
||||
/// and of the write that answers with the new choice.
|
||||
fn sandbox_json(state: &ClawState) -> Value {
|
||||
let choice = state.sandbox().choice();
|
||||
json!({
|
||||
"kind": choice.kind.as_str(),
|
||||
"url": choice.url,
|
||||
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
|
||||
"workspace": state.sandbox().workspace().display().to_string(),
|
||||
"local_workspace": state.sandbox().local_workspace().display().to_string(),
|
||||
"remote_workspace": crate::sandbox::REMOTE_WORKSPACE,
|
||||
})
|
||||
}
|
||||
|
||||
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and
|
||||
/// persist the choice. `token` is write-only; `clear_token` drops the
|
||||
/// stored one. The choice applies on the next turn, no restart.
|
||||
async fn sandbox_put(
|
||||
State(state): State<ClawState>,
|
||||
Json(body): Json<Value>,
|
||||
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
|
||||
let Some(kind) = body["kind"].as_str() else {
|
||||
return Err(bad_request("body must carry a sandbox kind"));
|
||||
};
|
||||
let kind = crate::sandbox::SandboxKind::parse(kind)
|
||||
.ok_or_else(|| bad_request(format!("unknown sandbox kind {kind:?}")))?;
|
||||
let current = state.sandbox().choice();
|
||||
let clear_token = body["clear_token"].as_bool().unwrap_or(false);
|
||||
let token = if clear_token {
|
||||
None
|
||||
} else {
|
||||
body["token"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| current.token.clone())
|
||||
};
|
||||
let choice = crate::sandbox::SandboxChoice {
|
||||
kind,
|
||||
url: body["url"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.or_else(|| current.url.clone()),
|
||||
token,
|
||||
};
|
||||
state.sandbox().set(choice).map_err(|err| match err {
|
||||
crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
|
||||
crate::sandbox::SandboxError::Store(_) => internal_error(err),
|
||||
})?;
|
||||
Ok(Json(sandbox_json(&state)))
|
||||
}
|
||||
|
||||
/// `GET /v1/providers`: every constructible backend and the active pair.
|
||||
/// The active pair is runtime state — the config file seeded it, the
|
||||
/// settings store owns it now. Each provider is one instance, named by
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
//! v1's starting point — and the resolver chain are assembled before
|
||||
//! the first model call; the model never decides its own permissions.
|
||||
//! The chain is the core toolsets (the shell over the interactive
|
||||
//! workspace, memory, `bootstrap_save`) plus every
|
||||
//! workspace, or over the sandbox root when one is selected; memory,
|
||||
//! `bootstrap_save`) plus every
|
||||
//! [`crate::extension::ClawExtension`]'s tools in the standard set's
|
||||
//! order. The system prompt is rendered per dispatch from the
|
||||
//! bootstrap template over the live SOUL/USER files.
|
||||
@@ -82,6 +83,7 @@ use crate::backends::BackendRegistry;
|
||||
use crate::bootstrap::{Bootstrap, DEFAULT_SYSTEM_MD, render_system};
|
||||
use crate::hub::{EventHub, TurnEvent, UserImage};
|
||||
use crate::notifications::NotificationStore;
|
||||
use crate::sandbox::SandboxState;
|
||||
use crate::steer::{SteerGuard, SteerRegistry};
|
||||
|
||||
/// The key prefixes of the resident context (see the module docs):
|
||||
@@ -245,6 +247,10 @@ pub struct InteractiveHandler {
|
||||
/// prompt, when provisioning succeeded — the same wiring whose env
|
||||
/// map lights the shell's inbox up.
|
||||
vision: Option<String>,
|
||||
/// Where commands run: this host when absent, a remote sandbox
|
||||
/// when the surface selected one. Read per dispatch, so a switch
|
||||
/// takes effect on the next turn.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
}
|
||||
|
||||
impl InteractiveHandler {
|
||||
@@ -301,9 +307,17 @@ impl InteractiveHandler {
|
||||
)))
|
||||
}),
|
||||
vision: vision.map(|wiring| wiring.section.to_owned()),
|
||||
sandbox: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the deployment's sandbox choice: commands run where it
|
||||
/// says, and a remote sandbox replaces the host shell for `bash`.
|
||||
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
|
||||
self.sandbox = Some(sandbox);
|
||||
self
|
||||
}
|
||||
|
||||
/// The agent for one dispatch: rebuilt per run over the restored
|
||||
/// session (the engine's own step counter is per-agent; the
|
||||
/// conversation lives in the session, not the agent). The system
|
||||
@@ -329,13 +343,23 @@ impl InteractiveHandler {
|
||||
None => provider,
|
||||
};
|
||||
let resolver = self.resolver(key);
|
||||
let workspace = self.workspace();
|
||||
let vision = if self
|
||||
.sandbox
|
||||
.as_ref()
|
||||
.is_some_and(|sandbox| sandbox.is_remote())
|
||||
{
|
||||
None
|
||||
} else {
|
||||
self.vision.as_deref()
|
||||
};
|
||||
let system = render_system(
|
||||
DEFAULT_SYSTEM_MD,
|
||||
key.as_str(),
|
||||
&self.workspace,
|
||||
&workspace,
|
||||
&self.bootstrap,
|
||||
&resolver.specs(),
|
||||
self.vision.as_deref(),
|
||||
vision,
|
||||
)
|
||||
.map_err(|err| format!("cannot render the bootstrap system prompt: {err}"))?;
|
||||
Agent::builder()
|
||||
@@ -356,6 +380,15 @@ impl InteractiveHandler {
|
||||
self
|
||||
}
|
||||
|
||||
/// The workspace the prompt names: the host path locally, the
|
||||
/// sandbox root when commands run elsewhere.
|
||||
fn workspace(&self) -> PathBuf {
|
||||
match &self.sandbox {
|
||||
Some(sandbox) => sandbox.workspace_for(&self.workspace),
|
||||
None => self.workspace.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The resolver chain one dispatch runs under: the core toolsets —
|
||||
/// the shell over the interactive workspace, memory,
|
||||
/// `bootstrap_save` — then every extension's tools in the standard
|
||||
@@ -364,8 +397,18 @@ impl InteractiveHandler {
|
||||
/// their asks and cards to the session that asked, and the handler
|
||||
/// serves every session.
|
||||
fn resolver(&self, key: &ResourceKey) -> Arc<ResolverChain> {
|
||||
let shell: Arc<dyn rhema_core::ToolResolver> = match &self.sandbox {
|
||||
Some(sandbox) if sandbox.is_remote() => {
|
||||
let workspace = sandbox.workspace_for(&self.workspace);
|
||||
let tools =
|
||||
ShellTools::with_executor(workspace, sandbox.executor(self.workspace.clone()));
|
||||
tools.install_approval(Arc::new(AllowAll));
|
||||
Arc::new(tools)
|
||||
}
|
||||
_ => self.tools.clone(),
|
||||
};
|
||||
let mut resolvers: Vec<Arc<dyn rhema_core::ToolResolver>> = vec![
|
||||
self.tools.clone(),
|
||||
shell,
|
||||
Arc::new(MemoryResolver::new(
|
||||
self.memory.clone(),
|
||||
Scope::Workspace(self.workspace.clone()),
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rhema_agent_tools::ShellTools;
|
||||
use rhema_autonomous_agent::{Handler, SessionContext, Source, SourceError, async_trait};
|
||||
use rhema_coding_agent::{AllowAll, CodingAgent, CodingAgentConfig};
|
||||
use rhema_core::{Event as ModelEvent, EventSink};
|
||||
@@ -34,6 +35,7 @@ use crate::handler::final_text;
|
||||
use crate::interactive::passthrough_key_fn;
|
||||
use crate::job_store::{CodingJobStore, JobStatus};
|
||||
use crate::notifications::{DEFAULT_DEVICE, NotificationStore};
|
||||
use crate::sandbox::SandboxState;
|
||||
|
||||
/// The source name the coding jobs ingest under.
|
||||
pub const JOBS_SOURCE: &str = "jobs";
|
||||
@@ -141,6 +143,9 @@ pub struct CodingJobHandler {
|
||||
/// Whether the jobs run the bounded request view (the config's
|
||||
/// `transcript`, on unless set false).
|
||||
transcript: bool,
|
||||
/// Where commands run: this host when absent, a remote sandbox when
|
||||
/// the surface selected one. Read per job.
|
||||
sandbox: Option<Arc<SandboxState>>,
|
||||
}
|
||||
|
||||
impl CodingJobHandler {
|
||||
@@ -160,9 +165,17 @@ impl CodingJobHandler {
|
||||
notifications,
|
||||
max_turn_steps,
|
||||
transcript,
|
||||
sandbox: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the deployment's sandbox choice: a job's commands run
|
||||
/// where it says, seeded from the instance's host path.
|
||||
pub fn with_sandbox(mut self, sandbox: Arc<SandboxState>) -> Self {
|
||||
self.sandbox = Some(sandbox);
|
||||
self
|
||||
}
|
||||
|
||||
/// One dispatch, failed with a reason on any step; every failure
|
||||
/// lands in the job row before it lands in the outcome, so the
|
||||
/// model's `status` read and the user's notification agree.
|
||||
@@ -212,7 +225,11 @@ impl CodingJobHandler {
|
||||
.map_err(|err| format!("job {job_id} could not start: {err}"))?;
|
||||
|
||||
let (provider, model) = self.backends.current();
|
||||
let mut config = CodingAgentConfig::new(provider, model, &workspace, AllowAll);
|
||||
let display = match &self.sandbox {
|
||||
Some(sandbox) => sandbox.workspace_for(&workspace),
|
||||
None => workspace.clone(),
|
||||
};
|
||||
let mut config = CodingAgentConfig::new(provider, model, &display, AllowAll);
|
||||
config.max_turn_steps = self.max_turn_steps;
|
||||
// A job's stashed session carries across runs and only ever
|
||||
// grows; the view is what keeps a repeat run's steps cheap.
|
||||
@@ -221,8 +238,18 @@ impl CodingJobHandler {
|
||||
config.transcript = self
|
||||
.transcript
|
||||
.then(rhema_transcript::TranscriptSettings::default);
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
match &self.sandbox {
|
||||
Some(sandbox) if sandbox.is_remote() => {
|
||||
config.tools = Some(Arc::new(ShellTools::with_executor(
|
||||
display,
|
||||
sandbox.executor(workspace.clone()),
|
||||
)));
|
||||
}
|
||||
_ => {
|
||||
crate::vision::apply(&mut config);
|
||||
crate::mcp::apply(&mut config);
|
||||
}
|
||||
}
|
||||
let stashed = self
|
||||
.store
|
||||
.session(&instance_name)
|
||||
|
||||
@@ -42,6 +42,8 @@
|
||||
//! workspace files handed to the human as fetchable cards
|
||||
//! - [`phone`] — the phone state and command queue: reported status to
|
||||
//! read, consent-gated control actions the device executes
|
||||
//! - [`sandbox`]: where `bash` runs, this host, or a remote daemon
|
||||
//! speaking the sandbox protocol over HTTP
|
||||
//! - [`watch_tools`] — the agent's watch-management tool set
|
||||
//! - [`notify_tools`] — the `notify` tool: the queue a device polls
|
||||
//! - [`task_tools`] — `schedule_task`, `list_tasks`, `cancel_task`
|
||||
@@ -89,6 +91,7 @@ pub mod notifications;
|
||||
pub mod notify_tools;
|
||||
pub mod openai;
|
||||
pub mod phone;
|
||||
pub mod sandbox;
|
||||
pub mod settings;
|
||||
pub mod steer;
|
||||
pub mod task_source;
|
||||
@@ -117,6 +120,7 @@ pub use interactive::InteractiveHandler;
|
||||
pub use mock::MockLoop;
|
||||
pub use notifications::{NotificationRecord, NotificationStore, NotificationStoreError};
|
||||
pub use rhema_forge_integration::{ForgeKind, resolve_token};
|
||||
pub use sandbox::{SandboxChoice, SandboxError, SandboxKind, SandboxState};
|
||||
pub use settings::SettingsStore;
|
||||
pub use task_source::{TASKS_SOURCE, TaskScheduler};
|
||||
pub use task_store::{TaskKind, TaskRecord, TaskStore, TaskStoreError};
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
//! Where the claw's `bash` runs: this host's processes, or a daemon
|
||||
//! speaking the sandbox protocol over HTTP.
|
||||
//!
|
||||
//! The choice is deployment state, persisted in the settings table and
|
||||
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw
|
||||
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`
|
||||
//! and gives the handlers a `ShellSandbox` executor over it. The tool
|
||||
//! spec, approval gate, output caps, and error shaping stay in
|
||||
//! `ShellTools`; only the machine changes.
|
||||
//!
|
||||
//! A remote sandbox starts empty. On the first command for a
|
||||
//! workspace, the executor probes `/workspace` and, when it is empty,
|
||||
//! sends the host workspace as a tarball through the protocol's seed
|
||||
//! route. Later edits stay in the sandbox; the claw does not copy them
|
||||
//! back.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use base64::Engine as _;
|
||||
use rhema_agent_tools::exec::{Executed, ShellError, ShellExecutor, default_executor_with};
|
||||
use rhema_sandbox::{ExecRequest, Sandbox, ShellSandbox, WorkspaceSeed};
|
||||
use rhema_sandbox_http::HttpSandbox;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::settings::SettingsStore;
|
||||
|
||||
/// The settings key the chosen sandbox is persisted under.
|
||||
pub const SANDBOX_KEY: &str = "sandbox";
|
||||
|
||||
/// The workspace path a remote sandbox exposes: one root per session,
|
||||
/// fixed by the protocol.
|
||||
pub const REMOTE_WORKSPACE: &str = "/workspace";
|
||||
|
||||
/// The per-command budget of the emptiness probe before a seed: long
|
||||
/// enough for a fresh sandbox, short enough that an unreachable daemon
|
||||
/// fails the turn rather than stalling it.
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// Which machine runs the shell.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SandboxKind {
|
||||
/// The daemon's own host, the original path.
|
||||
#[default]
|
||||
Local,
|
||||
/// A host speaking the sandbox protocol over HTTP.
|
||||
Http,
|
||||
}
|
||||
|
||||
impl SandboxKind {
|
||||
/// The stored spelling.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Local => "local",
|
||||
Self::Http => "http",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a stored spelling. Anything else is `None`, which every
|
||||
/// caller turns into the local default.
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"local" => Some(Self::Local),
|
||||
"http" => Some(Self::Http),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One sandbox choice: the kind and whatever it needs. `local` needs
|
||||
/// nothing; `http` needs a base URL and may carry a token.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub struct SandboxChoice {
|
||||
/// The machine kind.
|
||||
pub kind: SandboxKind,
|
||||
/// The `http` sandbox's base URL, no trailing slash after
|
||||
/// normalization.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
/// The shared secret the daemon checks, when it guards its routes.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
impl SandboxChoice {
|
||||
/// Trims the strings, drops blank ones, and validates what `http`
|
||||
/// needs to run. A choice that fails reads as a 400 at the route,
|
||||
/// never as a silent fallback.
|
||||
pub fn normalized(mut self) -> Result<Self, SandboxError> {
|
||||
self.url = self
|
||||
.url
|
||||
.map(|url| url.trim().trim_end_matches('/').to_owned())
|
||||
.filter(|url| !url.is_empty());
|
||||
self.token = self
|
||||
.token
|
||||
.map(|token| token.trim().to_owned())
|
||||
.filter(|token| !token.is_empty());
|
||||
if self.kind == SandboxKind::Http {
|
||||
let url = self
|
||||
.url
|
||||
.as_deref()
|
||||
.ok_or_else(|| SandboxError::Invalid("the http sandbox needs a url".to_owned()))?;
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
return Err(SandboxError::Invalid(
|
||||
"the http sandbox url must start with http:// or https://".to_owned(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Whether commands leave this host.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.kind == SandboxKind::Http
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a sandbox choice or operation failed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SandboxError {
|
||||
/// The choice cannot run as written.
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
/// The settings table failed.
|
||||
#[error("sandbox store failed: {0}")]
|
||||
Store(String),
|
||||
}
|
||||
|
||||
/// The chosen sandbox and the executors built over it, shared by every
|
||||
/// handler so a switch takes effect on the next turn without a restart.
|
||||
pub struct SandboxState {
|
||||
choice: RwLock<SandboxChoice>,
|
||||
settings: Arc<SettingsStore>,
|
||||
local_workspace: PathBuf,
|
||||
local: Arc<dyn ShellExecutor>,
|
||||
remote: Mutex<HashMap<String, Arc<HttpSandbox>>>,
|
||||
}
|
||||
|
||||
impl SandboxState {
|
||||
/// The state over `settings`, seeded by `seed` when no choice was
|
||||
/// stored. `local_workspace` is the chat workspace the settings
|
||||
/// surface reports; `shell_env` is layered over local commands.
|
||||
pub fn load(
|
||||
settings: Arc<SettingsStore>,
|
||||
seed: Option<SandboxChoice>,
|
||||
local_workspace: PathBuf,
|
||||
shell_env: &BTreeMap<String, String>,
|
||||
) -> Result<Self, SandboxError> {
|
||||
let stored = settings
|
||||
.get(SANDBOX_KEY)
|
||||
.map_err(|err| SandboxError::Store(err.to_string()))?;
|
||||
let choice = stored
|
||||
.as_deref()
|
||||
.and_then(|raw| serde_json::from_str::<SandboxChoice>(raw).ok())
|
||||
.and_then(|choice| choice.normalized().ok())
|
||||
.or_else(|| seed.and_then(|choice| choice.normalized().ok()))
|
||||
.unwrap_or_default();
|
||||
Ok(Self {
|
||||
choice: RwLock::new(choice),
|
||||
settings,
|
||||
local_workspace,
|
||||
local: default_executor_with(shell_env),
|
||||
remote: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The current choice.
|
||||
pub fn choice(&self) -> SandboxChoice {
|
||||
self.choice
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Whether commands leave this host.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.choice
|
||||
.read()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.is_remote()
|
||||
}
|
||||
|
||||
/// Saves and applies a choice. The next turn reads it; nothing is
|
||||
/// rebuilt in place. Answers the normalized choice that was stored.
|
||||
pub fn set(&self, choice: SandboxChoice) -> Result<SandboxChoice, SandboxError> {
|
||||
let choice = choice.normalized()?;
|
||||
let raw =
|
||||
serde_json::to_string(&choice).map_err(|err| SandboxError::Store(err.to_string()))?;
|
||||
self.settings
|
||||
.set(SANDBOX_KEY, &raw)
|
||||
.map_err(|err| SandboxError::Store(err.to_string()))?;
|
||||
*self.choice.write().unwrap_or_else(PoisonError::into_inner) = choice.clone();
|
||||
self.remote
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.clear();
|
||||
Ok(choice)
|
||||
}
|
||||
|
||||
/// The workspace a handler should name and start commands in: the
|
||||
/// host path locally, `/workspace` on a remote sandbox.
|
||||
pub fn workspace_for(&self, host: &Path) -> PathBuf {
|
||||
if self.is_remote() {
|
||||
PathBuf::from(REMOTE_WORKSPACE)
|
||||
} else {
|
||||
host.to_path_buf()
|
||||
}
|
||||
}
|
||||
|
||||
/// The chat workspace under the current choice, for the settings
|
||||
/// surface.
|
||||
pub fn workspace(&self) -> PathBuf {
|
||||
self.workspace_for(&self.local_workspace)
|
||||
}
|
||||
|
||||
/// The host workspace path, whatever the current choice.
|
||||
pub fn local_workspace(&self) -> &Path {
|
||||
&self.local_workspace
|
||||
}
|
||||
|
||||
/// An executor for one host workspace. Remote sessions are derived
|
||||
/// from the workspace path, so two workspaces never share a root.
|
||||
pub fn executor(
|
||||
self: &Arc<Self>,
|
||||
host_workspace: impl Into<PathBuf>,
|
||||
) -> Arc<dyn ShellExecutor> {
|
||||
Arc::new(ClawShell {
|
||||
state: Arc::clone(self),
|
||||
host_workspace: host_workspace.into(),
|
||||
local: self.local.clone(),
|
||||
seeded: AtomicBool::new(false),
|
||||
last: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// The cached HTTP client for one session. The map is cleared
|
||||
/// whenever the choice changes, so a new URL or token builds a new
|
||||
/// client.
|
||||
fn remote_sandbox(
|
||||
&self,
|
||||
choice: &SandboxChoice,
|
||||
host: &Path,
|
||||
) -> Result<Arc<HttpSandbox>, ShellError> {
|
||||
let url = choice
|
||||
.url
|
||||
.as_deref()
|
||||
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?;
|
||||
let session = session_name(host);
|
||||
{
|
||||
let remote = self.remote.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(sandbox) = remote.get(&session) {
|
||||
return Ok(sandbox.clone());
|
||||
}
|
||||
}
|
||||
let token = choice.token.as_deref().unwrap_or("");
|
||||
let sandbox = Arc::new(HttpSandbox::new(url.to_owned(), &session, token));
|
||||
self.remote
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.insert(session, sandbox.clone());
|
||||
Ok(sandbox)
|
||||
}
|
||||
}
|
||||
|
||||
/// One handler's view of the choice: local commands go straight to the
|
||||
/// host executor; remote commands go through the sandbox, seeded from
|
||||
/// the host workspace once per choice.
|
||||
struct ClawShell {
|
||||
state: Arc<SandboxState>,
|
||||
host_workspace: PathBuf,
|
||||
local: Arc<dyn ShellExecutor>,
|
||||
seeded: AtomicBool,
|
||||
last: Mutex<Option<SandboxChoice>>,
|
||||
}
|
||||
|
||||
impl ClawShell {
|
||||
/// Seeds the sandbox once per choice. An empty `/workspace` gets
|
||||
/// the host workspace as a tarball; a non-empty one is left alone
|
||||
/// so a restart never overwrites work done in the sandbox.
|
||||
async fn seed(
|
||||
&self,
|
||||
sandbox: &Arc<HttpSandbox>,
|
||||
cancelled: &AtomicBool,
|
||||
) -> Result<(), ShellError> {
|
||||
let mut sink = |_line: &str| {};
|
||||
let probe = sandbox
|
||||
.exec(
|
||||
ExecRequest {
|
||||
command: "ls -A /workspace 2>/dev/null | head -n 1".to_owned(),
|
||||
cwd: REMOTE_WORKSPACE.to_owned(),
|
||||
timeout: PROBE_TIMEOUT,
|
||||
},
|
||||
cancelled,
|
||||
&mut sink,
|
||||
)
|
||||
.await
|
||||
.map_err(protocol_error)?;
|
||||
if !probe.stdout.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let root = self.host_workspace.clone();
|
||||
let archive = tokio::task::spawn_blocking(move || tarball(&root))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
ShellError::Failed(format!("the workspace archive task failed: {err}"))
|
||||
})??;
|
||||
let Some(tar_gz_base64) = archive else {
|
||||
return Ok(());
|
||||
};
|
||||
sandbox
|
||||
.seed(&WorkspaceSeed::Tarball {
|
||||
name: "workspace.tar.gz".to_owned(),
|
||||
tar_gz_base64,
|
||||
})
|
||||
.await
|
||||
.map_err(protocol_error)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ShellExecutor for ClawShell {
|
||||
async fn run(
|
||||
&self,
|
||||
command: &str,
|
||||
cwd: &Path,
|
||||
timeout: Duration,
|
||||
cancelled: &AtomicBool,
|
||||
progress: &mut (dyn for<'a> FnMut(&'a str) + Send),
|
||||
) -> Result<Executed, ShellError> {
|
||||
let choice = self.state.choice();
|
||||
if !choice.is_remote() {
|
||||
return self
|
||||
.local
|
||||
.run(command, cwd, timeout, cancelled, progress)
|
||||
.await;
|
||||
}
|
||||
{
|
||||
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if last.as_ref() != Some(&choice) {
|
||||
*last = Some(choice.clone());
|
||||
self.seeded.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let sandbox = self.state.remote_sandbox(&choice, &self.host_workspace)?;
|
||||
if !self.seeded.load(Ordering::Relaxed) {
|
||||
self.seed(&sandbox, cancelled).await?;
|
||||
self.seeded.store(true, Ordering::Relaxed);
|
||||
}
|
||||
let sandbox: Arc<dyn Sandbox> = sandbox;
|
||||
ShellSandbox::new(sandbox)
|
||||
.run(
|
||||
command,
|
||||
Path::new(REMOTE_WORKSPACE),
|
||||
timeout,
|
||||
cancelled,
|
||||
progress,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a protocol failure onto the shell error the tool shapes into an
|
||||
/// `is_error` result.
|
||||
fn protocol_error(err: rhema_sandbox::SandboxError) -> ShellError {
|
||||
match err {
|
||||
rhema_sandbox::SandboxError::Timeout(secs) => ShellError::Timeout(secs),
|
||||
rhema_sandbox::SandboxError::Unavailable(message)
|
||||
| rhema_sandbox::SandboxError::Failed(message) => ShellError::Failed(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sandbox session name for one host workspace: a stable FNV-1a
|
||||
/// hash of the path, so the daemon can multiplex one root per session
|
||||
/// and a restart finds the same root.
|
||||
fn session_name(host: &Path) -> String {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for byte in host.to_string_lossy().as_bytes() {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
format!("rhema-claw-{hash:016x}")
|
||||
}
|
||||
|
||||
/// One host workspace as a gzipped tar, base64 for the protocol.
|
||||
/// `None` when the directory is missing or empty: nothing to seed.
|
||||
fn tarball(root: &Path) -> Result<Option<String>, ShellError> {
|
||||
if !root.is_dir() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut entries = std::fs::read_dir(root)
|
||||
.map_err(|err| ShellError::Failed(format!("cannot read the workspace {root:?}: {err}")))?;
|
||||
if entries.next().is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let output = std::process::Command::new("tar")
|
||||
.arg("-czf")
|
||||
.arg("-")
|
||||
.arg("-C")
|
||||
.arg(root)
|
||||
.arg(".")
|
||||
.output()
|
||||
.map_err(|err| {
|
||||
ShellError::Failed(format!("cannot archive the workspace with tar: {err}"))
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
let detail = String::from_utf8_lossy(&output.stderr);
|
||||
let detail = detail.trim();
|
||||
return Err(ShellError::Failed(if detail.is_empty() {
|
||||
"tar failed to archive the workspace".to_owned()
|
||||
} else {
|
||||
format!("tar failed to archive the workspace: {detail}")
|
||||
}));
|
||||
}
|
||||
Ok(Some(
|
||||
base64::engine::general_purpose::STANDARD.encode(output.stdout),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wiremock::matchers::{method, path_regex};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
fn state(choice: SandboxChoice) -> Arc<SandboxState> {
|
||||
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
|
||||
Arc::new(
|
||||
SandboxState::load(
|
||||
settings,
|
||||
Some(choice),
|
||||
PathBuf::from("/state/claw/workspaces/interactive"),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.expect("the state loads"),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_choice_is_local() {
|
||||
let choice = SandboxChoice::default().normalized().unwrap();
|
||||
assert_eq!(choice.kind, SandboxKind::Local);
|
||||
assert!(!choice.is_remote());
|
||||
assert_eq!(choice.kind.as_str(), "local");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_http_choice_needs_an_absolute_url() {
|
||||
let missing = SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: None,
|
||||
token: None,
|
||||
}
|
||||
.normalized();
|
||||
assert!(missing.is_err(), "a URL is required");
|
||||
|
||||
let relative = SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some("box.example:7600".to_owned()),
|
||||
token: None,
|
||||
}
|
||||
.normalized();
|
||||
assert!(relative.is_err(), "a bare host is not a URL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_remote_workspace_is_the_sandbox_root() {
|
||||
let state = state(SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some("http://box:7600/".to_owned()),
|
||||
token: None,
|
||||
});
|
||||
assert_eq!(state.workspace(), PathBuf::from(REMOTE_WORKSPACE));
|
||||
assert_eq!(
|
||||
state.choice().url.as_deref(),
|
||||
Some("http://box:7600"),
|
||||
"the trailing slash is trimmed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_choice_persists_and_reloads() {
|
||||
let settings = Arc::new(SettingsStore::in_memory().expect("the store opens"));
|
||||
let state = SandboxState::load(
|
||||
settings.clone(),
|
||||
None,
|
||||
PathBuf::from("/tmp/ws"),
|
||||
&BTreeMap::new(),
|
||||
)
|
||||
.expect("the state loads");
|
||||
assert_eq!(state.choice().kind, SandboxKind::Local);
|
||||
|
||||
state
|
||||
.set(SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some("https://box:7600".to_owned()),
|
||||
token: Some("secret".to_owned()),
|
||||
})
|
||||
.expect("the choice saves");
|
||||
|
||||
let reloaded =
|
||||
SandboxState::load(settings, None, PathBuf::from("/tmp/ws"), &BTreeMap::new())
|
||||
.expect("the state reloads");
|
||||
assert_eq!(reloaded.choice().kind, SandboxKind::Http);
|
||||
assert_eq!(reloaded.choice().url.as_deref(), Some("https://box:7600"));
|
||||
assert_eq!(reloaded.choice().token.as_deref(), Some("secret"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_remote_command_seeds_a_fresh_sandbox_and_runs() {
|
||||
let server = MockServer::start().await;
|
||||
// The emptiness probe: nothing at /workspace.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"exit_code": 0,
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"timed_out": false
|
||||
})))
|
||||
.up_to_n_times(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
// The command itself.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/exec$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"exit_code": 0,
|
||||
"stdout": "hi\n",
|
||||
"stderr": "",
|
||||
"timed_out": false
|
||||
})))
|
||||
.mount(&server)
|
||||
.await;
|
||||
// The seed: accepted, and the host workspace is not empty.
|
||||
Mock::given(method("POST"))
|
||||
.and(path_regex(r"^/rhema-claw-[0-9a-f]{16}/seed$"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"error": null
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
std::fs::write(dir.path().join("README.md"), "seed me").expect("the file writes");
|
||||
let state = state(SandboxChoice {
|
||||
kind: SandboxKind::Http,
|
||||
url: Some(server.uri()),
|
||||
token: None,
|
||||
});
|
||||
let executor = state.executor(dir.path());
|
||||
let cancelled = AtomicBool::new(false);
|
||||
let mut sink = |_line: &str| {};
|
||||
let executed = executor
|
||||
.run(
|
||||
"echo hi",
|
||||
Path::new(REMOTE_WORKSPACE),
|
||||
Duration::from_secs(5),
|
||||
&cancelled,
|
||||
&mut sink,
|
||||
)
|
||||
.await
|
||||
.expect("the remote command answers");
|
||||
assert_eq!(executed.stdout, b"hi\n");
|
||||
assert_eq!(executed.code, Some(0));
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
transcript: None,
|
||||
ingest_token: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
transcript: None,
|
||||
ingest_token: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ fn config(dir: &tempfile::TempDir, token: Option<&str>) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
ingest_token: None,
|
||||
transcript: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -2238,6 +2239,126 @@ async fn providers_gain_and_lose_backends_over_the_surface() {
|
||||
assert_eq!(gone.status(), 400);
|
||||
}
|
||||
|
||||
/// The sandbox surface: the default is this host, a remote choice
|
||||
/// persists across a rebuild, the token is write-only, and a choice
|
||||
/// without a URL or with an unknown kind is refused.
|
||||
#[tokio::test]
|
||||
async fn the_sandbox_choice_is_listed_and_switchable() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let daemon = Daemon::build(
|
||||
&config(&dir, None),
|
||||
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
|
||||
rhema_rsd::DispatcherConfig::default(),
|
||||
)
|
||||
.expect("the daemon assembles");
|
||||
let base = serve(&daemon).await;
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
let listed: Value = client
|
||||
.get(format!("{base}/v1/sandbox"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the sandbox reads")
|
||||
.json()
|
||||
.await
|
||||
.expect("the sandbox parses");
|
||||
assert_eq!(listed["kind"], "local");
|
||||
assert_eq!(listed["token_set"], false);
|
||||
assert_eq!(listed["remote_workspace"], "/workspace");
|
||||
assert!(
|
||||
listed["workspace"]
|
||||
.as_str()
|
||||
.is_some_and(|path| !path.is_empty())
|
||||
);
|
||||
|
||||
// A remote choice: the URL and token go in, the token never comes
|
||||
// back.
|
||||
let switched: Value = client
|
||||
.put(format!("{base}/v1/sandbox"))
|
||||
.json(&json!({
|
||||
"kind": "http",
|
||||
"url": "https://box.example:7600/",
|
||||
"token": "s3cret"
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the switch posts")
|
||||
.json()
|
||||
.await
|
||||
.expect("the switch parses");
|
||||
assert_eq!(switched["kind"], "http");
|
||||
assert_eq!(switched["url"], "https://box.example:7600");
|
||||
assert_eq!(switched["token_set"], true);
|
||||
assert_eq!(switched["workspace"], "/workspace");
|
||||
assert!(
|
||||
switched.get("token").is_none(),
|
||||
"the token stays write-only"
|
||||
);
|
||||
|
||||
// A remote choice without a URL is a 400, and an unknown kind too.
|
||||
let missing = client
|
||||
.put(format!("{base}/v1/sandbox"))
|
||||
.json(&json!({"kind": "http", "url": ""}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the refusal posts");
|
||||
assert_eq!(missing.status(), 400);
|
||||
let unknown = client
|
||||
.put(format!("{base}/v1/sandbox"))
|
||||
.json(&json!({"kind": "quantum"}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the refusal posts");
|
||||
assert_eq!(unknown.status(), 400);
|
||||
|
||||
// Back to this host: the remote fields stay staged for the next
|
||||
// switch, and the workspace path flips with the choice.
|
||||
let local: Value = client
|
||||
.put(format!("{base}/v1/sandbox"))
|
||||
.json(&json!({"kind": "local"}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the switch posts")
|
||||
.json()
|
||||
.await
|
||||
.expect("the switch parses");
|
||||
assert_eq!(local["kind"], "local");
|
||||
assert_eq!(local["token_set"], true);
|
||||
|
||||
// The persisted choice wins after a restart.
|
||||
drop(base);
|
||||
let daemon = Daemon::build(
|
||||
&config(&dir, None),
|
||||
mock_registry(Arc::new(MockProvider::new([reply("on it")]))),
|
||||
rhema_rsd::DispatcherConfig::default(),
|
||||
)
|
||||
.expect("the daemon rebuilds");
|
||||
let base = serve(&daemon).await;
|
||||
let reloaded: Value = client
|
||||
.get(format!("{base}/v1/sandbox"))
|
||||
.send()
|
||||
.await
|
||||
.expect("the sandbox reads")
|
||||
.json()
|
||||
.await
|
||||
.expect("the sandbox parses");
|
||||
assert_eq!(reloaded["kind"], "local");
|
||||
assert_eq!(reloaded["token_set"], true);
|
||||
|
||||
// `clear_token` drops the stored secret without moving the URL.
|
||||
let cleared: Value = client
|
||||
.put(format!("{base}/v1/sandbox"))
|
||||
.json(&json!({"kind": "local", "clear_token": true}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the clear posts")
|
||||
.json()
|
||||
.await
|
||||
.expect("the clear parses");
|
||||
assert_eq!(cleared["token_set"], false);
|
||||
assert_eq!(cleared["url"], "https://box.example:7600");
|
||||
}
|
||||
|
||||
/// The agent identity surface: the text fields round-trip with
|
||||
/// partial-save semantics (an absent field is left alone, an empty one
|
||||
/// clears), the avatar uploads and serves back with its content type,
|
||||
|
||||
@@ -66,6 +66,7 @@ fn config(dir: &tempfile::TempDir) -> ClawConfig {
|
||||
tools_bin: None,
|
||||
transcript: None,
|
||||
ingest_token: None,
|
||||
sandbox: None,
|
||||
disabled_mcp_servers: std::collections::BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user