use crate::config::{FetchHtml, Policy, ToolsConfig};
use crate::plugins::{Hooks, Verdict};
use crate::tools_defer::matches_pattern;
use async_trait::async_trait;
use serde::Serialize;
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt};
fn json_pointer_token(name: &str) -> String {
name.replace('~', "~0").replace('/', "~1")
}
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
#[error("invalid arguments: {0}")]
InvalidArgs(String),
#[error("{0}")]
Failed(String),
#[error("{0}")]
Deferred(String),
}
#[async_trait]
pub trait Tool: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn parameters(&self) -> Value;
fn describe_call(&self, args: &Value) -> String {
format!("{} {}", self.name(), args)
}
fn needs_approval(&self, _args: &Value) -> bool {
true
}
async fn call(&self, args: Value) -> Result<String, ToolError>;
async fn call_scoped(&self, args: Value, _scope: &CallScope<'_>) -> Result<String, ToolError> {
self.call(args).await
}
}
#[derive(Default)]
pub struct RunScope {
pub session: String,
pub children: crate::tools_delegate::ChildLedger,
pub cancel: crate::cancel::Cancel,
}
impl RunScope {
pub fn new(session: &str) -> Self {
Self {
session: session.to_string(),
children: crate::tools_delegate::ChildLedger::default(),
cancel: crate::cancel::Cancel::new(),
}
}
pub fn cancellable(mut self, cancel: &crate::cancel::Cancel) -> Self {
self.cancel = cancel.clone();
self
}
}
pub struct CallScope<'a> {
pub approver: &'a dyn Approver,
pub run: &'a RunScope,
pub registry: &'a ToolRegistry,
pub call_id: Option<&'a str>,
}
#[async_trait]
pub trait Approver: Send + Sync {
async fn decide(&self, call: &crate::approvals::Pending) -> crate::approvals::Decision;
async fn approve(&self, tool: &str, summary: &str) -> bool {
matches!(
self.decide(&crate::approvals::Pending::new(
"",
tool,
summary.to_string(),
String::new()
))
.await,
crate::approvals::Decision::Allow
)
}
}
pub struct DenyAll;
pub struct AllowAll;
#[async_trait]
impl Approver for DenyAll {
async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
crate::approvals::Decision::Deny("this run approves nothing".to_string())
}
}
#[async_trait]
impl Approver for AllowAll {
async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
crate::approvals::Decision::Allow
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ToolSpec {
#[serde(rename = "type")]
pub kind: &'static str,
pub function: ToolSpecFunction,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ToolSpecFunction {
pub name: String,
pub description: String,
pub parameters: Value,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolSource {
Builtin,
Plugin(String),
Config(String),
Skill(String),
}
impl ToolSource {
pub fn label(&self) -> String {
match self {
Self::Builtin => "builtin".to_string(),
Self::Plugin(name) => format!("plugin:{name}"),
Self::Config(name) => format!("config:{name}"),
Self::Skill(name) => format!("skill:{name}"),
}
}
}
impl Serialize for ToolSource {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
s.serialize_str(&self.label())
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ToolDescriptor {
pub name: String,
pub description: String,
pub parameters: Value,
pub policy: Policy,
pub source: ToolSource,
pub advertised: bool,
pub deferred: bool,
pub disabled: bool,
}
pub const TOOL_SCHEMA_ID: &str = "urn:eclipse:tools";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolOutcome {
pub output: String,
pub is_error: bool,
pub malformed: bool,
pub deferred: bool,
}
impl ToolOutcome {
fn ok(output: String) -> Self {
Self {
output,
is_error: false,
malformed: false,
deferred: false,
}
}
fn err(output: impl Into<String>) -> Self {
Self {
output: output.into(),
is_error: true,
malformed: false,
deferred: false,
}
}
pub(crate) fn unusable(output: impl Into<String>) -> Self {
Self {
output: output.into(),
is_error: true,
malformed: true,
deferred: false,
}
}
pub(crate) fn awaiting(output: impl Into<String>) -> Self {
Self {
output: output.into(),
is_error: true,
malformed: false,
deferred: true,
}
}
}
struct Entry {
tool: Arc<dyn Tool>,
policy: Policy,
source: ToolSource,
disabled: bool,
deferred: bool,
}
pub struct ToolRegistry {
tools: BTreeMap<String, Entry>,
max_output_bytes: usize,
hooks: Hooks,
deferral: DeferralPolicies,
}
#[derive(Debug, Clone, Copy)]
struct DeferralPolicies {
search: Policy,
describe: Policy,
call: Policy,
}
impl Default for DeferralPolicies {
fn default() -> Self {
Self {
search: Policy::Allow,
describe: Policy::Allow,
call: Policy::Allow,
}
}
}
impl Default for ToolRegistry {
fn default() -> Self {
Self::new(32 * 1024)
}
}
impl ToolRegistry {
pub fn new(max_output_bytes: usize) -> Self {
Self {
tools: BTreeMap::new(),
max_output_bytes,
hooks: Hooks::default(),
deferral: DeferralPolicies::default(),
}
}
pub fn with_deferral_policies(mut self, cfg: &ToolsConfig) -> Self {
self.deferral = DeferralPolicies {
search: cfg.tool_search,
describe: cfg.tool_describe,
call: cfg.tool_call,
};
self
}
pub fn with_hooks(mut self, hooks: Hooks) -> Self {
self.hooks = hooks;
self
}
pub fn hooks(&self) -> &Hooks {
&self.hooks
}
pub fn max_output_bytes(&self) -> usize {
self.max_output_bytes
}
pub fn from_config(cfg: &ToolsConfig, workspace_root: PathBuf) -> Self {
Self::from_config_with(cfg, workspace_root, Vec::new())
}
pub fn from_config_with(
cfg: &ToolsConfig,
workspace_root: PathBuf,
skill_roots: Vec<crate::skills::Root>,
) -> Self {
Self::from_config_full(cfg, workspace_root, skill_roots, None)
}
pub fn from_config_full(
cfg: &ToolsConfig,
workspace_root: PathBuf,
skill_roots: Vec<crate::skills::Root>,
scripts_dir: Option<PathBuf>,
) -> Self {
let root = std::fs::canonicalize(&workspace_root).unwrap_or(workspace_root);
let mut r = Self::new(cfg.max_output_bytes);
r.register(
Arc::new(ReadFile {
root: root.clone(),
max_bytes: cfg.max_output_bytes,
}),
cfg.read_file,
);
r.register(
Arc::new(crate::tools_search::SearchFiles::new(
root.clone(),
cfg.max_output_bytes,
)),
cfg.search_files,
);
r.register(
Arc::new(
WriteFile::new(root.clone(), scripts_dir.clone())
.guard_bytes(cfg.rewrite_guard_bytes),
),
cfg.write_file,
);
r.register(
Arc::new(crate::tools_patch::Patch::new(WriteFile::new(
root.clone(),
scripts_dir.clone(),
))),
cfg.patch,
);
r.register(
Arc::new(Shell {
root: root.clone(),
skill_roots,
scripts_dir: scripts_dir.clone(),
sandbox: crate::sandbox::Sandbox::new(cfg, &root, scripts_dir.as_deref()),
timeout: Duration::from_secs(cfg.shell_timeout_secs),
allowlist: cfg.shell_allowlist.clone(),
max_bytes: cfg.max_output_bytes,
kill_grace: SHELL_KILL_GRACE,
ask: cfg.shell_ask,
}),
cfg.shell,
);
if let Some(dir) = scripts_dir {
r.register(
Arc::new(crate::tools_script::ScriptTool::new(
dir.clone(),
Duration::from_secs(cfg.shell_timeout_secs),
cfg.max_output_bytes,
)),
cfg.script,
);
r.register(
Arc::new(crate::tools_exec::ExecuteCode::new(
dir,
root.clone(),
Duration::from_secs(cfg.shell_timeout_secs),
cfg.max_output_bytes,
SHELL_KILL_GRACE,
)),
cfg.execute_code,
);
}
r.register(
Arc::new(
Fetch::new(
Duration::from_secs(cfg.fetch_timeout_secs),
cfg.max_output_bytes,
)
.with_html(cfg.fetch_html),
),
cfg.fetch,
);
r.with_deferral_policies(cfg)
}
pub fn register(&mut self, tool: Arc<dyn Tool>, policy: Policy) {
self.register_with_source(tool, policy, ToolSource::Builtin);
}
pub fn register_with_source(
&mut self,
tool: Arc<dyn Tool>,
policy: Policy,
source: ToolSource,
) {
self.tools.insert(
tool.name().to_string(),
Entry {
tool,
policy,
source,
disabled: false,
deferred: false,
},
);
}
pub fn disable(&mut self, names: &[String]) -> Vec<String> {
let mut unknown = Vec::new();
for name in names {
match self.tools.get_mut(name) {
Some(entry) => entry.disabled = true,
None => unknown.push(name.clone()),
}
}
unknown
}
pub fn defer(&mut self, patterns: &[String]) -> Vec<String> {
let mut unknown = Vec::new();
let mut deferred = Vec::new();
for pattern in patterns {
let matched: Vec<String> = self
.tools
.iter()
.filter(|(name, entry)| {
matches_pattern(pattern, name)
|| matches_pattern(pattern, &entry.source.label())
})
.map(|(name, _)| name.clone())
.collect();
if matched.is_empty() && !pattern.contains(':') {
unknown.push(pattern.clone());
}
deferred.extend(matched);
}
for name in &deferred {
if let Some(entry) = self.tools.get_mut(name) {
entry.deferred = true;
}
}
if !deferred.is_empty() {
self.register_deferral_tools();
}
unknown
}
fn register_deferral_tools(&mut self) {
for (tool, policy) in [
(
Arc::new(crate::tools_defer::ToolSearch) as Arc<dyn Tool>,
self.deferral_policy(crate::tools_defer::SEARCH),
),
(
Arc::new(crate::tools_defer::ToolDescribe) as Arc<dyn Tool>,
self.deferral_policy(crate::tools_defer::DESCRIBE),
),
(
Arc::new(crate::tools_defer::ToolCall) as Arc<dyn Tool>,
self.deferral_policy(crate::tools_defer::CALL),
),
] {
if !self.tools.contains_key(tool.name()) {
self.register(tool, policy);
}
}
}
fn deferral_policy(&self, name: &str) -> Policy {
match name {
crate::tools_defer::SEARCH => self.deferral.search,
crate::tools_defer::DESCRIBE => self.deferral.describe,
crate::tools_defer::CALL => self.deferral.call,
_ => Policy::Allow,
}
}
pub fn descriptors(&self) -> Vec<ToolDescriptor> {
self.tools
.iter()
.map(|(name, entry)| ToolDescriptor {
name: name.clone(),
description: entry.tool.description().to_string(),
parameters: entry.tool.parameters(),
policy: entry.policy,
source: entry.source.clone(),
advertised: !entry.disabled && entry.policy != Policy::Deny && !entry.deferred,
deferred: entry.deferred,
disabled: entry.disabled,
})
.collect()
}
pub fn advertised_names(&self) -> Vec<String> {
self.descriptors()
.into_iter()
.filter(|d| d.advertised)
.map(|d| d.name)
.collect()
}
pub fn schema_document(&self) -> Value {
let mut defs = serde_json::Map::new();
let mut branches = Vec::new();
for d in self.descriptors() {
let pointer = json_pointer_token(&d.name);
defs.insert(d.name.clone(), d.parameters.clone());
if !d.advertised {
continue;
}
branches.push(json!({
"type": "object",
"description": d.description,
"properties": {
"name": { "const": d.name },
"arguments": { "$ref": format!("#/$defs/{pointer}") },
},
"required": ["name", "arguments"],
"additionalProperties": false,
}));
}
json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": TOOL_SCHEMA_ID,
"title": "Eclipse tool calls",
"description": "One branch per tool the model is offered: `name` pins the tool and `arguments` is validated against its parameters schema in `$defs`.",
"oneOf": branches,
"$defs": defs,
})
}
pub fn names(&self) -> Vec<String> {
self.tools.keys().cloned().collect()
}
pub fn only(&self, names: &[&str]) -> ToolRegistry {
let mut out = ToolRegistry {
tools: BTreeMap::new(),
max_output_bytes: self.max_output_bytes,
hooks: self.hooks.clone(),
deferral: self.deferral,
};
for (name, entry) in &self.tools {
if !names.contains(&name.as_str()) {
continue;
}
out.tools.insert(
name.clone(),
Entry {
tool: Arc::clone(&entry.tool),
policy: entry.policy,
source: entry.source.clone(),
disabled: entry.disabled,
deferred: entry.deferred,
},
);
}
out
}
pub fn without(&self, names: &[&str]) -> ToolRegistry {
let mut out = ToolRegistry {
tools: BTreeMap::new(),
max_output_bytes: self.max_output_bytes,
hooks: self.hooks.clone(),
deferral: self.deferral,
};
for (name, entry) in &self.tools {
if names.contains(&name.as_str()) {
continue;
}
out.tools.insert(
name.clone(),
Entry {
tool: Arc::clone(&entry.tool),
policy: entry.policy,
source: entry.source.clone(),
disabled: entry.disabled,
deferred: entry.deferred,
},
);
}
if !out.tools.values().any(|e| e.deferred) {
for bridge in ["tool_search", "tool_describe", "tool_call"] {
out.tools.remove(bridge);
}
}
out
}
pub fn specs(&self) -> Vec<ToolSpec> {
self.descriptors()
.into_iter()
.filter(|d| d.advertised)
.map(|d| ToolSpec {
kind: "function",
function: ToolSpecFunction {
name: d.name,
description: d.description,
parameters: d.parameters,
},
})
.collect()
}
pub async fn dispatch(
&self,
name: &str,
raw_args: &str,
approver: &dyn Approver,
) -> ToolOutcome {
self.dispatch_call(name, raw_args, approver, None).await
}
pub fn summary_of(&self, name: &str, raw_args: &str) -> String {
let Some(entry) = self.tools.get(name) else {
return format!("{name} {raw_args}");
};
let args = serde_json::from_str(raw_args).unwrap_or_else(|_| serde_json::json!({}));
entry.tool.describe_call(&args)
}
pub async fn dispatch_call(
&self,
name: &str,
raw_args: &str,
approver: &dyn Approver,
call_id: Option<&str>,
) -> ToolOutcome {
self.dispatch_scoped(name, raw_args, approver, call_id, &RunScope::default())
.await
}
pub async fn dispatch_scoped(
&self,
name: &str,
raw_args: &str,
approver: &dyn Approver,
call_id: Option<&str>,
run: &RunScope,
) -> ToolOutcome {
let Some(entry) = self.tools.get(name) else {
return ToolOutcome::unusable(format!("unknown tool `{name}`"));
};
let args: Value = if raw_args.trim().is_empty() {
json!({})
} else {
match serde_json::from_str(raw_args) {
Ok(v) => v,
Err(e) => {
return ToolOutcome::unusable(format!("arguments are not valid JSON: {e}"))
}
}
};
if entry.disabled {
return ToolOutcome::err(format!(
"tool `{name}` is disabled in the config (`[tools] disabled`)"
));
}
if entry.policy == Policy::Deny {
return ToolOutcome::err(format!("tool `{name}` is disabled by policy"));
}
if let Verdict::Deny(reason) = self.hooks.before(name, &args, call_id).await {
return self
.hooks
.after(name, &args, ToolOutcome::err(reason), call_id)
.await;
}
if entry.policy == Policy::Ask && entry.tool.needs_approval(&args) {
let summary = entry.tool.describe_call(&args);
let pending = crate::approvals::Pending::new(
call_id.unwrap_or_default(),
name,
summary.clone(),
raw_args.to_string(),
);
match approver.decide(&pending).await {
crate::approvals::Decision::Allow => {}
crate::approvals::Decision::Deny(reason) => {
return ToolOutcome::err(format!(
"the user declined to run `{name}`: {reason}"
));
}
crate::approvals::Decision::Defer => {
return ToolOutcome::awaiting(format!(
"`{name}` is not approved yet; the call is waiting for an answer"
));
}
}
}
let scope = CallScope {
approver,
run,
registry: self,
call_id,
};
let outcome = match entry.tool.call_scoped(args.clone(), &scope).await {
Ok(out) => ToolOutcome::ok(out),
Err(ToolError::Deferred(message)) => ToolOutcome::awaiting(message),
Err(e) => ToolOutcome::err(e.to_string()),
};
self.hooks.after(name, &args, outcome, call_id).await
}
}
pub fn truncate(mut s: String, max: usize) -> String {
if s.len() <= max {
return s;
}
let mut cut = max;
while !s.is_char_boundary(cut) {
cut -= 1;
}
let mut floor = cut.saturating_sub(200);
while !s.is_char_boundary(floor) {
floor += 1;
}
if let Some(at) = s[floor..cut]
.rfind(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ',' | ';' | '>' | '=' | '&'))
{
cut = floor + at;
}
s.truncate(cut);
s.push_str("\n[output truncated]");
s
}
pub(crate) fn str_arg<'a>(args: &'a Value, key: &str) -> Result<&'a str, ToolError> {
args.get(key)
.and_then(Value::as_str)
.ok_or_else(|| ToolError::InvalidArgs(format!("missing string field `{key}`")))
}
pub(crate) fn replace_file(path: &Path, content: &str) -> Result<(), ToolError> {
let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let mode = std::fs::metadata(&target).ok().map(|m| m.permissions());
let mut tmp = target.as_os_str().to_owned();
tmp.push(format!(".tmp{}", std::process::id()));
let tmp = PathBuf::from(tmp);
let wrote = std::fs::write(&tmp, content);
let wrote = match (wrote, mode) {
(Ok(()), Some(mode)) => std::fs::set_permissions(&tmp, mode),
(wrote, _) => wrote,
};
wrote
.and_then(|_| std::fs::rename(&tmp, &target))
.map_err(|e| {
let _ = std::fs::remove_file(&tmp);
ToolError::Failed(format!("cannot write {}: {e}", path.display()))
})
}
fn normalize(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::ParentDir => {
out.pop();
}
Component::CurDir => {}
other => out.push(other.as_os_str()),
}
}
out
}
pub fn confine(root: &Path, requested: &str) -> Result<PathBuf, ToolError> {
let joined = normalize(&root.join(requested));
let mut existing = joined.as_path();
while std::fs::symlink_metadata(existing).is_err() {
existing = existing
.parent()
.ok_or_else(|| ToolError::Failed("path has no existing ancestor".into()))?;
}
let canon = std::fs::canonicalize(existing)
.map_err(|e| ToolError::Failed(format!("cannot resolve path: {e}")))?;
if !canon.starts_with(root) {
return Err(ToolError::Failed(format!(
"path `{requested}` is outside the workspace"
)));
}
Ok(joined)
}
pub struct ReadFile {
root: PathBuf,
max_bytes: usize,
}
#[async_trait]
impl Tool for ReadFile {
fn name(&self) -> &str {
"read_file"
}
fn description(&self) -> &str {
"Read a UTF-8 text file inside the workspace."
}
fn parameters(&self) -> Value {
json!({"type":"object","properties":{"path":{"type":"string","description":"Path relative to the workspace"}},"required":["path"]})
}
fn describe_call(&self, args: &Value) -> String {
format!("read file {}", args["path"].as_str().unwrap_or("?"))
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let path = confine(&self.root, str_arg(&args, "path")?)?;
let fail = |e: std::io::Error| ToolError::Failed(format!("{}: {e}", path.display()));
let meta = tokio::fs::metadata(&path).await.map_err(fail)?;
if !meta.is_file() {
return Err(ToolError::Failed(format!(
"{}: not a regular file",
path.display()
)));
}
let file = tokio::fs::File::open(&path).await.map_err(fail)?;
let mut buf = Vec::new();
file.take(self.max_bytes as u64 + 1)
.read_to_end(&mut buf)
.await
.map_err(fail)?;
let cut = buf.len() > self.max_bytes;
match String::from_utf8(buf) {
Ok(text) => Ok(text),
Err(e) if cut && e.utf8_error().error_len().is_none() => {
let valid = e.utf8_error().valid_up_to();
let mut bytes = e.into_bytes();
bytes.truncate(valid);
Ok(format!("{}\u{FFFD}", String::from_utf8_lossy(&bytes)))
}
Err(_) => Err(ToolError::Failed(format!(
"{}: not valid UTF-8",
path.display()
))),
}
}
}
pub struct WriteFile {
root: PathBuf,
scripts: Option<PathBuf>,
description: String,
guard_bytes: usize,
}
impl WriteFile {
pub(crate) fn new(root: PathBuf, scripts: Option<PathBuf>) -> Self {
let description = match &scripts {
None => format!(
"Create or overwrite a text file inside the workspace ({}). A path outside it is \
refused, so a file that belongs elsewhere is written here and moved with `shell`. To change part \
of a file that already exists, use `patch`: a rewrite carries the whole file, and the whole file \
stays in the conversation afterwards.",
root.display()
),
Some(dir) => format!(
"Create or overwrite a text file inside the workspace ({}), or inside the scripts \
directory ({}) which takes an absolute path. A path outside both is refused. A script written \
there is not executable until you run `chmod +x` on it with `shell`; see the `script` tool. To \
change part of a file that already exists, use `patch`: a rewrite carries the whole file, and the \
whole file stays in the conversation afterwards.",
root.display(),
dir.display()
),
};
Self {
root,
scripts,
description,
guard_bytes: 0,
}
}
pub(crate) fn guard_bytes(mut self, bytes: usize) -> Self {
self.guard_bytes = bytes;
self
}
fn relative_to_scripts(&self, joined: &Path) -> Option<PathBuf> {
let dir = normalize(self.scripts.as_deref()?);
let canon = std::fs::canonicalize(&dir).ok();
std::iter::once(dir)
.chain(canon)
.find_map(|d| joined.strip_prefix(d).ok().map(Path::to_path_buf))
}
pub(crate) fn resolve(&self, requested: &str) -> Result<PathBuf, ToolError> {
let in_workspace = confine(&self.root, requested);
let Some(scripts) = &self.scripts else {
return in_workspace;
};
if let Ok(path) = in_workspace {
return Ok(path);
}
let outside = || {
ToolError::Failed(format!(
"path `{requested}` is outside the workspace ({}) and outside the scripts \
directory ({})",
self.root.display(),
scripts.display()
))
};
let joined = normalize(&self.root.join(requested));
let rest = self.relative_to_scripts(&joined).ok_or_else(outside)?;
let rest = rest.to_str().ok_or_else(outside)?;
std::fs::create_dir_all(scripts)
.map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
let canon = std::fs::canonicalize(scripts)
.map_err(|e| ToolError::Failed(format!("{}: {e}", scripts.display())))?;
confine(&canon, rest).map_err(|_| outside())
}
}
#[async_trait]
impl Tool for WriteFile {
fn name(&self) -> &str {
"write_file"
}
fn description(&self) -> &str {
&self.description
}
fn parameters(&self) -> Value {
let path = match &self.scripts {
Some(dir) => format!(
"Path relative to the workspace ({}), or an absolute path inside the scripts \
directory ({})",
self.root.display(),
dir.display()
),
None => format!("Path relative to the workspace ({})", self.root.display()),
};
json!({"type":"object","properties":{
"path":{"type":"string","description":path},
"content":{"type":"string"},
"force":{"type":"boolean","description":"Replace an existing file even if it is large. A rewrite sends the whole file and it stays in the conversation; `patch` changes only the lines you name. Default false."}
},"required":["path","content"]})
}
fn describe_call(&self, args: &Value) -> String {
let path = args["path"].as_str().unwrap_or("?");
let joined = normalize(&self.root.join(path));
let in_scripts =
!joined.starts_with(&self.root) && self.relative_to_scripts(&joined).is_some();
format!(
"write {} bytes to {path}{}",
args["content"].as_str().map(str::len).unwrap_or(0),
if in_scripts {
" (scripts directory)"
} else {
""
}
)
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let content = str_arg(&args, "content")?;
let path = self.resolve(str_arg(&args, "path")?)?;
if self.guard_bytes > 0 && !args["force"].as_bool().unwrap_or(false) {
if let Ok(meta) = tokio::fs::metadata(&path).await {
let existing = meta.len() as usize;
if existing >= self.guard_bytes {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string());
return Err(ToolError::Failed(format!(
"refused: {name} already exists at {} bytes. Rewriting it means sending all \
{existing} bytes again, and they stay in the conversation for the rest of the session. Use \
`patch` for the lines you want to change — that carries only those lines — or call write_file \
again with `force: true` if the file really has to be replaced whole.",
existing
)));
}
}
}
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e| ToolError::Failed(format!("{}: {e}", parent.display())))?;
}
tokio::fs::write(&path, content)
.await
.map_err(|e| ToolError::Failed(format!("{}: {e}", path.display())))?;
Ok(format!(
"wrote {} bytes to {}",
content.len(),
path.display()
))
}
}
pub struct Shell {
root: PathBuf,
skill_roots: Vec<crate::skills::Root>,
scripts_dir: Option<PathBuf>,
timeout: Duration,
allowlist: Vec<String>,
max_bytes: usize,
kill_grace: Duration,
sandbox: crate::sandbox::Sandbox,
ask: crate::config::ShellAsk,
}
pub(crate) const SHELL_KILL_GRACE: Duration = Duration::from_secs(2);
#[cfg(unix)]
pub(crate) mod pgroup {
use std::time::{Duration, Instant};
fn signal(pgid: u32, sig: libc::c_int) {
if let Ok(pgid) = libc::pid_t::try_from(pgid) {
unsafe { libc::kill(-pgid, sig) };
}
}
fn signal_pid(pid: u32, sig: libc::c_int) {
if let Ok(pid) = libc::pid_t::try_from(pid) {
unsafe { libc::kill(pid, sig) };
}
}
fn descendants(root: u32) -> Vec<u32> {
let mut parent_of: Vec<(u32, u32)> = Vec::new();
let Ok(entries) = std::fs::read_dir("/proc") else {
return Vec::new();
};
for entry in entries.flatten() {
let Some(pid) = entry
.file_name()
.to_str()
.and_then(|s| s.parse::<u32>().ok())
else {
continue;
};
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
continue;
};
let Some((_, rest)) = stat.rsplit_once(')') else {
continue;
};
let Some(ppid) = rest
.split_whitespace()
.nth(1)
.and_then(|s| s.parse::<u32>().ok())
else {
continue;
};
parent_of.push((pid, ppid));
}
let mut out = Vec::new();
let mut frontier = vec![root];
while let Some(parent) = frontier.pop() {
for (pid, ppid) in &parent_of {
if *ppid == parent && !out.contains(pid) {
out.push(*pid);
frontier.push(*pid);
}
}
}
out
}
fn stop_tree(pgid: u32, sig: libc::c_int, tree: &[u32]) {
signal(pgid, sig);
for pid in tree {
signal_pid(*pid, sig);
}
}
fn alive(pgid: u32) -> bool {
let Ok(pgid) = libc::pid_t::try_from(pgid) else {
return false;
};
let rc = unsafe { libc::kill(-pgid, 0) };
rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
pub async fn terminate(child: &mut tokio::process::Child, pgid: u32, grace: Duration) {
let tree = descendants(pgid);
stop_tree(pgid, libc::SIGTERM, &tree);
let deadline = Instant::now() + grace;
loop {
let _ = child.try_wait();
if !alive(pgid) && tree.iter().all(|pid| !alive_pid(*pid)) {
return;
}
if Instant::now() >= deadline {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
let mut late = descendants(pgid);
late.extend(tree);
late.sort_unstable();
late.dedup();
stop_tree(pgid, libc::SIGKILL, &late);
let _ = child.wait().await;
}
fn alive_pid(pid: u32) -> bool {
let Ok(pid) = libc::pid_t::try_from(pid) else {
return false;
};
let rc = unsafe { libc::kill(pid, 0) };
rc == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
pub(crate) fn kill_now(pgid: u32) {
let tree = descendants(pgid);
stop_tree(pgid, libc::SIGKILL, &tree);
}
pub struct Guard(Option<u32>);
impl Guard {
pub fn new(pgid: Option<u32>) -> Self {
Self(pgid)
}
pub fn disarm(&mut self) {
self.0 = None;
}
}
impl Drop for Guard {
fn drop(&mut self) {
if let Some(pgid) = self.0 {
stop_tree(pgid, libc::SIGKILL, &descendants(pgid));
}
}
}
}
#[cfg(not(unix))]
mod pgroup {
use std::time::Duration;
pub async fn terminate(child: &mut tokio::process::Child, _: u32, _: Duration) {
let _ = child.kill().await;
}
pub struct Guard;
impl Guard {
pub fn new(_: Option<u32>) -> Self {
Self
}
pub fn disarm(&mut self) {}
}
}
pub(crate) struct Drain {
buf: Arc<std::sync::Mutex<Vec<u8>>>,
cap: usize,
cut: Arc<std::sync::atomic::AtomicBool>,
task: tokio::task::JoinHandle<()>,
}
impl Drain {
pub(crate) fn start<R: AsyncRead + Unpin + Send + 'static>(
pipe: Option<R>,
cap: usize,
) -> Self {
let buf = Arc::new(std::sync::Mutex::new(Vec::new()));
let cut = Arc::new(std::sync::atomic::AtomicBool::new(false));
let task = tokio::spawn(drain_into(pipe, cap, buf.clone(), cut.clone()));
Self {
buf,
cap,
cut,
task,
}
}
pub(crate) fn take(&self) -> (String, bool) {
let buf = self
.buf
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let short = self.cut.load(std::sync::atomic::Ordering::SeqCst) || buf.len() > self.cap;
let text = String::from_utf8_lossy(&buf[..buf.len().min(self.cap)]).into_owned();
(text, short)
}
}
impl Drop for Drain {
fn drop(&mut self) {
self.task.abort();
}
}
pub(crate) async fn read_capped<R: AsyncRead + Unpin + Send + 'static>(
pipe: Option<R>,
cap: usize,
) -> (String, bool) {
let mut drain = Drain::start(pipe, cap);
let _ = (&mut drain.task).await;
drain.take()
}
async fn drain_into<R: AsyncRead + Unpin>(
pipe: Option<R>,
cap: usize,
buf: Arc<std::sync::Mutex<Vec<u8>>>,
cut: Arc<std::sync::atomic::AtomicBool>,
) {
let Some(mut pipe) = pipe else { return };
let mut chunk = [0u8; 8192];
loop {
let room = (cap + 1).saturating_sub(buf.lock().map(|b| b.len()).unwrap_or(0));
if room == 0 {
cut.store(true, std::sync::atomic::Ordering::SeqCst);
return;
}
let want = room.min(chunk.len());
match pipe.read(&mut chunk[..want]).await {
Ok(0) => return,
Ok(n) => {
if let Ok(mut buf) = buf.lock() {
buf.extend_from_slice(&chunk[..n]);
}
}
Err(_) => return,
}
}
}
const SHELL_META: &[char] = &[
';', '&', '|', '<', '>', '$', '`', '\n', '(', ')', '\\', '"', '\'', '*', '?',
];
fn looks_backgrounded(command: &str) -> bool {
if ["nohup", "setsid", "disown"]
.iter()
.any(|word| command.contains(word))
{
return true;
}
let bytes = command.as_bytes();
for (i, &c) in bytes.iter().enumerate() {
if c != b'&' {
continue;
}
let next = bytes.get(i + 1).copied().unwrap_or(b' ');
let prev = if i == 0 { b' ' } else { bytes[i - 1] };
if next == b'&' || prev == b'&' || next == b'>' || prev == b'>' {
continue;
}
return true;
}
false
}
impl Shell {
fn build_command(
&self,
command: &str,
dir: &Path,
) -> Result<tokio::process::Command, ToolError> {
let (program, args) = self.program_argv(command)?;
let plan = self.sandbox.plan(&program, &args, dir)?;
let mut c = tokio::process::Command::new(plan.program);
c.args(plan.args);
if let Some(dir) = &self.scripts_dir {
c.env(crate::tools_script::ENV_SCRIPTS_DIR, dir);
if self.allowlist.is_empty() {
if let Some(path) = crate::tools_script::path_with(dir) {
c.env("PATH", path);
}
}
}
Ok(c)
}
fn program_argv(&self, command: &str) -> Result<(OsString, Vec<OsString>), ToolError> {
if self.allowlist.is_empty() {
return Ok((OsString::from("sh"), vec!["-c".into(), command.into()]));
}
if command.contains(SHELL_META) {
return Err(ToolError::Failed(
"shell syntax is not allowed when shell_allowlist is set".into(),
));
}
let mut parts = command.split_whitespace();
let prog = parts
.next()
.ok_or_else(|| ToolError::InvalidArgs("empty command".into()))?;
if !self.allowlist.iter().any(|a| a == prog) {
return Err(ToolError::Failed(format!(
"`{prog}` is not in shell_allowlist"
)));
}
Ok((
OsString::from(prog),
parts.map(OsString::from).collect::<Vec<_>>(),
))
}
fn working_dir(&self, requested: Option<&str>) -> Result<PathBuf, ToolError> {
let Some(requested) = requested else {
return Ok(self.root.clone());
};
let refuse = |why: String| ToolError::Failed(format!("cwd `{requested}` refused: {why}"));
if requested.trim().is_empty() {
return Err(refuse("it is empty".into()));
}
let resolved = std::fs::canonicalize(self.root.join(requested))
.map_err(|e| refuse(format!("it cannot be resolved ({e})")))?;
if !resolved.is_dir() {
return Err(refuse(format!("{} is not a directory", resolved.display())));
}
if resolved.starts_with(&self.root) {
return Ok(resolved);
}
let inside_scripts = self
.scripts_dir
.as_ref()
.and_then(|dir| std::fs::canonicalize(dir).ok())
.is_some_and(|dir| resolved.starts_with(dir));
if inside_scripts {
return Ok(resolved);
}
let report = crate::skills::discover(&self.skill_roots);
let inside_a_skill = report.active().any(|(found, _)| {
std::fs::canonicalize(&found.dir).is_ok_and(|dir| resolved.starts_with(dir))
});
if inside_a_skill {
return Ok(resolved);
}
let scripts = self.scripts_dir.as_ref().map_or(String::new(), |dir| {
format!(", outside the scripts directory ({})", dir.display())
});
Err(refuse(format!(
"it resolves to {}, which is outside the workspace ({}){scripts} and outside every skill's directory",
resolved.display(),
self.root.display()
)))
}
fn afterwards(&self, command: &str, out: String) -> String {
if self.sandbox.degraded() {
return format!(
"{out}\n\n[shell_isolate = \"process\": bubblewrap (`bwrap`) is not on PATH, so this \
command ran uncontained — with your files, your network, and anything it started \
still running after it returned. Installing bubblewrap contains it.]"
);
}
if !self.sandbox.is_on() || !looks_backgrounded(command) {
return out;
}
format!(
"{out}\n\n[shell_isolate = \"{}\": anything this command started in the background \
was stopped when it returned, because the run's PID namespace dies with it. Set \
[tools] shell_isolate = \"off\" for this profile if a process has to outlive the \
call.]",
self.sandbox.mode()
)
}
}
#[async_trait]
impl Tool for Shell {
fn name(&self) -> &str {
"shell"
}
fn needs_approval(&self, args: &Value) -> bool {
if self.ask == crate::config::ShellAsk::Always {
return true;
}
match args["command"].as_str() {
Some(command) => crate::risk::danger(command).is_some(),
None => false,
}
}
fn description(&self) -> &str {
"Run a command in the workspace directory and return its exit code, stdout and stderr. \
Pass `cwd` to run it somewhere else inside the workspace, inside the scripts directory, or \
inside a skill's own directory (to run that skill's `bash scripts/x.sh` as written); any other \
directory is refused. The scripts directory is first on `PATH` (unless a shell allowlist is set) \
and named in `ECLIPSE_SCRIPTS_DIR`, so a script there runs as a bare command."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"command": {"type": "string"},
"cwd": {
"type": "string",
"description": "Directory to run in: relative to the workspace, or absolute. It must resolve inside the workspace, the scripts directory or a skill's directory."
}
},
"required": ["command"]
})
}
fn describe_call(&self, args: &Value) -> String {
let command = args["command"].as_str().unwrap_or("?");
match args["cwd"].as_str() {
Some(cwd) => format!("run `{command}` in {cwd}"),
None => format!("run `{command}`"),
}
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let command = str_arg(&args, "command")?;
let cwd = match args.get("cwd") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(s.as_str()),
Some(_) => return Err(ToolError::InvalidArgs("`cwd` must be a string".into())),
};
let dir = self.working_dir(cwd)?;
let mut cmd = self.build_command(command, &dir)?;
cmd.current_dir(&dir);
let out = run_to_completion(cmd, self.timeout, self.max_bytes, self.kill_grace).await?;
Ok(self.afterwards(command, out))
}
}
pub(crate) async fn start_retrying<F>(mut build: F, max_bytes: usize) -> Result<Running, ToolError>
where
F: FnMut() -> tokio::process::Command,
{
let mut attempt = 0u32;
loop {
match start(build(), max_bytes) {
Ok(running) => return Ok(running),
Err(e) if attempt < 4 && is_text_busy(&e) => {
attempt += 1;
tokio::time::sleep(Duration::from_millis(1 << attempt)).await;
}
Err(e) => return Err(ToolError::Failed(crate::tools_script::start_error(&e))),
}
}
}
#[cfg(unix)]
fn is_text_busy(e: &std::io::Error) -> bool {
e.raw_os_error() == Some(libc::ETXTBSY)
}
#[cfg(not(unix))]
fn is_text_busy(_: &std::io::Error) -> bool {
false
}
pub(crate) async fn run_built<F>(
mut build: F,
timeout: Duration,
max_bytes: usize,
kill_grace: Duration,
) -> Result<String, ToolError>
where
F: FnMut() -> tokio::process::Command,
{
let mut running = start_retrying(&mut build, max_bytes).await?;
let status = match tokio::time::timeout(timeout, running.wait()).await {
Ok(done) => done?,
Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
};
Ok(running.finish(status).await)
}
pub(crate) async fn run_to_completion(
cmd: tokio::process::Command,
timeout: Duration,
max_bytes: usize,
kill_grace: Duration,
) -> Result<String, ToolError> {
let mut running = spawn(cmd, max_bytes)?;
let status = match tokio::time::timeout(timeout, running.wait()).await {
Ok(done) => done?,
Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
};
Ok(running.finish(status).await)
}
const DRAIN_GRACE: Duration = Duration::from_millis(500);
pub(crate) struct Running {
guard: pgroup::Guard,
pgid: Option<u32>,
pub(crate) child: tokio::process::Child,
out: Drain,
err: Drain,
}
pub(crate) fn spawn(cmd: tokio::process::Command, max_bytes: usize) -> Result<Running, ToolError> {
start(cmd, max_bytes).map_err(|e| ToolError::Failed(crate::tools_script::start_error(&e)))
}
pub(crate) fn start(
mut cmd: tokio::process::Command,
max_bytes: usize,
) -> std::io::Result<Running> {
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true);
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd.spawn()?;
let pgid = child.id();
let guard = pgroup::Guard::new(pgid);
let (stdout, stderr) = (child.stdout.take(), child.stderr.take());
let out = Drain::start(stdout, max_bytes);
let err = Drain::start(stderr, max_bytes);
Ok(Running {
guard,
pgid,
child,
out,
err,
})
}
impl Running {
pub(crate) async fn wait(&mut self) -> Result<std::process::ExitStatus, ToolError> {
match self.child.wait().await {
Ok(status) => {
self.guard.disarm();
Ok(status)
}
Err(e) => Err(ToolError::Failed(format!("failed to wait: {e}"))),
}
}
pub(crate) async fn timed_out(&mut self, timeout: Duration, kill_grace: Duration) -> ToolError {
if let Some(pgid) = self.pgid {
pgroup::terminate(&mut self.child, pgid, kill_grace).await;
}
self.guard.disarm();
ToolError::Failed(format!("timed out after {}s", timeout.as_secs()))
}
pub(crate) async fn finish(mut self, status: std::process::ExitStatus) -> String {
self.guard.disarm();
let stalled = tokio::time::timeout(DRAIN_GRACE, async {
let _ = (&mut self.out.task).await;
let _ = (&mut self.err.task).await;
})
.await
.is_err();
if stalled {
self.out.task.abort();
self.err.task.abort();
}
let (out, out_cut) = self.out.take();
let (err, err_cut) = self.err.take();
let note = |cut| if cut { "\n[truncated]" } else { "" };
let held = if stalled {
"\n[a process the command started still holds its output pipe; this call did not wait \
for it]"
} else {
""
};
format!(
"exit code: {}\nstdout:\n{out}{}\nstderr:\n{err}{}{held}",
status.code().map_or("signal".into(), |c| c.to_string()),
note(out_cut),
note(err_cut),
)
}
}
const HTML_READ_FACTOR: usize = 8;
pub struct Fetch {
timeout: Duration,
max_bytes: usize,
html: FetchHtml,
#[cfg(test)]
allow_internal: bool,
}
impl Fetch {
pub fn new(timeout: Duration, max_bytes: usize) -> Self {
Self {
timeout,
max_bytes,
html: FetchHtml::Text,
#[cfg(test)]
allow_internal: false,
}
}
pub fn with_html(mut self, html: FetchHtml) -> Self {
self.html = html;
self
}
fn reach(&self) -> crate::http::Reach {
#[cfg(test)]
if self.allow_internal {
return crate::http::Reach::Anywhere;
}
crate::http::Reach::Public
}
}
#[async_trait]
impl Tool for Fetch {
fn name(&self) -> &str {
"fetch"
}
fn description(&self) -> &str {
"HTTP GET a public http(s) URL and return the response body as text. HTML pages are \
converted to approximate plain text unless `raw` is true. \
Private, loopback and link-local hosts are blocked."
}
fn parameters(&self) -> Value {
json!({"type":"object","properties":{
"url":{"type":"string"},
"raw":{"type":"boolean","description":"return HTML source instead of converted text"}
},"required":["url"]})
}
fn describe_call(&self, args: &Value) -> String {
format!("GET {}", args["url"].as_str().unwrap_or("?"))
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let raw = str_arg(&args, "url")?;
let url = reqwest::Url::parse(raw)
.map_err(|e| ToolError::InvalidArgs(format!("invalid URL: {e}")))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(ToolError::InvalidArgs(
"only http(s) URLs are allowed".into(),
));
}
let mut resp = crate::http::get(&url, self.timeout, self.reach(), &[])
.await
.map_err(ToolError::Failed)?;
let status = resp.status();
let location = resp
.headers()
.get(reqwest::header::LOCATION)
.map(|v| format!("location: {}\n", String::from_utf8_lossy(v.as_bytes())))
.unwrap_or_default();
let content_type = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let want_raw = match args.get("raw").and_then(Value::as_bool) {
Some(raw) => raw,
None => self.html == FetchHtml::Raw,
};
let declared_html = content_type
.as_deref()
.is_some_and(|c| c.to_ascii_lowercase().contains("html"));
let limit = if declared_html && !want_raw {
self.max_bytes.saturating_mul(HTML_READ_FACTOR)
} else {
self.max_bytes
};
let mut body = Vec::new();
while let Some(chunk) = resp
.chunk()
.await
.map_err(|e| ToolError::Failed(e.to_string()))?
{
body.extend_from_slice(&chunk);
if body.len() > limit {
break;
}
}
let cut = body.len() > limit;
body.truncate(limit);
let text = String::from_utf8_lossy(&body).into_owned();
let (note, text) = if !want_raw
&& crate::html::looks_like_html(content_type.as_deref(), &text)
{
(
"note: HTML converted to approximate plain text (pass \"raw\": true for the source)\n",
crate::html::to_text(&text),
)
} else {
("", text)
};
let marker = if cut {
"\n[response body truncated]"
} else {
""
};
Ok(format!(
"status: {status}\n{location}{note}{}{marker}",
truncate(text, self.max_bytes)
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::ShellIsolate;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Echo;
#[async_trait]
impl Tool for Echo {
fn name(&self) -> &str {
"echo"
}
fn description(&self) -> &str {
"echo"
}
fn parameters(&self) -> Value {
json!({"type":"object"})
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
Ok(str_arg(&args, "text")?.to_string())
}
}
#[test]
fn a_pattern_matches_a_source_as_well_as_a_name() {
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(Echo), Policy::Allow);
registry.register_with_source(
Arc::new(Other),
Policy::Allow,
ToolSource::Plugin("mcp:homeassistant".into()),
);
let unknown = registry.defer(&["plugin:mcp:*".to_string()]);
assert!(unknown.is_empty(), "a wildcard that matches is not a typo");
let described = registry.descriptors();
let deferred: Vec<&str> = described
.iter()
.filter(|d| d.deferred)
.map(|d| d.name.as_str())
.collect();
assert_eq!(deferred, ["other"], "the MCP tool, not the built-in");
let names: Vec<String> = registry.names();
assert!(names.iter().any(|n| n == "tool_search"), "{names:?}");
let mut bare = ToolRegistry::new(4096);
bare.register(Arc::new(Echo), Policy::Allow);
assert!(bare.defer(&["plugin:mcp:*".to_string()]).is_empty());
assert!(
!bare.names().iter().any(|n| n == "tool_search"),
"nothing deferred, nothing registered to reach it"
);
assert_eq!(bare.defer(&["nosuchtool".to_string()]), ["nosuchtool"]);
assert_eq!(bare.defer(&["note_*".to_string()]), ["note_*"]);
assert!(bare.defer(&["plugin:nowhere:*".to_string()]).is_empty());
}
#[test]
fn without_takes_a_tool_out_of_the_registry_rather_than_hiding_it() {
let mut registry = ToolRegistry::new(4096);
registry.register(Arc::new(Echo), Policy::Allow);
registry.register(Arc::new(Other), Policy::Allow);
registry.defer(&["other".to_string()]);
let read_only = registry.without(&["other"]);
assert_eq!(read_only.names(), vec!["echo".to_string()]);
assert!(
registry.names().iter().any(|n| n == "other"),
"the lead kept the tool the flare was not given"
);
assert_eq!(read_only.without(&["nosuchtool"]).names().len(), 1);
}
struct Other;
#[async_trait]
impl Tool for Other {
fn name(&self) -> &str {
"other"
}
fn description(&self) -> &str {
"the other one"
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {"text": {"type": "string", "description": "what to say"}},
"required": ["text"],
"additionalProperties": false
})
}
async fn call(&self, _: Value) -> Result<String, ToolError> {
Ok("other".into())
}
}
struct Slashed;
#[async_trait]
impl Tool for Slashed {
fn name(&self) -> &str {
"a/b~c"
}
fn description(&self) -> &str {
"escaped"
}
fn parameters(&self) -> Value {
json!({"type": "object", "properties": {}})
}
async fn call(&self, _: Value) -> Result<String, ToolError> {
Ok(String::new())
}
}
struct CountingApprover(AtomicUsize, bool);
#[async_trait]
impl Approver for CountingApprover {
async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
self.0.fetch_add(1, Ordering::SeqCst);
if self.1 {
crate::approvals::Decision::Allow
} else {
crate::approvals::Decision::Deny("no".to_string())
}
}
}
fn registry(policy: Policy) -> ToolRegistry {
let mut r = ToolRegistry::new(64);
r.register(Arc::new(Echo), policy);
r
}
fn model_output(r: &ToolRegistry, out: ToolOutcome) -> String {
truncate(out.output, r.max_output_bytes())
}
const KEYWORDS: &[&str] = &[
"$schema",
"$id",
"$ref",
"$defs",
"$comment",
"title",
"description",
"type",
"properties",
"required",
"additionalProperties",
"items",
"enum",
"const",
"default",
"oneOf",
"anyOf",
"allOf",
"not",
"minLength",
"maxLength",
"pattern",
"format",
"minimum",
"maximum",
"minItems",
"maxItems",
"uniqueItems",
"examples",
"deprecated",
];
fn check_schema(node: &Value, path: &str, problems: &mut Vec<String>) {
match node {
Value::Object(map) => {
for (k, v) in map {
if k == "properties" || k == "$defs" {
if let Value::Object(props) = v {
for (name, sub) in props {
check_schema(sub, &format!("{path}.{k}.{name}"), problems);
}
} else {
problems.push(format!("{path}.{k} is not an object"));
}
continue;
}
if !KEYWORDS.contains(&k.as_str()) {
problems.push(format!("{path}: unknown keyword `{k}`"));
}
check_schema(v, &format!("{path}.{k}"), problems);
}
if let Some(Value::Array(req)) = map.get("required") {
if let Some(Value::Object(props)) = map.get("properties") {
for r in req {
if let Some(name) = r.as_str() {
if !props.contains_key(name) {
problems.push(format!(
"{path}: `required` names `{name}`, which is not in `properties`"
));
}
}
}
}
}
}
Value::Array(items) => {
for (i, v) in items.iter().enumerate() {
check_schema(v, &format!("{path}[{i}]"), problems);
}
}
Value::String(_) if path.ends_with(".$ref") => {}
_ => {}
}
}
fn assert_schema_is_sound(doc: &Value, defs: &serde_json::Map<String, Value>) {
let mut problems = Vec::new();
check_schema(doc, "$", &mut problems);
let mut refs = Vec::new();
fn collect_refs(node: &Value, out: &mut Vec<String>) {
match node {
Value::Object(map) => {
for (k, v) in map {
if k == "$ref" {
if let Some(r) = v.as_str() {
out.push(r.to_string());
}
}
collect_refs(v, out);
}
}
Value::Array(a) => a.iter().for_each(|v| collect_refs(v, out)),
_ => {}
}
}
collect_refs(doc, &mut refs);
assert!(!refs.is_empty(), "the document refers to $defs");
for r in &refs {
let target = r
.strip_prefix("#/$defs/")
.unwrap_or_else(|| panic!("a $ref must point into $defs: {r}"));
let key = target.replace("~1", "/").replace("~0", "~");
if !defs.contains_key(&key) {
problems.push(format!("$ref {r} does not resolve"));
}
}
assert!(problems.is_empty(), "{problems:#?}");
}
#[test]
fn every_tool_describes_itself_in_one_place() {
let r = registry(Policy::Allow);
let d = r.descriptors();
assert_eq!(d.len(), 1);
assert_eq!(d[0].name, "echo");
assert_eq!(d[0].policy, Policy::Allow);
assert_eq!(d[0].source, ToolSource::Builtin);
assert!(d[0].advertised);
assert_eq!(r.specs()[0].function.parameters, d[0].parameters);
assert_eq!(r.specs()[0].function.description, d[0].description);
}
#[test]
fn provenance_says_which_plugin_offered_a_tool() {
let mut r = ToolRegistry::new(64);
r.register(Arc::new(Echo), Policy::Ask);
assert_eq!(r.descriptors()[0].source.label(), "builtin");
let mut r = ToolRegistry::new(64);
r.register_with_source(
Arc::new(Echo),
Policy::Ask,
ToolSource::Plugin("memory-bank".into()),
);
assert_eq!(r.descriptors()[0].source.label(), "plugin:memory-bank");
let json = serde_json::to_value(r.descriptors()).unwrap();
assert_eq!(json[0]["source"], "plugin:memory-bank");
}
#[test]
fn the_schema_document_describes_every_advertised_tool_and_only_those_branches() {
let mut r = ToolRegistry::new(64);
r.register(Arc::new(Echo), Policy::Allow);
r.register_with_source(Arc::new(Other), Policy::Deny, ToolSource::Builtin);
let doc = r.schema_document();
assert_eq!(
doc["$schema"],
"https://json-schema.org/draft/2020-12/schema"
);
assert_eq!(doc["$id"], TOOL_SCHEMA_ID);
let defs = doc["$defs"].as_object().expect("$defs is an object");
assert!(defs.contains_key("echo") && defs.contains_key("other"));
assert_schema_is_sound(&doc, defs);
let branches = doc["oneOf"].as_array().expect("oneOf is an array");
assert_eq!(branches.len(), 1, "{branches:#?}");
assert_eq!(branches[0]["properties"]["name"]["const"], "echo");
assert_eq!(
branches[0]["properties"]["arguments"]["$ref"],
"#/$defs/echo"
);
}
#[test]
fn a_real_argument_object_validates_against_its_own_branch() {
let mut r = ToolRegistry::new(64);
r.register_with_source(Arc::new(Other), Policy::Allow, ToolSource::Builtin);
let doc = r.schema_document();
let defs = doc["$defs"].as_object().unwrap();
assert_schema_is_sound(&doc, defs);
let branch = &doc["oneOf"][0];
let name = branch["properties"]["name"]["const"].as_str().unwrap();
assert_eq!(name, "other");
let target = branch["properties"]["arguments"]["$ref"]
.as_str()
.unwrap()
.strip_prefix("#/$defs/")
.unwrap();
let schema = &defs[target];
let required: Vec<&str> = schema["required"]
.as_array()
.unwrap()
.iter()
.filter_map(|v| v.as_str())
.collect();
assert_eq!(required, ["text"]);
let args = json!({"text": "hi"});
for key in &required {
assert!(args.get(*key).is_some(), "missing {key}");
let want = schema["properties"][*key]["type"].as_str().unwrap();
assert_eq!(
want,
match &args[*key] {
Value::String(_) => "string",
Value::Number(_) => "number",
_ => "other",
}
);
}
}
#[tokio::test]
async fn a_disabled_tool_is_not_offered_and_cannot_be_called() {
let mut r = registry(Policy::Allow);
assert_eq!(r.advertised_names(), ["echo"]);
assert!(r.disable(&["echo".into()]).is_empty());
assert!(r.specs().is_empty(), "not offered to the model");
assert!(r.advertised_names().is_empty());
assert_eq!(r.descriptors().len(), 1);
assert!(!r.descriptors()[0].advertised);
assert_eq!(r.names(), ["echo"]);
let out = r.dispatch("echo", "{\"text\":\"x\"}", &AllowAll).await;
assert!(out.is_error);
assert!(out.output.contains("`[tools] disabled`"), "{}", out.output);
}
#[test]
fn disabling_overrides_an_allow_policy_and_reports_names_that_match_nothing() {
let mut r = ToolRegistry::new(64);
r.register(Arc::new(Echo), Policy::Allow);
let unknown = r.disable(&["echo".into(), "nosuchtool".into()]);
assert_eq!(unknown, ["nosuchtool"], "a typo is reported, not ignored");
assert!(r.specs().is_empty());
let mut r = ToolRegistry::new(64);
r.register(Arc::new(Echo), Policy::Deny);
assert!(!r.descriptors()[0].advertised);
assert!(r.descriptors()[0].source == ToolSource::Builtin);
}
#[test]
fn a_tool_name_with_pointer_characters_still_produces_a_resolving_ref() {
let mut r = ToolRegistry::new(64);
r.register_with_source(Arc::new(Slashed), Policy::Allow, ToolSource::Builtin);
let doc = r.schema_document();
let defs = doc["$defs"].as_object().unwrap();
assert_schema_is_sound(&doc, defs);
}
#[tokio::test]
async fn dispatch_does_not_cap_the_output_the_hooks_will_see() {
let mut r = ToolRegistry::new(8);
r.register(Arc::new(Echo), Policy::Allow);
let long = "x".repeat(64);
let out = r
.dispatch("echo", &json!({"text": long}).to_string(), &AllowAll)
.await;
assert_eq!(
out.output.len(),
64,
"the cap belongs to the caller, after the hooks: {:?}",
out.output
);
let cut = truncate(format!("{} tail", "y".repeat(20)), 8);
assert!(
cut.starts_with("yyyyyyy") && cut.ends_with("[output truncated]"),
"{cut:?}"
);
assert!(
!cut.contains("tail"),
"and the fragment past the cut is gone"
);
}
#[tokio::test]
async fn dispatch_runs_allowed_tool() {
let out = registry(Policy::Allow)
.dispatch("echo", r#"{"text":"hi"}"#, &DenyAll)
.await;
assert_eq!(out, ToolOutcome::ok("hi".into()));
}
#[tokio::test]
async fn dispatch_reports_unknown_tool_bad_json_and_bad_args() {
let r = registry(Policy::Allow);
assert!(r.dispatch("nope", "{}", &AllowAll).await.is_error);
let bad = r.dispatch("echo", "{oops", &AllowAll).await;
assert!(bad.is_error && bad.output.contains("not valid JSON"));
let missing = r.dispatch("echo", "", &AllowAll).await;
assert!(missing.is_error && missing.output.contains("`text`"));
}
#[tokio::test]
async fn deny_policy_blocks_and_hides_tool() {
let r = registry(Policy::Deny);
assert!(r.specs().is_empty());
let out = r.dispatch("echo", r#"{"text":"x"}"#, &AllowAll).await;
assert!(out.is_error && out.output.contains("disabled"));
}
#[tokio::test]
async fn ask_policy_consults_approver() {
let r = registry(Policy::Ask);
let yes = CountingApprover(AtomicUsize::new(0), true);
assert!(!r.dispatch("echo", r#"{"text":"x"}"#, &yes).await.is_error);
assert_eq!(yes.0.load(Ordering::SeqCst), 1);
let no = CountingApprover(AtomicUsize::new(0), false);
let out = r.dispatch("echo", r#"{"text":"x"}"#, &no).await;
assert!(out.is_error && out.output.contains("declined"));
assert_eq!(r.specs().len(), 1);
}
#[tokio::test]
async fn allow_policy_does_not_prompt() {
let a = CountingApprover(AtomicUsize::new(0), false);
registry(Policy::Allow)
.dispatch("echo", r#"{"text":"x"}"#, &a)
.await;
assert_eq!(a.0.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn output_is_truncated_on_char_boundary() {
let r = registry(Policy::Allow);
let out = r
.dispatch(
"echo",
&json!({"text": "é".repeat(100)}).to_string(),
&AllowAll,
)
.await;
let out = model_output(&r, out);
assert!(out.ends_with("[output truncated]"), "{out:?}");
assert!(out.len() < 100);
}
fn builtin(dir: &Path, tweak: impl FnOnce(&mut ToolsConfig)) -> ToolRegistry {
let mut cfg = ToolsConfig {
read_file: Policy::Allow,
write_file: Policy::Allow,
shell: Policy::Allow,
fetch: Policy::Deny,
..ToolsConfig::default()
};
tweak(&mut cfg);
ToolRegistry::from_config(&cfg, dir.to_path_buf())
}
#[tokio::test]
async fn builtin_defaults_are_gated() {
let dir = tempfile::tempdir().unwrap();
let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
assert_eq!(
r.names(),
[
"fetch",
"patch",
"read_file",
"search_files",
"shell",
"write_file"
]
);
let out = r
.dispatch("shell", r#"{"command":"rm -rf everything"}"#, &DenyAll)
.await;
assert!(out.is_error && out.output.contains("declined"));
let out = r
.dispatch("shell", r#"{"command":"echo hi"}"#, &DenyAll)
.await;
assert!(!out.is_error, "ordinary work is not gated: {}", out.output);
let out = r
.dispatch("write_file", r#"{"path":"a","content":"b"}"#, &DenyAll)
.await;
assert!(!out.is_error, "{}", out.output);
assert!(dir.path().join("a").exists());
let out = r
.dispatch(
"write_file",
r#"{"path":"/tmp/escape","content":"b"}"#,
&DenyAll,
)
.await;
assert!(
out.is_error && out.output.contains("outside the workspace"),
"{}",
out.output
);
}
#[tokio::test]
async fn search_files_is_offered_unasked_and_fenced_by_the_workspace() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("src")).unwrap();
std::fs::write(dir.path().join("src/a.rs"), "let needle = 1;\n").unwrap();
let r = ToolRegistry::from_config(&ToolsConfig::default(), dir.path().to_path_buf());
let listed = r
.descriptors()
.into_iter()
.find(|d| d.name == "search_files")
.expect("the tool is registered");
assert_eq!(listed.policy, Policy::Allow);
assert!(listed.advertised);
let out = r
.dispatch("search_files", r#"{"pattern":"needle"}"#, &DenyAll)
.await;
assert!(!out.is_error, "{}", out.output);
assert!(out.output.contains("a.rs:1"), "{}", out.output);
let out = r
.dispatch(
"search_files",
r#"{"pattern":"needle","path":".."}"#,
&DenyAll,
)
.await;
assert!(
out.is_error && out.output.contains("outside the workspace"),
"{}",
out.output
);
}
#[tokio::test]
async fn file_tools_round_trip_and_confine() {
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |_| {});
let w = r
.dispatch(
"write_file",
r#"{"path":"sub/a.txt","content":"hello"}"#,
&DenyAll,
)
.await;
assert!(!w.is_error, "{}", w.output);
let rd = r
.dispatch("read_file", r#"{"path":"sub/a.txt"}"#, &DenyAll)
.await;
assert_eq!(rd.output, "hello");
for bad in ["../escape.txt", "/etc/passwd", "sub/../../x"] {
let out = r
.dispatch("read_file", &json!({"path": bad}).to_string(), &DenyAll)
.await;
assert!(
out.is_error && out.output.contains("outside"),
"{bad}: {}",
out.output
);
}
let out = r
.dispatch(
"write_file",
r#"{"path":"../escape.txt","content":"x"}"#,
&DenyAll,
)
.await;
assert!(out.is_error);
}
#[cfg(unix)]
#[tokio::test]
async fn symlink_escape_is_blocked() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
std::fs::write(outside.path().join("secret"), "s").unwrap();
std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
let r = builtin(dir.path(), |_| {});
let out = r
.dispatch("read_file", r#"{"path":"link/secret"}"#, &DenyAll)
.await;
assert!(out.is_error && out.output.contains("outside"));
}
#[cfg(unix)]
#[tokio::test]
async fn dangling_symlink_cannot_be_written_through() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let target = outside.path().join("created");
std::os::unix::fs::symlink(&target, dir.path().join("evil")).unwrap();
let r = builtin(dir.path(), |_| {});
let out = r
.dispatch("write_file", r#"{"path":"evil","content":"x"}"#, &DenyAll)
.await;
assert!(out.is_error, "{}", out.output);
assert!(!target.exists());
}
#[tokio::test]
async fn read_file_is_bounded_and_regular_files_only() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("big.txt"), "é".repeat(1000)).unwrap();
std::fs::create_dir(dir.path().join("d")).unwrap();
let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
let out = r
.dispatch("read_file", r#"{"path":"big.txt"}"#, &DenyAll)
.await;
let shown = model_output(&r, out);
assert!(shown.ends_with("[output truncated]"), "{shown:?}");
assert!(shown.len() < 100);
let out = r.dispatch("read_file", r#"{"path":"d"}"#, &DenyAll).await;
assert!(out.is_error && out.output.contains("not a regular"));
}
#[cfg(unix)]
#[tokio::test]
async fn a_fifo_is_refused_instead_of_hanging_the_turn() {
let dir = tempfile::tempdir().unwrap();
assert!(std::process::Command::new("mkfifo")
.arg(dir.path().join("pipe"))
.status()
.map(|s| s.success())
.unwrap_or(false));
let r = builtin(dir.path(), |_| {});
let out = tokio::time::timeout(
std::time::Duration::from_secs(3),
r.dispatch("read_file", r#"{"path":"pipe"}"#, &DenyAll),
)
.await
.expect("a FIFO must not block the read");
assert!(out.is_error, "{}", out.output);
assert!(out.output.contains("not a regular"), "{}", out.output);
}
#[tokio::test]
async fn a_binary_file_is_not_text_at_any_size() {
let dir = tempfile::tempdir().unwrap();
let mut binary = vec![0u8; 200];
binary[10] = 0xff;
std::fs::write(dir.path().join("small.bin"), &binary[..50]).unwrap();
std::fs::write(dir.path().join("big.bin"), &binary).unwrap();
std::fs::write(dir.path().join("text.txt"), "aaéé".repeat(40)).unwrap();
let r = builtin(dir.path(), |c| c.max_output_bytes = 64);
let out = r
.dispatch("read_file", r#"{"path":"small.bin"}"#, &DenyAll)
.await;
assert!(
out.is_error,
"an under-cap binary is not text: {}",
out.output
);
let out = r
.dispatch("read_file", r#"{"path":"big.bin"}"#, &DenyAll)
.await;
assert!(
out.is_error,
"an over-cap binary is not text either: {}",
out.output
);
let out = r
.dispatch("read_file", r#"{"path":"text.txt"}"#, &DenyAll)
.await;
assert!(!out.is_error, "{}", out.output);
assert!(out.output.starts_with("aaé"), "{}", out.output);
}
#[cfg(unix)]
#[tokio::test]
async fn shell_output_is_capped_and_flooding_child_stops() {
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| {
c.max_output_bytes = 256;
c.shell_timeout_secs = 10;
});
let out = r.dispatch("shell", r#"{"command":"yes"}"#, &DenyAll).await;
assert!(!out.is_error, "{}", out.output);
let shown = model_output(&r, out);
assert!(
shown.contains("[truncated]") || shown.contains("[output truncated]"),
"{shown:?}"
);
assert!(shown.len() < 300, "{} bytes", shown.len());
}
#[cfg(unix)]
#[tokio::test]
async fn a_background_child_does_not_hold_the_turn() {
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| {
c.max_output_bytes = 4096;
c.shell_timeout_secs = 30;
c.shell_isolate = crate::config::ShellIsolate::Off;
});
let asked = std::time::Instant::now();
let out = tokio::time::timeout(
std::time::Duration::from_secs(3),
r.dispatch("shell", r#"{"command":"sleep 5 & echo started"}"#, &DenyAll),
)
.await
.expect("a background child must not hold the call — `#368`");
assert!(!out.is_error, "{}", out.output);
assert!(
out.output.contains("started"),
"what the child itself printed: {}",
out.output
);
assert!(
out.output.contains("still holds its output pipe"),
"the result says why it stopped reading: {}",
out.output
);
assert!(asked.elapsed() < std::time::Duration::from_secs(3));
}
#[cfg(unix)]
fn process_alive(pid: i32) -> bool {
std::fs::read_to_string(format!("/proc/{pid}/stat"))
.ok()
.and_then(|s| {
s.rsplit(')')
.next()
.map(|state| !state.trim_start().starts_with(['Z', 'X']))
})
.unwrap_or(false)
}
#[cfg(unix)]
async fn timeout_kills_grandchild(command: &str, grace: Duration) {
let dir = tempfile::tempdir().unwrap();
let mut r = ToolRegistry::new(4096);
r.register(
Arc::new(Shell {
root: std::fs::canonicalize(dir.path()).unwrap(),
skill_roots: Vec::new(),
scripts_dir: None,
timeout: Duration::from_secs(1),
allowlist: Vec::new(),
max_bytes: 4096,
kill_grace: grace,
sandbox: crate::sandbox::Sandbox::off(),
ask: crate::config::ShellAsk::Dangerous,
}),
Policy::Allow,
);
let started = std::time::Instant::now();
let out = r
.dispatch("shell", &json!({"command": command}).to_string(), &DenyAll)
.await;
assert!(
out.is_error && out.output.contains("timed out"),
"{}",
out.output
);
let pid: i32 = std::fs::read_to_string(dir.path().join("child.pid"))
.unwrap()
.trim()
.parse()
.unwrap();
for _ in 0..100 {
if !process_alive(pid) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).unwrap_or_default();
assert!(
!process_alive(pid),
"grandchild {pid} survived the timeout after {:.2}s; stat = {stat:?}",
started.elapsed().as_secs_f32()
);
assert!(started.elapsed() < Duration::from_secs(8));
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_terminates_background_grandchild() {
timeout_kills_grandchild(
"sleep 300 & echo $! > child.pid; wait",
Duration::from_secs(2),
)
.await;
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_terminates_a_grandchild_that_left_the_process_group() {
timeout_kills_grandchild(
"setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait",
Duration::from_secs(2),
)
.await;
}
#[cfg(unix)]
#[tokio::test]
async fn a_cancelled_run_kills_a_grandchild_that_left_the_process_group() {
let dir = tempfile::tempdir().unwrap();
let mut r = ToolRegistry::new(4096);
r.register(
Arc::new(Shell {
root: std::fs::canonicalize(dir.path()).unwrap(),
skill_roots: Vec::new(),
scripts_dir: None,
timeout: Duration::from_secs(30),
allowlist: Vec::new(),
max_bytes: 4096,
kill_grace: Duration::from_secs(2),
sandbox: crate::sandbox::Sandbox::off(),
ask: crate::config::ShellAsk::Dangerous,
}),
Policy::Allow,
);
let registry = Arc::new(r);
let call = {
let registry = Arc::clone(®istry);
let args = json!({
"command": "setsid sh -c 'echo $$ > child.pid; exec sleep 300' & wait"
})
.to_string();
tokio::spawn(async move { registry.dispatch("shell", &args, &DenyAll).await })
};
let pid = wait_for_pid(&dir.path().join("child.pid")).await;
call.abort();
let _ = call.await;
for _ in 0..100 {
if !process_alive(pid) {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
assert!(
!process_alive(pid),
"grandchild {pid} survived the drop: {:#?}",
std::fs::read_to_string(format!("/proc/{pid}/stat"))
);
}
#[cfg(unix)]
async fn wait_for_pid(path: &std::path::Path) -> i32 {
for _ in 0..100 {
if let Ok(text) = std::fs::read_to_string(path) {
if let Ok(pid) = text.trim().parse::<i32>() {
return pid;
}
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
panic!("the script never wrote {}", path.display());
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_escalates_to_sigkill_when_sigterm_is_ignored() {
timeout_kills_grandchild(
"trap '' TERM; sleep 300 & echo $! > child.pid; wait",
Duration::from_millis(300),
)
.await;
}
#[cfg(unix)]
#[tokio::test]
async fn shell_runs_in_workspace_with_timeout_and_allowlist() {
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| c.shell_timeout_secs = 1);
let out = r
.dispatch("shell", r#"{"command":"echo hi; pwd"}"#, &DenyAll)
.await;
assert!(!out.is_error);
assert!(out.output.contains("exit code: 0") && out.output.contains("hi"));
let slow = r
.dispatch("shell", r#"{"command":"sleep 5"}"#, &DenyAll)
.await;
assert!(slow.is_error && slow.output.contains("timed out"));
let r = builtin(dir.path(), |c| c.shell_allowlist = vec!["echo".into()]);
let ok = r
.dispatch("shell", r#"{"command":"echo a b"}"#, &DenyAll)
.await;
assert!(ok.output.contains("a b"), "{}", ok.output);
for bad in ["ls", "echo hi; ls", "echo $(ls)"] {
let out = r
.dispatch("shell", &json!({"command": bad}).to_string(), &DenyAll)
.await;
assert!(out.is_error, "{bad}");
}
}
#[cfg(unix)]
fn shell_with_skills(workspace: &Path, skills: &Path) -> ToolRegistry {
let cfg = ToolsConfig {
shell: Policy::Allow,
..ToolsConfig::default()
};
let roots = vec![crate::skills::Root {
source: crate::skills::Source::Shared,
dir: skills.to_path_buf(),
}];
ToolRegistry::from_config_with(&cfg, workspace.to_path_buf(), roots)
}
#[cfg(unix)]
async fn shell_in(r: &ToolRegistry, command: &str, cwd: &str) -> ToolOutcome {
r.dispatch(
"shell",
&json!({"command": command, "cwd": cwd}).to_string(),
&DenyAll,
)
.await
}
#[cfg(unix)]
#[tokio::test]
async fn shell_cwd_is_accepted_inside_the_workspace_and_refused_elsewhere() {
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path().join("ws");
std::fs::create_dir_all(workspace.join("sub")).unwrap();
std::fs::write(workspace.join("file.txt"), "x").unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, workspace.join("link")).unwrap();
let r = shell_with_skills(&workspace, &tmp.path().join("skills"));
let out = shell_in(&r, "pwd", "sub").await;
assert!(!out.is_error, "{}", out.output);
assert!(out.output.contains("/ws/sub"), "{}", out.output);
let absolute = workspace.join("sub").display().to_string();
assert!(!shell_in(&r, "pwd", &absolute).await.is_error);
for (cwd, why) in [
("/etc", "outside the workspace"),
("..", "outside the workspace"),
("link", "outside the workspace"),
("missing", "cannot be resolved"),
("file.txt", "not a directory"),
(" ", "empty"),
] {
let out = shell_in(&r, "pwd", cwd).await;
assert!(out.is_error, "{cwd:?} should be refused: {}", out.output);
assert!(
out.output.contains(&format!("cwd `{cwd}` refused")),
"names what was refused: {}",
out.output
);
assert!(out.output.contains(why), "{cwd:?}, {why}: {}", out.output);
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_skills_own_script_runs_from_its_directory_but_a_broken_skills_does_not() {
let tmp = tempfile::tempdir().unwrap();
let workspace = tmp.path().join("ws");
std::fs::create_dir_all(&workspace).unwrap();
let skills = tmp.path().join("skills");
let good = skills.join("backup");
std::fs::create_dir_all(good.join("scripts")).unwrap();
std::fs::write(
good.join("SKILL.md"),
"---\nname: backup\n---\nRun `bash scripts/backup.sh`.\n",
)
.unwrap();
std::fs::write(
good.join("scripts/backup.sh"),
"echo backed up from $(basename \"$PWD\")\n",
)
.unwrap();
let broken = skills.join("broken");
std::fs::create_dir_all(&broken).unwrap();
std::fs::write(
broken.join("SKILL.md"),
"---\ndescription: no name\n---\nbody\n",
)
.unwrap();
let r = shell_with_skills(&workspace, &skills);
let out = shell_in(&r, "bash scripts/backup.sh", &good.display().to_string()).await;
assert!(!out.is_error, "{}", out.output);
assert!(
out.output.contains("backed up from backup"),
"{}",
out.output
);
let nested = good.join("scripts").display().to_string();
assert!(!shell_in(&r, "pwd", &nested).await.is_error);
let out = shell_in(&r, "pwd", &skills.display().to_string()).await;
assert!(
out.is_error,
"the skills directory is not a skill's directory"
);
let out = shell_in(&r, "pwd", &broken.display().to_string()).await;
assert!(out.is_error, "{}", out.output);
assert!(
out.output.contains("outside every skill's directory"),
"{}",
out.output
);
}
#[cfg(unix)]
fn shell_with_scripts(workspace: &Path, scripts: &Path, allowlist: &[&str]) -> ToolRegistry {
let cfg = ToolsConfig {
shell: Policy::Allow,
shell_allowlist: allowlist.iter().map(|s| s.to_string()).collect(),
..ToolsConfig::default()
};
ToolRegistry::from_config_full(
&cfg,
workspace.to_path_buf(),
Vec::new(),
Some(scripts.to_path_buf()),
)
}
#[cfg(unix)]
#[tokio::test]
async fn shell_finds_a_script_as_a_bare_command_and_is_told_where_the_scripts_are() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
std::fs::create_dir_all(&workspace).unwrap();
std::fs::create_dir_all(&scripts).unwrap();
let script = scripts.join("hello-script");
std::fs::write(&script, "#!/bin/sh\necho hello from $1\n").unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
let imposter = scripts.join("date");
std::fs::write(&imposter, "#!/bin/sh\necho fake date\n").unwrap();
std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
let r = shell_with_scripts(&workspace, &scripts, &[]);
let out = r
.dispatch(
"shell",
&json!({"command": "hello-script world; date; echo dir=$ECLIPSE_SCRIPTS_DIR; \
echo last=${PATH##*:}"})
.to_string(),
&DenyAll,
)
.await;
assert!(!out.is_error, "{}", out.output);
let dir = scripts.display().to_string();
assert!(out.output.contains("hello from world"), "{}", out.output);
assert!(out.output.contains(&format!("dir={dir}")), "{}", out.output);
assert!(
out.output.contains(&format!("last={dir}")),
"the scripts directory is on PATH, last: {}",
out.output
);
assert!(
!out.output.contains("fake date"),
"a real command wins over a script of the same name: {}",
out.output
);
}
#[cfg(unix)]
#[tokio::test]
async fn an_allowlisted_shell_does_not_let_a_script_take_the_place_of_a_program() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
std::fs::create_dir_all(&workspace).unwrap();
std::fs::create_dir_all(&scripts).unwrap();
let imposter = scripts.join("echo");
std::fs::write(&imposter, "#!/bin/sh\necho imposter\n").unwrap();
std::fs::set_permissions(&imposter, std::fs::Permissions::from_mode(0o755)).unwrap();
let r = shell_with_scripts(&workspace, &scripts, &["echo", "env"]);
let out = r
.dispatch("shell", r#"{"command":"echo real"}"#, &DenyAll)
.await;
assert!(
out.output.contains("real") && !out.output.contains("imposter"),
"{}",
out.output
);
let out = r.dispatch("shell", r#"{"command":"env"}"#, &DenyAll).await;
assert!(
out.output
.contains(&format!("ECLIPSE_SCRIPTS_DIR={}", scripts.display())),
"{}",
out.output
);
}
#[cfg(unix)]
#[tokio::test]
async fn shell_cwd_accepts_the_scripts_directory_and_the_refusal_names_it() {
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
std::fs::create_dir_all(&workspace).unwrap();
std::fs::create_dir_all(&scripts).unwrap();
let r = shell_with_scripts(&workspace, &scripts, &[]);
let out = shell_in(&r, "pwd", &scripts.display().to_string()).await;
assert!(!out.is_error, "{}", out.output);
assert!(out.output.contains("/scripts"), "{}", out.output);
let out = shell_in(&r, "pwd", "/etc").await;
assert!(
out.is_error
&& out.output.contains("outside the workspace")
&& out.output.contains("outside the scripts directory")
&& out.output.contains("outside every skill's directory"),
"{}",
out.output
);
}
fn writer(workspace: &Path, scripts: &Path) -> ToolRegistry {
let cfg = ToolsConfig {
write_file: Policy::Allow,
..ToolsConfig::default()
};
ToolRegistry::from_config_full(
&cfg,
workspace.to_path_buf(),
Vec::new(),
Some(scripts.to_path_buf()),
)
}
async fn write_to(r: &ToolRegistry, path: &str) -> ToolOutcome {
r.dispatch(
"write_file",
&json!({"path": path, "content": "#!/bin/sh\n"}).to_string(),
&DenyAll,
)
.await
}
#[tokio::test]
async fn write_file_writes_in_the_scripts_directory_even_before_it_exists() {
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("cfg/scripts"));
std::fs::create_dir_all(&workspace).unwrap();
let r = writer(&workspace, &scripts);
let target = scripts.join("backup.sh");
let out = write_to(&r, &target.display().to_string()).await;
assert!(!out.is_error, "{}", out.output);
assert_eq!(std::fs::read_to_string(&target).unwrap(), "#!/bin/sh\n");
let out = write_to(&r, &format!("{}/sub/../again.sh", scripts.display())).await;
assert!(!out.is_error, "{}", out.output);
assert!(scripts.join("again.sh").is_file());
}
#[tokio::test]
async fn write_file_still_writes_in_the_workspace_when_scripts_are_configured() {
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
std::fs::create_dir_all(&workspace).unwrap();
let r = writer(&workspace, &scripts);
let out = write_to(&r, "notes/a.txt").await;
assert!(!out.is_error, "{}", out.output);
assert!(workspace.join("notes/a.txt").is_file());
assert!(!scripts.exists(), "a workspace write must not create it");
}
#[tokio::test]
async fn a_big_file_is_not_clobbered_by_accident() {
let dir = tempfile::tempdir().unwrap();
let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(100);
let big = dir.path().join("index.html");
std::fs::write(&big, "x".repeat(500)).unwrap();
let refused = tool
.call(json!({"path": "index.html", "content": "tiny"}))
.await
.unwrap_err()
.to_string();
assert!(refused.contains("already exists at 500 bytes"), "{refused}");
assert!(
refused.contains("`patch`"),
"it names the cheap path: {refused}"
);
assert!(
refused.contains("force: true"),
"and how to mean it: {refused}"
);
assert_eq!(
std::fs::read_to_string(&big).unwrap().len(),
500,
"nothing was written"
);
tool.call(json!({"path": "index.html", "content": "tiny", "force": true}))
.await
.unwrap();
assert_eq!(std::fs::read_to_string(&big).unwrap(), "tiny");
let small = dir.path().join("notes.md");
tool.call(json!({"path": "notes.md", "content": "one"}))
.await
.unwrap();
tool.call(json!({"path": "notes.md", "content": "two"}))
.await
.unwrap();
assert_eq!(std::fs::read_to_string(&small).unwrap(), "two");
tool.call(json!({"path": "fresh.html", "content": "y".repeat(400)}))
.await
.unwrap();
assert!(dir.path().join("fresh.html").exists());
let loose = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(0);
loose
.call(json!({"path": "index.html", "content": "free"}))
.await
.unwrap();
assert_eq!(std::fs::read_to_string(&big).unwrap(), "free");
}
#[tokio::test]
async fn the_guard_refuses_at_the_threshold_not_only_above_it() {
let dir = tempfile::tempdir().unwrap();
let tool = WriteFile::new(dir.path().to_path_buf(), None).guard_bytes(64);
std::fs::write(dir.path().join("exact.txt"), "x".repeat(64)).unwrap();
let refused = tool
.call(json!({"path": "exact.txt", "content": "y"}))
.await
.unwrap_err()
.to_string();
assert!(refused.contains("already exists at 64 bytes"), "{refused}");
assert_eq!(
std::fs::read_to_string(dir.path().join("exact.txt"))
.unwrap()
.len(),
64,
"nothing was written"
);
std::fs::write(dir.path().join("under.txt"), "x".repeat(63)).unwrap();
tool.call(json!({"path": "under.txt", "content": "y"}))
.await
.unwrap();
assert_eq!(
std::fs::read_to_string(dir.path().join("under.txt")).unwrap(),
"y"
);
}
#[cfg(unix)]
#[tokio::test]
async fn write_file_refuses_everywhere_else_and_names_both_roots() {
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
let elsewhere = tmp.path().join("elsewhere");
std::fs::create_dir_all(&workspace).unwrap();
std::fs::create_dir_all(&scripts).unwrap();
std::fs::create_dir_all(&elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, scripts.join("link")).unwrap();
let r = writer(&workspace, &scripts);
let sibling = format!("{}-other/x.sh", scripts.display());
for requested in [
"/etc/eclipse-test".to_string(),
elsewhere.join("x.sh").display().to_string(),
format!("{}/../escape.sh", scripts.display()),
format!("{}/link/x.sh", scripts.display()),
sibling,
] {
let out = write_to(&r, &requested).await;
assert!(out.is_error, "{requested} should be refused");
assert!(
out.output.contains(&workspace.display().to_string())
&& out.output.contains(&scripts.display().to_string()),
"{requested}: {}",
out.output
);
}
assert!(!elsewhere.join("x.sh").exists());
assert!(!tmp.path().join("escape.sh").exists());
}
#[test]
fn the_approval_line_for_write_file_says_when_the_destination_is_the_scripts_directory() {
let tmp = tempfile::tempdir().unwrap();
let (workspace, scripts) = (tmp.path().join("ws"), tmp.path().join("scripts"));
let tool = WriteFile::new(workspace, Some(scripts.clone()));
let line = tool.describe_call(
&json!({"path": scripts.join("a.sh").display().to_string(), "content": "x"}),
);
assert!(line.ends_with("(scripts directory)"), "{line}");
let line = tool.describe_call(&json!({"path": "a.txt", "content": "x"}));
assert!(!line.contains("scripts"), "{line}");
}
#[cfg(unix)]
#[tokio::test]
async fn shell_without_a_cwd_still_runs_in_the_workspace_root() {
let tmp = tempfile::tempdir().unwrap();
let r = shell_with_skills(tmp.path(), &tmp.path().join("skills"));
let out = r.dispatch("shell", r#"{"command":"pwd"}"#, &DenyAll).await;
let root = std::fs::canonicalize(tmp.path()).unwrap();
assert!(
out.output.contains(&root.display().to_string()),
"{}",
out.output
);
let out = r
.dispatch("shell", r#"{"command":"pwd","cwd":7}"#, &DenyAll)
.await;
assert!(
out.is_error && out.output.contains("`cwd` must be a string"),
"{}",
out.output
);
}
#[tokio::test]
async fn fetch_rejects_non_http_schemes() {
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
let out = r
.dispatch("fetch", r#"{"url":"file:///etc/passwd"}"#, &DenyAll)
.await;
assert!(out.is_error && out.output.contains("http"));
}
#[tokio::test]
async fn fetch_blocks_internal_targets_before_connecting() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| c.fetch = Policy::Allow);
for url in [
format!("http://127.0.0.1:{port}/"),
format!("http://localhost:{port}/"),
format!("http://svc.localhost:{port}/"),
format!("http://[::1]:{port}/"),
format!("http://[::ffff:127.0.0.1]:{port}/"),
format!("http://2130706433:{port}/"),
"http://169.254.169.254/latest/meta-data/".to_string(),
"http://8.8.8.8/".to_string(),
] {
let out = r
.dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
.await;
assert!(
out.is_error && out.output.contains("blocked"),
"{url}: {}",
out.output
);
}
let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
assert!(accepted.is_err(), "blocked fetch connected anyway");
}
#[tokio::test]
async fn fetch_does_not_follow_redirects() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf).await;
s.write_all(
b"HTTP/1.1 302 Found\r\nlocation: http://127.0.0.1:9/elsewhere\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
)
.await
.unwrap();
});
let mut r = ToolRegistry::new(4096);
r.register(
Arc::new(Fetch {
allow_internal: true,
..Fetch::new(Duration::from_secs(5), 4096)
}),
Policy::Allow,
);
let out = r
.dispatch("fetch", &json!({"url": url}).to_string(), &DenyAll)
.await;
server.await.unwrap();
assert!(!out.is_error, "{}", out.output);
assert!(
out.output.contains("302")
&& out
.output
.contains("location: http://127.0.0.1:9/elsewhere")
);
}
async fn fetch_from_mock(
headers: &'static str,
body: &'static str,
html: FetchHtml,
args: Value,
) -> ToolOutcome {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf).await;
let resp = format!(
"HTTP/1.1 200 OK\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
s.write_all(resp.as_bytes()).await.unwrap();
});
let mut r = ToolRegistry::new(4096);
r.register(
Arc::new(
Fetch {
allow_internal: true,
..Fetch::new(Duration::from_secs(5), 4096)
}
.with_html(html),
),
Policy::Allow,
);
let mut args = args;
args["url"] = json!(url);
let out = r.dispatch("fetch", &args.to_string(), &DenyAll).await;
server.await.unwrap();
out
}
const PAGE: &str = "<!doctype html><html><head><title>T</title><script>evil()</script></head>\
<body><h1>Hello</h1><p>one & two</p></body></html>";
#[tokio::test]
async fn fetch_converts_html_to_text_by_default() {
let out = fetch_from_mock(
"content-type: text/html; charset=utf-8\r\n",
PAGE,
FetchHtml::Text,
json!({}),
)
.await;
assert!(!out.is_error, "{}", out.output);
assert!(out.output.starts_with("status: 200 OK\n"), "{}", out.output);
assert!(
out.output.contains("note: HTML converted"),
"{}",
out.output
);
assert!(
out.output.ends_with("T\n\nHello\n\none & two"),
"{}",
out.output
);
assert!(!out.output.contains("<p>") && !out.output.contains("evil"));
let out = fetch_from_mock("", PAGE, FetchHtml::Text, json!({})).await;
assert!(out.output.contains("Hello") && !out.output.contains("<h1>"));
}
#[tokio::test]
async fn fetch_can_return_raw_html_per_call_or_by_config() {
let ct = "content-type: text/html\r\n";
let out = fetch_from_mock(ct, PAGE, FetchHtml::Text, json!({"raw": true})).await;
assert!(out.output.contains("<h1>Hello</h1>") && !out.output.contains("note: HTML"));
let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({})).await;
assert!(
out.output.contains("<script>evil()</script>"),
"{}",
out.output
);
let out = fetch_from_mock(ct, PAGE, FetchHtml::Raw, json!({"raw": false})).await;
assert!(out.output.contains("note: HTML converted") && !out.output.contains("<h1>"));
}
#[tokio::test]
async fn fetch_leaves_non_html_bodies_alone() {
let out = fetch_from_mock(
"content-type: application/json\r\n",
r#"{"html":"<p>x</p>"}"#,
FetchHtml::Text,
json!({}),
)
.await;
assert!(
out.output.ends_with(r#"{"html":"<p>x</p>"}"#),
"{}",
out.output
);
assert!(!out.output.contains("note:"));
}
#[cfg(unix)]
fn bwrap_present() -> bool {
std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
.any(|d| d.join("bwrap").is_file())
}
#[cfg(unix)]
fn any_process(marker: &str) -> bool {
std::process::Command::new("pgrep")
.arg("-f")
.arg(marker)
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[cfg(unix)]
#[tokio::test]
async fn isolation_stops_a_daemon_that_leaves_the_process_group() {
if !bwrap_present() {
return;
}
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| c.shell_isolate = ShellIsolate::Process);
let marker = "sleep 297.41";
let started =
json!({ "command": format!("setsid {marker} >/dev/null 2>&1 & echo ok") }).to_string();
let out = r.dispatch("shell", &started, &DenyAll).await;
assert!(!out.is_error, "{}", out.output);
tokio::time::sleep(Duration::from_millis(500)).await;
assert!(!any_process(marker), "a daemon outlived the run");
assert!(out.output.contains("shell_isolate"), "{}", out.output);
}
#[cfg(unix)]
#[tokio::test]
async fn fs_mode_writes_inside_the_workspace_and_nowhere_else() {
if !bwrap_present() {
return;
}
let dir = tempfile::tempdir().unwrap();
let r = builtin(dir.path(), |c| {
c.shell_isolate = ShellIsolate::Fs;
c.shell_isolate_hide = Vec::new();
});
let command = "touch made-here && echo inside=$(test -f made-here && echo ok) \
etc=$(test -w /etc && echo writable || echo read-only) \
tmp=$(touch /tmp/x && echo writable || echo read-only)";
let args = json!({ "command": command }).to_string();
let out = r.dispatch("shell", &args, &DenyAll).await;
assert!(!out.is_error, "{}", out.output);
assert!(
dir.path().join("made-here").exists(),
"workspace write was lost"
);
assert!(out.output.contains("inside=ok"), "{}", out.output);
assert!(out.output.contains("etc=read-only"), "{}", out.output);
assert!(out.output.contains("tmp=writable"), "{}", out.output);
}
#[cfg(unix)]
#[tokio::test]
async fn fs_mode_hides_a_path_even_inside_the_workspace() {
if !bwrap_present() {
return;
}
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("secret")).unwrap();
std::fs::write(dir.path().join("secret/key"), "TOPSECRET").unwrap();
let secret = dir.path().join("secret");
let r = builtin(dir.path(), move |c| {
c.shell_isolate = ShellIsolate::Fs;
c.shell_isolate_hide = vec![secret];
});
let args = json!({ "command": "ls -A secret | wc -l" }).to_string();
let out = r.dispatch("shell", &args, &DenyAll).await;
assert!(!out.is_error, "{}", out.output);
assert!(out.output.contains("\n0\n"), "{}", out.output);
}
#[cfg(unix)]
#[tokio::test]
async fn a_hide_that_would_erase_the_workspace_is_skipped_and_said_so() {
if !bwrap_present() {
return;
}
let dir = tempfile::tempdir().unwrap();
let parent = dir.path().parent().unwrap().to_path_buf();
let r = builtin(dir.path(), move |c| {
c.shell_isolate = ShellIsolate::Fs;
c.shell_isolate_hide = vec![parent];
});
let args = json!({ "command": "touch kept && ls -A | wc -l" }).to_string();
let out = r.dispatch("shell", &args, &DenyAll).await;
assert!(!out.is_error, "{}", out.output);
assert!(
dir.path().join("kept").exists(),
"the workspace was erased: {}",
out.output
);
}
#[test]
fn specs_use_openai_function_format() {
let v = serde_json::to_value(registry(Policy::Allow).specs()).unwrap();
assert_eq!(v[0]["type"], "function");
assert_eq!(v[0]["function"]["name"], "echo");
}
#[cfg(unix)]
#[test]
fn replacing_a_file_keeps_its_mode() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("run.sh");
std::fs::write(&path, "#!/bin/sh\necho one\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
replace_file(&path, "#!/bin/sh\necho two\n").expect("the edit lands");
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o755, "an executable stays executable");
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"#!/bin/sh\necho two\n"
);
}
#[cfg(unix)]
#[test]
fn replacing_through_a_symlink_edits_the_target_and_keeps_the_link() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real.sh");
let link = dir.path().join("link.sh");
std::fs::write(&real, "old\n").unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
replace_file(&link, "new\n").expect("the edit lands");
let meta = std::fs::symlink_metadata(&link).unwrap();
assert!(
meta.file_type().is_symlink(),
"the link is still a link, not a copy of the file"
);
assert_eq!(std::fs::read_to_string(&real).unwrap(), "new\n");
}
}