eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! The tool bridge: a program the agent wrote, calling the agent's own tools.
//!
//! A script is only as useful as what it can reach. Without a bridge, a script the model writes
//! can read files and run programs, and that is all — every *decision* it would want to make
//! with a tool (search this, patch that, ask that endpoint) has to come back to the model as
//! twenty round trips, each one re-sending the conversation. With a bridge, the loop lives in the
//! script where a loop belongs, and the model sees one result.
//!
//! **The protocol is one JSON line each way over a Unix socket.** The parent listens; the child
//! gets the path in [`ENV_TOOL_SOCKET`] and sends `{"name": …, "arguments": {…}}`, and reads back
//! `{"ok": true, "output": …}` or `{"ok": false, "error": …}`. No framing beyond a newline, no
//! handshake, no version: there is one writer and one reader, and the child is the one we just
//! started. `eclipse tool <name> [json]` is the client, so a script in any language can reach the
//! bridge with `curl --unix-socket` or with four lines of anything.
//!
//! **A call through the bridge is a call.** It goes to
//! [`ToolRegistry::dispatch_scoped`], so the tool named faces `[tools] disabled`, its policy, the
//! plugin hooks, the approval prompt on its own `describe_call`, and the output cap — the same
//! funnel a call from the model goes through. The bridge is a *transport*, not a privilege: the
//! only thing it adds is that the caller is a program.
//!
//! **The wait is a `select!`, not a spawn.** The child's tool calls are answered on the same task
//! that is waiting for it, so the registry and the run scope are borrowed for the duration and
//! nothing needs an `Arc` back into the registry. The output readers are their own tasks — a
//! child that fills its stdout pipe must not stop serving its own requests.

use crate::tools::{CallScope, ToolError};
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};

/// Where the child finds the bridge. Set for every process Eclipse starts; absent means there is
/// no bridge, which is what `eclipse tool` outside a run reports.
pub const ENV_TOOL_SOCKET: &str = "ECLIPSE_TOOL_SOCKET";

/// The most one request or response may be. A tool call is a few kilobytes of JSON; a megabyte is
/// a mistaken write, and reading it unbounded is a way to be eaten by a child that loops.
const MAX_LINE_BYTES: u64 = 1024 * 1024;

/// One request, as the child sends it.
#[derive(serde::Deserialize)]
struct Request {
    name: String,
    #[serde(default)]
    arguments: serde_json::Value,
}

/// One answer, as the child reads it.
#[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>,
}

/// A listening socket for the length of one run, removed when it goes out of scope.
pub struct Bridge {
    path: PathBuf,
    listener: tokio::net::UnixListener,
    /// The directory the socket lives in, removed with it. Kept separate from `path` so a failed
    /// unlink cannot leave the directory behind as well.
    dir: PathBuf,
}

impl Bridge {
    /// Bind a socket in a fresh 0700 directory under the system temporary directory.
    ///
    /// The directory is per-run and mode 0700: the socket is only as private as the directory
    /// that holds it, and a predictable path in a shared `/tmp` would let another user connect
    /// and call tools as the agent.
    ///
    /// Must be called inside a Tokio runtime: the listener is handed to the reactor here, so that
    /// `accept` in [`Self::wait_serving`] can be one arm of a `select!`.
    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,
        })
    }

    /// The path the child is told about.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Answer one request from `conn`. Reads exactly one line, so a child that connects and says
    /// nothing is bounded by its own timeout rather than by ours.
    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,
            // A connection that says nothing is a health check or a mistake; either way there is
            // nothing to answer and no reason to hold the run open.
            _ => 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) => {
                // The same funnel as a call the model made. `call_id: None` because the ids
                // belong to model-issued calls and a hook correlating them must not match a
                // script's call to a model's.
                let raw = req.arguments.to_string();
                let outcome = scope
                    .registry
                    .dispatch_scoped(&req.name, &raw, scope.approver, None, scope.run)
                    .await;
                // `#453`: a scripted call has nowhere to pause — the parent turn is inside the
                // `script` call, so there is no boundary to stop at and no later process that can
                // resume the child. Answering "waiting for an answer" would be a lie the child can
                // never resolve, so this says what happened: the call was refused, and the route
                // that can wait is the model's own turn.
                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;
    }

    /// Wait for the child, answering tool calls while it runs.
    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() => {
                    // A refused connection is the child's problem to report; a run must not die
                    // because one connect failed.
                    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);
    }
}

/// A nonce for the socket directory. Not cryptography: it only has to differ from another
/// Eclipse starting in the same second, and 0700 on the directory does the rest.
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)
}

/// Run `cmd` with a bridge: bounded by `timeout`, killed as a group, output capped, and its tool
/// calls answered until it exits.
///
/// Same guarantees as [`crate::tools::run_to_completion`], because it starts the process the same
/// way; the difference is only in what the parent is doing while it waits.
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
}

/// [`run_with_bridge`] for a child that has to be built again if starting it is refused —
/// `ETXTBSY` on a script another thread was writing, say. The bridge socket is bound once, so the
/// retry is the same bridge with a new process.
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)
}

/// What a child reports when it asks the bridge for a tool.
#[derive(serde::Deserialize)]
struct ClientResponse {
    ok: bool,
    #[serde(default)]
    output: String,
    #[serde(default)]
    error: String,
}

/// One tool call over the bridge, from the child's side: what `eclipse tool` runs.
///
/// Returns the text to print and the exit code to leave with, because a script's `&&` chain
/// depends on it: 0 when the tool ran, 1 when it refused or failed, 2 when there is no bridge.
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("")))
        }
    }

    /// Speak the protocol from the child's side, exactly as `eclipse tool` does.
    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
    }

    /// Start a child that lives long enough to be asked something, then serve it.
    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: &registry,
            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();
        // The child has exited; the client finished first because it was one round trip.
        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}"
        );
    }

    /// `#453`: a deferred call reached from inside a script is refused, and it says so. The turn
    /// cannot pause there, so "waiting for an answer" would name a wait nothing will ever end.
    #[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());
    }
}