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