1use crate::tools::{CallScope, ToolError};
28use std::path::{Path, PathBuf};
29use std::time::Duration;
30use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
31
32pub const ENV_TOOL_SOCKET: &str = "ECLIPSE_TOOL_SOCKET";
35
36const MAX_LINE_BYTES: u64 = 1024 * 1024;
39
40#[derive(serde::Deserialize)]
42struct Request {
43 name: String,
44 #[serde(default)]
45 arguments: serde_json::Value,
46}
47
48#[derive(serde::Serialize)]
50struct Response<'a> {
51 ok: bool,
52 #[serde(skip_serializing_if = "Option::is_none")]
53 output: Option<&'a str>,
54 #[serde(skip_serializing_if = "Option::is_none")]
55 error: Option<&'a str>,
56}
57
58pub struct Bridge {
60 path: PathBuf,
61 listener: tokio::net::UnixListener,
62 dir: PathBuf,
65}
66
67impl Bridge {
68 pub fn bind() -> Result<Self, ToolError> {
77 let base = std::env::temp_dir();
78 let dir = base.join(format!("eclipse-bridge-{}-{}", std::process::id(), nonce()));
79 std::fs::create_dir_all(&dir)
80 .map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", dir.display())))?;
81 #[cfg(unix)]
82 {
83 use std::os::unix::fs::PermissionsExt;
84 let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
85 }
86 let path = dir.join("tools.sock");
87 let listener = std::os::unix::net::UnixListener::bind(&path)
88 .map_err(|e| ToolError::Failed(format!("cannot bind {}: {e}", path.display())))?;
89 listener
90 .set_nonblocking(true)
91 .map_err(|e| ToolError::Failed(format!("cannot set non-blocking: {e}")))?;
92 let listener = tokio::net::UnixListener::from_std(listener)
93 .map_err(|e| ToolError::Failed(format!("cannot watch {}: {e}", path.display())))?;
94 Ok(Self {
95 path,
96 listener,
97 dir,
98 })
99 }
100
101 pub fn path(&self) -> &Path {
103 &self.path
104 }
105
106 async fn serve(&self, conn: tokio::net::UnixStream, scope: &CallScope<'_>) {
109 let (read, mut write) = conn.into_split();
110 let mut line = String::new();
111 let mut reader = BufReader::new(read);
112 let body = match tokio::time::timeout(
113 Duration::from_secs(1),
114 (&mut reader).take(MAX_LINE_BYTES).read_line(&mut line),
115 )
116 .await
117 {
118 Ok(Ok(n)) if n > 0 => line,
119 _ => return,
122 };
123 let reply = match serde_json::from_str::<Request>(&body) {
124 Err(e) => serde_json::to_string(&Response {
125 ok: false,
126 output: None,
127 error: Some(&format!("request is not JSON: {e}")),
128 })
129 .unwrap_or_else(|_| "{\"ok\":false,\"error\":\"unserialisable\"}".into()),
130 Ok(req) => {
131 let raw = req.arguments.to_string();
135 let outcome = scope
136 .registry
137 .dispatch_scoped(&req.name, &raw, scope.approver, None, scope.run)
138 .await;
139 let refused = outcome.deferred.then(|| {
145 format!(
146 "`{}` needs your approval, and a call from inside a script cannot wait for \
147 one: it was refused. Make the call from the model's turn, where it can \
148 pause, or run it yourself once you have decided.",
149 req.name
150 )
151 });
152 let response = if let Some(reason) = refused.as_deref() {
153 Response {
154 ok: false,
155 output: None,
156 error: Some(reason),
157 }
158 } else if outcome.is_error {
159 Response {
160 ok: false,
161 output: None,
162 error: Some(outcome.output.as_str()),
163 }
164 } else {
165 Response {
166 ok: true,
167 output: Some(outcome.output.as_str()),
168 error: None,
169 }
170 };
171 serde_json::to_string(&response)
172 .unwrap_or_else(|_| "{\"ok\":false,\"error\":\"unserialisable\"}".into())
173 }
174 };
175 let mut reply = reply;
176 reply.push('\n');
177 let _ = write.write_all(reply.as_bytes()).await;
178 let _ = write.flush().await;
179 }
180
181 pub(crate) async fn wait_serving(
183 &self,
184 running: &mut crate::tools::Running,
185 scope: &CallScope<'_>,
186 ) -> Result<std::process::ExitStatus, ToolError> {
187 loop {
188 tokio::select! {
189 accepted = self.listener.accept() => {
190 if let Ok((conn, _)) = accepted {
193 self.serve(conn, scope).await;
194 }
195 }
196 status = running.wait() => return status,
197 }
198 }
199 }
200}
201
202impl Drop for Bridge {
203 fn drop(&mut self) {
204 let _ = std::fs::remove_file(&self.path);
205 let _ = std::fs::remove_dir(&self.dir);
206 }
207}
208
209fn nonce() -> u64 {
212 use std::time::{SystemTime, UNIX_EPOCH};
213 SystemTime::now()
214 .duration_since(UNIX_EPOCH)
215 .map(|d| d.as_nanos() as u64)
216 .unwrap_or(0)
217}
218
219pub async fn run_with_bridge(
225 cmd: tokio::process::Command,
226 max_bytes: usize,
227 timeout: Duration,
228 kill_grace: Duration,
229 scope: &CallScope<'_>,
230) -> Result<String, ToolError> {
231 let mut once = Some(cmd);
232 run_with_bridge_built(
233 || once.take().expect("built once"),
234 max_bytes,
235 timeout,
236 kill_grace,
237 scope,
238 )
239 .await
240}
241
242pub async fn run_with_bridge_built<F>(
246 mut build: F,
247 max_bytes: usize,
248 timeout: Duration,
249 kill_grace: Duration,
250 scope: &CallScope<'_>,
251) -> Result<String, ToolError>
252where
253 F: FnMut() -> tokio::process::Command,
254{
255 let bridge = Bridge::bind()?;
256 let mut running = crate::tools::start_retrying(
257 || {
258 let mut cmd = build();
259 cmd.env(ENV_TOOL_SOCKET, bridge.path());
260 cmd
261 },
262 max_bytes,
263 )
264 .await?;
265 let status = match tokio::time::timeout(timeout, bridge.wait_serving(&mut running, scope)).await
266 {
267 Ok(done) => done?,
268 Err(_) => return Err(running.timed_out(timeout, kill_grace).await),
269 };
270 Ok(running.finish(status).await)
271}
272
273#[derive(serde::Deserialize)]
275struct ClientResponse {
276 ok: bool,
277 #[serde(default)]
278 output: String,
279 #[serde(default)]
280 error: String,
281}
282
283pub async fn call_over_bridge(name: &str, arguments: &str) -> (String, i32) {
288 let Some(path) = std::env::var_os(ENV_TOOL_SOCKET) else {
289 return (
290 format!(
291 "no tool bridge: {ENV_TOOL_SOCKET} is not set. `eclipse tool` reaches the tools of \
292 the run that started this program; outside a run there is nothing to call — use \
293 `eclipse run` and let the agent's script call it."
294 ),
295 2,
296 );
297 };
298 let args: serde_json::Value = if arguments.trim().is_empty() {
299 serde_json::json!({})
300 } else {
301 match serde_json::from_str(arguments) {
302 Ok(v) => v,
303 Err(e) => {
304 return (
305 format!(
306 "arguments are not JSON: {e}. Pass an object, e.g. '{{\"path\": \"x\"}}'"
307 ),
308 2,
309 )
310 }
311 }
312 };
313 let request = serde_json::json!({"name": name, "arguments": args}).to_string();
314 let stream = match tokio::net::UnixStream::connect(&path).await {
315 Ok(s) => s,
316 Err(e) => {
317 return (
318 format!(
319 "cannot reach the tool bridge at {}: {e}. The run that started this program \
320 may have finished.",
321 PathBuf::from(&path).display()
322 ),
323 2,
324 )
325 }
326 };
327 let (read, mut write) = stream.into_split();
328 let mut request = request;
329 request.push('\n');
330 if let Err(e) = write.write_all(request.as_bytes()).await {
331 return (format!("cannot send to the tool bridge: {e}"), 2);
332 }
333 let _ = write.flush().await;
334 let mut line = String::new();
335 let mut reader = BufReader::new(read);
336 match tokio::time::timeout(
337 Duration::from_secs(60),
338 (&mut reader).take(MAX_LINE_BYTES).read_line(&mut line),
339 )
340 .await
341 {
342 Ok(Ok(0)) | Err(_) => (
343 "the tool bridge closed the connection without answering".to_string(),
344 2,
345 ),
346 Ok(Ok(_)) => match serde_json::from_str::<ClientResponse>(&line) {
347 Ok(r) if r.ok => (r.output, 0),
348 Ok(r) => (r.error, 1),
349 Err(e) => (format!("the tool bridge's answer is not JSON: {e}"), 2),
350 },
351 Ok(Err(e)) => (format!("cannot read from the tool bridge: {e}"), 2),
352 }
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358 use crate::config::Policy;
359 use crate::tools::{spawn, AllowAll, DenyAll, RunScope, Tool, ToolRegistry};
360
361 struct Echo;
362
363 #[async_trait::async_trait]
364 impl Tool for Echo {
365 fn name(&self) -> &str {
366 "echo"
367 }
368 fn description(&self) -> &str {
369 "Say back what it was given."
370 }
371 fn parameters(&self) -> serde_json::Value {
372 serde_json::json!({"type":"object","properties":{"msg":{"type":"string"}}})
373 }
374 async fn call(&self, args: serde_json::Value) -> Result<String, ToolError> {
375 Ok(format!("echo: {}", args["msg"].as_str().unwrap_or("")))
376 }
377 }
378
379 async fn ask(path: &Path, body: &str) -> String {
381 let stream = tokio::net::UnixStream::connect(path).await.unwrap();
382 let (read, mut write) = stream.into_split();
383 let mut req = body.to_string();
384 req.push('\n');
385 write.write_all(req.as_bytes()).await.unwrap();
386 let mut line = String::new();
387 BufReader::new(read).read_line(&mut line).await.unwrap();
388 line
389 }
390
391 async fn with_child(
393 policy: Policy,
394 approver: &dyn crate::tools::Approver,
395 body: &'static str,
396 ) -> String {
397 let mut registry = ToolRegistry::new(4096);
398 registry.register(std::sync::Arc::new(Echo), policy);
399 let run = RunScope::default();
400 let scope = CallScope {
401 approver,
402 run: &run,
403 registry: ®istry,
404 call_id: None,
405 };
406 let bridge = Bridge::bind().unwrap();
407 let mut cmd = tokio::process::Command::new("sh");
408 cmd.arg("-c").arg("sleep 0.6");
409 cmd.env(ENV_TOOL_SOCKET, bridge.path());
410 let mut running = spawn(cmd, 4096).unwrap();
411 let path = bridge.path().to_path_buf();
412 let client = tokio::spawn(async move { ask(&path, body).await });
413 let _ = bridge.wait_serving(&mut running, &scope).await.unwrap();
414 client.await.unwrap()
416 }
417
418 #[tokio::test]
419 async fn a_request_over_the_bridge_runs_the_named_tool_and_answers() {
420 let answer = with_child(
421 Policy::Allow,
422 &AllowAll,
423 r#"{"name":"echo","arguments":{"msg":"hi"}}"#,
424 )
425 .await;
426 assert!(answer.contains("\"ok\":true"), "{answer}");
427 assert!(answer.contains("echo: hi"), "{answer}");
428 }
429
430 #[tokio::test]
431 async fn a_tool_that_asks_still_asks_when_a_program_calls_it() {
432 let answer = with_child(
433 Policy::Ask,
434 &DenyAll,
435 r#"{"name":"echo","arguments":{"msg":"hi"}}"#,
436 )
437 .await;
438 assert!(answer.contains("\"ok\":false"), "{answer}");
439 assert!(
440 answer.contains("declined"),
441 "the bridge is a transport, not a privilege: {answer}"
442 );
443 }
444
445 #[tokio::test]
448 async fn a_call_that_needs_an_answer_is_refused_because_a_script_cannot_wait() {
449 struct Defering;
450 #[async_trait::async_trait]
451 impl crate::tools::Approver for Defering {
452 async fn decide(
453 &self,
454 _call: &crate::approvals::Pending,
455 ) -> crate::approvals::Decision {
456 crate::approvals::Decision::Defer
457 }
458 }
459 let answer = with_child(
460 Policy::Ask,
461 &Defering,
462 r#"{"name":"echo","arguments":{"msg":"hi"}}"#,
463 )
464 .await;
465 assert!(answer.contains("\"ok\":false"), "{answer}");
466 assert!(
467 answer.contains("cannot wait"),
468 "the refusal names the reason: {answer}"
469 );
470 assert!(
471 !answer.contains("is not approved yet"),
472 "and does not claim something is waiting: {answer}"
473 );
474 assert!(
475 !answer.contains("echo: hi"),
476 "the tool did not run: {answer}"
477 );
478 }
479
480 #[tokio::test]
481 async fn an_unknown_tool_is_answered_rather_than_dropped() {
482 let answer = with_child(
483 Policy::Allow,
484 &AllowAll,
485 r#"{"name":"nope","arguments":{}}"#,
486 )
487 .await;
488 assert!(answer.contains("\"ok\":false"), "{answer}");
489 assert!(answer.contains("unknown tool"), "{answer}");
490 }
491
492 #[tokio::test]
493 async fn a_request_that_is_not_json_gets_an_answer_saying_so() {
494 let answer = with_child(Policy::Allow, &AllowAll, "not json at all").await;
495 assert!(answer.contains("not JSON"), "{answer}");
496 }
497
498 #[tokio::test]
499 async fn a_socket_directory_is_private_to_the_user() {
500 let bridge = Bridge::bind().unwrap();
501 #[cfg(unix)]
502 {
503 use std::os::unix::fs::PermissionsExt;
504 let mode = std::fs::metadata(bridge.dir.as_path())
505 .unwrap()
506 .permissions()
507 .mode()
508 & 0o777;
509 assert_eq!(
510 mode, 0o700,
511 "the socket is only as private as its directory"
512 );
513 }
514 assert!(bridge.path().exists());
515 let path = bridge.path().to_path_buf();
516 drop(bridge);
517 assert!(!path.exists(), "the socket is removed with the run");
518 }
519
520 #[tokio::test]
521 async fn a_nonce_differs_between_two_bridges_in_the_same_process() {
522 let a = Bridge::bind().unwrap();
523 let b = Bridge::bind().unwrap();
524 assert_ne!(a.path(), b.path());
525 }
526}