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
Generated
+171
-3
@@ -411,6 +411,23 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
@@ -893,8 +910,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"wasi",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -904,8 +923,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1339,6 +1361,12 @@ version = "0.4.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
||||
|
||||
[[package]]
|
||||
name = "lru-slab"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
@@ -1673,6 +1701,62 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn"
|
||||
version = "0.11.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
"pin-project-lite",
|
||||
"quinn-proto",
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-proto"
|
||||
version = "0.11.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand 0.10.4",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quinn-udp"
|
||||
version = "0.5.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
@@ -1696,7 +1780,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"getrandom 0.4.3",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1706,7 +1801,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1718,6 +1813,21 @@ dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||
|
||||
[[package]]
|
||||
name = "rand_pcg"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df"
|
||||
dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.13.1"
|
||||
@@ -1772,6 +1882,8 @@ dependencies = [
|
||||
"native-tls",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"quinn",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1779,6 +1891,7 @@ dependencies = [
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-native-tls",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -1788,6 +1901,7 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-streams",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1846,6 +1960,7 @@ dependencies = [
|
||||
name = "rhema-claw"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
@@ -1865,6 +1980,8 @@ dependencies = [
|
||||
"rhema-provider",
|
||||
"rhema-provider-registry",
|
||||
"rhema-rsd",
|
||||
"rhema-sandbox",
|
||||
"rhema-sandbox-http",
|
||||
"rhema-transcript",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
@@ -2035,7 +2152,7 @@ dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"futures-util",
|
||||
"rand",
|
||||
"rand 0.8.8",
|
||||
"reqwest",
|
||||
"rhema-core",
|
||||
"rhema-provider",
|
||||
@@ -2175,6 +2292,34 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-sandbox"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4f35d9fcdee82dae2c455729d54aa19603c870da2d916f0dc115f2e8d8446181"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"rhema-agent-tools",
|
||||
"rhema-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-sandbox-http"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e14df93c046a0226941c8b59a86e9af305b8c91bde69b26790ce6534d71709a1"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"reqwest",
|
||||
"rhema-sandbox",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rhema-transcript"
|
||||
version = "0.3.0"
|
||||
@@ -2227,6 +2372,12 @@ dependencies = [
|
||||
"sqlite-wasm-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.6"
|
||||
@@ -2260,6 +2411,7 @@ version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||
dependencies = [
|
||||
"web-time",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -2665,6 +2817,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
@@ -3036,6 +3194,16 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web-time"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "1.0.12"
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ FROM debian:stable-slim
|
||||
# bash and git are load-bearing, not conveniences: the coding agent shells
|
||||
# out via `bash -c` and clones/fetches in its per-thread workspaces.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash git ca-certificates \
|
||||
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
|
||||
|
||||
@@ -67,7 +67,7 @@ FROM debian:stable-slim
|
||||
# load-bearing too: a `{git}` seed is a `git clone` (tarball seeds need
|
||||
# neither).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bash git ca-certificates \
|
||||
&& apt-get install -y --no-install-recommends bash git tar ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Numeric USER: Kubernetes cannot verify runAsNonRoot against a name.
|
||||
|
||||
+43
-1
@@ -17,6 +17,8 @@ import type {
|
||||
NewAccount,
|
||||
ProviderCredentials,
|
||||
ProvidersState,
|
||||
SandboxSelection,
|
||||
SandboxState,
|
||||
StreamStatus,
|
||||
} from '~/composables/useClaw'
|
||||
import { useTranscript } from '~/composables/useTranscript'
|
||||
@@ -58,7 +60,13 @@ const SETTINGS_SECTIONS: { label: string; entries: { id: string; label: string }
|
||||
],
|
||||
},
|
||||
{ label: 'Providers', entries: [{ id: 'providers', label: 'Model providers' }] },
|
||||
{ label: 'System', entries: [{ id: 'about', label: 'About' }] },
|
||||
{
|
||||
label: 'System',
|
||||
entries: [
|
||||
{ id: 'sandbox', label: 'Sandbox' },
|
||||
{ id: 'about', label: 'About' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
function parseHash(): Route {
|
||||
@@ -265,6 +273,8 @@ const mutatingIdentity = ref(false)
|
||||
const accounts = ref<ClawAccount[] | null>(null)
|
||||
const accountsLoading = ref(false)
|
||||
const mutatingAccounts = ref(false)
|
||||
const sandboxState = ref<SandboxState | null>(null)
|
||||
const savingSandbox = ref(false)
|
||||
const streamStatus = ref<StreamStatus>('connecting')
|
||||
const busy = ref(false)
|
||||
const authRequired = ref(false)
|
||||
@@ -499,6 +509,30 @@ async function removeProvider(id: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshSandbox(): Promise<void> {
|
||||
try {
|
||||
sandboxState.value = await claw.sandbox()
|
||||
apiError.value = null
|
||||
} catch (err) {
|
||||
noteApiError(err)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSandbox(choice: SandboxSelection): Promise<void> {
|
||||
savingSandbox.value = true
|
||||
try {
|
||||
sandboxState.value = await claw.setSandbox(choice)
|
||||
pushNotice(
|
||||
choice.kind === 'http' ? 'sandbox: remote host' : 'sandbox: this machine',
|
||||
)
|
||||
apiError.value = null
|
||||
} catch (err) {
|
||||
noteApiError(err)
|
||||
} finally {
|
||||
savingSandbox.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function send(message: { text: string; images: StagedImage[] }): Promise<void> {
|
||||
// The optimistic row renders the staged previews; the stream's
|
||||
// user_message echo carries the stored ids and dedupes against it.
|
||||
@@ -581,6 +615,7 @@ function saveToken(): void {
|
||||
void refreshSessions()
|
||||
void refreshIdentity()
|
||||
void refreshAccounts()
|
||||
void refreshSandbox()
|
||||
}
|
||||
|
||||
// --- the one live subscription ---------------------------------------
|
||||
@@ -657,6 +692,7 @@ onMounted(() => {
|
||||
void refreshIdentity()
|
||||
void refreshProviders()
|
||||
void refreshAccounts()
|
||||
void refreshSandbox()
|
||||
void refreshSessions()
|
||||
healthTimer = setInterval(checkHealth, 30000)
|
||||
sessionsTimer = setInterval(() => void refreshSessions(), 20000)
|
||||
@@ -789,6 +825,12 @@ onUnmounted(() => {
|
||||
@add="addProvider"
|
||||
@remove="removeProvider"
|
||||
/>
|
||||
<SettingsSandboxPage
|
||||
v-show="route.section === 'sandbox'"
|
||||
:state="sandboxState"
|
||||
:saving="savingSandbox"
|
||||
@save="saveSandbox"
|
||||
/>
|
||||
<SettingsAboutPage v-show="route.section === 'about'" :claw-up="clawUp" />
|
||||
</template>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
<script setup lang="ts">
|
||||
// The Sandbox page: where the agent's `bash` runs. The choice saves as
|
||||
// a whole; the token is write-only, so an empty field keeps whatever
|
||||
// the claw already stored. Presentational: data flows in as props,
|
||||
// intent flows up as events.
|
||||
import type { SandboxKind, SandboxSelection, SandboxState } from '~/composables/useClaw'
|
||||
|
||||
const props = defineProps<{
|
||||
state: SandboxState | null
|
||||
saving: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
save: [choice: SandboxSelection]
|
||||
}>()
|
||||
|
||||
const kind = ref<SandboxKind>('local')
|
||||
const url = ref('')
|
||||
const token = ref('')
|
||||
const clearToken = ref(false)
|
||||
|
||||
const dirty = computed(() => {
|
||||
const state = props.state
|
||||
if (!state) return false
|
||||
if (kind.value !== state.kind) return true
|
||||
if (kind.value !== 'http') return false
|
||||
const normalized = url.value.trim().replace(/\/+$/, '')
|
||||
if (normalized !== (state.url ?? '')) return true
|
||||
return token.value.trim() !== '' || clearToken.value
|
||||
})
|
||||
|
||||
const urlValid = computed(() => /^https?:\/\/.+/.test(url.value.trim()))
|
||||
|
||||
const ready = computed(() => kind.value !== 'http' || urlValid.value)
|
||||
|
||||
const urlHint = computed(() =>
|
||||
url.value.trim() && !urlValid.value
|
||||
? 'The URL must start with http:// or https://.'
|
||||
: 'The sandboxd base URL, for example https://box.example:7600.',
|
||||
)
|
||||
|
||||
function sync(): void {
|
||||
const state = props.state
|
||||
if (!state) return
|
||||
kind.value = state.kind
|
||||
url.value = state.url ?? ''
|
||||
token.value = ''
|
||||
clearToken.value = false
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.state,
|
||||
(state) => {
|
||||
if (state) sync()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
function discard(): void {
|
||||
sync()
|
||||
}
|
||||
|
||||
function save(): void {
|
||||
if (!dirty.value || props.saving || !ready.value) return
|
||||
const choice: SandboxSelection = { kind: kind.value }
|
||||
if (kind.value === 'http') {
|
||||
choice.url = url.value.trim()
|
||||
if (token.value.trim() !== '') {
|
||||
choice.token = token.value.trim()
|
||||
} else if (clearToken.value) {
|
||||
choice.clear_token = true
|
||||
}
|
||||
}
|
||||
emit('save', choice)
|
||||
}
|
||||
|
||||
// The path the staged choice would use, not the saved one.
|
||||
const workspacePath = computed(() => {
|
||||
const state = props.state
|
||||
if (!state) return ''
|
||||
return kind.value === 'http' ? state.remote_workspace : state.local_workspace
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<PageHeader title="Sandbox" subtitle="Where the agent's bash runs.">
|
||||
<template #actions>
|
||||
<button :disabled="!dirty || saving" @click="discard">Discard</button>
|
||||
<button class="primary" :disabled="!dirty || saving || !ready" @click="save">
|
||||
{{ saving ? 'Saving…' : 'Save' }}
|
||||
</button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="scroll">
|
||||
<p v-if="!state" class="muted">loading sandbox…</p>
|
||||
|
||||
<template v-else>
|
||||
<SettingCard title="Execution" meta="applies on the next turn">
|
||||
<label class="option" :class="{ selected: kind === 'local' }">
|
||||
<input v-model="kind" type="radio" value="local" :disabled="saving" />
|
||||
<span class="option-text">
|
||||
<span class="option-title">
|
||||
This machine
|
||||
<span v-if="state.kind === 'local'" class="current">current</span>
|
||||
</span>
|
||||
<span class="option-detail">
|
||||
Commands run as processes on the daemon's host.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label class="option" :class="{ selected: kind === 'http' }">
|
||||
<input v-model="kind" type="radio" value="http" :disabled="saving" />
|
||||
<span class="option-text">
|
||||
<span class="option-title">
|
||||
Remote sandbox
|
||||
<span v-if="state.kind === 'http'" class="current">current</span>
|
||||
</span>
|
||||
<span class="option-detail">
|
||||
Commands run on a host that speaks the sandbox protocol over HTTP.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</SettingCard>
|
||||
|
||||
<SettingCard v-if="kind === 'http'" title="Remote sandbox">
|
||||
<SettingRow
|
||||
title="URL"
|
||||
:description="urlHint"
|
||||
>
|
||||
<input
|
||||
v-model="url"
|
||||
type="text"
|
||||
class="mono"
|
||||
placeholder="https://box.example:7600"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="saving"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
title="Token"
|
||||
:description="state.token_set
|
||||
? 'A token is stored. Leave this blank to keep it.'
|
||||
: 'The shared secret the daemon checks. Leave it blank when the daemon has none.'"
|
||||
>
|
||||
<input
|
||||
v-model="token"
|
||||
type="password"
|
||||
:placeholder="state.token_set ? 'stored' : 'optional'"
|
||||
autocomplete="off"
|
||||
:disabled="saving || clearToken"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
v-if="state.token_set"
|
||||
title="Stored token"
|
||||
:description="clearToken
|
||||
? 'The stored token is removed when you save.'
|
||||
: 'The token stays in the settings table until you replace or forget it.'"
|
||||
>
|
||||
<button class="ghost" :disabled="saving" @click="clearToken = !clearToken">
|
||||
{{ clearToken ? 'Keep token' : 'Forget token' }}
|
||||
</button>
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
|
||||
<AppCallout v-if="kind === 'http'" variant="info" title="Remote commands start from a copy">
|
||||
On first use the claw sends the local workspace to the sandbox as a tarball.
|
||||
Later edits stay in the sandbox; the claw does not copy them back.
|
||||
</AppCallout>
|
||||
|
||||
<SettingCard title="Workspace">
|
||||
<SettingRow
|
||||
title="Path"
|
||||
description="Where the agent's bash starts under this choice."
|
||||
>
|
||||
<code>{{ workspacePath }}</code>
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.scroll {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0 24px 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
max-width: 860px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--text3);
|
||||
padding: 8px 2px;
|
||||
}
|
||||
|
||||
.option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 13px 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.option:hover {
|
||||
background: var(--elevated);
|
||||
}
|
||||
|
||||
.option.selected {
|
||||
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
|
||||
}
|
||||
|
||||
.option input[type='radio'] {
|
||||
flex: none;
|
||||
margin: 3px 0 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.option-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.option-title {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.option-detail {
|
||||
color: var(--text3);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.current {
|
||||
color: var(--accent-text);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@@ -220,6 +220,34 @@ export interface ActiveBackend {
|
||||
active: { provider: string; model: string }
|
||||
}
|
||||
|
||||
/** Where the agent's `bash` runs: this host or a daemon speaking the
|
||||
* sandbox protocol over HTTP. */
|
||||
export type SandboxKind = 'local' | 'http'
|
||||
|
||||
/** The sandbox state `GET /v1/sandbox` serves. The token never rides
|
||||
* the wire; `token_set` says whether one is stored. */
|
||||
export interface SandboxState {
|
||||
kind: SandboxKind
|
||||
url: string | null
|
||||
token_set: boolean
|
||||
/** Where `bash` starts under the current choice. */
|
||||
workspace: string
|
||||
/** The daemon's chat workspace, whatever the choice. */
|
||||
local_workspace: string
|
||||
/** The path a remote sandbox exposes. */
|
||||
remote_workspace: string
|
||||
}
|
||||
|
||||
/** The body `PUT /v1/sandbox` takes. `token` is write-only, and
|
||||
* `clear_token` drops the stored one. An omitted `url` keeps the
|
||||
* current one. */
|
||||
export interface SandboxSelection {
|
||||
kind: SandboxKind
|
||||
url?: string
|
||||
token?: string
|
||||
clear_token?: boolean
|
||||
}
|
||||
|
||||
/** A failed API call: the status plus the claw's `error` string when it sent one. */
|
||||
export class ClawError extends Error {
|
||||
/** HTTP status; 0 when the claw was unreachable at all. */
|
||||
@@ -383,6 +411,11 @@ export interface ClawApi {
|
||||
/** `DELETE /v1/providers/{id}` — remove a backend instance; answers
|
||||
* the new providers state. The last backend is refused claw-side. */
|
||||
removeProvider(id: string): Promise<ProvidersState>
|
||||
/** `GET /v1/sandbox`: where the agent's `bash` runs. */
|
||||
sandbox(): Promise<SandboxState>
|
||||
/** `PUT /v1/sandbox`: switch the sandbox, persisted claw-side. The
|
||||
* choice applies on the next turn. */
|
||||
setSandbox(choice: SandboxSelection): Promise<SandboxState>
|
||||
/** `GET /v1/accounts` — the stored accounts, redacted. */
|
||||
accounts(): Promise<ClawAccount[]>
|
||||
/** `POST /v1/accounts` — store an account (the secret is write-only),
|
||||
@@ -563,6 +596,18 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
})) as ProvidersState
|
||||
}
|
||||
|
||||
async function sandbox(): Promise<SandboxState> {
|
||||
return (await get('/v1/sandbox', token.value)) as SandboxState
|
||||
}
|
||||
|
||||
async function setSandbox(choice: SandboxSelection): Promise<SandboxState> {
|
||||
return (await send('/v1/sandbox', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...authHeaders(token.value) },
|
||||
body: JSON.stringify(choice),
|
||||
})) as SandboxState
|
||||
}
|
||||
|
||||
async function accounts(): Promise<ClawAccount[]> {
|
||||
const body = (await get('/v1/accounts', token.value)) as { accounts: ClawAccount[] }
|
||||
return body.accounts
|
||||
@@ -757,6 +802,8 @@ export function useClaw(token: Ref<string | null>): ClawApi {
|
||||
models,
|
||||
setCredentials,
|
||||
removeProvider,
|
||||
sandbox,
|
||||
setSandbox,
|
||||
accounts,
|
||||
addAccount,
|
||||
removeAccount,
|
||||
|
||||
Reference in new issue
Block a user