use crate::tools::{CallScope, ToolError};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
pub const ENV_TOOL_SOCKET: &str = "ECLIPSE_TOOL_SOCKET";
const MAX_LINE_BYTES: u64 = 1024 * 1024;
#[derive(serde::Deserialize)]
struct Request {
name: String,
#[serde(default)]
arguments: serde_json::Value,
}
#[derive(serde::Serialize)]
struct Response<'a> {
ok: bool,
#[serde(skip_serializing_if = "Option::is_none")]
output: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<&'a str>,
}
pub struct Bridge {
path: PathBuf,
listener: tokio::net::UnixListener,
dir: PathBuf,
}
impl Bridge {
pub fn bind() -> Result<Self, ToolError> {
let base = std::env::temp_dir();
let dir = base.join(format!("eclipse-bridge-{}-{}", std::process::id(), nonce()));
std::fs::create_dir_all(&dir)
.map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", dir.display())))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
}
let path = dir.join("tools.sock");
let listener = std::os::unix::net::UnixListener::bind(&path)
.map_err(|e| ToolError::Failed(format!("cannot bind {}: {e}", path.display())))?;
listener
.set_nonblocking(true)
.map_err(|e| ToolError::Failed(format!("cannot set non-blocking: {e}")))?;
let listener = tokio::net::UnixListener::from_std(listener)
.map_err(|e| ToolError::Failed(format!("cannot watch {}: {e}", path.display())))?;
Ok(Self {
path,
listener,
dir,
})
}
pub fn path(&self) -> &Path {
&self.path
}
async fn serve(&self, conn: tokio::net::UnixStream, scope: &CallScope<'_>) {
let (read, mut write) = conn.into_split();
let mut line = String::new();
let mut reader = BufReader::new(read);
let body = match tokio::time::timeout(
Duration::from_secs(1),
(&mut reader).take(MAX_LINE_BYTES).read_line(&mut line),
)
.await
{
Ok(Ok(n)) if n > 0 => line,
_ => return,
};
let reply = match serde_json::from_str::<Request>(&body) {
Err(e) => serde_json::to_string(&Response {
ok: false,
output: None,
error: Some(&format!("request is not JSON: {e}")),
})
.unwrap_or_else(|_| "{\"ok\":false,\"error\":\"unserialisable\"}".into()),
Ok(req) => {
let raw = req.arguments.to_string();
let outcome = scope
.registry
.dispatch_scoped(&req.name, &raw, scope.approver, None, scope.run)
.await;
let refused = outcome.deferred.then(|| {
format!(
"`{}` needs your approval, and a call from inside a script cannot wait for \
one: it was refused. Make the call from the model's turn, where it can \
pause, or run it yourself once you have decided.",
req.name
)
});
let response = if let Some(reason) = refused.as_deref() {
Response {
ok: false,
output: None,
error: Some(reason),
}
} else if outcome.is_error {
Response {
ok: false,
output: None,
error: Some(outcome.output.as_str()),
}
} else {
Response {
ok: true,
output: Some(outcome.output.as_str()),
error: None,
}
};
serde_json::to_string(&response)
.unwrap_or_else(|_| "{\"ok\":false,\"error\":\"unserialisable\"}".into())
}
};
let mut reply = reply;
reply.push('\n');
let _ = write.write_all(reply.as_bytes()).await;
let _ = write.flush().await;
}
pub(crate) async fn wait_serving(
&self,
running: &mut crate::tools::Running,
scope: &CallScope<'_>,
) -> Result<std::process::ExitStatus, ToolError> {
loop {
tokio::select! {
accepted = self.listener.accept() => {
if let Ok((conn, _)) = accepted {
self.serve(conn, scope).await;
}
}
status = running.wait() => return status,
}
}
}
}
impl Drop for Bridge {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
let _ = std::fs::remove_dir(&self.dir);
}
}
fn nonce() -> u64 {
use std::time::{SystemTime, UNIX_EPOCH};
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0)
}
pub async fn run_with_bridge(
cmd: tokio::process::Command,
max_bytes: usize,
timeout: Duration,
kill_grace: Duration,
scope: &CallScope<'_>,
) -> Result<String, ToolError> {
let mut once = Some(cmd);
run_with_bridge_built(
|| once.take().expect("built once"),
max_bytes,
timeout,
kill_grace,
scope,
)
.await
}
pub async fn run_with_bridge_built<F>(
mut build: F,
max_bytes: usize,
timeout: Duration,
kill_grace: Duration,
scope: &CallScope<'_>,
) -> Result<String, ToolError>
where
F: FnMut() -> tokio::process::Command,
{
let bridge = Bridge::bind()?;
let mut running = crate::tools::start_retrying(
|| {
let mut cmd = build();
cmd.env(ENV_TOOL_SOCKET, bridge.path());
cmd
},
max_bytes,
)
.await?;
let status = match tokio::time::timeout(timeout, bridge.wait_serving(&mut running, scope)).await
{
Ok(done) => done?,
Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
};
Ok(running.finish(status).await)
}
#[derive(serde::Deserialize)]
struct ClientResponse {
ok: bool,
#[serde(default)]
output: String,
#[serde(default)]
error: String,
}
pub async fn call_over_bridge(name: &str, arguments: &str) -> (String, i32) {
let Some(path) = std::env::var_os(ENV_TOOL_SOCKET) else {
return (
format!(
"no tool bridge: {ENV_TOOL_SOCKET} is not set. `eclipse tool` reaches the tools of \
the run that started this program; outside a run there is nothing to call — use \
`eclipse run` and let the agent's script call it."
),
2,
);
};
let args: serde_json::Value = if arguments.trim().is_empty() {
serde_json::json!({})
} else {
match serde_json::from_str(arguments) {
Ok(v) => v,
Err(e) => {
return (
format!(
"arguments are not JSON: {e}. Pass an object, e.g. '{{\"path\": \"x\"}}'"
),
2,
)
}
}
};
let request = serde_json::json!({"name": name, "arguments": args}).to_string();
let stream = match tokio::net::UnixStream::connect(&path).await {
Ok(s) => s,
Err(e) => {
return (
format!(
"cannot reach the tool bridge at {}: {e}. The run that started this program \
may have finished.",
PathBuf::from(&path).display()
),
2,
)
}
};
let (read, mut write) = stream.into_split();
let mut request = request;
request.push('\n');
if let Err(e) = write.write_all(request.as_bytes()).await {
return (format!("cannot send to the tool bridge: {e}"), 2);
}
let _ = write.flush().await;
let mut line = String::new();
let mut reader = BufReader::new(read);
match tokio::time::timeout(
Duration::from_secs(60),
(&mut reader).take(MAX_LINE_BYTES).read_line(&mut line),
)
.await
{
Ok(Ok(0)) | Err(_) => (
"the tool bridge closed the connection without answering".to_string(),
2,
),
Ok(Ok(_)) => match serde_json::from_str::<ClientResponse>(&line) {
Ok(r) if r.ok => (r.output, 0),
Ok(r) => (r.error, 1),
Err(e) => (format!("the tool bridge's answer is not JSON: {e}"), 2),
},
Ok(Err(e)) => (format!("cannot read from the tool bridge: {e}"), 2),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Policy;
use crate::tools::{spawn, AllowAll, DenyAll, RunScope, Tool, ToolRegistry};
struct Echo;
#[async_trait::async_trait]
impl Tool for Echo {
fn name(&self) -> &str {
"echo"
}
fn description(&self) -> &str {
"Say back what it was given."
}
fn parameters(&self) -> serde_json::Value {
serde_json::json!({"type":"object","properties":{"msg":{"type":"string"}}})
}
async fn call(&self, args: serde_json::Value) -> Result<String, ToolError> {
Ok(format!("echo: {}", args["msg"].as_str().unwrap_or("")))
}
}
async fn ask(path: &Path, body: &str) -> String {
let stream = tokio::net::UnixStream::connect(path).await.unwrap();
let (read, mut write) = stream.into_split();
let mut req = body.to_string();
req.push('\n');
write.write_all(req.as_bytes()).await.unwrap();
let mut line = String::new();
BufReader::new(read).read_line(&mut line).await.unwrap();
line
}
async fn with_child(
policy: Policy,
approver: &dyn crate::tools::Approver,
body: &'static str,
) -> String {
let mut registry = ToolRegistry::new(4096);
registry.register(std::sync::Arc::new(Echo), policy);
let run = RunScope::default();
let scope = CallScope {
approver,
run: &run,
registry: ®istry,
call_id: None,
};
let bridge = Bridge::bind().unwrap();
let mut cmd = tokio::process::Command::new("sh");
cmd.arg("-c").arg("sleep 0.6");
cmd.env(ENV_TOOL_SOCKET, bridge.path());
let mut running = spawn(cmd, 4096).unwrap();
let path = bridge.path().to_path_buf();
let client = tokio::spawn(async move { ask(&path, body).await });
let _ = bridge.wait_serving(&mut running, &scope).await.unwrap();
client.await.unwrap()
}
#[tokio::test]
async fn a_request_over_the_bridge_runs_the_named_tool_and_answers() {
let answer = with_child(
Policy::Allow,
&AllowAll,
r#"{"name":"echo","arguments":{"msg":"hi"}}"#,
)
.await;
assert!(answer.contains("\"ok\":true"), "{answer}");
assert!(answer.contains("echo: hi"), "{answer}");
}
#[tokio::test]
async fn a_tool_that_asks_still_asks_when_a_program_calls_it() {
let answer = with_child(
Policy::Ask,
&DenyAll,
r#"{"name":"echo","arguments":{"msg":"hi"}}"#,
)
.await;
assert!(answer.contains("\"ok\":false"), "{answer}");
assert!(
answer.contains("declined"),
"the bridge is a transport, not a privilege: {answer}"
);
}
#[tokio::test]
async fn a_call_that_needs_an_answer_is_refused_because_a_script_cannot_wait() {
struct Defering;
#[async_trait::async_trait]
impl crate::tools::Approver for Defering {
async fn decide(
&self,
_call: &crate::approvals::Pending,
) -> crate::approvals::Decision {
crate::approvals::Decision::Defer
}
}
let answer = with_child(
Policy::Ask,
&Defering,
r#"{"name":"echo","arguments":{"msg":"hi"}}"#,
)
.await;
assert!(answer.contains("\"ok\":false"), "{answer}");
assert!(
answer.contains("cannot wait"),
"the refusal names the reason: {answer}"
);
assert!(
!answer.contains("is not approved yet"),
"and does not claim something is waiting: {answer}"
);
assert!(
!answer.contains("echo: hi"),
"the tool did not run: {answer}"
);
}
#[tokio::test]
async fn an_unknown_tool_is_answered_rather_than_dropped() {
let answer = with_child(
Policy::Allow,
&AllowAll,
r#"{"name":"nope","arguments":{}}"#,
)
.await;
assert!(answer.contains("\"ok\":false"), "{answer}");
assert!(answer.contains("unknown tool"), "{answer}");
}
#[tokio::test]
async fn a_request_that_is_not_json_gets_an_answer_saying_so() {
let answer = with_child(Policy::Allow, &AllowAll, "not json at all").await;
assert!(answer.contains("not JSON"), "{answer}");
}
#[tokio::test]
async fn a_socket_directory_is_private_to_the_user() {
let bridge = Bridge::bind().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(bridge.dir.as_path())
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(
mode, 0o700,
"the socket is only as private as its directory"
);
}
assert!(bridge.path().exists());
let path = bridge.path().to_path_buf();
drop(bridge);
assert!(!path.exists(), "the socket is removed with the run");
}
#[tokio::test]
async fn a_nonce_differs_between_two_bridges_in_the_same_process() {
let a = Bridge::bind().unwrap();
let b = Bridge::bind().unwrap();
assert_ne!(a.path(), b.path());
}
}