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    /// The path is short on purpose — a Unix socket path is capped at `SUN_LEN`, and a scripts
75    /// directory under a deep config path can easily be half of that budget already.
76    ///
77    /// A caller that runs the child under `shell_isolate = "fs"` binds [`Self::dir`] into the
78    /// namespace, because the child gets a fresh `/tmp` and would otherwise be told about a path
79    /// that does not exist where it runs (#550).
80    ///
81    /// Must be called inside a Tokio runtime: the listener is handed to the reactor here, so that
82    /// `accept` in [`Self::wait_serving`] can be one arm of a `select!`.
83    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    /// The path the child is told about.
109    pub fn path(&self) -> &Path {
110        &self.path
111    }
112
113    /// The directory holding the socket: what a caller binds into an `fs` namespace (#550).
114    pub fn dir(&self) -> &Path {
115        &self.dir
116    }
117
118    /// Answer one request from `conn`. Reads exactly one line, so a child that connects and says
119    /// nothing is bounded by its own timeout rather than by ours.
120    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            // A connection that says nothing is a health check or a mistake; either way there is
132            // nothing to answer and no reason to hold the run open.
133            _ => 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                // The same funnel as a call the model made. `call_id: None` because the ids
144                // belong to model-issued calls and a hook correlating them must not match a
145                // script's call to a model's.
146                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                // `#453`: a scripted call has nowhere to pause — the parent turn is inside the
152                // `script` call, so there is no boundary to stop at and no later process that can
153                // resume the child. Answering "waiting for an answer" would be a lie the child can
154                // never resolve, so this says what happened: the call was refused, and the route
155                // that can wait is the model's own turn.
156                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    /// Wait for the child, answering tool calls while it runs.
194    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                    // A refused connection is the child's problem to report; a run must not die
203                    // because one connect failed.
204                    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
221/// A nonce for the socket directory. Not cryptography: it only has to differ from another
222/// Eclipse starting in the same second, and 0700 on the directory does the rest.
223fn 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
231/// Run `cmd` with a bridge: bounded by `timeout`, killed as a group, output capped, and its tool
232/// calls answered until it exits.
233///
234/// Same guarantees as [`crate::tools::run_to_completion`], because it starts the process the same
235/// way; the difference is only in what the parent is doing while it waits.
236pub 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
256/// [`run_with_bridge`] for a child that has to be built again if starting it is refused —
257/// `ETXTBSY` on a script another thread was writing, say. The bridge socket is bound once, so the
258/// retry is the same bridge with a new process.
259pub 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/// What a child reports when it asks the bridge for a tool.
288#[derive(serde::Deserialize)]
289struct ClientResponse {
290    ok: bool,
291    #[serde(default)]
292    output: String,
293    #[serde(default)]
294    error: String,
295}
296
297/// One tool call over the bridge, from the child's side: what `eclipse tool` runs.
298///
299/// Returns the text to print and the exit code to leave with, because a script's `&&` chain
300/// depends on it: 0 when the tool ran, 1 when it refused or failed, 2 when there is no bridge.
301pub 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    /// Speak the protocol from the child's side, exactly as `eclipse tool` does.
394    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    /// Start a child that lives long enough to be asked something, then serve it.
406    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: &registry,
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        // The child has exited; the client finished first because it was one round trip.
429        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    /// `#453`: a deferred call reached from inside a script is refused, and it says so. The turn
460    /// cannot pause there, so "waiting for an answer" would name a wait nothing will ever end.
461    #[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}