Skip to main content

eclipse_core/
tools_bridge.rs

1//! The tool bridge: a program the agent wrote, calling the agent's own tools.
2//!
3//! A script is only as useful as what it can reach. Without a bridge, a script the model writes
4//! can read files and run programs, and that is all — every *decision* it would want to make
5//! with a tool (search this, patch that, ask that endpoint) has to come back to the model as
6//! twenty round trips, each one re-sending the conversation. With a bridge, the loop lives in the
7//! script where a loop belongs, and the model sees one result.
8//!
9//! **The protocol is one JSON line each way over a Unix socket.** The parent listens; the child
10//! gets the path in [`ENV_TOOL_SOCKET`] and sends `{"name": …, "arguments": {…}}`, and reads back
11//! `{"ok": true, "output": …}` or `{"ok": false, "error": …}`. No framing beyond a newline, no
12//! handshake, no version: there is one writer and one reader, and the child is the one we just
13//! started. `eclipse tool <name> [json]` is the client, so a script in any language can reach the
14//! bridge with `curl --unix-socket` or with four lines of anything.
15//!
16//! **A call through the bridge is a call.** It goes to
17//! [`ToolRegistry::dispatch_scoped`], so the tool named faces `[tools] disabled`, its policy, the
18//! plugin hooks, the approval prompt on its own `describe_call`, and the output cap — the same
19//! funnel a call from the model goes through. The bridge is a *transport*, not a privilege: the
20//! only thing it adds is that the caller is a program.
21//!
22//! **The wait is a `select!`, not a spawn.** The child's tool calls are answered on the same task
23//! that is waiting for it, so the registry and the run scope are borrowed for the duration and
24//! nothing needs an `Arc` back into the registry. The output readers are their own tasks — a
25//! child that fills its stdout pipe must not stop serving its own requests.
26
27use crate::tools::{CallScope, ToolError};
28use std::path::{Path, PathBuf};
29use std::time::Duration;
30use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
31
32/// Where the child finds the bridge. Set for every process Eclipse starts; absent means there is
33/// no bridge, which is what `eclipse tool` outside a run reports.
34pub const ENV_TOOL_SOCKET: &str = "ECLIPSE_TOOL_SOCKET";
35
36/// The most one request or response may be. A tool call is a few kilobytes of JSON; a megabyte is
37/// a mistaken write, and reading it unbounded is a way to be eaten by a child that loops.
38const MAX_LINE_BYTES: u64 = 1024 * 1024;
39
40/// One request, as the child sends it.
41#[derive(serde::Deserialize)]
42struct Request {
43    name: String,
44    #[serde(default)]
45    arguments: serde_json::Value,
46}
47
48/// One answer, as the child reads it.
49#[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
58/// A listening socket for the length of one run, removed when it goes out of scope.
59pub struct Bridge {
60    path: PathBuf,
61    listener: tokio::net::UnixListener,
62    /// The directory the socket lives in, removed with it. Kept separate from `path` so a failed
63    /// unlink cannot leave the directory behind as well.
64    dir: PathBuf,
65}
66
67impl Bridge {
68    /// Bind a socket in a fresh 0700 directory under the system temporary directory.
69    ///
70    /// The directory is per-run and mode 0700: the socket is only as private as the directory
71    /// that holds it, and a predictable path in a shared `/tmp` would let another user connect
72    /// and call tools as the agent.
73    ///
74    /// Must be called inside a Tokio runtime: the listener is handed to the reactor here, so that
75    /// `accept` in [`Self::wait_serving`] can be one arm of a `select!`.
76    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    /// The path the child is told about.
102    pub fn path(&self) -> &Path {
103        &self.path
104    }
105
106    /// Answer one request from `conn`. Reads exactly one line, so a child that connects and says
107    /// nothing is bounded by its own timeout rather than by ours.
108    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            // A connection that says nothing is a health check or a mistake; either way there is
120            // nothing to answer and no reason to hold the run open.
121            _ => 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                // The same funnel as a call the model made. `call_id: None` because the ids
132                // belong to model-issued calls and a hook correlating them must not match a
133                // script's call to a model's.
134                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                // `#453`: a scripted call has nowhere to pause — the parent turn is inside the
140                // `script` call, so there is no boundary to stop at and no later process that can
141                // resume the child. Answering "waiting for an answer" would be a lie the child can
142                // never resolve, so this says what happened: the call was refused, and the route
143                // that can wait is the model's own turn.
144                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    /// Wait for the child, answering tool calls while it runs.
182    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                    // A refused connection is the child's problem to report; a run must not die
191                    // because one connect failed.
192                    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
209/// A nonce for the socket directory. Not cryptography: it only has to differ from another
210/// Eclipse starting in the same second, and 0700 on the directory does the rest.
211fn 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
219/// Run `cmd` with a bridge: bounded by `timeout`, killed as a group, output capped, and its tool
220/// calls answered until it exits.
221///
222/// Same guarantees as [`crate::tools::run_to_completion`], because it starts the process the same
223/// way; the difference is only in what the parent is doing while it waits.
224pub 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
242/// [`run_with_bridge`] for a child that has to be built again if starting it is refused —
243/// `ETXTBSY` on a script another thread was writing, say. The bridge socket is bound once, so the
244/// retry is the same bridge with a new process.
245pub 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/// What a child reports when it asks the bridge for a tool.
274#[derive(serde::Deserialize)]
275struct ClientResponse {
276    ok: bool,
277    #[serde(default)]
278    output: String,
279    #[serde(default)]
280    error: String,
281}
282
283/// One tool call over the bridge, from the child's side: what `eclipse tool` runs.
284///
285/// Returns the text to print and the exit code to leave with, because a script's `&&` chain
286/// depends on it: 0 when the tool ran, 1 when it refused or failed, 2 when there is no bridge.
287pub 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    /// Speak the protocol from the child's side, exactly as `eclipse tool` does.
380    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    /// Start a child that lives long enough to be asked something, then serve it.
392    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: &registry,
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        // The child has exited; the client finished first because it was one round trip.
415        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    /// `#453`: a deferred call reached from inside a script is refused, and it says so. The turn
446    /// cannot pause there, so "waiting for an answer" would name a wait nothing will ever end.
447    #[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}